Standard headers for C++ are typically installed in /usr/include/c++/4.x (in Linux). Since most of the headers do not have any extension (.h, .hpp, etc.), vim cannot recognize the format for these files as C++.
I have seen this other question in SO, but the solutions posted in there do not solve my problem. One solution there involves using modeline
but standard C++ headers do not include a vim-friendly signature. Instead, they include in the first line something like:
// <algorithm> -*- C++ -*-
I guess I could search for that pattern (-*- C++ -*-
) in order to detect the file type. The other solution posted in the previously mentioned SO question actually goes in that direction. The answer suggests to use:
au BufRead * if search('MagicPattern', 'nw') | setlocal ft=cpp | endif
so I have tried to do:
au BufRead * if search('-*- C++ -*-', 'nw') | setlocal ft=cpp | endif
but it does not work (i.e., the file type is not detected).
Is it possible to detect the file type using that approach? Does it exist any plugin or any other way to solve this?
n.m's answer does the trick, but this is better:
au BufRead * if search('\M-*- C++ -*-', 'n', 1) | setlocal ft=cpp | endif
The extra argument to search
is the stopline, and ensures that this rule will only be applied to files with the pattern in line 1.
This is important because, without the stopline any files that contain the pattern, including your vimrc, will satisfy the match and potentially be highlighted using the wrong syntax rules.
Also, using stopline the w
flag is unnecessary.
Look at :help search
for more information.
*
is normally special in Vim searches. To disable it, use \M
in the beginning of the search string, i.e.
au BufRead * if search('\M-*- C++ -*-', 'nw') | setlocal ft=cpp | endif
This actually works for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With