1

This little snippet aims to make a little autocomplete script in VimL. the first code:

cat % | grep function | sed  's/(/ /g' | awk '{print $3}'

list all the method inside a php class. For example the output of this command could be:

__construct
__toString
foo
bar

If I send to complete function an array

call complete(col('.'), ["__construct", "__toString", "foo", "bar"])

I can see this menu:

enter image description here

So the final question is, ... how can I transform this:

__construct
__toString
foo
bar

into this ["__construct", "__toString", "foo", "bar"]?

Here my wrong code:

inoremap <F5> <C-R>=CustomComplete()<CR>
func! CustomComplete()
    let l:functions = system("cat % | grep function | sed  's/(/ /g' | awk '{print $3}'")
    call complete(col('.'), l:functions)
    return ''
endfunc
2
  • 1
    Couple of tangential points: a). Shouldn't it be $2? b). You don't need to use grep and sed in addition to awk: awk -F '[( ]' '/function/ {print $3}' does the same thing as your pipeline. The vim-slime guy even suggests replacing grep with awk entirely!
    – Rich
    Aug 17 '17 at 13:49
  • Ah, I see why you're using $3. Disregard query a). Sorry!
    – Rich
    Aug 17 '17 at 13:58
3

You can split() system() result into a list, or you can directly use systemlist().

BTW, I wouldn't have used a sequence of external programs. Looks like your code is equivalent (untested) to the following which I suspect to be more efficient than cat + grep + sed + awk:

let lines_with_functions = filter(getline(1, '$'), 'v:val =~ "function"')
let fnames = map(lines_with_functions, 'matchstr(v:val, "\\vfunction\\s+\\zs\\I\\i*\\ze\\s*\\(")')
2
  • when I press F5 is just si pasted in the file "cat: % No such file or directory"
    – sensorario
    Aug 17 '17 at 13:10
  • Indeed, you would have needed expand('%:p') instead of the string '%'. But honestly, we don't need system() here. Aug 17 '17 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.