How do I right-align a block of text to a specific column width using an Ex command?
Answer
:[range]right {width}
Explanation
Vim has built-in Ex commands for text alignment — :right, :left, and :center — that work over any line range without plugins. These are handy for formatting comment banners, aligning output columns, or preparing plain-text tables.
How it works
:[range]right {width}— right-aligns each line in the range by padding it with leading spaces until the last character falls on column{width}- If
{width}is omitted, Vim usestextwidth(or 80 iftextwidth=0) :[range]left {indent}— removes leading whitespace (left-aligns), with an optional indent column:[range]center {width}— centers each line within{width}columns
Example
Starting with three lines:
Hello
World
Vim
After :%right 20:
Hello
World
Vim
After :%center 20:
Hello
World
Vim
Tips
- Works naturally with visual selections: select lines in visual mode, then press
:and typeright 40 - Useful for creating decorative headers:
:.center 60centers the current line in a 60-column field :left 0strips all leading indentation from a range — equivalent to:%s/^\s*//- The width argument accepts Vim expressions, so
:right &textwidthuses your configuredtextwidth