【问题标题】:Isearch return t if found for loop function in Emacs Lisp如果在 Emacs Lisp 中找到循环函数,Isearch 返回 t
【发布时间】:2012-11-06 13:27:39
【问题描述】:

如何编写一个函数,只要找到一个变量,它就会返回 t(为了允许循环):

(setq x 1)
(while ("backward search for regexp "%x" equals true") ;where x is variable
  (setq x (+ x 1))
(insert (concat "%" (int-to-string x)))
)

示例:如果找到 %1 (x=1),它会将 x 加 1。如果找到 %2 (x=2),它会将 x 加 1。 假设在向后搜索中找不到 %3,while 循环停止并插入 "%" + "3" (%3)。

我只是不明白如何在向后搜索中返回 true。

【问题讨论】:

    标签: function loops emacs while-loop


    【解决方案1】:

    search-backward 接受一个可选的第三个参数,当它不是 nil 时,告诉它在搜索不成功的情况下返回 nil:

    (setq x 1)
    (while (search-backward (format "%%%d" x) nil t)
      (setq x (1+ x)))
    (insert (format "%%%d" x))
    

    现在,如果我尝试了解您真正想要做什么(例如在点插入第一个之前没有出现的 %d 字符串),那么您可能希望将搜索包装在 save-excursion 表单中避免移动点:

    (setq x 1)
    (while (save-excursion (search-backward (format "%%%d" x) nil t))
      (setq x (1+ x)))
    (insert (format "%%%d" x))
    

    【讨论】:

    • 除了把1+换成+1,格式部分看不懂? %%%d 在搜索中是否等于“%”?
    • format 将字符串作为其第一个参数。此字符串表示将用于输出以下参数的格式。 %d 格式化数字,%s 格式化字符串,%%% 符号本身。这个构造比(concat "%" (int-to-string x))更简洁一点
    【解决方案2】:

    Francesco的帮助下

    (defun Navi-insert-question ()
      (interactive)
      (setq x 1)
      (while (save-excursion 
      (search-backward (concat comment-start " Question: " (int-to-string x)) nil t))
      (setq x (+ 1 x)))
      (insert (concat comment-start " Question: " (int-to-string x))))
    

    它现在可以在 R 中插入,例如:“# Question: 1”,当它存在于缓冲区上方时,它将插入“# Question: 2”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 2015-04-10
      • 2017-10-21
      • 2018-09-24
      相关资源
      最近更新 更多