Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim automatic hard wrapping long comments in C++?

To reproduce my issue:

$ vim -u NONE test.cpp
:set nocompatible
:set tw=20
:set fo=croql

Now type in the following text:

/*
    test test test test test test test test test
*/

Notice that there is no leading asterisk on the line containing the tests. Vim will insert this by default, remove it.

Vim should be auto-wrapping this, but it doesn't.

How can I make Vim wrap automatically in comments, and only in comments? :set fo+=t works, but then everything gets wrapped and I do not want automatic hard wrapping for code.

like image 531
orlp Avatar asked Jun 02 '26 21:06

orlp


2 Answers

With my OnSyntaxChange plugin, you can change the 'fo' option value depending on whether the cursor inside a comment or not:

call OnSyntaxChange#Install('Comment', '^Comment$', 0, 'a')
autocmd User SyntaxCommentEnterA setlocal fo+=t
autocmd User SyntaxCommentLeaveA setlocal fo-=t

It's also available on GitHub.

like image 116
Ingo Karkat Avatar answered Jun 04 '26 10:06

Ingo Karkat


I'm using VIM 8.2 and it CAN wrap comments out of the box.

Short answer how

set tw=80
set fo=croaq

Check your comments option with :set comments?. I must contains /*, * and */ sequences.

Long answer

You can read details in :help formatoptions, :help fo-table and :help comments.

The tw=80 option is for limiting line width.

The formatoptions uses next flags here:

  • The c flag is to apply wrapping only for comments
  • The r and o flag is for auto-inserting the comment-leader on new lines (* symbol for /* styled comment in C-like languages).
  • The a will auto-format your paragraphs while you are typing.
  • The q option will handle the comment leader the correct way.

For some types of buffers you can apply formatoptions for all text like next:

  "Limit line width for git commit messages to 72 characters
autocmd FileType gitcommit setlocal tw=72
  "Auto format all text for git commit messages and markdown files
autocmd FileType gitcommit,markdown setlocal formatoptions+=t

Here

  • The t flag is to apply wrapping for text (additionally to c)

The comments option will help vim to detect comments correctly.

like image 45
shved Avatar answered Jun 04 '26 10:06

shved



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!