Posts Tagged ‘imenu’

Imenu

Thursday, July 16th, 2009

Imenu is a built-in emacs package for navigating around source files. It is a feature that allows you to jump around by scanning on predefined regex’s - mostly to variable of function declarations. Imenu is very useful for quickly navigating around a source file - I recommend you start using it whenever you need to navigate to a different function in the same file. The default for imenu is to use emac’s built in completion for variables; however, I much prefer using ido’s completion, and for that you need the following commands and function in your initialization file:

(require 'imenu)

This just allows you to use the imenu commands.

(defun ido-goto-symbol ()
  "Will update the imenu index and then use ido to select a symbol to navigate to"
  (interactive)
  (imenu--make-index-alist)
  (let ((name-and-pos '())
	(symbol-names '()))
    (flet ((addsymbols (symbol-list)
		       (when (listp symbol-list)
			 (dolist (symbol symbol-list)
			   (let ((name nil) (position nil))
			     (cond
			      ((and (listp symbol) (imenu--subalist-p symbol))
			       (addsymbols symbol))
			      ((listp symbol)
			       (setq name (car symbol))
			       (setq position (cdr symbol)))
			      ((stringp symbol)
			       (setq name symbol)
			       (setq position (get-text-property 1 'org-imenu-marker symbol))))
			     (unless (or (null position) (null name))
			       (add-to-list 'symbol-names name)
			       (add-to-list 'name-and-pos (cons name position))))))))
      (addsymbols imenu--index-alist))
    (let* ((selected-symbol (ido-completing-read "Symbol? " symbol-names))
	   (position (cdr (assoc selected-symbol name-and-pos))))
      (if (markerp position)
	  (goto-char position) (goto-char (overlay-start position))))))

This is the function that uses ido for imenu. Since imenu occasionally has multiple levels - you select whether you want functions or variables, etc - this loops through all those sublists and adds all possibilities to a list. Once the list is compiled, it prompts you using ido for which definition you want to go to.

(setq imenu-auto-rescan t)

This just ensures that whenever you call imenu or the new function ido-goto-symbol you get the latest information, and not only functions which may have been cached.

(global-set-key (kbd "M-s") 'ido-goto-symbol)

I use this function quite frequently, so I rebound it to M-s. M-s is usually a prefix key for a few commands, but the only one I use that this interferes with is occur, but I use that rarely enough that I’m fine with just having to M-x occur. I use ido-goto-symbol enough that I really want it to be as few key presses as possible, so using something like M-s M-s would be pretty irritating.