How do I center-align or right-align lines of text in Vim without an external tool?
Answer
:[range]center [width]
Explanation
Vim's built-in :left, :center, and :right Ex commands align text without plugins or external tools. They operate on any line range and are handy for formatting comments, banners, or structured text in documentation and configuration files.
How it works
All three commands take an optional [width] argument (defaults to textwidth, or 80 if textwidth is 0):
:[range]left [indent]— Strips leading whitespace, then addsindentspaces (default 0):[range]center [width]— Centers each line withinwidthcolumns:[range]right [width]— Right-justifies each line withinwidthcolumns
Example
Given these three lines:
hello
vim
a longer title
Running :%center 40 produces:
hello
vim
a longer title
Running :%right 40 on the original:
hello
vim
a longer title
Tips
- Apply to a visual selection:
:'<,'>center 60 - Center only lines matching a pattern:
:g/^===/center 78— great for section headers in comments - All three commands are undoable with
u - Use
:'<,'>leftto strip all leading whitespace from a selection (normalizes indent to column 0) - Use
:[range]left 4to set a uniform indent of 4 spaces across a range