Align Right in Visual Block

I would like to know how to right-align in a visual block without changing the text before and the block.

I have used this code before:

:<C-U>'<,'>s/\%V\(.\{-}\)\(\s\{-}\)\%(\%V\@!\|$\)/\2\1/ 

      

However, I noticed that this doesn't work when there are only spaces after the visual block. (There must be text after the visual block to do the work on the code)

Isn't there a way to align text to the right in a visual block that is written after the block?

Example:

text before +align text     text after 
text before   align text    text after
text before  align text     text after
text before     align text+ text after 

      

What I want to do is select a block of text from +

to +

(see example above) and align it to the right. The output should be:

text before      align text text after 
text before      align text text after
text before      align text text after
text before      align text text after 

      

A job is done on the code, but it doesn't work when nothing is written on each line align text

.

+3


source to share


3 answers


To solve the problem correctly, handling all corner cases, I would use the following function.



function! RightAlignVisual() range
    let lim = [virtcol("'<"), virtcol("'>")]
    let [l, r] = [min(lim), max(lim)]
    exe "'<,'>" 's/\%'.l.'v.*\%<'.(r+1).'v./\=StrPadLeft(submatch(0),r-l+1)'
endfunction
function! StrPadLeft(s, w)
    let s = substitute(a:s, '^\s\+\|\s\+$', '', 'g')
    return repeat(' ', a:w - strwidth(s)) . s
endfunction

      

+3


source


:'<,'>s/\%V.*\%V/\=printf("%*s", col("'>")-col("'<"), substitute(submatch(0), '^\s*\|\s*$', '', 'g'))

      



+1


source


I am using this. Place the cursor in front of the text to be aligned to the right. Run :Right

How it works:

  • v0

    Visualy select text from current position to start of line
  • d

    Delete selected text and place in clipboard
  • :Right

    Align the text on the right side of the cursor
  • 0

    Place the cursor in the first column
  • gv

    Visualy select the same area we deleted before
  • p

    Replace selection with deleted text

    command! Right execute "normal v0d\<CR>:right\<CR>0gvp"

+1


source







All Articles