Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM script to surround multiline comment with comment character

Tags:

vim

For header style comments (including major new sections of code within the file) at my place of work, we use the following standard:

##################################
# This is a multiline comment    #
# and we've surrounded it by the #
# comment symbol.                #
##################################

When there's a lengthy multiline comment (as there so often is in descriptive headers), this can take a minute. It's such a trivial task that I'd like to automate it. My goal is to write a script that allows me to select a range (in visual mode), enter the command, and enter the comment character, resulting in enclosing the selected lines in a box like above. I've made some attempts at a VIM script, but honestly, having never written a VIM script before, my code is a mess, and I think it would actually be detrimental to the cause to post it.

Any suggestions as to how to go about building this?

like image 393
Andrew LaPrise Avatar asked Jan 12 '23 11:01

Andrew LaPrise


1 Answers

you don't need "minutes" to do that job. with vim's ctrl-v block selection with I or c and r (replace) you could do that pretty easy. However if you need do it 100 times a day, this little function may help you:

let g:wrap_char = '#'
function! WrapThem() range
    let lines = getline(a:firstline,a:lastline)
    let maxl = 0
    for l in lines
        let maxl = len(l)>maxl? len(l):maxl
    endfor
    let h = repeat(g:wrap_char, maxl+4)
    for i in range(len(lines))
        let ll = len(lines[i])
        let lines[i] = g:wrap_char . ' ' . lines[i] . repeat(' ', maxl-ll) . ' ' . g:wrap_char
    endfor  
    let result = [h]
    call extend(result, lines)
    call add(result,h)
    execute a:firstline.','.a:lastline . ' d'
    let s = a:firstline-1<0?0:a:firstline-1
    call append(s, result)
endfunction

source that file, note that

  • the g:wrap_char you could set any char for your border, here I used #.
  • you can visual select lines and wrap them with the char
  • you can give range in command line by calling the function
  • you could create your own command as a wrapper of that function or create mappings

A little demo:

enter image description here

like image 170
Kent Avatar answered Jan 28 '23 20:01

Kent