-1

如何编写一个函数,只要找到一个变量,它就会返回 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。

4

2 回答 2

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))
于 2012-11-06T13:38:07.433 回答
1

弗朗切斯科的帮助下

(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”。

于 2012-11-06T14:14:21.497 回答