I'm experimenting with creating my own commenting function, for vimscript learning purposes.
I've did the following:
function! Comment() range
for line_number in range(a:firstline, a:lastline)
let current_line = getline(line_number)
let current_line_commented = substitute(current_line, '^', '# ', "")
call setline(line_number, current_line_commented)
endfor
endfunction
command! -range Comment call Comment()
However when calling the command with a given range (:'<,'>Comment) only the first line of the selection gets the # added in front, and no other errors are reported.
What am I missing to get every line from the range substituted?
Unlike a mapping (that when invoked in visual mode automatically gets the :'<,'> prepended to the function :call), a custom command needs to be passed the range explicitly:
command! -range Comment <line1>,<line2>call Comment()
:help :command-range unfortunately only mentions the related <count>, but you'll find the information further down at :help <line1>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With