Can I make vim do syntax highlighting on C++ headers that don't have extensions?

倾然丶 夕夏残阳落幕 提交于 2019-11-27 15:29:36

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: setlocal ft=cpp: */

EDIT: More details, prompted by the comments :) :

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 modeline=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.

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.

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

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.

ahcox

With default vim settings, add this to the top of a file to have vim pick up the filetype:

/* vim: set filetype=cpp: */

If you are in another language, adjust accordingly, e.g.:

# vim: set filetype=python:

modeline Versus modelines Clarification

In the answer, https://stackoverflow.com/a/10584645,

set modeline=5

Should be:

set modelines=5

See docs: https://stackoverflow.com/a/10584645. Specifically, modeline is a boolean enable flag that is on by default http://vimdoc.sourceforge.net/htmldoc/options.html#%27modeline%27, and modelines takes an integer argument (defaulting to 5 in any case) that sets the number of lines to be looked at if modeline is enabled http://vimdoc.sourceforge.net/htmldoc/options.html#%27modelines%27.

None of this is of interest to the OP, but I add it here for anyone who arrives from a search to remind themselves how to tell vim the filetype at the top of a file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!