Vim: How to insert a column on the right side of a file

Viewed 417

I have a file like this, '¬' represents a line break.

aaaaaa¬
bb¬
cccccccc¬
ddddd¬

I know I can insert a column on the left in visual block mode and change it to this,

eaaaaaa¬
ebb¬
ecccccccc¬
eddddd¬

However, is there any easy way to insert a column on the right at any specified column to make it look like this? Thanks.

aaaaaa              e¬
bb                  e¬
cccccccc            e¬
ddddd               e¬
3 Answers

Here is the simplest methods I could think of:

gg                  " move the cursor to line 1
A          <Esc>    " append the desired number of spaces and leave insert mode
<C-v>               " start visual-block mode
G                   " expand the selection to the last line
re                  " replace the content of the visual selection with e

This requires :set virtualedit=block and :set nostartofline. See :help 'virtualedit' and :help 'startofline'.

A nice way is to do:

:%norm A e to append a space followed by an 'e' to every line in the file (following your notation where ¬ indicates a newline):

aaaaaa e¬
bb e¬
cccccccc e¬
ddddd e¬

:%!column -t will get it all aligned by calling an external program to filter the file contents:

aaaaaa    e¬
bb        e¬
cccccccc  e¬
ddddd     e¬

:%norm $20i will shift the column of e¬ more to the right, you could do (that is for every line, go to the end, and insert N spaces before the e) to insert 20 extra spaces:

aaaaaa                       e¬
bb                           e¬
cccccccc                     e¬
ddddd                        e¬

If the last column was more than one character wide, you could tweak the above command like :%norm $b20i (to move 'back' to the start of the word in the last column).

If you want to do the above on only some lines of the file, you can simply visually select those lines before hitting : and omit the %.

My workaround for doing this is like follows:

  1. add sufficient spaces to the end of all lines to allow using visual block mode later:

    • 20A <ESC>
    • j.j.j. ...
  2. use visual block mode to insert the column inside the spaces

  3. delete trailing spaces again (:s/\s*$//)

Related