3

Given the file alfa.c:

// Lorem ipsum dolor sit amet, apeirian constituam interpretaris no his, soluta salutandi persequeris vel ne, facete impedit contentiones te eam. Ut utamur habemus qualisque usu
#include <stdio.h>
int main() {
  puts("hello world");
}

I would like to format all long comments to get results like this:

// Lorem ipsum dolor sit amet, apeirian constituam interpretaris no his, soluta salutandi
// persequeris vel ne, facete impedit contentiones te eam. Ut utamur habemus qualisque usu
#include <stdio.h>
int main() {
  puts("hello world");
}

I see Vim has an option to format comments, however I did not see any Ex mode commands. Is this possible?

1

2 Answers 2

3

Depending on your configuration you can achieve the desired result with:

gq

If you want to use this as a ex command you can use:

normal! gqq

to format the current line.

Aslo, it's worth adding the flags a and c to your 'formatoption' configuration:

set fo+=ac

This will try to preserve the current comment formatting as well as automatically formatting the paragraph.

You may want to have a look at:

  • :h format
  • :h gq
  • :h fo-table
  • :h 'fo'
1
0

You can set a limit for a line, like 80 columns for a line.

Then you can set a autocommand to split such lines whenever you save the file.

:au BufWrite *.* :%s#^\s\*//.\{78\}#&\r//#g

Put this in your ~/.vimrc.

4
  • 1
    I like this approach, but I can't get it to work @SibiCoder, Pattern not found: .{80,}. But even if it did it looks like this will take anything above 80 characters and turn it into a comment. This seems problematic.
    – Tumbler41
    Commented Jun 13, 2016 at 22:14
  • What problems? Can you explain? I will refine my answer
    – SibiCoder
    Commented Jun 14, 2016 at 2:38
  • 2
    1st: I think you have one of the magic settings on (or off) for your regex. To make your regex work I get: ^\s*\/\/.\{78\}. 2nd: if you had a line of code that was more than 80 characters, this would take it and turn it into a comment. Edit: I guess you fixed this issue by searching for //.
    – Tumbler41
    Commented Jun 14, 2016 at 13:24
  • 2
    3rd: This, of course only takes C-style comments into account. 4th: In the case where you have a REALLY long line (more than 160 characters) you will still end up with lines that are greater than 80.
    – Tumbler41
    Commented Jun 14, 2016 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.