How do I center, right-align, or left-align lines of text using Ex commands?
Answer
:center / :right / :left
Explanation
Vim has built-in Ex commands to align text: :center, :right, and :left. These are especially handy for formatting comments, headers, and prose — no plugin required.
How it works
:[range]center [width]— centers each line in the range withinwidthcolumns (defaults totextwidthor 80):[range]right [width]— right-aligns each line withinwidthcolumns:[range]left [margin]— left-aligns each line, removing leading whitespace (optionalmarginadds indentation)
When used after a visual selection, the range is automatically set to '<,'> so only the selected lines are affected.
Example
Given these lines (textwidth=40):
Chapter One
The Beginning
Visually select both lines and run :'<,'>center 40:
Chapter One
The Beginning
Or right-align with :'<,'>right 40:
Chapter One
The Beginning
Tips
- Combine with
:%to align the entire file::%center 72 :left 4effectively re-indents lines to 4 spaces regardless of current indentation- These commands respect your current
textwidthif no width argument is given, making them useful for writing prose or documentation with a consistent column width - For code-style alignment (aligning
=signs or columns), look into:!column -tor alignment plugins