• +43 660 1453541
  • contact@germaniumhq.com

Vim Ultimate Editing: UltiSnips


Vim Ultimate Editing: UltiSnips

We continue today our learning about what makes Vim the ultimate editor. To reiterate, we have three reasons that we were analyzing:

First, we looked at the console support. Now, we’re looking at UltiSnips, and in the next article, we shall look at the configuration that can be versioned, and why snippets that are plain text make more sense.

UltiSnips is a plugin, that it’s in my opinion by far the best plugin for any editor. It allows you to create snippets of code that are easily expandable. You want to create a function macro? No problem, write a snippet:

#
# snippet: fun
# w (word boundary),
# m (trim spaces on the right of the script)
# create a function
#
snippet def "create a function" wm
def ${1:function_name}(${2:params}):
	${0:pass}
endsnippet

What’s going to happen is the that whenever I’ll type def<tab> the code from the snippet will be inserted, with the correct indentation, and the cursor will jump to the function_name, then to the params, then last to pass.

Here’s a far more advanced example of it in action straight from the project GitHub’s page:

UltiSnips in action

In this case, we’re using python. What’s amazing is that the snippets are organized by file type. So in your system, there will be a python.snippets file, for your Python snippets, a cpp.snippets file, containing your snippets for C++, a bash.snippets file containing your bash snippets, so on, and so forth. There’s also an all.snippets containing snippets for everything.

Now, if you remember yesterday’s article, Vim supports multiple file types. UltiSnips understands multiple file types.

What that means is that if you have a file with the type django.python3.python, while the syntax coloring is displayed for python, UltiSnips will use the following files to load its snippets:

  • python.snippets

  • python3.snippets

  • django.snippets

  • all.snippets - this is always checked

So what is possible now is having completion enabled depending on the technologies used. And don’t forget, you can just set the filetype as whatever you want.

This also makes UltiSnips a repository of knowledge for the technologies that you’re learning. You don’t remember how to do an if/else in Handlebars? Again, just have a snippet for it:

#
# snippet: ife
# Add an if/else statement
#
snippet ife "Add an if/else statement" wm
{{#if ${1:expression}}}
	${VISUAL}
{{else}}
	${0:}
{{/if}}
endsnippet

Using the same snippet triggers for all the languages simplifies things a lot.