我经常发现在Emacs中需要在标记的区域周围添加/删除括号。
目前,我通过以下方式手动添加:
- 将光标移动到所需区域的一端,输入开放分隔符;
- 将光标移动到所需区域的另一端,输入关闭分隔符;
并以相反的方式进行删除。
然而,由于光标的移动,这似乎很麻烦且容易出错。从安全角度来看,如果我成对地删除括号,我会感觉更安全,因为这是一个原子操作
Emacs中是否有内置或手工制作的函数可以针对标记的区域执行此操作?
我经常发现在Emacs中需要在标记的区域周围添加/删除括号。
目前,我通过以下方式手动添加:
并以相反的方式进行删除。
然而,由于光标的移动,这似乎很麻烦且容易出错。从安全角度来看,如果我成对地删除括号,我会感觉更安全,因为这是一个原子操作
Emacs中是否有内置或手工制作的函数可以针对标记的区域执行此操作?
用 delete-pair
函数删除一对括号、方括号或其他字符:
您无需标记区域。
M-x delete-pair
C-M-u
退出括号,然后使用 M-x delete-pair
。M--
(负参数),然后使用 M-x delete-pair
使用括号将区域包起来:
M-(
。
(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))))))
前者在区域周围插入括号,让光标停留在右括号之后。后者仅在括号精确包围区域且匹配正确时才删除括号。
例如,它将拒绝删除这些括号:
(x a b c d (y) z)
^ ^
this and 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 ?\` ?\'))
C-x C-x
、C-M-f
和C-M-b
?((a + b))
。我很想把它们删掉;2. 是的,我知道这些键,但是在前面的情况下,((a + b))
。当我删除外部开括号(
后,就不能方便地跳到右括号)
。 - modelleryas/selected-text
。要删除,您可以执行类似于re-search-backward
/re-search-forward
的操作,并删除所需的字符。 - lawlist(region-beginning)
和(region-end)
。因此,您可以使用这两个点来添加和删除括号。 - lawlist