Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing too long comment lines in Vim

Tags:

vim

I'm looking for a convenient way to fix comments where line lengths exceed a certain number of characters in Vim. I'm fine with doing this manually with code, especially since it's not that frequent, plus refactoring long lines is often language, or even code-style dependent, but with comments this is pure drudgery.

What happens is I often spot some issue in a comment, tweak one or two words and the line spills out of the, say, 80 character limit. I move the last word to the next line and then the next line spills, and so on. Does anyone know a way to do this automatically in Vim?

like image 650
Tomek Kaftal Avatar asked Oct 23 '22 11:10

Tomek Kaftal


1 Answers

I would recommend putting the following into your vimrc if this is a regular issue:

nnoremap <leader>f gqip

This maps the leader f shortcut (f is for "format") to format the comment (considered a paragraph after setting some formatoption flags) with gq which formats the comment to be the width of the currently set textwidth or tw option. You should set textwidth in your .vimrc with textwidth=80.

Formatoptions is the other thing you should fiddle with, specifically in your case by adding the acq flags with formatoptions+=acq. Be careful to remove the t flag with formatoptions-=t because that will automatically wrap all of your code, not just recognized comments. After doing all this you should be able to hit f and format inside only the comment, irrespective of whether is is surrounded by blank lines.

Here is the relevant info on formatoptions so you can make your own choices.

t       Auto-wrap text using textwidth

c       Auto-wrap comments using textwidth, inserting the current comment
    leader automatically.

r       Automatically insert the current comment leader after hitting
    <Enter> in Insert mode.

o       Automatically insert the current comment leader after hitting 'o' or
    'O' in Normal mode.

q       Allow formatting of comments with "gq".
    Note that formatting will not change blank lines or lines containing
    only the comment leader.  A new paragraph starts after such a line,
    or when the comment leader changes.

w       Trailing white space indicates a paragraph continues in the next line.
    A line that ends in a non-white character ends a paragraph.

a       Automatic formatting of paragraphs.  Every time text is inserted or
    deleted the paragraph will be reformatted.  See |auto-format|.
    When the 'c' flag is present this only happens for recognized
    comments.
like image 86
Hydrox24 Avatar answered Nov 15 '22 03:11

Hydrox24