centering and filling multiple space with # in VIM

Viewed 95

I want to make some nice separation between different parts of the file in Vim :

I want to fill a line by #'s and then write in the center my title :

############################## Centered Title ################################

So, for now (since by default the terminal is 80 characters wide), I do

i (insert mode)
# 
esc
79 . 

Which makes a line of #'s.

Then I have to count the width of my title, compute the starting point, go to the computed starting point and replace with R.

It is a bit tedious ... In the other hand, I know to center a text in VIM by using :center in visual mode.

Is it possible to combine both to have more directly what I am looking for ?

1 Answers

As answers in linked thread does not contain explained vimscript solution I would share the one I wrote at that moment.

function Foo()
    let title = input('Title: ')
    put =title
    center
    let line=getline(line('.'))
    let spaces = matchstr(line, '^\s*\ze\s')
    let prefix = substitute(spaces, ' ', '#', 'g')
    call setline(line('.'), prefix . ' ' . trim(line) . ' ')
    normal 80A#
    normal d80|
endfunction

noremap <leader>x :call Foo()<cr>
let title = input('Title: ') -> Function that ask for title and store it in var
put =title -> paste content to current line
center -> center it to fill beginning with spaces
let line=getline(line('.')) -> get content of current line into variable
let spaces = matchstr(line, '^\s*\ze\s') -> stores all whitespaces expect last one into variable
let prefix = substitute(spaces, ' ', '#', 'g') -> converts spaces to #
call setline(line('.'), prefix . ' ' . trim(line) . ' ') -> changes content of current line
normal 80A# -> append many # at the end of line
normal d80| -> delete everything after 80 column
Related