How do I automatically fill a new file with a boilerplate template when creating it in Vim?
Answer
autocmd BufNewFile *.py 0r ~/.vim/templates/python.py
Explanation
When you create a new file in Vim (e.g., :e newfile.py), the BufNewFile autocmd event fires before the empty buffer is displayed. You can hook into this event to automatically read a template file into the new buffer using :0r (read file at line 0, before the first line), giving you instant boilerplate without any manual steps.
How it works
BufNewFile *.py— fires when a new file matching*.pyis created0r {file}— reads{file}into the current buffer, inserting at line 0 (before line 1)- The template file can contain any text: shebang lines, license headers, class skeletons, etc.
- Use
expand('<afile>')within the autocmd for dynamic content based on the filename
Example
Add to your vimrc:
mkdir -p ~/.vim/templates
" ~/.vim/templates/python.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main():
pass
if __name__ == '__main__':
main()
" In vimrc:
if has('autocmd')
augroup templates
autocmd!
autocmd BufNewFile *.py 0r ~/.vim/templates/python.py
autocmd BufNewFile *.sh 0r ~/.vim/templates/shell.sh
autocmd BufNewFile *.html 0r ~/.vim/templates/html.html
augroup END
endif
Now :e script.py opens with the Python template already populated.
Tips
- Wrap autocmds in an
augroupwithautocmd!to prevent duplication on vimrc reload - Use
autocmd BufNewFile * if &ft == 'go' | 0r ~/.vim/templates/go.go | endiffor filetype-based selection - After inserting the template, reposition the cursor with a second autocmd using
normal! Gto jump to the end