Reputation: 715
How do I "M-x replace-string" across all buffers in emacs?
Upvotes: 28
Views: 7591
Reputation: 73274
M-x 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 -- e.g. encounters a read-only dired buffer containing a matching filename.
C-hm 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))
Upvotes: 23
Reputation: 201
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)))))
Upvotes: 1
Reputation: 30699
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):
dired-mark-files-regexp
) -- mark files whose names match a regexpdired-mark-files-containing-regexp
) -- mark files whose text (content) matches a regexpdired-mark-extension
) -- mark files whose names have the same extension (e.g., .el
)Be sure to load standard library dired-x.el
(and perhaps dired-aux.el
).
Upvotes: 3
Reputation: 74440
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.
Upvotes: 3