vimtricks.wiki Concise Vim tricks, one at a time.

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:

  1. Press gD to jump to line 1 where MAX_RETRIES is globally defined.
  2. Press gd to find the local occurrence (which in this case may also go to line 1 since there is no local definition of MAX_RETRIES).

With the cursor on retries at line 5:

  1. Press gd to jump to line 4 where retries is locally defined.
  2. Press gD to 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 like vim.lsp in Neovim.
  • Despite these limitations, gd and gD are very useful for quick navigation in vanilla Vim.

Next

How do you yank a single word into a named register?