【问题标题】:Emacs - Using perform-replace with counterEmacs - 使用带计数器的执行替换
【发布时间】:2018-05-19 13:41:41
【问题描述】:

我正在尝试在 elisp 中编写一个命令,以自动对给定文件中的单元测试重新编号。为了帮助我轻松定位失败的测试,我通常使用以下语法(使用 GoogleTest):

TEST(testCaseName, T0XX_Test_Description)

我已经能够使用带有 re-search-forward / replace-match 的 while 循环编写工作命令:

(defun renumber-tests-auto(&optional num)
 "Automatically renumber the tests from the current location in
 the active buffer. Optional argument sets the current test
 number (instead of 1).  This function automatically updates
 all test numbers from the current location until the end of
 the buffer without querying the user for each test."

  (interactive "NStarting test number: ")
  (save-excursion
  (setq num (or num 1 ))
  (while (re-search-forward ", +T0[0-9]+" nil t )
    (replace-match
      (concat ", T" (format "%03d" num )))
    (setq num (+ 1 num))
    )
  )
)

但是,我也非常希望有这个函数的交互式版本,使用 perform-replace 交互式地查询用户的每个测试。当然,我可以简单地在我的代码中手动处理查询行为,但是,鉴于此功能已经存在,我真的不想重新实现它。此外,我想确保此命令与其他内置查询替换函数具有相同的接口。

我最近失败的尝试如下:

(defun renumber-tests(&optional num)
  (interactive "NStarting test number: ")
  (save-excursion
    (setq num (or num 1 ))
    (perform-replace ", +T0[0-9]+"
                 (concat ", T" (format "%03d" (+ 1 num )
                                   ))
                 t t nil)
  )
)

但是,这不会在每次运行时更新 num 的值(我也尝试过 (setq num (+ 1 num) )并得到相同的结果。

我非常感谢那些在 elisp 方面更有经验的人的帮助 - 如果有任何方法可以使它按我的意图工作。

【问题讨论】:

    标签: replace emacs


    【解决方案1】:

    您正在调用perform-replace,并带有string作为替换文本。您必须提供替换功能才能进行动态替换。引用文档:

    REPLACEMENTS 是字符串、字符串列表或 cons 单元格 包含一个函数及其第一个参数。该函数被调用 像这样生成每个替换:(funcall(汽车替换) (cdr replacements) replace-count) 它必须返回一个字符串。

    这样你也可以摆脱突变:

    (defun renumber-tests(&optional num)
      (interactive "NStarting test number: ")
      (save-excursion
        (perform-replace ", +T0[0-9]+"
                 (list (lambda (replacement replace-count)
                     (concat ", T" (format "%03d" (+ replace-count (or num 1))))))
                 t t nil)))
    

    【讨论】:

    • 谢谢。我知道它需要某种 lambda 函数,但我完全不知道如何使用 lisp 来做到这一点。我已经在 C++ 中工作了多年,但直到现在才开始随意涉足 lisp...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    相关资源
    最近更新 更多