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 usingtextwidthc— auto-wrap comments usingtextwidth, inserting comment leaderr— insert comment leader after pressing Enter in insert modeo— insert comment leader after pressingoorOq— allow formatting comments withgqj— remove comment leader when joining linesn— 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 inafter/ftplugin/ - Remove unwanted flags:
set formatoptions-=tstops auto-wrapping text - Use
autocmd FileType * set fo-=oto globally disable comment leader ono - Check current value:
:set formatoptions?