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

How do I center or right-align a block of text using Vim's built-in Ex commands?

Answer

:{range}center [width]

Explanation

Vim provides three built-in Ex commands for text alignment: :center, :right, and :left. These operate on a range of lines and pad them with spaces to produce the desired alignment, all without any plugin or external tool.

How it works

  • :[range]center [width] — center each line within width columns (default: textwidth)
  • :[range]right [width] — right-align each line within width columns
  • :[range]left [indent] — left-align each line, optionally adding indent spaces

The [range] follows standard Vim range syntax: % for the whole file, '<,'> for a visual selection, or 1,5 for specific lines.

Example

Starting with these lines:

hello
world

Running :%center 40 produces:

                 hello
                 world

Running :%right 40 on the same lines:

                                   hello
                                   world

Tips

  • If width is omitted, :center and :right use textwidth (or 80 if unset)
  • :left 0 strips all leading whitespace from a range — useful for dedenting a block
  • Combine with a visual selection: select lines, press :, then type center 72 to center them within 72 columns
  • Great for ASCII banners, formatted comment headers, or aligned output in text files

Next

How do I make the tilde key work as a case-toggle operator so I can use motions like ~w or ~ip?