How to search for text in a specific file type/extension in vim with FZF and Ag?

2.4k Views Asked by At

I have recently started using vim and i have been playing around with it for sometime now.

i use FZF with Ag to get searching files and searching in files done. but i am not able to search in particular file types for example

i want to search "getUserInfo" only in .js files.

here are my configs

bashrc

[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh
export FZF_DEFAULT_COMMAND='ag -g ""'
export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"

init.vim

Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'

i simply use :Ag in vim to search in entire directory

3

There are 3 best solutions below

1
On

Both of the other answers did not work for me, after digging through related issues to the one Gregory linked I found a solution that worked for me:

let s:ag_options = ' --python '

command! -bang -nargs=* Agpy call fzf#vim#ag(<qargs>,s:ag_options,<bang>0)

If you type

ag --list-file-types

Into the terminal you can determine what to replace --python with in the above example to capture the correct filetype.

Finally you simply type :Agpy or whatever you name the command into vim to execute.

This also executes in whatever your present working directory is, which is preferable to only a fixed directory in the other example.

1
On

You can use --js to restrict the search to JavaScript files:

$ ag getUserInfo --js

See $ man ag.

0
On

To use a file type search with FZF, you'll need to add a customized configuration in your .vimrc. For example, if you only wanted to search fo javascript files, you add this:

autocmd! VimEnter * command! -nargs=* -complete=file AgJS :call fzf#vim#ag_raw('--js '. <q-args> .' ~/myRepo/src/')

Note the specification of a directory (~/myRepo/src/). To invoke this kind of search, you'd use the :AgJS command. That command in turn, can be bound to some other mapping.

Customization is discussed in the plugin documentation: https://github.com/junegunn/fzf.vim#example-customizing-files-command

Your specific feature request was discussed in an issue: https://github.com/junegunn/fzf.vim/issues/92