How do I add / remove parentheses around a marked area in Emacs?
I often find it necessary to add / remove parentheses / brackets around the marked area in Emacs.
I am currently adding manually:
- Move the cursor to one end of the intended area, enter the opening separator;
- Move the cursor to the other end of the intended area, enter the final separator;
And removal in another way.
However, this seems cumbersome and error prone due to cursor movement. From a security point of view, if I remove the parentheses in pairs, I feel safer because it is an atomic operation
Is there a built-in or hand-crafted function in Emacs to do this in relation to the marked area?
source to share
Try the following functions:
(defun surround-with-parens ()
(interactive)
(save-excursion
(goto-char (region-beginning))
(insert "("))
(goto-char (region-end))
(insert ")"))
(defun delete-surrounded-parens ()
(interactive)
(let ((beginning (region-beginning))
(end (region-end)))
(cond ((not (eq (char-after beginning) ?\())
(error "Character at region-begin is not an open-parenthesis"))
((not (eq (char-before end) ?\)))
(error "Character at region-end is not a close-parenthesis"))
((save-excursion
(goto-char beginning)
(forward-sexp)
(not (eq (point) end)))
(error "Those parentheses are not matched"))
(t (save-excursion
(goto-char end)
(delete-backward-char 1)
(goto-char beginning)
(delete-char 1))))))
The first inserts parentheses around the region, leaving point after the closing parenthesis. The latter only removes the parentheses if they are exactly * surrounded by the scope, and if they match correctly.
For example, it will refuse to remove those parentheses:
(x a b c d (y) z)
^ ^
this and this
* This can be improved by looking inward for parentheses rather than being on the exact region boundaries; I will do this later if I have time.
source to share
try this:
(global-set-key "\M-'" 'insert-quotations)
(global-set-key "\M-\"" 'insert-quotes)
(global-set-key (kbd "C-'") 'insert-backquote)
(defun insert-quotations (&optional arg)
"Enclose following ARG sexps in quotation marks.
Leave point after open-paren."
(interactive "*P")
(insert-pair arg ?\' ?\'))
(defun insert-quotes (&optional arg)
"Enclose following ARG sexps in quotes.
Leave point after open-quote."
(interactive "*P")
(insert-pair arg ?\" ?\"))
(defun insert-backquote (&optional arg)
"Enclose following ARG sexps in quotations with backquote.
Leave point after open-quotation."
(interactive "*P")
(insert-pair arg ?\` ?\'))
source to share