How do I make Vim automatically reformat paragraphs as I type so lines stay within the textwidth?
Answer
:set formatoptions+=a
Explanation
Vim's formatoptions setting controls how automatic text formatting works. Adding the a flag enables automatic paragraph reformatting: as you insert or delete text, Vim continuously rewraps the paragraph so no line exceeds textwidth. This turns Vim into a word-processor-like editor for prose and documentation writing.
How it works
:set textwidth=80— sets the target line width (required forato have any effect):set formatoptions+=a— enables auto-format mode; paragraphs reformat on every insert- A paragraph is delimited by blank lines; only the current paragraph reflows as you type
The a flag is most useful combined with other formatoptions flags:
set textwidth=80
set formatoptions+=a " auto-reformat
set formatoptions+=w " trailing whitespace = paragraph continuation
Example
With textwidth=40 and formatoptions+=a, typing in a paragraph:
The quick brown fox jumps over the lazy
dog and then runs back again
After inserting "very " before "quick":
The very quick brown fox jumps over
the lazy dog and then runs back again
Vim automatically rewrapped the line to stay within 40 characters.
Tips
- Disable temporarily with
:set formatoptions-=a(useful when pasting) - The
qflag informatoptionsletsgqreformat manually even withouta - For code, add
aonly via a filetype-specific autocmd (e.g., for markdown/text files) 'formatexpr'can be set to a custom function for language-aware reformatting- Check current flags with
:set formatoptions?