问题描述
我有一个项目,其中包含一堆遵循标准 C++ 头文件命名约定的 C++ 头文件;也就是说,一个名为 Foo 的类将在名为 Foo
的文件中声明,而不是在 Foo.h
或 Foo.hh
中声明.有没有一种好方法可以配置 vim 来仅对这些文件进行语法高亮显示?一个不太令人愉快的回退是为所有没有扩展名的文件启用 C++ 风格的突出显示.我不确定是否有任何更复杂的方法来检测文件的类型,而不是仅仅依靠其扩展名.
I have a project with a bunch of C++ header files that follow the standard C++ header naming convention; that is, a class called Foo would be declared in a file called Foo
, not Foo.h
or Foo.hh
. Is there a good way to configure vim to do syntax highlighting for these files only? A slightly-less-pleasing fallback would be to enable C++-style highlighting for all files that don't have an extension. I'm not sure if there's any more sophisticated way to detect the type of file instead of relying solely on its extension.
推荐答案
您可以为此使用 modeline
功能.模式行允许您在文件的前几行/最后几行的注释中设置某些选项.
You can use the modeline
feature for this. Modelines allow you to set certain options from within a comment in the first/last few lines of your file.
这使它成为设置编码指南、折叠参数的好地方.出于安全原因,无法设置某些选项.有关详细信息,请参阅文档.
This makes it a great place to set parameters for coding guidelines, folding. Some options cannot be set for security reasons. See the documentation for more information.
把它放在文件的顶部或底部:
Put this at the top or bottom of the file:
/* vim: set ft=cpp: */
更多详细信息,由评论提示:) :
More details, prompted by the comments :) :
它只有在模式行启用时才有效.在正常情况下,它应该是默认的.要确保启用它,或更改检测到的区域的大小,请在 .vimrc
中设置 modeline
选项:
It will only work if modeline is enabled. In normal circumstances it should be by default. To make sure it is enabled, or to change the size of the area it is detected in, set the modeline
option in your .vimrc
:
set modelines=5
将确保在每个文件的前五行或最后五行中检测到上面引用的行.
will make sure the line like the one quoted above will be detected in the first five or the last five lines of each file.
在modeline中,setlocal
的意思是为文件加载的缓冲区设置选项.ft
选项,也称为filetype
, 是决定语法高亮语言的因素.值 cpp
是 C++ 文件使用的值.
Inside the modeline, setlocal
means to set options for the buffer the file is loaded in. The ft
option, also known as filetype
, is what determines the syntax highlighting language. The value cpp
is the one that is used by C++ files.
编辑 2:没有模式行,多做一点工作,如果你能识别出一个神奇的模式:
EDIT 2: Without the modeline, with a bit more work, if you can identify a magic pattern:
au BufRead * if search('MagicPattern', 'nw') | setlocal ft=cpp | endif
含义:每次打开文件时,检查"MagicPattern"
是否在其中.如果是,则将其视为 C++.模式参数是正则表达式的 vim 方言;查看帮助模式
了解详情.
Meaning: Every time you open a file, check if "MagicPattern"
is in there. If it is, treat it as C++. The pattern argument is in vim dialect of regular expressions; check help pattern
for details.
这篇关于我可以让 vim 在没有扩展的 C++ 头文件上做语法高亮吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!