简体   繁体   中英

How do I “M-x replace-string” across all buffers in emacs?

如何跨emacs中的所有缓冲区“Mx replace-string”?

Mx ibuffer RET t U

But you'll probably want to be a bit more restrictive than that, because it will abort if it can't do a replacement -- eg encounters a read-only dired buffer containing a matching filename.

Ch m within ibuffer to read the mode help, and learn how to easily mark just the buffers you're interested in.

Edit: a non-regexp version of ibuffer-do-replace-regexp can easily be written by modifying the original definition:

;; defines ibuffer-do-replace-string
(define-ibuffer-op replace-string (from-str to-str)
  "Perform a `replace-string' in marked buffers."
  (:interactive
   (let* ((from-str (read-from-minibuffer "Replace string: "))
          (to-str (read-from-minibuffer (concat "Replace " from-str
                                                " with: "))))
     (list from-str to-str))
   :opstring "replaced in"
   :complex t
   :modifier-p :maybe)
  (save-window-excursion
    (switch-to-buffer buf)
    (save-excursion
      (goto-char (point-min))
      (let ((case-fold-search ibuffer-case-fold-search))
        (while (search-forward from-str nil t)
          (replace-match to-str nil t))))
    t))

There are a bunch of different choices, it kind of depends on how you want to do it.

Check out the Emacs Wiki for SearchBuffers . Of interest would be moccur-edit and icicles.

Thanks to Trey for mentioning Icicles buffer searching in this regard.

Let me mention also Q ( dired-do-query-replace ) in Dired. Very handy. And be aware that you can easily mark sets of files in Dired using keys such as these (and there are more):

  • % m ( dired-mark-files-regexp ) -- mark files whose names match a regexp
  • % g ( dired-mark-files-containing-regexp ) -- mark files whose text (content) matches a regexp
  • * . ( dired-mark-extension ) -- mark files whose names have the same extension (eg, .el )

Be sure to load standard library dired-x.el (and perhaps dired-aux.el ).

I found this on a website some long time ago, sorry I don't remember the source. If you find a read-only buffer, it will stop, so be careful.

Just place this in your .emacs

(defun query-replace-in-open-buffers (arg1 arg2)
  "query-replace in open files"
  (interactive "sQuery Replace in open Buffers: \nsquery with: ")
  (mapcar
   (lambda (x)
     (find-file x)
     (save-excursion
       (beginning-of-buffer)
       (query-replace arg1 arg2)))
   (delq
    nil
    (mapcar
     (lambda (x)
       (buffer-file-name x))
     (buffer-list)))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM