Automatic insertion of C/C++ header gates
From Vim Tips Wiki
Tip 514 • Previous Tip • Next Tip
Created: July 21, 2003 Complexity: basic Author: Morten Fjord-Larsen Minimum version: 5.7 Karma: 63/30 Imported from: Tip#514
C/C++ header files should be guarded against multiple inclusions using preprocessor directives, e.g.:
#ifndef FOO_H #define FOO_H /* Declarations. */ #endif
Placing the following snippet in your vimrc file, makes Vim insert these preprocessor gates automatically, when a new header file is created:
function! s:insert_gates()
let gatename = substitute(toupper(expand("%:t")), "\\.", "_", "g")
execute "normal! i#ifndef " . gatename
execute "normal! o#define " . gatename . " "
execute "normal! Go#endif /* " . gatename . " */"
normal! kk
endfunction
autocmd BufNewFile *.{h,hpp} call <SID>insert_gates()
[edit] Comments
TO DO
The following is from a proposed new tip that has now been deleted. What is required to make this work? It assumes you start with something?
Here is an alternative, intended to produce:
#ifndef __FILENAME_H #define __FILENAME_H #endif //__FILENAME_H
This will add this kind of block at the top of a new .h file at the press of a key. Add to your vimrc file:
nnoremap <F12> "%phr_I#ifndef __<Esc>gUwyypldwidefine <Esc>yypldwiendif //<Esc>O<Esc>
