How do I make Vim remove the comment leader from the second line when joining two comment lines?
Answer
:set formatoptions+=j
Explanation
Adding the j flag to formatoptions causes Vim to strip the comment leader from the second line when two comment lines are joined with J. Without it, joining produces a doubled-up leader in the middle of the merged text.
How it works
Jjoins the current line with the next, normally inserting a space between them- With
jinformatoptions, Vim detects comment leaders (defined bycommentsoption) and removes the leader from the beginning of the second line before joining - Without
j: joining// line oneand// line two→// line one // line two - With
j: joining// line oneand// line two→// line one line two
Example
With default settings:
// This function handles
// connection pooling.
After pressing J: // This function handles // connection pooling.
After :set formatoptions+=j and pressing J:
// This function handles connection pooling.
Tips
- Check existing flags with
:set formatoptions? - The
jflag requires Vim 7.3.541 or later - Filetypes often set their own
formatoptions; use:set formatoptions+=jin anautocmdorftpluginto persist it - Related flag:
r(auto-insert leader on Enter),o(auto-insert leader ono/O) —jdoes not affect those