How do I center-align text within a specific width in Vim?
Answer
:center
Explanation
The :center command pads a line with leading spaces so the text is centered within a given width. This is useful for formatting headings, ASCII art, or any text that needs to be visually centered without leaving Vim.
How it works
:center— center the current line usingtextwidth(or 80 if not set):center 60— center the current line within 60 columns:%center— center all lines in the file:'<,'>center— center the selected lines
Vim also provides :left and :right for left and right alignment respectively.
Example
Before:
My Title
Subtitle Here
After :center 40:
My Title
Subtitle Here
:1,2center 40
Tips
- Set
textwidthfirst with:set textwidth=80to avoid specifying width each time :leftremoves all leading whitespace,:right 80right-aligns to column 80- Combine with visual selection to align specific blocks of text