How do I center, right-align, or left-align lines of text within a fixed column width using Ex commands?
Answer
:{range}center {width}
Explanation
Vim has built-in Ex commands for text alignment: :center, :right, and :left. These are especially useful for formatting prose, ASCII banners, structured comments, and tabular text—without needing a plugin.
How it works
:{range}center {width}— centers each line in the range, padding with spaces to fit within{width}columns (defaults to'textwidth'):{range}right {width}— right-aligns lines to the given column width:{range}left {indent}— left-aligns lines, removing excess leading whitespace (optional{indent}sets the indent level)
All three commands accept any Ex range. Omit the range to act on the current line.
Example
Given these lines selected visually:
Hello
World
Running :'<,'>center 40 produces:
Hello
World
Running :'<,'>right 40 produces:
Hello
World
Tips
- Use
:%center 80to center every line in the file at width 80 - Combine with visual line mode (
V) to select paragraphs before centering :leftwithout a width strips all leading whitespace from each line- If
{width}is omitted, Vim uses'textwidth'(defaulting to 80 if'textwidth'is 0)