帮助使用交互式Emacs Lisp函数替换文本

时间:2009-01-17 22:49:20

标签: emacs elisp

我已经使用Emacs几个月了,我想开始使用elisp编程。具体来说,我想编写自己的interactive函数。但是,我有点失落。 (interactive ...)有很多选择,我不确定我想要哪一个。然后,我真的不知道我需要的功能的名称。如果有人能帮我把我的伪代码变成真正的代码,我会非常感激! (和往常一样,任何提供信息的地方的链接都会很好。现在我刚刚阅读this.

这是我想要做的伪代码:

(defun my-func (buffer) ; I think I need the buffer as an arg?
  "does some replacements"
  (interactive ???) ; ?
  (let (replacements (list
   '("a-regexp-string" . "a-replacement-string-with-backreferences")
   ...)) ; more of the above
    (while replacements
      (let (current (car replacements)) ; get a regexp-replacement pair
        (some-regexp-replace-func buffer (car current) (cdr current)) ; do the replacement
        (setq replacements (cdr replacements))))))

1 个答案:

答案 0 :(得分:5)

首先,根据你的函数的外观,你可能会在当前缓冲区中执行它,所以不,你不需要有一个'buffer'参数。如果这是一个不好的假设,我可以更改代码。接下来,在'let'中如果要分配变量,则需要在每对var / value周围设置另一组parens。最后,当循环遍历列表时,我更喜欢使用类似函数式编程的函数(mapcar,mapc等)。我将尝试在此处列出一些评论:

(defun my-func ()
  "Do some replacements"
  (interactive)
  (let ((replacements (list '("foo" . "bar")
                            '("baz" . "quux"))))
    (save-excursion ; So point isn't moved after this function
      (mapc (lambda (x) ; Go through the list, with this 'inline' function
                        ; being called with each element as the variable 'x'
              (goto-char (point-min)) ; Start at the beginning of the buffer
              (while (re-search-forward (car x) nil t) ; Search for the car of the replacement
                (replace-match (cdr x)))) ; And replace it with the cdr
            replacements)))) ; The list we're mapc'ing through

至于阅读内容,我建议使用Emacs附带的Elisp手册。