Ivan Tkalin

I’m a software engineer. I solve problems.

IDE-like "Go to Declaration" in Vim

I always wanted ‘Go to declaration’ feature in Vim with fuzzy-search, like in many modern IDEs. Of course, Vim has a built-in support of tags jumping, but for some programming languages, like Ruby (when you may have dozens of classes named Base), locating and picking the right declaration may be painful. I didn’t find any existing solutions, so I wrote a small plugin for that.

Here is a demo showing how this plugin works for Ruby file, but it’s not limited to Ruby.

Prerequisites

  1. You need to have tags working for your project. Configuring tags generation is out of scope of this article, because it’s language specific. For ruby you can check this guide, but, please, keep in mind that it is outdated, and now I use ripper-tags instead of ctags to generate tags.

    Vim wiki has an article describing how to configure tags in Vim.

  2. You need CtrlP plugin to be installed and working

Installation

  1. Install vim-ctrlp-tjump plugin using your favorite method. I recommend using NeoBundle, Vundle or Pathogen.

  2. Create mappings (optional):

     nnoremap <c-]> :CtrlPtjump<cr>
     vnoremap <c-]> :CtrlPtjumpVisual<cr>
    

    This is not necessary step. You can use commands :CtrlPtjump and :CtrlPtjumpVisual without mappings or create your custom mappings. Personally I find remapping of <c-]> convenient, because it is default Vim’s mapping for :tag command.

Usage

  1. Move cursor to the Class/Method usage in your code

  2. Press c-] (if you have created mapping) or just execute :CtrlPtjump command (or :CtrlPtjumpVisual in visual mode) in the command line. You should see CtrlP window with all definitions of the tag under cursor:

    You can type path/file fragments to narrow down the search using CtrlP’s fuzzy-search.

    Press Enter to open declaration in the same window, Ctrl-T to open declaration in the new Tab. Ctrl-S and Ctrl-V will open declaration in a horizontal or vertical split respectively.

Configuration

Sometimes paths to declarations can be really long, for example for tags for ruby gems. There is an option to display paths in a shortened format:

let g:ctrlp_tjump_shortener = ['/home/.*/gems/', '.../']

If there is only one tag found, it is possible to open it without opening CtrlP window:

let g:ctrlp_tjump_only_silent = 1

Conclusion

Using tags and vim-ctrlp-tjump plugin significantly improved my workflow of working with large Ruby codebases in Vim.

If you have any questions about plugin or suggestions on how to improve this guide, please feel free to comment