Utlisnips configuration and crash-course

Utlisnips is an amazing snippet-completion engine for Vim. In this article, I go over a simple set up that I use personally.

Making custom snippets available to UltiSnips

If you intend to create custom snippets (which you will!), first create a directory named UltiSnips somewhere in your .vim folder. Note that S is capital in UltiSnips, to avoid frustration of things not working.

      mkdir $HOME/.vim/my-snippets/UltiSnips

You will be adding all your custom snippet files to this folder. So, snippets for the filetype myext go into $HOME/.vim/my-snippets/UltiSnips/myext.snippets. I have previously written on steps to [let vim auto-detect filetypes for custom file-extensions](associate-filetype-with-file-extension-in-vim].

To make these custom snippet files discoverable, add the my-snippets directory to your runtimepath. The way UltiSnips works is by searching through all directories named UltiSnips (ahem) in the runtimepath.

      set runtimepath+=~/.vim/my-snippets

Example of custom UltiSnips snippet

Here's an example UltiSnips snippet that can go inside your snippets file.

      snippet for "for loop" b
      for ${1:item} in ${2:items}:

It is self-explanatory. All variables that you wish to fill are marked with their indices. When you type for and hit the TAB key, it expands into the given boilerplate and jumps to the placeholder marked 1:item. You enter the desired text and hit Ctrl+j to move to the next placeholder.

Now, when you have plenty of snippets, it is difficult to remember all of them. So, when you are editing a file, it is useful if UltiSnips can present to you the list of available snippets. To do this, just set the following key-mapping in your $HOME/.vimrc

Listing available UltiSnips snippets

      let g:UltiSnipsListSnippets="<esc>[Z" " this is Shift+Tab .. It is written like this based on hitting Shift+Tab in cat. You can choose some other key-combo

Now, for me, hitting Shift+Tab will present the list of all available snippets that are relevant to the file being edited. Neat!