Last updated
The Vim philosophy encourages users to automate repeated actions and provides a rich toolkit with great documentation to achieve that. One example of this type of micro-optimisation is having a template or skeleton file that populates the vim buffer when a new file is opened.
With just a few lines in the ~/.vimrc
file it is possible to build a rich library of skeleton templates. There is no need to use a plugin and add a dependency overhead to your Vim configuration.
A skeleton file is a template to scaffold the creation of new files. This means that whenever a new file is created a standard template is applied and applied to the Vim buffer. For a ruby
file for example, the template may be an empty ruby class. The contents of the file are less important than the idea that for a specific file extension like .go
or .js
Vim can populate a new file with the contents of a template.
A simple example is a shell script. Shell scripts should start with a shebang and often there is debate about the correct type of shebang for a bash script. My personal preference is to use
#!/usr/bin/env bash
To ensure that I remember to add this in a consistent way this is a perfect candidate for a skeleton file.
The single line template is saved into ~/.vim/templates/skeleton.sh
. You may wish to add license or usage information to this template.
To use a skeleton template when creating a new file the following will populate a new file with a .sh
extension with the shell script template.
if has("autocmd")
augroup templates
autocmd BufNewFile *.sh 0r ~/.vim/templates/skeleton.sh
augroup END
endif
This can be explained as
templates
..sh
extension read the contents of ~/.vim/templates/skeleton.sh
and inserted it at line 0.Suppose that we have created a new bash script called backup
. This will not use the template as there is no .sh
extension. Because Vim can read a file from disk and write it into the buffer this is not a problem. In Vim simply read the file into the buffer.
:read ~/.vim/templates/skeleton.sh
Vim’s lightweight approach to templating is extremely flexible, comes with zero dependencies and can be integrated into your dotfiles. It ensures consistency of style either for your own scripts or can be used as part of a standardised approach for a team.
For more see :help template
.
Have an update or suggestion for this article? You can edit it here and send me a pull request.
Build your own Vim statusline
Statuslines in Vim are not hard to create. Making your own means one less dependency in your life.
Custom Vim Bindings in tmux 2.4
tmux 2.4 made a significant change to key bindings. Here is how to support custom keybindings for versions before and after tmux 2.4
Using template files in Vim
Vim templates or skeletons, allow you to specify a template to be used for new files with a certain extension.