lets say i want to add header guards for .h and .hpp files. name of the header guards must depend on the name of the file. How does one make that on every creation of .h and .hpp file via nerdtree, those header guards are inserted?
Insert header guards in .h and .hpp files via nerdtree and vim
268 Views Asked by JerryThePineapple At
3
There are 3 best solutions below
0
On
The typical approach is to use a template-expander plugin. That's what I do with mu-template -- which even support naming policies for inclusion guards that can be overridden differently in different projects.
It can also be done manually by listening BufNewFile event and then expanding inclusion guards manually (see perreal's answer for instance).
PS: NerdTree is unrelated to the problem nor the solution.
0
On
Straight forward solution with autocmd
function! InsertHeaderGuard()
" Modify the define name format to your liking
let def = 'header_' . localtime() . '_' . expand('%:t:r') . '_' . expand('%:e')
" Append to the buffer
call append(0, '#ifndef ' . def)
call append(1, '#define ' . def)
call append(2, '')
call append(3, '')
call append(4, '')
call append(5, '#endif')
" Place cursor at line 4 column 1
call cursor(4, 1)
endfunction
" C++ headers
autocmd BufNewFile *.hpp call InsertHeaderGuard()
It insert include guard and put cursor inside the guard so you can start typing instead moving the cursor to the position
Note:
- Ignore syntax highlight error in my answer

This can get you started: