Defining a Vim Skeleton File

1 minute read

Defining a Vim Skeleton File

Skeletons (what Vim calls template files) can be any file defined in your vim config. I’ve put mine in a subdirectory called templates/ to keep them organized.

So if you wanted to automatically ad the shebang to every bash file you created, you’d create a template file at ~/.vim/templates/skeleton.sh with the following contents:

#!/usr/bin/env bash

Once you have the skeleton defined you need to tell vim to use it. You can do this anywhere in your vim config. I’ve put it in a skeleton.vim file inside my plugins directory:

if has("autocmd")
  augroup templates
    autocmd BufNewFile *.sh 0r ~/.vim/templates/skeleton.sh
  augroup END
endif

This snippet checks that the current vim installation has the autocmd feature, then creates a group called templates. autocmd BufNewFile *.sh means this should be run automatically when a new .sh file is created. Then 0r (or line 0, replace) adds the contents of the skeleton.sh file we created

To populate a file that does not have the .sh extension, you’d use the following (with :read):

:read ~/.vim/templates/skeleton.sh

You can read more about skeletons/templates by doing :help template

Metadata

Source: shapeshed-vim-templates

Relevant Context(s):

Related Notes:

-