Setup Ultisnips for vim

I’ve been using vim as a handy tool to write small Java programs to verify my new findings. I need to type some trivial functions frequently, which is very quick in Intellij Idea with live templates but not in Vim. The Ultisnips plugin comes to the rescue.

The plugin offers the same functionality as live templates. You can define a snippet keyword and use a trigger(default is tab) to auto expand the whole snippet. Here is a quick installation and snippets configuration guide. I record it here as I found the readme of the GitHub project hard to get started with.

Install on mac

1. Install python3 support vim. This is a required step otherwise you will get a lot of python3 errors later. The default vim on macOS is compiled by Apple which has no python3 support. It can be verified by vim --version command.  Use brew to install the vim.

brew install vim

After brew install, open a new shell window to verify the vim. It should be brew-compiled now.

2. Install Ultisnips plugin.  I’m using vim-plug to manage vim plugin. You can find the plug install guide for different plugin managers on the vimawesome website.

Add Plug 'sirver/ultisnips' to the plug config part of .vimrc. And then run the following in Vim:
:source %
:PlugInstall

Setup snippets

By default, all snippets should be put into the folder ultisnips under vim runtime path. Run :set runtimepath in Vim shows the total paths. I put the folder under ~/.vim. And all snippet files should end up with.snippets.  For example, the file should be named java.snippets or put under folder java for java snippets.

Setup let g:UltiSnipsSnippetDirectories=["custom-folder"] in .vimrc to customize the snippet folder name. A sample snippet below is for your quick start reference.

snippet sout "system out"
System.out.println($1)
endsnippet

snippet main "main func"
public static void main(String ...args) {
	$1
}
endsnippet

As to the readme, you can go to the vim-snippets repo to get the collected snippets for most programming languages. But you may want to write your own snippets as people’s habits differ. And everyone should add the snippets.snippets file as a start coz you can expand usnip when writing a new snippet.

For full features, you can read the “Authoring snippets” part of the plugin help file.