vimtricks.wiki Concise Vim tricks, one at a time.

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 within width columns (defaults to textwidth or 80)
  • :[range]right [width] — right-aligns each line within width columns
  • :[range]left [margin] — left-aligns each line, removing leading whitespace (optional margin adds 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 4 effectively re-indents lines to 4 spaces regardless of current indentation
  • These commands respect your current textwidth if 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 -t or alignment plugins

Next

How do I highlight all occurrences of a yanked word without typing a search pattern?