Daniel Wu
Daniel Wu

Reputation: 6003

function failed when call it from a command in vim

When I find the word in the current file, I need to first type "/keyword", but I can't see all the matched rows, So I tried to use the following command to do a shortcut, but it doesn't work, could you please help check why it failed?

function! FindCurrentFile(pattern)
    echo a:pattern
    execute ":vimgrep" . a:pattern . " %"
    execute ":cw"
endfunction

command! -nargs=1 Fi call FindCurrentFile(<args>)

Upvotes: 0

Views: 115

Answers (3)

glts
glts

Reputation: 22734

By the way, if you just need a quick overview over the matches you can simply use

:g//print

or

:g//p

(You may even leave out the p completely, since :print is the default operation for the :global command.)

When the current buffer has line numbers turned off, the results produced by :g//p can be difficult to take in fast. In that case use :g//# to show the matches with the line numbers.

Another trick that works for keywords is the normal mode command [I. It shows a quick overview of all the instances of the keyword under the cursor in the current buffer. See :h [I.

Upvotes: 3

Kent
Kent

Reputation: 195229

try to change the line in your function into this:

execute ':vimgrep "' . a:pattern . '" ' . expand("%")

Upvotes: 2

Idan Arye
Idan Arye

Reputation: 12633

<args> is replace with the command argument as is - that means that if you write:

Fi keyword

the command will run:

call FindCurrentFile(keyword)

which is wrong - because you want to pass the string "keyword", not a variable named keyword.

What you need is <q-args>, which quotes the argument.

BTW, if you wanted more than one argument, you had to use <f-args>, which quotes multiple arguments and separates them with ,.

Upvotes: 2

Related Questions