In the modern world boilerplate is something that we as developers just got used to as part of the job and part of all mainstream frameworks used today, but it's a pain to manage all that by hand specially when you don't want to keep running generators
commands (some frameworks don't even have those generators commands đĽ)
It would be awesome to let our editor deal with this part while allowing us to focus on what pay the bills, right? Well, vim got you cover!
In the help page for :help skeleton
you can find pretty much all the basics you want for templates, basically you write the template you want in a file like ~/.vim/templates/c_main.c
:
int main () {
return 0;
}
After that, you declare a simple autocmd to insert it when a new file is made:
autocmd BufNewFile *.c 0r ~/.vim/templates/c_main.c
And voilĂ ! When you create a new file with :e main.c
the content will be inserted automatically
WARNING: This doesn't work from the command like, just with the :e command
But let's add a little caviar to this receipt by applying the goodness of vim script! We'll define a template for a simple react component that follows the pattern ComponentName/index.tsx
, the idea is to insert a new component with the right name based on the folder. Cool right?
First, we'll define the template in ~/.vim/templates/react_component.tsx
export const %component_name% = () => {
return <h1>%component_name%</h1>;
};
Notice the %component_name%
, this will be used to replace with the folder name.
Now we add our autocmd:
autocmd BufNewFile */**/index.tsx 0r ~/.vim/templates/react_component.tsx | %s/%component_name%/\=expand('%:h:t')
Notice that our pattern is much more narrow this time, we want to match only index.tsx
files that have a folder as its parent. Another important part to keep track is the \=
in the substitution command, this is an expansion for vim script, so we can use the function expand('%:h:t')
as part of the substitution
Tip: you can read more about the substitution pattern with :help \=
The result is as we expect:
Top comments (10)
Great post! Congrats
Thanks for the support 𼰠means a lot
This is an awesome feature that I never know about. I need to start doing this with
flake.nix
files, and maybe*.nu
files.I've been doing this for rails controllers/models, etc.. and it's been great ! Let me know if I can help you with anything
Cheers to your first article published! Very interesting content btw. Keep writing!
Thanks a lot, cousin â¤ď¸ youâre an inspiration for me to invest in things that I like
congrats! great post! âď¸
Thanks a lot <3
Congratulations! This is amazing!
Thanks â¤ď¸