Emacs source code navigation

Recently I have been spending a lot of time with a large amount of unfamiliar C code. Navigating a code base that is unfamiliar can be quite a challenge so I went on a search for useful Emacs features to make it easier.

The most useful tool I have found is etags. With etags you can quickly jump to the source file where a function is defined. If the source file is not already open in a buffer Emacs will open it for you. First you need to generate a TAGS file. To create a TAGS file run

find . -name '*.[ch]' | xargs etags

in the top directory of the source tree. Now start Emacs. M-x visit-tags-table will prompt you for the location of the tags file. Emacs now knows the name and location of all function definitions in the source tree. To jump to a function use M-. (that’s Meta-Period) and type the name of the function. If you simply press enter Emacs will jump to the function declaration that matches the word under the cursor. Very nice. As useful as this feature is it would still be very annoying if you couldn’t easily move back to where you jumped from. To jump backwards use M-*.

The etags system also gives you the ability to do auto-completion on function names that are in the TAGS file. Here is the necessary .emacs LISP code to bind this functionality to CTRL-Tab.

(add-hook 'c-mode-common-hook
        (lambda ()
                (define-key c-mode-map [(ctrl tab)] 'complete-tag)))

If you are a fan of long descriptive function names this is a very nice feature.

Finally, if you want to use etags with your own source tree you can add a Makefile target like this:

etags:
        find . -name '*.[ch]' | xargs etags

6 thoughts on “Emacs source code navigation”

  1. Can’t believe there are no comments — either you’ve only published for my benefit or I’m the last guy in the world to learn this *MOST* valuable trick/tool!

    Thanks so much — learning lisp and emacs at the same time as a ‘hobby’ — used to be a good C programmer but am suffering from brain rot programming in dBase and MS-Access ;-(

    Bob.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>