Hubro
Hubro

Reputation: 59313

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

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

Upvotes: 10

Views: 2882

Answers (3)

Daan Bakker
Daan Bakker

Reputation: 6332

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!

Upvotes: 1

Peter Rincker
Peter Rincker

Reputation: 45087

I would suggest you use a relative address like so:

:m-2

For more help see:

:h range

Upvotes: 2

Prince Goulash
Prince Goulash

Reputation: 15715

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.

Upvotes: 9

Related Questions