(or emacs irrelevant)

occur-dwim (Do What I Mean)

I'd like to share a little snippet that I like to use instead of a plain M-s o (occur).


(defun occur-dwim ()
  "Call `occur' with a sane default."
  (push (if (region-active-p)
          (let ((sym (thing-at-point 'symbol)))
            (when (stringp sym)
              (regexp-quote sym))))
  (call-interactively 'occur))

It will offer as the default candidate:

  • the current region, if it's active
  • the current symbol, otherwise

It's pretty good, since I actually want the default candidate in 95% of the cases. Some other functions, such as rgrep are smart like this out-of-the-box.

A Hydra that goes nicely with occur

Since occur, like some other functions (grep, rgrep, compile), works with next-error, it's possible to use this Hydra to navigate the occur matches:

(hydra-create "M-g"
  '(("h" first-error "first")
    ("j" next-error "next")
    ("k" previous-error "prev")))

Hydra was introduced in an earlier post, and is available in GNU ELPA.

What goes around comes around

I usually do a quick internet search to see where I got the code that I'm posting here, reason being that it's nice to list the source, as well as there could be more advanced stuff out there on the same topic.

I saw a few results for "occur-dwim" so I thought that I just copy-pasted it from somewhere. Slight disappointment turned into a small sense of pride, when I found that the source of the copy-pastes was my old Stack Overflow answer:)