How do I jump to the global definition of a variable or function in Vim?
Answer
gD
Explanation
How it works
Vim provides two built-in commands for jumping to where an identifier is defined, without needing tags or an LSP:
- gd (lowercase) searches backward from the current position to the beginning of the current function for the first occurrence of the word under the cursor. This finds the local definition.
- gD (uppercase) searches backward from the current position to the beginning of the file. This finds the global definition, which is typically where a module-level variable, import, or top-level function is first introduced.
The gD command is useful for quickly navigating to where a constant, global variable, or function is first defined at the top of the file, especially in languages like C, Python, or JavaScript where global definitions appear near the top.
Example
Consider this Python file:
MAX_RETRIES = 3 # line 1 (global definition)
def process():
retries = 0 # line 4 (local definition)
while retries < MAX_RETRIES: # line 5 (cursor here)
retries += 1
With the cursor on MAX_RETRIES at line 5:
- Press
gDto jump to line 1 whereMAX_RETRIESis globally defined. - Press
gdto find the local occurrence (which in this case may also go to line 1 since there is no local definition ofMAX_RETRIES).
With the cursor on retries at line 5:
- Press
gdto jump to line 4 whereretriesis locally defined. - Press
gDto also jump to line 4, since line 4 is the first occurrence in the file.
Limitations
- These commands use simple text searching, not actual language parsing. They look for the first occurrence of the word.
- For true semantic navigation, use ctags with
Ctrl-]or an LSP client likevim.lspin Neovim. - Despite these limitations,
gdandgDare very useful for quick navigation in vanilla Vim.