How to use file templates in vim

Cherry Ramatis - Jun 4 '23 - - Dev Community

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;
}


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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>;
};


Enter fullscreen mode Exit fullscreen mode

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')


Enter fullscreen mode Exit fullscreen mode

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:

https://asciinema.org/a/w30ozGvQIVGsoa8WGik66NxOC

New react component

. . . . . . . . . . . . . . . . . . . . . .