Wikia

Vim Tips Wiki

Changes: Jumps to a local/global definition by same key

Edit

Back to page

(refactoring)
(refactoring)
 
Line 25: Line 25:
 
normal! gd
 
normal! gd
 
if getpos('.') == l:pos
 
if getpos('.') == l:pos
execute "tag" expand('<cword>')
+
execute 'tag' expand('<cword>')
 
endif
 
endif
 
endfunction
 
endfunction

Latest revision as of 01:16, August 3, 2012

Tip 1455 Printable Monobook Previous Next

created 2007 · complexity basic · author Shotaro Aoyama · version n/a


When you want to jump to a definition of a variable, what do you do? Use C-] or gd?

C-] finds only global variables (and functions; ctags extracts only global objects).

On the other hand, gd detects only local variables.

I think it's a bit complicated to choose between them. So I wrote this function:

function! GoDefinition()
  let l:pos = getpos('.')
  normal! gd
  if getpos('.') == l:pos
    execute 'tag' expand('<cword>')
  endif
endfunction
nnoremap <C-]> :<C-U>call GoDefinition()<CR>

This function first does gd to try to find a local definition of a variable under the cursor, and if it failed then probably the variable is a global variable, so it tries :tag.

This way, you can jump to the definition of both local and global variables with the same key.

CommentsEdit

Around Wikia's network

Random Wiki