tags:

views:

2426

answers:

5

How can i jump to to a function definition using VIM? For example with Visual Assist i can type ALT+g under a function and it opens a context menu listing the files with definitions.

How can i do something like this in vim?

+12  A: 

Use ctags. Generate a tags file, and tell vim where it is using the :tags command. Then you can just to the function definition using ctrl-]

There are more tags tricks and tips in this question

Paul Tomblin
Will this work for PHP? I forgot to mention that I need it to work with C,C++,php and python.
Jon Clegg
php is C-like enough that "Exuberant ctags" should work with it. Don't know if it has a python mode.
Paul Tomblin
No love for Cscope?
greyfade
No experience with Cscope. What is is?
Paul Tomblin
+4  A: 

As Paul Tomblin mentioned you have to use ctags. You could also consider using plugins to select appropriate one or to preview the definition of the function under cursor. Without plugins you will have a headache trying to select one of the hundreds overloaded 'doAction' methods as built in ctags support doesn't take in account the context - just a name.

Also you can use cscope and its 'find global symbol' function. But your vim have to be compiled with +cscope support which isn't default one option of build.

If you know that the function is defined in the current file, you can use 'gD' keystrokes in a normal mode to jump to definition of the symbol under cursor.

Here is the most downloaded plugin for navigation
http://www.vim.org/scripts/script.php?script_id=273

Here is one I've written to select context while jump to tag
http://www.vim.org/scripts/script.php?script_id=2507

Mykola Golubyev
+1  A: 

To second Paul's response: yes, ctags (especially exuberant-ctags (http://ctags.sourceforge.net/)) is great. I have also added this to my vimrc, so I can use one tags file for an entire project:

set tags=tags;/
David Wolever
+3  A: 

If everything is contained in one file, there's the command gd (as in 'goto definition'), which will take you to the first occurrence in the file of the word under the cursor, which is often the definition.

Scottie T
+1  A: 

Another common technique is to place the function name in the first column. This allows the definition to be found with a simple search.

int
main(int argc, char *argv[])
{
    ...
}

The above function could then be found with /^main inside the file or with :grep -r '^main' *.c in a directory. As long as code is properly indented the only time the identifier will occur at the beginning of a line is at the function definition.

Of course, if you aren't using ctags from this point on you should be ashamed of yourself! However, I find this coding standard a helpful addition as well.

Judge Maygarden