Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim different textwidth for multiline C comments?

Tags:

In our C++ code base we keep 99 column lines but 79-some-odd column multiline comments. Is there a good strategy to do this automagically? I assume the modes are already known because of smart comment line-joining and leading * insertion.

like image 332
cdleary Avatar asked Aug 13 '10 08:08

cdleary


2 Answers

Apparently both code and comments use the same textwidth option. As far as I can see, the only trick is to set this option dynamically:

 :autocmd CursorMoved,CursorMovedI * :if match(getline(.), '^\s*\*') == 0 | :setlocal textwidth=79 | :else | :setlocal textwidth=99 | :endif

Here the critical part is detecting when we are in a comment. If you only format comments this way:

/*
 * my comment
 */

my regex should work... unless you have lines in the code starting with * (which I guess can happen in C, less frequently in C++). If you use comments like this:

// comment line 1
// comment line 2

the regex is even simpler to write. If you want to cover all possible situations, including corner cases, well... I guess the best thing would be to define a separate detection function and call that from the :autocmd instead of match().

like image 70
UncleZeiv Avatar answered Oct 18 '22 15:10

UncleZeiv


I came across this same problem and think that I have found a suitable solution.

What I wanted my comments to word wrap so that when I'm typing I don't have to worry about formating text. This works well with comment text. But I wasn't comfortable with having vim format my code. So I wanted vim to highlight every thing in red after x column.

To do this with only cpp code you would add the following to your ~/.vim/ftdetect/cpp.vim file.

set textwidth=79
match ErrorMsg '\%>99v.\+'

note: You may have to create the file and folders if they don't exist.

If you have problems with this make sure that you have formatoptions set to:

formatoptions=croql

You can see this by running :set formatoptions inside of vim.

like image 36
William Clemens Avatar answered Oct 18 '22 14:10

William Clemens