Emacs

Emacs Mx 查詢替換環繞文件?

  • December 5, 2016

我經常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

有沒有辦法:

  • 在我們打到文件的結尾之後循環回到文件的開頭?
  • 在命令執行的中間反轉搜尋和替換的方向。

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)

評估此程式碼後,您可以使用 呼叫包裝的搜尋M-x my-query-replace,或將其綁定到您方便的東西:

(global-set-key "\C-cq" 'my-query-replace)

引用自:https://unix.stackexchange.com/questions/48289