tags:

views:

84

answers:

3

In Emacs how can I easily copy all lines matching a particular regex? Preferably highlighting the matching lines as I type.

occur gets partway there by coping them into a buffer, but it adds lots of extra stuff.

+5  A: 

How about this:

(defun copy-lines-matching-re (re)
  "find all lines matching the regexp RE in the current buffer
putting the matching lines in a buffer named *matching*"
  (interactive "sRegexp to match: ")
  (let ((result-buffer (get-buffer-create "*matching*")))
    (with-current-buffer result-buffer 
      (erase-buffer))
    (save-match-data 
      (save-excursion
        (goto-char (point-min))
        (while (re-search-forward re nil t)
          (princ (buffer-substring-no-properties (line-beginning-position) 
                                                 (line-beginning-position 2))
                 result-buffer))))
    (pop-to-buffer result-buffer)))
Trey Jackson
How do you do this so quickly? It's also a completely different solution to the one I was expecting. I was assuming it would use occur mode. Thanks.
Singletoned
Um... it's a common type of thing to do. There's really only 3 things going on here. 1) make a buffer, 2) search current buffer, 3) insert search result in the new buffer...
Trey Jackson
+1  A: 

I've been using this happily for a long time:

    (defun occur-mode-clean-buffer ()
  "Removes all commentary from the *Occur* buffer, leaving the
unadorned lines."
  (interactive)
  (if (get-buffer "*Occur*")
      (save-excursion
        (set-buffer (get-buffer "*Occur*"))
        (fundamental-mode)
        (goto-char (point-min))
        (toggle-read-only 0)
        (set-text-properties (point-min) (point-max) nil)
        (if (looking-at (rx bol (one-or-more digit)
                            (or " lines matching \""
                                " matches for \"")))
            (kill-line 1))
        (while (re-search-forward (rx bol
                                      (zero-or-more blank)
                                      (one-or-more digit)
                                      ":")
                                  (point-max)
                                  t)
          (replace-match "")
          (forward-line 1)))

    (message "There is no buffer named \"*Occur*\".")))

(define-key occur-mode-map (kbd "C-c C-x") 'occur-mode-clean-buffer)
offby1
+3  A: 

You can use keep-lines to get what you want, copy them, and then undo. For the opposite, there is also flush-lines to get rid of lines you don't want.

scottfrazer