Emacs Mx 查询替换环绕文档?

Emacs Mx 查询替换环绕文档?

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

有没有办法:

  • 到达文档末尾后循环回到文档开头?

  • 在命令执行过程中反转搜索和替换的方向。

答案1

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)

答案2

我在 Emacs 24+ 上使用了以下命令:

;; query replace all from buffer start
(fset 'my-query-replace-all 'query-replace)
(advice-add 'my-query-replace-all
            :around
            #'(lambda(oldfun &rest args)
               "Query replace the whole buffer."
               ;; set start pos
               (unless (nth 3 args)
                 (setf (nth 3 args)
                       (if (use-region-p)
                           (region-beginning)
                         (point-min))))
               (unless (nth 4 args)
                 (setf (nth 4 args)
                       (if (use-region-p)
                           (region-end)
                         (point-max))))
               (apply oldfun args)))
(global-set-key "\C-cr" 'my-query-replace-all)

考虑区域替换情况,以及传递的任何 START 和 END 参数。

相关内容