How to use return value from function in Vim command?

I am trying to make something very simple, but for some reason it does not work. Command:

:m 10 

moves the current line to the right below line 10 and

 :echo line(".") - 2 

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

 :m line(".") - 2 

This led to an error:

M14: Invalid address

So, I realized that functions are not evaluated unless I use the = symbol, so I tried:

 :m =line(".") - 2 

Which gave me the same error. To be sure that the spaces were not the cause, I tried:

 :m =line(".") 

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


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

 :echo type(5) 0 :echo type(line(".")) 0 
+4
source share
3 answers

To evaluate the expression and pass it to the 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 with one variable "m" line(".") - 2 . This variable is evaluated and then executed as a string in ex-mode.

See :help execute more details.

+4
source

I would suggest you use a relative address:

 :m-2 

For more help see:

 :h range 
+2
source

Actually, your initial answer was almost right:

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

It would work. Other solutions are also correct, but you should take a look at the vim documentation on the case of expressions ( :h quote_= ), and I'm sure you will find something interesting!

+1
source

All Articles