【问题标题】:Help with an interactive Emacs Lisp function for replacing text用于替换文本的交互式 Emacs Lisp 函数的帮助
【发布时间】:2009-01-17 22:49:19
【问题描述】:

我已经使用 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))))))

【问题讨论】:

    标签: emacs elisp


    【解决方案1】:

    首先,从您的函数的外观来看,您可能会在当前缓冲区中执行此操作,所以不,您不需要“缓冲区”参数。如果这是一个错误的假设,我可以更改代码。接下来,在“让”中,如果要分配给变量,则需要在每对 var/value 周围使用另一组括号。最后,在遍历列表时,我更喜欢使用函数式编程的函数(mapcar、mapc 等)。我将尝试在这里内联一些 cmets:

    (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 手册。

    【讨论】:

    • 非常感谢,这帮助我了解了正在发生的事情并走上正轨。我只需要使用re-search-forward 而不是非正则表达式版本,而不是将t 传递给replace-match,以便匹配组的引用起作用。再次感谢!
    • 是的,我只是回来修这些 :)
    猜你喜欢
    • 1970-01-01
    • 2011-05-27
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    相关资源
    最近更新 更多