Vim 使用自动命令 BufNewFile 时颜色方案未加载

Vim colorscheme not loading when using autocommand BufNewFile

当尝试使用自动命令自动打开相应的 .cpp 或 .h 文件时,我遇到打开的相应文件没有颜色方案。 我不太熟悉 vimscript,但我相信 Vim 正在打开文件,认为它是文件类型“.txt”,因此使用默认的配色方案。

~/.vimrc 中的两个自动命令行:

au BufRead,BufNewFile *.cpp exe "bel vsplit" fnameescape(expand("%:r").".h")
au BufRead,BufNewFile *.h exe "vsplit" fnameescape(expand("%:r").".cpp")

如有任何帮助,我们将不胜感激。

如果以后有人想看这个,解决方案是 Vim 正在加载第二个文件作为 syntax=none。所以在每个自动命令的末尾添加 | set syntax=cpp 修复它。

你的答案是一个解决方法(虽然你应该使用 :setlocal 而不是 :set 以避免语法泄漏到从那个打开的新缓冲区),但它不会解决根本原因,您会在 :help autocmd-nested:

找到解释

By default, autocommands do not nest. If you use ":e" or ":w" in an autocommand, Vim does not execute the BufRead and BufWrite autocommands for those commands. If you do want this, use the "nested" flag for those commands in which you want nesting.

语法高亮(你在标题中说了 colorscheme,但实际上只是语法高亮使用的颜色和字体属性)基于 :autocmd 事件( 也是如此文件类型插件,所以你也不会在拆分文件中找到任何与 C++ 相关的设置,假设你的 ~/.vimrc 中有 :filetype plugin on)。如果没有 nested 属性,拆分文件将被打开,但 none 的常用操作将被 运行 执行。尽管通常嵌套可能会出现问题,但这是需要嵌套的情况之一。

au BufRead,BufNewFile *.cpp nested exe "bel vsplit" fnameescape(expand("%:r").".h")
au BufRead,BufNewFile *.h   nested exe "vsplit" fnameescape(expand("%:r").".cpp")

不幸的是,这引入了另一个问题:一个 autocmd 将触发另一个,反之亦然(达到一个限制)。您需要保护这些操作,以便仅在文件尚未打开时才进行拆分。 (这也提高了通用方式的可用性,当您打开一个文件而另一个文件已经打开时。):help bufwinnr() 检查目标缓冲区是否已经在 window:

中可见
au BufRead,BufNewFile *.cpp nested if bufwinnr("^" . expand("%:r").".h$")   == -1 | exe "bel vsplit" fnameescape(expand("%:r").".h") | endif
au BufRead,BufNewFile *.h   nested if bufwinnr("^" . expand("%:r").".cpp$") == -1 | exe "vsplit" fnameescape(expand("%:r").".cpp") | endif