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

How do I control automatic text wrapping and comment formatting in Vim?

Answer

:set formatoptions+=cro

Explanation

The formatoptions setting controls how Vim automatically formats text as you type — including comment continuation, auto-wrapping, and paragraph formatting. Understanding these flags lets you fine-tune editing behavior for code vs prose.

How it works

  • t — auto-wrap text using textwidth
  • c — auto-wrap comments using textwidth, inserting comment leader
  • r — insert comment leader after pressing Enter in insert mode
  • o — insert comment leader after pressing o or O
  • q — allow formatting comments with gq
  • j — remove comment leader when joining lines
  • n — recognize numbered lists when formatting

Example

" Good defaults for code editing
set formatoptions=tcroqnj
With 'r' enabled:
// comment line 1
// |  ← pressing Enter auto-inserts '//' 

With 'j' enabled:
// first line
// second line
J →
// first line second line  (comment leader removed)

Tips

  • Vim's filetype plugins often override formatoptions — set yours in after/ftplugin/
  • Remove unwanted flags: set formatoptions-=t stops auto-wrapping text
  • Use autocmd FileType * set fo-=o to globally disable comment leader on o
  • Check current value: :set formatoptions?

Next

How do I return to normal mode from absolutely any mode in Vim?