tags:

views:

458

answers:

2

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.

A: 

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.

William Clemens
Sorry, but no -- this is the same solution I got to this question that I asked: http://stackoverflow.com/questions/235439/ Highlighting junk all over the place is much less finesse than I'm hoping for!
cdleary
+12  A: 

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().

UncleZeiv
+1, I would have posted a similar proposition but it would've been identical to this one.
progo