How do I center or right-align text within a specific column width in Vim?
Answer
:center / :left / :right
Explanation
Vim has three built-in Ex commands for aligning text without any plugins: :left, :center, and :right. These work on a range of lines and accept an optional width argument (defaulting to textwidth if set, or 80 otherwise). They're ideal for formatting comment headers, ASCII banners, or any structured plain text.
How it works
:[range]left [width]— strips leading whitespace and left-aligns the lines:[range]center [width]— centers each line within the given column width:[range]right [width]— right-aligns each line within the given column width
The width argument is the total column width to align within. If omitted, Vim uses textwidth (or 80 if textwidth is 0).
Example
Starting with these three lines selected visually:
Project Report
Q3 2024
All Rights Reserved
Running :'<,'>center 60 produces:
Project Report
Q3 2024
All Rights Reserved
Running :'<,'>right 60 produces:
Project Report
Q3 2024
All Rights Reserved
Tips
- Visually select lines first, then type
:center 72— Vim auto-inserts'<,'>for the range - Use
:set textwidth=78so you can omit the width argument and just type:center - These commands work great with
=formatting workflows for comment banners in code :rightwithout a width defaults to 80, which can surprise you if your lines are longer