Vim different textwidth for multiline C comments?

梦想与她 提交于 2019-12-20 17:29:02

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/3475072/vim-different-textwidth-for-multiline-c-comments

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