mkaz.blog

Working with Vim

Snippets

I use the Snippy plugin for Neovim for all my snippet needs. Snippets have replaced templates for me. Previously I setup a template file to automatically load on a new empty file. For example, a new HTML file would load a stubbed out html-head-body set of tags.

However, setting it up automatically got annoying when doing temporary things. Plus, it was fragile when templates didn't exist for a filetype. Now I just use snippets, it is easier to manually insert the template I want.

Install

See the plugins section for full explanation. I add the following to my vim-plug config :

Plug 'dcampos/nvim-snippy'

Configuration

A standard configuration:

-- Snippy
require('snippy').setup({
    mappings = {
        is = {
            ['<Tab>'] = 'expand_or_advance',
            ['<S-Tab>'] = 'previous',
        },
        nx = {
            ['<leader>x'] = 'cut_text',
        },
    },
})

The snippets directory by default is ${XDG_CONFIG_HOME}/nvim/snippets in your Neovim config directory. Use local_snippet_dir to set your own local snippet directory.

Using Snippets

Create a file in the snippet directory based on your filetype, for example python.snippets. This file holds all the snippets for the Python filetype. Use _.snippets to define a snippets file loaded for all filetypes.

Define an individual snippet. The following defines the fear snippet. The text indented will be what is inserted after typing "fear" and then hitting TAB key.

snippet fear
    I must not fear.
    Fear is the mind-killer.
    Fear is the little-death that brings total obliteration.
    I will face my fear.
    I will permit it to pass over me and through me.
    And when it has gone past I will turn the inner eye to see its path.
    Where the fear has gone there will be nothing.
    Only I will remain.

You can define as many snippets as you like in a single snippets file.

Placeholders

Put a ${1} in the snippet definition where you want the cursor to be after the snippet is entered. Add additional placeholders ${2} where the cursor will go on next TAB.

Include a description in the placeholder for a default, or guidance. Here is my example empty python snippet, after inserting it moves to fill in the description comment and then end in main function.

snippet #!
    #!/usr/bin/env python3
    """
    ${1:description}
    """


    def main():
        ${2:pass}


    if __name__ == "__main__":
        main()

Resources

See the honza/vim-snippets repository for hundreds of pre-defined snippets. The repo can be included as a vim plugin, but it is all a bit too much for me. I prefer picking and choosing which ones I want instead of including everything there.