Saturday, November 3, 2012

Emacs: Search for Symbol at Point

One thing I regularly do is to try and look for other occurrences of the symbol at point in my buffer. This can serve as a poor man’s way of finding the definition or callers of a function, or uses of a variable. It’s kind of annoying to do that in Emacs by default, sadly. The following code from my .emacs will enable the key shortcut C-d in isearch to yank the symbol at point into the search string. So C-s C-d will then start a search for that symbol, and already highlight it. Keep hitting C-s to move to further occurrences.

(define-key isearch-mode-map (kbd "C-d")
  'fc/isearch-yank-symbol)
(defun fc/isearch-yank-symbol ()
  "Yank the symbol at point into the isearch minibuffer.

C-w does something similar in isearch, but it only looks for
the rest of the word. I want to look for the whole string. And
symbol, not word, as I need this for programming the most."
  (interactive)
  (isearch-yank-string
   (save-excursion
     (when (and (not isearch-forward)
                isearch-other-end)
       (goto-char isearch-other-end))
     (thing-at-point 'symbol))))