如何在 emacs 中为特定的正则表达式包装 align-regexp

Jos*_*vin 5 emacs elisp

我经常在一个区域上使用 align-regexp 和 regexp " [^ ]+_"。所以我想我会为它定义一个函数,这样我就可以将它绑定到一个键上:

(defun align-members ()
  (interactive)
  (align-regexp " [^ ]+_"))
Run Code Online (Sandbox Code Playgroud)

但是 emacs 抱怨 align-regexp 需要三个参数。查看文档,我看到它需要 BEG 和 END。我不确定(interactive)emacs 中的东西是如何工作的,但是通过阅读我收集的文档,我应该这样做:

(defun align-members (BEG END)
  (interactive "r")
  (align-regexp BEG END " [^ ]+_"))
Run Code Online (Sandbox Code Playgroud)

但是 emacs 然后在 align-regexp 的调用堆栈深处抱怨它所期望的integer-or-marker-p,而是为零。我究竟做错了什么?

Ole*_*liv 5

你应该写如下

(defun align-members (BEG END)
  (interactive "r")
  (align-regexp BEG END (concat "\\(\\s-*\\)" " [^ ]+_") 1 1))
Run Code Online (Sandbox Code Playgroud)

或者更简单一点

(defun align-members (BEG END)
  (interactive "r")
  (align-regexp BEG END "\\(\\s-*\\) [^ ]+_" 1 1))
Run Code Online (Sandbox Code Playgroud)

要理解它,请查看align-regexp来源,这里有它的一部分。

(interactive
 (append
  (list (region-beginning) (region-end))
  (if current-prefix-arg
      (list (read-string "Complex align using regexp: "
                         "\\(\\s-*\\)")
            (string-to-number
             (read-string
              "Parenthesis group to modify (justify if negative): " "1"))
            (string-to-number
             (read-string "Amount of spacing (or column if negative): "
                          (number-to-string align-default-spacing)))
            (y-or-n-p "Repeat throughout line? "))
    (list (concat "\\(\\s-*\\)"
                  (read-string "Align regexp: "))
          1 align-default-spacing nil))))
Run Code Online (Sandbox Code Playgroud)

如你看到的:

  • "\\(\\s-*\\)"向您的正则表达式添加一个字符串
  • 它设置 1 和align-default-spacing可选参数


N.N*_*.N. 0

的文档align-regexp

如果指定了前缀 arg,则应提供带括号的空格的完整正则表达式

所以我在你的正则表达式中加上了空格,这似乎使它起作用:

(defun align-members (beg end)
  (interactive "r")
  (align-regexp beg end "\\( \\)[^ ]+_"))
Run Code Online (Sandbox Code Playgroud)