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

时间:2014-08-02 16:46:40

标签: emacs

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

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

  1. 将光标移动到目标区域的一端,键入开始分隔符;
  2. 将光标移动到目标区域的另一端,键入结束分隔符;
  3. 并以相反的方式去除。

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

    在Emacs中是否有内置或手工制作的功能来处理标记区域?

3 个答案:

答案 0 :(得分:3)

  • 删除一对周围的字符(parens,bracket,whatever)  围绕性别:C-M-u M-x delete-pair
  • 用parens封闭一个区域:标记该区域和M-(

答案 1 :(得分: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

*这可以通过向内搜索括号而不是要求它们位于该区域的确切边界来改进;如果我有时间,我会稍后再做。

答案 2 :(得分: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