Working With Matching Lines In Emacs

This is another note to myself. For some reason I have a hard time remembering the handful of commands that do things to the lines in a buffer that match a regular expression. The table below are the ones that I know about but have a hard time remembering. If you have any similar commands that you find useful, leave a comment.

Command Alias Action
keep-lines delete-non-matching-lines Delete lines not matching regexp
flush-lines delete-matching-lines Delete lines matching regexp
how-many count-matches Count lines matching regexp
occur list-matching-lines Show lines matching regexp in another buffer
highlight-lines-matching-regexp hi-lock-line-face-buffer Highlight lines matching regexp

Update Phil reminds me of highlight-lines-matching-regexp, which I meant to include but forgot. (See what I mean?) He also mentions multi-occur (just like occur but it acts on multiple buffers) and multi-occur-in-matching-buffers (like multi-occur but you specify the buffers with a regexp), which he says he finds particularly useful.

This entry was posted in General and tagged . Bookmark the permalink.
  • Phil

    As well as `occur', there's also `multi-occur' and `multi-occur-in-matching-buffers' (I find the latter particularly useful).

    For highlighting, `highlight-lines-matching-regexp' is an alias for `hi-lock-line-face-buffer' in `hi-lock.el'.

    • jcs

      Yup. I meant to list highlight-lines-matching-regexp but forgot about it (as usual). I've updated the post with it and also mentioned the two multi-occur commands you mentioned. Thanks for the info.

  • Okay this is probably tangential to your post but I am kind of new to emacs, and something that has always bothered me is the regex.
    Is there something that lets one use perl regex in emacs?

  • for me, i learned list-matching-lines and other alias before i learned their original function name. So, i find it easy to remember. Basically, they all just contain "matching" or "matching-line".

    multi-occur and multi-occur-in-matching-buffers are new to me. Thanks Phil and jcs for bringing this up.

    • Phil

      The multi-occur functions are even more powerful in conjunction with the new occur-edit mode in Emacs 24.

      My most common use for them is simply to search ALL open buffers; I have a custom function + binding to supply the regexp automatically to multi-occur-in-matching-buffers. The regex excludes TAGS files, but of course that's ugly, so I was meaning to convert it to use multi-occur instead with a buffer list argument, so that I can do a positive match against the buffer list for TAGS (and anything else sensible), filter those buffers out of the list, and use the remainder as the argument.

  • Win Treese

    Note that `how-many' (aka `count-matches') counts matches, not lines. This matters if there is more than one match in a line.