Align character in column

2 Points

Ferran Pelayo Monfort Ferran Pelayo Monfort

7 years ago

Searches the character passed from the starting column on a visual block and aligns the lines to it.

function! MaxColumn(string, startline, endline, column)
    let l:cursor_save = getpos('.')
    let l:max_column = 0
    for line in range(a:endline - a:startline + 1)
        call cursor(a:startline + line, a:column)
        call search(a:string, 'c', line('.'))
        let l:current_column = col('.')
        if l:current_column > l:max_column
            let l:max_column = l:current_column
        endif
    endfor
    call setpos('.', l:cursor_save)
    return l:max_column
endfunction

function! Align(string) range
    let col = min([ virtcol("'<"), virtcol("'>") ])
    let l:cursor_save = getpos('.')
    let l:max_column = MaxColumn(a:string, a:firstline, a:lastline, col)
    for line in range(a:lastline - a:firstline + 1)
        call cursor(a:firstline + line, col)
        if search(a:string, 'c', line('.')) != 0
            let delta_col = (l:max_column - col('.'))
            if delta_col > 0
                exe "normal ".delta_col."i "
            endif
        endif
    endfor
    call setpos('.', l:cursor_save)
endfunction

command! -nargs=1 -range Align '<,'>call Align(<f-args>)

Zenith-One

Zenith-One 7 years ago

Colons being the thing I want to align most, I added vmap <leader>: :Align :<CR>, with vmap <leader>= :Align =<CR> close behind. Note: that works in all visual modes, not just block