Two hooks for Emacs Occur

Occur is the best search function in Emacs. It

  • Lists search results from the entire buffer (not just from the cursor forward or from the cursor backward)
  • Lists the results in a separate buffer (so you are not unnecessarily moving away from your current location in the original buffer to find a wanted search result)
  • Provides line numbers for matched results

Additional functions of occur include easy walking through the results with n and p keys in the *Occur* buffer, which displays the relevant location of the original buffer in the other window. A somewhat esoteric use case of occur is recursivity, i.e. performing another occur on the *Occur* buffer.

By default, the *Occur* buffer is just one popup that does not gain automatic focus. Also, it is reused when performing a new occur, losing the previous contents.

When you have lots of searches to perform and you need to keep track of their entire bunch, it is better to have all old and new search buffers separately available. For this, there is occur-rename-buffer whose documentation says that it is meant to be hooked as follows:


(add-hook 'occur-hook 'occur-rename-buffer)

From then on, every time you occur, the popup buffer with search results is no longer named *Occur* but *Occur: <buffer name where you performed occur>*. When you perform multiple searches in different buffers, all the results are in new buffers and you can keep track of them based on the buffer name.

Another thing — more often than not it is desirable to have automatic focus on the *Occur* buffer as soon as it pops up. Therefore:

(add-hook 'occur-hook (lambda () (other-window 1)))

Leave a Reply

Your email address will not be published. Required fields are marked *