TomCaps
TomCaps

Reputation: 2527

How to get a function's return value after the :e command in Vim

I wrote a function to get the full path of the current file under the cursor

nmap <F12> :echo GetFullPath()<cr>
function! GetFullPath()
    let currentFile=expand("<cfile>")
    let afterChangeSlash=substitute(currentFile,"/","\\","g")
    let fullPath="e:\\Test\\".afterChangeSlash
    return fullPath
endfunction

When I call the function after the :echo command, I get the expected result,like:

:echo GetFullPath()

e:\Test\test.h

However,When I call it after the :e(edit) command:

:e GetFullPath()

Vim just create a new file named GetFullPath()

Why the command :e will treat a function call literally while the command :echo won't?

Upvotes: 3

Views: 1014

Answers (2)

sidyll
sidyll

Reputation: 59277

You can use :execute to build your ex command string and execute it:

:exe "e ".GetFullPath()

Or use the `=` syntax to expand a Vim expression:

:e `=GetFullPath()`

If you check the help for :edit and :echo, you'll notice that the former expects its argument to be the file name (literally), while :echo expects an expression which will be evaluated.

Upvotes: 6

holygeek
holygeek

Reputation: 16185

Some ex commands expect to be given an expression, while some others expect to be given a string. For your case to make it work use exec:

nmap <F12> :exec 'e ' . GetFullPath()

Upvotes: 0

Related Questions