Insert header guards in .h and .hpp files via nerdtree and vim

268 Views Asked by At

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?

3

There are 3 best solutions below

1
perreal On

This can get you started:

function Cpp_print_header()                                          
  let header_guard_name = toupper(expand('%:t:gs/[^0-9a-zA-Z_]/_/g'))
  let str_header_guard = ["#ifndef " . header_guard_name,            
    \"#define " . header_guard_name,                                 
    \"",                                                             
    \"#endif /* " . header_guard_name . " */"]                       
  call setline(line("$"), str_header_guard)                          
                                                                     
endfunction                                                          
                                                                     
command CppPrintHeader :call Cpp_print_header()                      
autocmd BufNewFile *.h,*.hpp :CppPrintHeader
0
Luc Hermitte 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
Foxie Flakey 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

Output

Note:

  1. Ignore syntax highlight error in my answer