Vim Recipes Navigation Navigating Source Code

Navigating Source Code

Problem

You're editing the source code for a computer program, and want to navigate it efficiently.

Solution

The commands below allow movement around source code in the context of typical constructs. For instance, % finds the end of the if/elsif/else block, or a comment, your cursor is over, and moves you to the end of it.

Key Move To
% End of construct A construct is a bracket pair, an if/elsif/else block, or a comment. For example, if you hit % on an opening bracket you'd jump to the corresponding closing bracket. See :help % for more details.
[[ Backwards to the beginning of the current function.
][ Forwards to the beginning of the current function.
]} Beginning of the current block.
[{ End of the current block.
}[ Beginning of the current comment block.
}] End of the current comment block.
gd First usage of the current variable name Occurrences in comments are ignored.. (Mnemonic: go to definition).
gD Go to the first global gd looks for the definition closest to your current position, thus respecting the lexical scoping rules of many languages. gD starts searching from the first line of the file, so prefers variables with a global scope. usage of the current variable name.

Discussion

The shortcuts available for text files are supported for source code, too, so review them if you haven't already.

There's a lot to remember here. Despite my best efforts, I suspect that the descriptions above are still confusing. To understand these shortcuts you really need to try them yourself. Open some source code written in your favourite language with Vim, make sure that syntax highlighting is on (:syntax on), and bounce back and forth between those braces.