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

How do I center-align a line or range of lines to a specific column width in Vim?

Answer

:[range]center {width}

Explanation

Vim has a built-in :center command that pads lines with leading spaces to visually center them within a given column width. This is useful for formatting comment banners, ASCII art headings, and any text that needs visual centering — no plugins needed.

How it works

  • :center {width} — centers the current line within {width} columns
  • :%center 80 — centers every line in the file within 80 columns
  • '<,'>center — centers the visually selected range
  • Omitting {width} uses the 'textwidth' value (defaults to 80 if 'textwidth' is 0)

The command strips existing leading whitespace, then adds the exact number of spaces needed to center the text.

Example

Given a line:

Section Title

Running :center 60 produces:

                   Section Title

(23 leading spaces, since "Section Title" is 13 chars and (60-13)/2 = 23)

Tips

  • :left and :right are companion commands for left- and right-alignment with optional indent width
  • :left 4 indents by exactly 4 spaces (useful for block indenting without >>)
  • Right-alignment: :'<,'>right 80 right-aligns selected lines to column 80
  • These commands modify the buffer in place — use u to undo if the result isn't right

Next

How do I comment out all lines matching a pattern at once using vim-commentary?