I am trying to gather a toolbox of Vim commands/queries, in command or search mode, for navigating a code-base without using Ctags or other external tools. Ctags are great but support can vary depending on the development environment you are stuck on. I would like to just rely on Vim knowledge.
2 Answers
"Include search" is one such tool:
[I and ]I " search current buffer and included files for
" the word under the cursor, skipping comments
:ilist foo " same as above but for 'foo'
:ilist /foo " same as above but for a word containing 'foo'
Related to "include search", "definition search" is interesting, too:
[D and ]D " search current buffer and included files for
" the definition of the symbol under the cursor
:dlist foo " same as above but for definition of 'foo'
:dlist /foo " same as above but for a definition containing 'foo'
:dlist / " list all definitions from the current buffer
" and included files
Both tools depend on a variety of options that may or may not be set by your filetype plugins.
See :help include-search
.
You can also use gd
and gD
as lightweight versions of [D
and ]D
.
See :help gd
.
In the current buffer, the command below will list every function definition and its line number:
:g/func/#
See :help :g
.
:grep
and :vimgrep
are also useful, if only because their result is fed into the quickfix list that can be navigated with :cn
, :cp
… and displayed in the very handy quickfix window.
See :help :grep
, :help :vimgrep
and :help quickfix
.
Speaking of the quickfix list/window, I wrote this function (based on the work of others) to display the results of [I
, ]I
, :ilist
, [D
, ]D
and :dlist
in the quickfix list/window. YMMV of course.
While not strictly a navigation tool, I find the preview window very useful for taking a look at the signature of the function I'm working with.
See :help preview-window
.
That said…
Vim doesn't know anything about your code beyond a few regex patterns that may or may not fit your coding style or whatever. This means that code navigation is better done with the help of external tools like ctags, cscope or GNU GLOBAL.
There are a lot of ways for navigating through code (included in Vim and external), I still discover them. What I use in daily work is:
- Greping text in the project files and navigating via quickfix window (I use silver searcher for greping).
- Using language related plugins, I know there are ones for javascript, ruby, go, that allow to jump between modules of the program (in javascript plugin is
gf
-command Ctrl+O
,Ctrl+I
- jump back or forward in "history" of the navigationg;
- jump onto last edited place in the file- Using marks for placing "bookmarks" on the particular places. You can place mark with
'[some_letter]
command, if letter is capital then you'll get mark which will be reachable from any file (buffer).
gd
. This takes cursor to the local declaration of the variable under cursor.