How do I control when Vim automatically wraps text or continues comment markers with formatoptions?
Answer
:set formatoptions
Explanation
The formatoptions setting is a string of single-character flags that governs Vim's automatic text formatting: when lines wrap, whether comment syntax continues on new lines, and how gq reformats text. Understanding and tuning these flags is one of the most impactful config changes an experienced Vim user can make.
How it works
Key flags and their effects:
| Flag | Effect |
|---|---|
t |
Auto-wrap text at textwidth while inserting |
c |
Auto-wrap comments at textwidth and insert the comment leader |
r |
Insert comment leader after pressing <Enter> in insert mode |
o |
Insert comment leader after o or O in normal mode |
q |
Allow gq to format comments |
n |
Recognize numbered lists when formatting with gq |
j |
Remove comment leader when joining lines with J (Neovim default) |
l |
Do not break long lines if they were already long when insert mode began |
Add flags with +=, remove with -=.
Example
Stop Vim from automatically inserting // or * when you press Enter inside a comment:
:set formatoptions-=cro
Enable auto-wrap for prose at 80 columns and numbered-list awareness:
:set textwidth=80
:set formatoptions+=tn
Tips
- View current value:
:set formatoptions? - Apply per-filetype via
ftplugin:setlocal formatoptions-=croin~/.vim/ftplugin/python.vim - The
jflag (on by default in Neovim) is excellent::set formatoptions+=jmakesJjoin comment lines cleanly without doubling the// - See all flags with
:help fo-table formatoptionsis often silently overridden by filetype plugins — put your settings in anautocmd FileTypeto ensure they stick