vimtricks.wiki Concise Vim tricks, one at a time.

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

  • J joins the current line with the next, normally inserting a space between them
  • With j in formatoptions, Vim detects comment leaders (defined by comments option) and removes the leader from the beginning of the second line before joining
  • Without j: joining // line one and // line two// line one // line two
  • With j: joining // line one and // 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 j flag requires Vim 7.3.541 or later
  • Filetypes often set their own formatoptions; use :set formatoptions+=j in an autocmd or ftplugin to persist it
  • Related flag: r (auto-insert leader on Enter), o (auto-insert leader on o/O) — j does not affect those

Next

How do I mark and delete multiple files at once from within Vim's built-in file explorer netrw?