How to insert enough spaces to align text to column number using Vim?

For alignment, there are three well-known plugins:

  • the venerable Align - Help folks to align text, eqns, declarations, tables, etc
  • the modern tabular
  • the contender vim-easy-align

With the first, your problem can be solved via

:%Align -e

You can do it with no plug-in, like this:

:%s#\(.*\)\zs\ze-e#\=repeat(' ',58-len(submatch(1)))

Note: This assumes that -e is the last of line. But you can capture it otherwise if it is not suitable to your case.

Explanation:

  • %s#\(.*\) - captures the line before the -e.
  • \zs\ze - starts and stops the match here.
  • -e# - just before the -e.
  • Using \zs and \ze here let us to add our spaces directly before -e (otherwise concatenation with .submatch(x) would have been possible).
  • \=repeat(' ',58-len(submatch(1))) - replace this location with a variable number of spaces and where 58 is your aimed column.

Tags:

Vi

Vim