Santiago Lizardo - Technology entrepreneur

Vim: Jump to classes and functions defined in different files

Date Tue Jul 05 20:13:57 UTC 2011

I use Vim everyday. No matter what file format I'm opening (as long as it is a text file) Vim recognises it and help me with its edition. The shortcuts save me lot of time and impress my colleagues :)

But sometimes shortcuts are not enough. If you look at other people using robusts IDE such as Eclipse or Netbeans you feel like you are missing something: The ability to jump from one file to another using parent classes, overrided methods and global variables.

Fortunately for me, an smart guy invented something called exuberant tags. What it does is to create an index with all the tags (keywords such as method names, class names, variables, interfaces and so on) that later on you can use in Vim to automagically move between files in seconds. (and I'm talking I've tested it with a huge project of thousand of files!).

Enough theory, let's start practicing. What you need to start using ctags is install it (of course). Do so issuing your favourite apt-get command or (if you are an old-school linux user) compiling it by yourself.

Let's see how to do it the old way:

wget http://prdownloads.sourceforge.net/ctags/ctags-5.8.tar.gz

tar xvfz ctags-5.8.tar.gz

cd ctags-5.8/

./configure --prefix=/home/slizardo/apps/ctags

make && make install

Done! Don't forget to add the bin folder to the PATH environment variable. ( export PATH=$PATH:/home/slizardo/apps/ctags/bin )

The first part is completed. Now it's turn to create the keywords ("tags") database, taken from our source repository.

ctags -f ~/project_tags \
  -h ".php" -R \
  --exclude="\.svn" \
  --totals=yes \
  --tag-relative=yes \
  --language-force=PHP \
  --PHP-kinds=+cfiv \
  --regex-PHP='/abstract\s+class\s+([^ ]+)/\1/c/' \
  --regex-PHP='/interface\s+([^ ]+)/\1/i/' \
  --regex-PHP='/(public|static|abstract|protected|private)+\s+function\s+([^ (]+)/\2/f/' \
  --regex-PHP='/\$([a-zA-Z_][a-zA-Z0-9_]*)/\1/v/' \
  Projects/openquestions/webapp

The previous command tells among other things:

  • Exclude SVN repositories
  • Treat the code as PHP syntax
  • Index classes, functions (and methods), interfaces and variables using the given regular expressions
  • Traverse the directory Projects/openquestions/webapp to find the source code

Last step, and the most exciting. Open your Vim, execute the command :set tags=~/project_tags place the cursor over a keyword and press CTRL+]... voilà! You have jumped from file A to file B without notice it! You want to go to the previous file? No prob, press CTRL+T and you're back.

Happy Viming!

Keywords: php,python,vim,editor,jump,navigate,ide

comments powered by Disqus