简体   繁体   中英

Can't pass filepath as function argument in vim

I have this function in my vimrc:

function! MyFunc(fl)
  :!cat fl
" :!cat a:fl
" :!cat &fl
endfunction
command! -nargs=1 RunFunc :call MyFunc(<f-args>)

The problem is when I run :RunFunc ~/scripts/0-test in vim command, I get the error:

cat: f: No such file or directory
shell returned 1

I have looked at various websites like this , this , this , this and this , but none worked for me.

First, you don't need that colon in a scripting context:

function! MyFunc(fl)
  !cat fl
endfunction
command! -nargs=1 RunFunc :call MyFunc(<f-args>)

Second, you can't pass an expressions like that. You need to concatenate the whole thing with :help:execute :

function! MyFunc(fl)
  execute "!cat " .. fl
endfunction
command! -nargs=1 RunFunc :call MyFunc(<f-args>)

Third, function arguments are typed with a: :

function! MyFunc(fl)
  execute "!cat " .. a:fl
endfunction
command! -nargs=1 RunFunc :call MyFunc(<f-args>)

As for websites… they are useless. Vim comes with an exhaustive documentation that should be your first hit when stumbling on something and it just so happens that the user manual—which is mandatory reading—has a whole chapter on writing vimscript: :help usr_41.txt .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM