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

How do I align key=value pairs on one line using a substitute expression in Vim?

Answer

:s/\v(\S+)\s*=\s*(.*)/\=printf('%-20s = %s', submatch(1), submatch(2))/

Explanation

When a line contains uneven key = value spacing, quick manual fixes are easy to get wrong. A substitute expression lets you normalize and align in one operation. :s/\v(\S+)\s*=\s*(.*)/\=printf('%-20s = %s', submatch(1), submatch(2))/ reformats the current line by padding the key field to a fixed width and rebuilding the assignment cleanly.

How it works

  • \v enables very magic mode so the regex stays compact.
  • (\S+) captures the key (non-whitespace token before =).
  • \s*=\s* tolerates any spacing around =.
  • (.*) captures the remaining value text.
  • \=... switches replacement into expression mode.
  • printf('%-20s = %s', submatch(1), submatch(2)) emits a left-aligned 20-character key column plus normalized delimiter spacing.

This is useful for config files, test fixtures, and generated snippets where readability matters but you do not want to run a heavyweight formatter for a tiny block. It is also safer than ad-hoc spacing edits because every run applies the same deterministic format.

Example

Before:

timeout=30
retries   =5
service_name =api

On each line, run:

:s/\v(\S+)\s*=\s*(.*)/\=printf('%-20s = %s', submatch(1), submatch(2))/

After:

timeout              = 30
retries              = 5
service_name         = api

Tips

  • Change 20 in %-20s to fit your preferred column width.
  • Add the g flag if multiple assignments appear on one line.
  • Use the same pattern in a visual range for batch cleanup.

Next

How do I reindent the previous visual selection and keep it selected?