I'm writing C code using vim and are searching for a possibility to right-align my comments so that they all end at col 80. To give a short example:

int a = 80; /* initialize a */
int b = 7; /* initialize b */
printf("%d + %d = %d", a, b, a+b); /*calculate the result */

should turn into

int a = 80;                               /* initialize a */
int b = 7;                                /* initialize b */
printf("%d + %d = %d", a, b, a+b); /*calculate the result */
                                                           ^col 80

I have installed vim-easy-align to do other formattings but did not find out yet how to perform this alignment. Maybe someone knows how?

I do not insist on vim-easy-align. If you have another plugin that does the job.. Just tell me ;).


My AlignFromCursor plugin provides a <Leader>ri mapping and :RightAlignFromCursor command which do that. Just place the cursor in the whitespace before the comment (either manually or via a :[range]normal command) and invoke the mapping or command. It uses 'textwidth' or a prefixed [count].


Here is how to do it with plain vim commands, no plugins used:

In normal mode, place your cursor at the first character of the string you want to right-align, like the comment delimiter, and then press leader then tab to right align the text.

nnoremap <leader><tab> mc80A <esc>080lDgelD`cP

With explainations:

mc80A <esc>080lDgelD`cP
| |        |   ||  ||
mc|        |   ||  ||    Mark the position of the cursor
  |        |   ||  ||
  80A <esc>|   ||  ||    Append 80 spaces at the end
           |   ||  ||
           080l||  ||    Go the the 80th column from the beginning of the line
               ||  ||
               D|  ||    Delete what is next
                |  ||
                gel||    goes after the last string char
                   D|    Delete the characters remaining (complement to go 80)
                    `cP  and paste these to shift the string up to 80 column.

To mark multiple comments, you can search the next occurence of a comment delimiter and press leadertabnleadertabnleadertabn...

  • This is why I love Vim. – Eric M Feb 27 '18 at 16:21

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.