Create template code on creating a new file
If you are working a lot on a language and are creating many new files, always having to type the same boiler plate code every time is cumbersome.
To solve this in Vim(Neovim), we can create an auto command to pre populate the file with some code from a template file.
- Create a folder, lets call it
templates
in .config folder. - Add a file in the language you are working on with some boiler plate code, lets call the file
hello
and since I needed it for my C language study created it with.c
extension. - Fill it with the following code.
#include <stdio.h>
int main() {
printf("%s", "Hello, world!\n");
return 0;
}
- Add the below code to your
init.lua
or whereever you see fit.
-- Create an auto command when a new .c file is created and execute the command.
-- The command reads the contents of the hello.c file into the 0th line
vim.api.nvim_create_autocmd("BufNewFile", {
pattern = "*.c",
command = "0r ~/.config/nvim/templates/hello.c"
})
- Everytime you open a new file like
vim main.c
, the code in thehello.c
file should populate themain.c
file.