imbichie
imbichie

Reputation: 1606

What is wrong with this simple vim function?

Please have a look to the below vim function which I written in my /.gvimrc file. The function id for deleting the "n" number of last characters in each line from the range of lines specified by "start_line" and "end_line".

function RLNC (n, start_line, end_line)
    execute . a:start_line . "," . a:end_line . "s/.\{" . a:n . "}$//"
endfunction

but when I make the same as a function and call it in the vim

:call RLNC(3, 128, 203)

This is the actual operation I am doing here

:start_line,end_lines/.\{n}$//

This is nothing but

:128,203s/.\{3}$//

Please help me to find what is going wrong..?

its is giving errors

Upvotes: 0

Views: 83

Answers (2)

imbichie
imbichie

Reputation: 1606

Thank for your reply, I am new to vim function and all. So I don't know much about the ":command!" and all. So I put it as function in the /.gvimrc file like below :

function RLNC (start_line, end_line, n)
  if (a:start_line <= a:end_line)
    execute printf(':%d,%ds/.\{%d}$//', a:start_line, a:end_line, a:n)
  else
    execute printf('Start line %d is more than End line %d ', a:start_line, a:end_line)
  endif
endfunction

and its working fine when I use the :call RLNC(128, 203, 3) in my gvim files.

Thanks You

Upvotes: 0

Ingo Karkat
Ingo Karkat

Reputation: 172570

The error is:

E15: Invalid expression: . a:start_line . "," . a:end_line . "s/.\{" . a:n . "}$//"

So, the first period is suspect. The :execute command takes (one or multiple) expressions. String concatenation via . is only done between strings, not at the beginning.

Just leave off the first .:

execute a:start_line . "," . a:end_line . "s/.\{" . a:n . "}$//"

The manual concatenation is tedious. Better use printf():

execute printf("%d,%ds/.\{%d}$//", a:start_line, a:end_line, a:n)

The next problem is that inside double quotes, the backslash must be escaped (doubled). Better use single quotes:

execute printf('%d,%ds/.\{%d}$//', a:start_line, a:end_line, a:n)

Finally, Vim has a special syntax to pass a range to a function. See :help function-range-example. You do not need to use this, but it makes the invocation more natural:

:128,203call RLNC(3)

However, I would probably go ahead and define a custom command wrapping the function.

:command! -range -nargs=1 RLNC call RLNC(<args>, <line1>, <line2>)

If your function isn't actually more complex, we can now inline this and get rid of the function altogether:

:command! -range -nargs=1 RLNC execute printf('%d,%ds/.\{%d}$//', <line1>, <line2>, <args>)

(Note that without a function, the last search pattern gets clobbered.)

Upvotes: 3

Related Questions