Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vimscript function range only applying to the first line

Tags:

function

vim

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?

like image 242
jviotti Avatar asked Jan 28 '26 03:01

jviotti


1 Answers

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>.

like image 154
Ingo Karkat Avatar answered Jan 30 '26 21:01

Ingo Karkat