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
.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
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
.shextension read the contents of
~/.vim/templates/skeleton.shand 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.
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
Have an update or suggestion for this article? You can edit it here and send me a pull request.
Using HashiCorp Vault with LDAP
How to use HashiCorp Vault to setup an LDAP backed secret store with read-only access for users in groups and read-write access for specific users
Linux and Unix xargs command tutorial with examples
Tutorial on using xargs, a UNIX and Linux command for building and executing command lines from standard input. Examples of cutting by character, byte position, cutting based on delimiter and how to modify the output delimiter.
Copy a file in Go
How to copy a file in Go. The ioutil package does not offer a shorthand way of copying a file. Instead the os package should be used.