Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the return value from a function in a Vim command?

Tags:

vim

I'm trying to do something which sound super easy, but for some reason it's not working. The command:

:m 10

moves the current line to right below line 10, and

:echo line(".") - 2

prints out the line number of the line two lines up from the cursor. After reading the documentation, I wrote this command:

:m line(".") - 2

It resulted in this error:

M14: Invalid address

So I figured that functions aren't evaluated unless I use the = symbol, so I tried:

:m =line(".") - 2

Which gave me the same error. Just to be sure the spaces wasn't the cause, I tried:

:m =line(".")

Which still gives me the same error! What am I doing wrong here?


I have made sure that :m accepts integers and that line() returns integers.

:echo type(5)
0
:echo type(line("."))
0
like image 560
Hubro Avatar asked Jan 15 '13 22:01

Hubro


3 Answers

In order to evaluate an expression and pass it to a ex-mode command, you need to use the execute command. In your case, this works:

:execute "m" line(".") - 2

You can think of execute as a function taking a single variable "m" line(".") - 2. This variable is evaluated and then executed as a string in ex-mode.

For more help, see :help execute.

like image 68
Prince Goulash Avatar answered Nov 07 '22 05:11

Prince Goulash


I would suggest you use a relative address like so:

:m-2

For more help see:

:h range
like image 2
Peter Rincker Avatar answered Nov 07 '22 05:11

Peter Rincker


Actually, your original answer was almost right:

:m <C-R>=line(".") - 2

Would have worked. The other solutions are also correct, but you should take a look at the vim documentation about the expression register (:h quote_=) and I'm sure you'll find something interesting!

like image 1
Daan Bakker Avatar answered Nov 07 '22 06:11

Daan Bakker