代码之家  ›  专栏  ›  技术社区  ›  J Cooper

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

  •  4
  • J Cooper  · 技术社区  · 16 年前

    我已经使用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 回复  |  直到 16 年前
        1
  •  5
  •   scottfrazer    16 年前

    首先,从函数的外观来看,您可能在当前缓冲区中执行此操作,因此不需要使用“buffer”参数。如果这是一个错误的假设,我可以更改代码。下一步,在“let”中,如果要为变量赋值,则需要在每对var/值周围再设置一组参数。最后,当在列表中循环时,我更喜欢使用函数编程,比如函数(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