Wikia

Vim Tips Wiki

Changes: Convenience wrapper for setline

Edit

Back to page

(Move categories to tip template)
(Remove html character entities)
 
Line 26: Line 26:
 
let lineno=line('.')
 
let lineno=line('.')
 
"check arguments
 
"check arguments
if (a:0 < 1)
+
if (a:0 < 1)
 
return
 
return
elseif (a:0 &gt; 1)
+
elseif (a:0 > 1)
 
let lineno=a:2
 
let lineno=a:2
 
endif
 
endif
Line 40: Line 40:
 
<pre>
 
<pre>
 
function Setline(text,...) abort
 
function Setline(text,...) abort
let l = ( a:0&gt;0 ? a:1 : line('.') )
+
let l = ( a:0>0 ? a:1 : line('.') )
 
return setline(a:text,l)
 
return setline(a:text,l)
 
endfunction
 
endfunction
Line 53: Line 53:
 
<pre>
 
<pre>
 
function! ReplaceLine (...)
 
function! ReplaceLine (...)
return a:0 &lt; 1 ? 1 : setline ( a:0 &gt; 1 ? a:2 : line( '.' ), a:1 )
+
return a:0 < 1 ? 1 : setline ( a:0 > 1 ? a:2 : line( '.' ), a:1 )
 
endfunction
 
endfunction
 
</pre>
 
</pre>

Latest revision as of 23:28, September 29, 2008

Tip 904 Printable Monobook Previous Next

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

CommentsEdit

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

Returns:

1 if no argument specified (this is like a failed call to setline) The return from setline (probably 0, as the line number).


Around Wikia's network

Random Wiki