How to expand variables in vim commands?
Asked Answered
A

2

14

I'm trying to get a variable expanded in a command call. Here's what I have in my .vimrc:

command! -nargs=1 -complete=dir TlAddPm call s:TlAddPm(<f-args>)
function! s:TlAddPm(dir)
    let flist = system("find " . shellescape(a:dir) . " -type f -name '*.pm' | sort")
    TlistAddFiles `=flist`
endfun

At the : prompt, the `=flist` syntax seems to work (or, at least it did with a w: variable), but in the .vimrc file it doesn't — TlistAddFiles is just passed the string `=flist`.


Thanks to Andrew Barnett's and Mykola Golubyev's answers, I've now got this, which appears to work. Is there no better way?

command! -nargs=1 -complete=dir TlAddPm call s:TlAddPm(<f-args>)
function! s:TlAddPm(dir)
    let findres = system("find " . shellescape(a:dir) . " -type f -name '*.pm' | sort")
    let flist = []
    for w in split(findres, '\n')
        let flist += [ fnameescape(w) ]
    endfor
    exe "TlistAddFiles " . join(flist)
endfun
Ahrendt answered 20/3, 2009 at 15:51 Comment(5)
what is the definition of TlistAddFiles?Hurlburt
It's from the taglist plugin vim-taglist.sourceforge.netAhrendt
do you call s:TlAddPm(dir) from the .vimrc?Hurlburt
yes, I call it from .vimrc ... see the command! line (the first line in the code example)Ahrendt
Check out your code refactoring.Hurlburt
H
8

Try just

let joined = join(split(flist))
exec 'TlistAddFiles '.joined

To your edit:

 let flist = split(findres, '\n')
 call map(flist, 'fnameescape(v:val)')
Hurlburt answered 20/3, 2009 at 16:2 Comment(3)
TlistAddFiles flist just passes the string flist.Ahrendt
TlistAddFiles string(joined) .... passes string(joined). And the join() line complains that a list is required.Ahrendt
Yeah, the exec seems required.Ahrendt
M
4

Something like

exe "TlistAddFiles `=".flist

might work.

Manos answered 20/3, 2009 at 16:3 Comment(4)
Thats closer. Passes a string like View/JSON.pm^@View/TT.pm^@ ... just need to figure out how to split on null and also pass each to filenameescape.Ahrendt
FYI: I used exe "TlistAddFilesRecursive " . flist ... the `= stuff is weird syntax that makes the expansion work at the : prompt.Ahrendt
In that case, how about an 'xargs' at the end of your system string?Manos
Well, that'd make problems for file names with spaces in them. But I've come up with something that (while ugly) works... See the question update.Ahrendt

© 2022 - 2024 — McMap. All rights reserved.