Search code examples
vimmacroscenter

An easy way to center text between first and last non-white word in vim?


Is there an easy way using a macro or ~10 line function (no plugin!) to center some text between the first and last word (=sequence of non-blank characters) on a line? E.g. to turn

        >>> No user serviceable parts below.               <<<

into

        >>>       No user serviceable parts below.         <<<

by balancing the spaces +/-1? You can assume no tabs and the result should not contain tabs, but note that the first word may not start in column 1. (EDIT: ... in fact, both delimiter words as well as the start and end of the text to center may be on arbitrary columns.)


Solution

  • source this function:

    fun! CenterInSpaces()
        let l   = getline('.')
        let lre = '\v^\s*\S+\zs\s*\ze'
        let rre = '\v\zs\s*\ze\S+\s*$'
        let sp  = matchstr(l,lre)
        let sp  = sp.matchstr(l,rre)
        let ln  = len(sp)
        let l   = substitute(l,lre,sp[:ln/2-1],'')
        let l   = substitute(l,rre,sp[ln/2:],'')
        call setline('.',l)
    endf
    

    note

    • this function might NOT work in all cases. I just wrote it quick for usual case. this is not a plugin after all

    • the codes lines could be reduced by combining function calls. but i think it is clear in this way, so I just leave it like this.

    • if it worked for you, you could create a map

    • it works like this: (last two lines I typed @: to repeat cmd call)

    enter image description here