created March 29, 2005 · complexity basic · author salmanhalim · version 5.7
Occasionally, when writing scripts, I have to use the setline functionality to change the contents of a line; more often than not, the cursor is already on the line that I want changed. Just to make life a little bit easier, I wrote a version of setline (called Setline) that does two things:
1. Changes the order of the input parameters so the text for replacement is provided before the line number.
2. If no line number is provided (only one parameter) it assumes you mean the current line -- I use this mode the most.
Otherwise, it is just a wrapper for the built-in setline and calls it after setting up the line number and swapping the order of the parameters.
Here is my wrapper for the built-in setline function:
function! Setline(...) let lineno=line('.') "check arguments if (a:0 < 1) return elseif (a:0 > 1) let lineno=a:2 endif return setline (lineno, a:1) endfunction
Here is a bit simpler version of your function:
function Setline(text,...) abort let l = ( a:0>0 ? a:1 : line('.') ) return setline(a:text,l) endfunction
I wrote mine a while ago, and for some reason, wanted something that wouldn't abort with an error. Your version, however, is truer to the original.
I probably didn't realize the existence of the ternary operator back when I wrote it, so melding your idea into mine:
function! ReplaceLine (...) return a:0 < 1 ? 1 : setline ( a:0 > 1 ? a:2 : line( '.' ), a:1 ) endfunction
Still does what I want (doesn't abort), but is a bit more efficient (ternary overload, of course).
1 if no argument specified (this is like a failed call to setline) The return from setline (probably 0, as the line number).