我经常M-x query-replace
在 Emacs ( M-%
)上使用,我喜欢我可以灵活地在这些选项之间进行选择:
Spacebar Replace text and find the next occurrence
Del Leave text as is and find the next occurrence
. (period) Replace text, then stop looking for occurrences
! (exclamation point) Replace all occurrences without asking
^ (caret) Return the cursor to previously replaced text
Run Code Online (Sandbox Code Playgroud)
有没有办法:
到达文件末尾后循环回到文件的开头?
在命令执行过程中反转查找和替换的方向。
query-replace
是一个非常重要的函数,所以我不愿意在全局范围内改变它。我所做的是将其复制到一个新函数 ,my-query-replace
它最初具有相同的行为。然后,我建议该函数在到达缓冲区末尾后在缓冲区的开头重复查询替换搜索。这可能过于谨慎 - 您可以修改建议以应用于query-replace
而不是my-query-replace
,并在全局范围内启用此行为。
;; copy the original query-replace-function
(fset 'my-query-replace 'query-replace)
;; advise the new version to repeat the search after it
;; finishes at the bottom of the buffer the first time:
(defadvice my-query-replace
(around replace-wrap
(FROM-STRING TO-STRING &optional DELIMITED START END))
"Execute a query-replace, wrapping to the top of the buffer
after you reach the bottom"
(save-excursion
(let ((start (point)))
ad-do-it
(beginning-of-buffer)
(ad-set-args 4 (list (point-min) start))
ad-do-it)))
;; Turn on the advice
(ad-activate 'my-query-replace)
Run Code Online (Sandbox Code Playgroud)
评估此代码后,您可以使用 调用包装的搜索M-x my-query-replace
,或将其绑定到对您来说方便的东西:
(global-set-key "\C-cq" 'my-query-replace)
Run Code Online (Sandbox Code Playgroud)