在当前缓冲区执行(re-search-forward str)
后,有时候希望有一种简便的方法返回到先前的缓冲区位置。此行为类似于缓冲区更改的(undo)
操作。 所以如果我连续进行两次向前搜索,首先从位置A到B,然后从B到C,我希望按下一个键可以后退一步(从C到B),再次按下这个键将使我回到A..
re-search-forward
(如果你使用它,即使它是一个命令,你也应该使用它),那么不要设置标记以便能够返回到起始点。(point)
)保存为变量beg
,然后使用goto-char beg
。(elisp)The Mark
一节中的这个段落。 Novice Emacs Lisp programmers often try to use the mark for the
wrong purposes. The mark saves a location for the user's
convenience. An editing command should not alter the mark unless
altering the mark is part of the user-level functionality of the
command. (And, in that case, this effect should be documented.)
To remember a location for internal use in the Lisp program, store
it in a Lisp variable. For example:
(let ((beg (point)))
(forward-line 1)
(delete-region beg (point))).
使用这个
(global-set-key
(kbd "M-p")
(lambda()(interactive) (set-mark-command 4)))
isearch-forward-regexp
,而不适用于普通的re-search-forward
(后者不会设置标记)。
但是在elisp中没有问题-只需在re-search-forward
之前调用push-mark
即可。set-mark-command
函数的参数有什么作用?(也就是说:数字 4
) - Håkon Hæglandshow-marks
模式(http://www.emacswiki.org/emacs/show-marks.el)。也许这可以用于我的目的? - Håkon Hægland4
是一个特殊值(不一定是针对这个函数,但是在一般情况下是特殊的)。当使用C-u
(一次,没有明确的数字)时,它会传递原始值(4)
,当作为数值前缀参数解释时,它只是4
。请参见C-h i g
(elisp) Prefix Command Arguments
。在代码中看到传递4
或'(4)
以触发函数的前缀参数行为并不罕见。 - philsC-u C-SPC
(或 C-u C-@
)已经足够满足你的需求了。这与被接受的答案是一样的,但使用了现有的绑定。 - phils(defun my-search-fun (str)
(interactive)
(push-mark)
(beginning-of-buffer)
(re-search-forward str))
(defun my-undo-search ()
(interactive)
(pop-mark)
(goto-char (mark))
C-s
和C-r
绑定到isearch-forward-regexp
和isearch-backward-regexp
,因此前后移动只需要按下正确的键组合。不按RET
,即不退出搜索模式,C-g
将取消搜索并返回到搜索起始位置。如果我在找到其中一个匹配模式时按下了RET
,那么C-U SPC
也会将我带回到开始搜索的位置。 - nymo