How do I jump to the local definition of a variable in Vim?
Answer
gd
Explanation
The gd command jumps to the local definition of the word under the cursor. It searches backward from the current position to find the first occurrence of the identifier within the current function or block, making it a quick way to find where a variable was declared.
How it works
gdstands for "go to definition" (local)- Vim searches backward from the cursor position for the first occurrence of the word under the cursor
- The search starts from the beginning of the current function or block scope
- The cursor jumps to that first occurrence, which is typically the declaration
Example
Given the code with the cursor on result in the return statement:
function calculate(x) {
const result = x * 2;
console.log(result);
return result;
}
Pressing gd jumps the cursor to the result on the const result = x * 2; line — the first occurrence in the local scope.
Tips
- Use
gD(uppercase) to go to the global definition — it searches from the top of the file instead of the current scope - Use
<C-o>to jump back to where you were after inspecting the definition - Use
*to search for all occurrences of the word under the cursor instead - For language-aware "go to definition" (across files, respecting imports), you will need an LSP plugin
gdworks purely on text matching — it does not understand language semantics, but it is fast and works without any plugins