如何在Emacs中添加/删除标记区域周围的括号?

7

我经常发现在Emacs中需要在标记的区域周围添加/删除括号。

目前,我通过以下方式手动添加:

  1. 将光标移动到所需区域的一端,输入开放分隔符;
  2. 将光标移动到所需区域的另一端,输入关闭分隔符;

并以相反的方式进行删除。

然而,由于光标的移动,这似乎很麻烦且容易出错。从安全角度来看,如果我成对地删除括号,我会感觉更安全,因为这是一个原子操作

Emacs中是否有内置或手工制作的函数可以针对标记的区域执行此操作?


  1. 我想知道为什么你经常需要这样做,因为我几乎从不这样做。是什么情况导致你有这种需求?
  2. 关于光标移动,我假设你知道 C-x C-xC-M-fC-M-b
- Drew
@Drew 你好,关于你的问题:1. 比如说在代码审查时,我发现有人加了不必要的括号 ((a + b))。我很想把它们删掉;2. 是的,我知道这些键,但是在前面的情况下,((a + b))。当我删除外部开括号 ( 后,就不能方便地跳到右括号 ) - modeller
库yasnippet可以将任何内容围绕选定区域包含 - 当我编写LaTeX文档并用粗体、居中、斜体等代码包围选定区域时,我经常这样做。请参见yas/selected-text。要删除,您可以执行类似于re-search-backward / re-search-forward的操作,并删除所需的字符。 - lawlist
一个区域也有起始点和结束点 -- (region-beginning)(region-end)。因此,您可以使用这两个点来添加和删除括号。 - lawlist
@lawlist 感谢你的建议。我会花些时间去尝试一下。目前我还不熟悉elisp。 - modeller
显示剩余2条评论
3个回答

12

delete-pair 函数删除一对括号、方括号或其他字符: 您无需标记区域。

  • 在一对括号前:使用 M-x delete-pair
  • 在一对括号内:使用 C-M-u 退出括号,然后使用 M-x delete-pair
  • 在一对括号后:使用 M--(负参数),然后使用 M-x delete-pair

使用括号将区域包起来:

  • 标记区域,然后使用M-(

1
尝试使用这些函数:

(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

* 如果向内搜索括号而不需要它们在区域的确切边界上,可能会使其更加完善。如果我有时间,我将稍后完成此操作。


抱歉兄弟,我得选择另一个答案作为选定答案。但我喜欢你提供的其他答案。 - modeller
@modeller 嘿,没关系!我很高兴你说了些什么,因为现在我知道了另一个答案 :) - Lily Chung

0

试试这个:

(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 ?\` ?\'))

https://www.emacswiki.org/emacs/InsertPair


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接