VIM script for voluminous multi-line comment with comment

For comments on the header style (including the main new sections of code in 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 is a long multi-line comment (as is often the case in descriptive headings), this may take a minute. This is such a trivial task that I would like to automate. My goal is to write a script that allows me to select a range (in visual mode), enter a command and enter a comment character, as a result of which the selected lines are placed in the field as shown above. I made several attempts on a VIM script, but to be honest, I never wrote a VIM script, my code is a mess, and I think that it really harms the reason to post it.

Any suggestions on how to do this?

+4
source share
2 answers

you don’t need “minutes” to do this job. with choosing a vim block ctrl-vwith I or cand r (replace)you could do it pretty easily. However, if you need to do this 100 times a day, this little function can 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

specify this file, note that

  • g:wrap_charyou can set any char for your border, here I used #.
  • you can visually select strings and wrap them with char
  • you can specify a range on the command line by calling the function
  • you could create your own command as a shell of this function or create mappings

A small demonstration:

enter image description here

+6
source
0

All Articles