vim autocmd BufNewfile 执行了多次

vim autocmd BufNewfile executed multiple times

我的 ~/.vimrc 只包含

so ~/config/vim/vimrc

~/config/vim/vimrc 包含常用选项、少量映射和不同文件类型的源文件,我有 :

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

然后,如果我向 shell 询问:

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                 |

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

here 所述,Vim 会在您每次打开新文件时创建一个 new 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