Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing :endfunction error for vim function

Tags:

vim

In my vimrc file I am trying to write a function that take in two lines numbers as arguments and then comments out all the lines in that range. I am using a substitute for the start of the line '^' and replacing it with '#' which works fine when I call from outside a function. For the function I have this so far:

function Comment(line1, line2) a:line1,a:line2s/^/#/g endfunction

This is not working though and I am getting an error when I try to start Vim saying 'Missing :endfunction'

like image 377
user2802557 Avatar asked Oct 21 '25 02:10

user2802557


1 Answers

In your command:

a:line1,a:line2s/^/#/g

Some parts are variables (a:line1 and a:line2). They need to be evaluated. To do so, you can wrap every part of your command inside a string, except the variables, then concatenate all the parts with the dot operator, and finally pass the result to the command :execute to execute it as a regular Ex command:

execute a:line1.','.a:line2.'s/^/#/g'

If you need a command to call it, you could try this one:

function! Comment(line1, line2)
    execute a:line1.','.a:line2.'s/^/#/'
endfunction

command! -range=% Comment call Comment(<line1>,<line2>)

It defines the :Comment command which calls the function with the same name. It accepts a range, because it's defined with the -range attribute. If you don't provide a range to the command, it will use the whole buffer, because % (=1,$) is defined as the default range. See :h user-commands for more info.

To use the command, you could visually select some lines, then execute:

:'<,'>Comment

To use the function, assuming you wanted to comment the lines whose address are between 10 and 20, you could execute:

:call Comment(10,20)

It's not linked to your issue, but if you don't add a bang to the keyword function, every time you will source your script, you'll have the error:

E122: Function Comment already exists, add ! to replace it

Same thing for the command, you probably want to add a bang after the keyword command, otherwise you'll have the error:

E174: Command already exists: add ! to replace it
like image 165
user852573 Avatar answered Oct 25 '25 11:10

user852573



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!