Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting file type for C++ standard headers with vim

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?

like image 921
betabandido Avatar asked Jun 05 '12 20:06

betabandido


2 Answers

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.

like image 93
pb2q Avatar answered Oct 16 '22 16:10

pb2q


* 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.

like image 23
n. 1.8e9-where's-my-share m. Avatar answered Oct 16 '22 18:10

n. 1.8e9-where's-my-share m.