5

Here is an example that I am working with. It is intended to add a boilerplate to a file, and then comment out those lines using Vim BlockComment() plugin function. The goal is to mark the line number before I read from the file and after I have completed reading from the file, so that I can comment out the range of lines just inserted.

However, I am having a time figuring out what the syntax should be to indicate that range. The commented line below is my attempt to call a function with a given range using variables. The commented part has a syntax error, but, if I provide a hard-coded range as shown below, the script works. How do we put my range in as a variable in this case?

function! AddBoilerPlate()
    let s:beginLine = line(".")
    r /Users/danieljbrieckjr/myBolierPlate.txt
    exe "normal! joDate Created: " . strftime("%B %d, %Y")
    exe "normal! oLast Modified: " . strftime("%B %d, %Y")

    let s:endLine = line(".")

"--------------------------------------------------
"     s:beginLine, s:endLine call Comment()
"-------------------------------------------------- 

    1,3 call Comment()

endfunction

1 Answer 1

13

One can prepare a string containing the target command, and then use :execute to run it:

:exec s:beginLine..','..s:endLine 'call Comment()'
Sign up to request clarification or add additional context in comments.

6 Comments

What if you need the return value of Comment()?
@StephenTalley: As far as I know, it is not possible. The simplest workaround is to create a helper function that takes the range line numbers as regular arguments, and call that the regular way.
@athos: It’s the string concatenation operator. It is indeed not strictly necessary here, as the :execute command concatenates all its arguments inserting spaces in between, and the Vim command syntax allows for spaces in line range expressions, so :exec s:beginLine ',' s:endLine 'call Comment()' would work just as well. It is simply my preference to pass line ranges to :execute as ready-made single-string arguments like that.
@ib. thanks for explanation. My confusion was, i thought the string concatenation operator is single dot ., but here comes a double dot .., after your explanation i googled and found .. is recommended for disambiguity. Learnt something new :)
@athos: Yeah, historically, it was just ., but at some point in Vim 8 (see :helpg Add "\.\.") the .. version was introduced for disambiguation, which is now the required syntax in Vim9 script and in the regular Vim script dialects starting with version 2 (see :h scriptversion-2). For backward compatibility, both the . and .. concatenation operators work in default Vim script.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.