How do I navigate through code using tags and the tag stack?
Answer
<C-]> / <C-t>
Explanation
The <C-]> command jumps to the definition of the keyword under the cursor using a tags file, and <C-t> jumps back. Vim maintains a tag stack that works like a browser history, letting you dive deep into code and unwind back.
Setup
Generate a tags file with Universal Ctags:
ctags -R --languages=python,go,javascript .
This creates a tags file in your project root that Vim reads automatically.
Navigation
<C-]> " Jump to definition of word under cursor
<C-t> " Pop back to where you jumped from
:tag name " Jump to the definition of 'name'
:tselect " If multiple matches, show a selection list
g<C-]> " Like <C-]> but show selection if multiple matches
:tags " Show the tag stack
Example workflow
- Cursor is on
processRequestinmain.go <C-]>— jumps to the definition inhandler.go- Cursor is on
validateInputinside that function <C-]>— jumps to its definition invalidator.go<C-t>— back tohandler.go<C-t>— back tomain.go
Tips
:tnextand:tprevcycle through multiple tag matches- Use
:stag nameto open the tag in a new split - Set
:set tags=./tags;to search upward for the tags file from the current file's directory - In Neovim with LSP,
gdand<C-]>can use the LSP for more accurate navigation - The tag stack is separate from the jumplist —
<C-t>only pops tags, while<C-o>works with all jumps