Wikia

Vim Tips Wiki

Add trailing blanks to lines for easy visual blocks

Talk0
1,612pages on
this wiki
Revision as of 03:50, April 27, 2008 by JohnBot (Talk | contribs)

Tip 828 Printable Monobook Previous Next

created December 3, 2004 · complexity basic · author Micha Shepher · version 5.7


I love using the visual block feature to move columns around (<ctrl-v>, blockwise-visual).

However, this does not work conveniently on the last column when lines are not of equal length. <ctrl-v> marks then a block which is equal in width to the shortest line.

In order to pad all lines to a given width with trailing blanks you can use the following functions:

" truncate line 'line' to no more than 'limit' width
function! Truncate( line, limit )
  call cursor(a:line,a:limit)
  norm d$
endfunc

" Pad all lines with trailing blanks to 'limit' length.
function! AtOnce( limit )
  norm mm
  g/^/norm 100A
  g/^/call Truncate( getline('.'), a:limit )
  let @/=""
  norm 'm
endfunc

You may alternatively use the oneliner:

:g/^/exe "norm! 100A" | call cursor(getline('.'), 79) | norm d$

Comments

Try using 'virtualedit', as in :set ve+=block


Also if you want to block-select to the end of the line, press Ctrl-v for virtual edit and $ for end of line. Then move the cursor up or down and the block will match everything till the end.


I have had good luck with <shift-v>, --Visual Line-- as well... Sort of bypasses having to type V and then $.


All of your suggestions would work, but if you need to add a column, but precisely aligned, how would you achieve that without blank padding? For example,

1. Test 1
2. Test 2 has a longer description
3. Test 3
4. Test 4

And you need to add the string "- PASSED" to the end of each line with g/^/exe "norm! A - PASSED".

Without the padding of blanks you can't have the required result.


ctrl-v + virtual edit (set ve) will allow you to yank blocks and get the line padding automatically.

As far as aligning columns goes, you can also use Align.vim. You can align on tabs (\tab), change tabs to @s and align on @s, etc (see [/scripts/script.php?script_id=294 vimscript#294]).


As for adding text to the end of the bock (assuming you want the added text to line up). 1. Type:

:set ve=all

2. Hit ctr-v and highlight the block. 3. Type:

A - PASSED<esc>

You should see " - PASSED" added to the end of every line, all nice and neatly.


Around Wikia's network

Random Wiki