Last Updated: February 25, 2016
·
563
· dradtke

Insert perfectly-centered headers in Vim

When organizing source code, it's often very helpful to insert large, easily-identifiable headers to indicate where sections begin and end. Unfortunately, text editors don't provide a built-in way to center text the way word processors do, but it's not too difficult to write up a quick method that will take care of the formatting for you.

For example, say that I want to insert headers like this in my Haskell source code (this would look much better if coderwall actually kept code blocks monospaced...):

module Main where

{----------------------------------------------------}
{-              Begin Important Stuff               -}
{----------------------------------------------------}

main = putStrLn "hello world"

If you count the spaces, you'll see that they're equal (well, nearly; the right side has one additional space because the title has an odd number of letters).

To let Vim handle counting spaces for you, put these in your .vimrc:

function! s:GetHeaderSpaceCount(str, n)
    return (a:n - len(a:str)) / 2
endfunction

function! GetHeader(str)
    let header_width = 80
    if &filetype =~ 'haskell'
        let sep = '{-'.repeat('-', header_width-4).'-}'
        let blank = repeat(' ', s:GetHeaderSpaceCount(a:str, header_width-4))
        let title = '{-'.blank.a:str.blank
        if (len(a:str) % 2) == 1
            let title = title.' '
        endif
        let title = title.'-}'
        return sep."\n".title."\n".sep
    else
        return 'Unrecognized filetype.'
    endif
endfunction

Then to insert a header, go into insert mode and type <Ctrl+R>=GetHeader("Begin Important Stuff") and hit Enter.

Other filetypes can easily be enabled by adding another check in the GetHeader method, and their logic will likely be very similar to the example I have for Haskell.

Enjoy your new centered headers!