2

One thing that I often need to do is reformat a code comment with gq or gw. For example, I often want to convert something like this:

// Lorem ipsum 
// dolor
// sir 
// amet
int foo(int x) {
    return 17;
}

into this:

// Lorem ipsum dolor sir amet
int foo(int x) {
    return 17;
}

Is there a vim motion I can use to select the entire comment block under the cursor? I tried using gq} and gqipbut they also reformat the code under the comment, which is too much.

// Lorem ipsum dolor sir amet
int foo(int x) { return 17; }

So far the best I could think is manually counting lines, using something like gq4j. But there ought to be a better way...

3
  • Unfortunately no, there isn't Jul 10 '20 at 19:27
  • It's not completely reliable, but if your Vim binary includes the patch 8.2.0915, try this mapping: ono <silent> ix :exe search('.$', 'W', 0, 0, {-> synstack(line('.'), col('.'))->map('synIDattr(v:val, "name")')->match('\ccomment') != -1}) ? 'norm! k' : ''<cr>
    – user938271
    Jul 10 '20 at 20:27
  • @user938271: Could you please write that as an answer instead of as a comment?
    – hugomg
    Jul 10 '20 at 20:56
3

If using plug-ins is acceptable to you, then the vim-commentary plug-in can help you.

It defines a gc text object to select a comment, which you can use in operator pending mode. Use gqgc anywhere in the comment block to format the comment.

Note that if you are using C or C++ you may need to tell Vim to use // comments instead of /**/ comments. You can define either the 'commentstring' option or alternatively the b:commentary_format buffer variable.

set commentstring=//%s

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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