多次执行vim-autocmd-BufNewfile



My~/.vimrc仅包含

so ~/config/vim/vimrc

~/config/vim/virc包含常用的选项,一些映射和不同文件类型的源文件,我有:

autocmd FileType cpp so ~/config/vim/filetype/cpp.vimrc

在该文件中,我定义了以下函数,每次打开新的cpp标头时都要调用该函数,以避免双重包含:

python import vim
function! s:insert_gates()
python << endPython
hpp = vim.current.buffer.name
hpp = hpp[hpp.rfind('/') + 1:]
hpp = hpp.upper()
hpp = hpp.replace('.', '_')
vim.current.buffer.append("#ifndef " + hpp)
vim.current.buffer.append("# define " + hpp)
vim.current.buffer.append("")
vim.current.buffer.append("#endif")
endPython
endfunction
autocmd BufNewFile *.hpp call <SID>insert_gates()

然后,如果我问我的外壳:

vim -O3 t1.hpp t2.hpp t3.hpp

我得到了:

|                     |#ifndef T2_HPP       |#ifndef T3_HPP       |
|                     |# define T2_HPP      |# define T3_HPP      |
|                     |                     |                     |
|                     |#endif               |#endif               |
|                     |                     |#ifndef T3_HPP       |
|                     |                     |# define T3_HPP      |
|                     |                     |                     |
|                     |                     |#endif               |
|                     |                     |                     |
|_____________________|_____________________|_____________________|
|t1.h                 |t2.h                 |t3.h                 |

这不是我想要的。。。你看到我的错误了吗?谢谢

如本文所述,每次打开新文件时,Vim都会创建一个新的autocmd。为了防止这种情况,请将.vimrc的该部分替换为:

python import vim
function! s:insert_gates()
python << endPython
hpp = vim.current.buffer.name
hpp = hpp[hpp.rfind('/') + 1:]
hpp = hpp.upper()
hpp = hpp.replace('.', '_')
vim.current.buffer.append("#ifndef " + hpp)
vim.current.buffer.append("# define " + hpp)
vim.current.buffer.append("")
vim.current.buffer.append("#endif")
endPython
endfunction
augroup insertgates
    autocmd!
    autocmd BufNewFile *.hpp call <SID>insert_gates()
augroup END

最新更新