Search code examples
pythonvimtext-filestext-parsing

How to transpose the contents of lines and columns in a file in Vim?


I know I can use Awk, but I am on a Windows box, and I am making a function for others that may not have Awk. I also know I can write a C program, but I would love not to have something that requires compilation and maintenance for a little Vim utility I am making.

The original file might be:

THE DAY WAS LONG 
THE WAY WAS FAST

and after the transposition, it should become:

TT
HH
EE

DW
AA
YY

WW
AA
SS

LF
OA
NS
GT

Update


Solution

  • Here is a command in Vim language. So you don't have to compile Vim with +python support.

    function! s:transpose()
        let maxcol = 0
        let lines = getline(1, line('$'))
    
        for line in lines
            let len = len(line)
            if len > maxcol 
                let maxcol = len
            endif
        endfor
    
        let newlines = []
        for col in range(0, maxcol - 1)
            let newline = ''
            for line in lines
                let line_with_extra_spaces = printf('%-'.maxcol.'s', line)
                let newline .= line_with_extra_spaces[col]
            endfor
            call add(newlines, newline)
        endfor
    
        1,$"_d
        call setline(1, newlines)
    endfunction
    
    command! TransposeBuffer call s:transpose()
    

    Put this in newly created .vim file inside vim/plugin dir or put this to your [._]vimrc.
    Execute :TransposeBuffer to transpose current buffer