Skip to content

Instantly share code, notes, and snippets.

@chausies
Last active August 29, 2015 14:25
Show Gist options
  • Save chausies/dd8eba4ce9a75236b0cd to your computer and use it in GitHub Desktop.
Save chausies/dd8eba4ce9a75236b0cd to your computer and use it in GitHub Desktop.
Banner the current line/selection in vim. Uses tcomment plugin once to find the correct comment-style for the filetype.
" banner comments
fu! Banner(opt)
let l:l1 = line("'<")
let l:l2 = line("'>")
let l:spac = indent(line("."))-1
let l:lines = getline(l:l1, l:l2)
exe substitute(
\ substitute('%1d%2', "%1", l:l1, ""),
\ "%2", l:l2-l:l1+1, "")
let l:maxim = 0
for l in l:lines
if len(l) > l:maxim + l:spac
let l:maxim = len(l) - l:spac
endif
endfor
let l:s = tcomment#GetCommentDef(&ft)['commentstring']
if strpart(l:s, len(l:s)-2, 2) == "%s"
let l:t1 = strpart(l:s, 0, len(l:s)-2)
let l:t1 = join(reverse(split(l:t1, '\zs')), "")
let l:s = join([l:s, l:t1], "")
endif
let l:bar = repeat('-', l:maxim)
let l:lines = [l:bar] + l:lines + [l:bar]
let l:newlines = copy(l:lines)
let l:i = 0
for l in l:lines
let l:l = strpart(l, l:spac, len(l)-l:spac)
if a:opt == 'center'
let l:amt_left = l:maxim - len(l:l)
let l:beg_spac = l:amt_left/2
if l:amt_left % 2 == 0
let l:end_spac = l:amt_left/2
else
let l:end_spac = l:amt_left/2 + 1
endif
else
let l:beg_spac = 0
let l:end_spac = l:maxim - len(l:l)
endif
let l:temp = join([repeat(' ', l:beg_spac), l:l, repeat(' ', l:end_spac)], "")
let l:temp = substitute(l:s, "%s", l:temp, "")
if l:i == 0 || l:i == len(l:lines)-1
let l:temp = substitute(l:temp, '\s', '-', "g")
endif
let l:newlines[l:i] = join([repeat(' ', l:spac), l:temp, ], "")
let l:i = l:i + 1
endfor
call append(l1-1, l:newlines)
endfu
vmap <leader>bb <Esc>:call Banner("")<CR>
vmap <leader>bc <Esc>:call Banner("center")<CR>
nmap <leader>bb V<leader>bb
nmap <leader>bc V<leader>bc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment