rollschild
rollschild

Reputation: 145

Vim: how to jump to definition in a split window

I would like to define a command, gv, which jumps to definition in a split window. I'm aware that gd is the command to jump to definition but in the existing window.

I tried this mapping:

nnoremap <silent> gv :vsplit<CR>gd

But it didn't work. It opened up the exactly same file in a split window, without actually jumping to definition. Seems like the gd command after <CR> was ignored. How do I fix this?

I saw some answers mentioning <C-]> but is there away to implement this without generating tags?

Hopefully this makes sense. Thanks in advance!

Upvotes: 5

Views: 6386

Answers (2)

r_31415
r_31415

Reputation: 8972

You don't actually need to define a new mapping/command for this. If you press CTRL-W d (or type :dsp <word>), it will show you the definition in a new window. From the documentation:

CTRL-W CTRL-D                   *CTRL-W_CTRL-D* *CTRL-W_d*
CTRL-W d        Open a new window, with the cursor on the first
            macro definition line that contains the keyword
            under the cursor.  The search starts from the
            beginning of the file.  If a count is given, the
            count'th matching line is jumped to.

However, if you really want to press gv and have the definition shown, an alternative to romainl's solution is the following:

nnoremap gv :vertical dsplit <C-R><C-w><cr>

Upvotes: 0

romainl
romainl

Reputation: 196476

:help gd jumps to the local definition of the word under the cursor. That "local definition" is always in the same buffer no matter what so I hope you don't expect it to jump to some other buffer.

Your mapping:

nnoremap <silent> gv :vsplit<CR>gd

works as expected, here: the window is split and the cursor jumps to the local definition of the word under the cursor:

gd

First jump is with gd, second jump is with your gv.


If you want a "jump to definition" that works across files, gd and gD are not what you want. See :help ctags, :help cscope and :help include-search. Note that those features are not particularly smart. If you want something that understands your code better than you do, look elsewhere.

Upvotes: 7

Related Questions