Last Updated: February 25, 2016
·
1.148K
· jmitchell

Search all open Emacs buffers

Suppose you get some error message from your program or are looking at a previous VCS commit. You want to edit the source file responsible, and you're even fairly sure it's already open in one of your many Emacs buffers. Or maybe you want to find all the 'TODO' or 'FIXME' comments littered in your open buffers. How do you quickly find the buffer you want?

Thanks to offby1 this is really easy!

;; I know that string is in my Emacs somewhere!

(defcustom search-all-buffers-ignored-files (list (rx-to-string '(and bos (or ".bash_history" "TAGS") eos)))
  "Files to ignore when searching buffers via \\[search-all-buffers]."
  :type 'editable-list)

(require 'grep)
(defun search-all-buffers (regexp prefix)
  "Searches file-visiting buffers for occurence of REGEXP.  With
prefix > 1 (i.e., if you type C-u \\[search-all-buffers]),
searches all buffers."
  (interactive (list (grep-read-regexp)
                     current-prefix-arg))
  (message "Regexp is %s; prefix is %s" regexp prefix)
  (multi-occur
   (if (member prefix '(4 (4)))
       (buffer-list)
     (remove-if
      (lambda (b) (some (lambda (rx) (string-match rx  (file-name-nondirectory (buffer-file-name b)))) search-all-buffers-ignored-files))
      (remove-if-not 'buffer-file-name (buffer-list))))

   regexp))

(global-set-key [f7] 'search-all-buffers)

(source)