Use fzf.vim to Show Search Result in Vim

Why fzf.vim

Even though I am a Vimer. I prefer complete solutions, with boundless possible of customization, for coding with Vim (actually NeoVim which I use).

The plugin fzf.vim is such a strong performer of them. It can not only help you search files, contents from files, tags or windows, but also provide you features to change the themes of your editor in it just like a GUI editor do.

Some Searching Tricks

You should spend some time on learning how to use fzf.vim smoothly if you have no experience of using fzf. Now, let me show you some tricks.

Respecting .gitignore

TL;DR

Add this line in your .vimrc:

1
let $FZF_DEFAULT_COMMAND = 'rg --files'

Here Is Why

Let’s say we have a rust project with target directory. When calling :Files we find all files even though those in the directory target which we expected ignored by specified in .gitignore.

image.png

Because the fzf does not understand the .gitignore. Let us reproduct it in command line with fzf.

image.png

But don’t be sad. We can config it to out purpose. Before that, we need a searching engine which respect .gitignore, such as the silver searcher or ripgrep. Let’s use ripgrep (called rg as usual) as an example.

We can use the command rg --files to list all files without those ignored by .gitignore. And we can list them in fzf with rg --files | fzf.

Now we just need to specify the fzf.vim use the command rg --files to search as default.

1
let $FZF_DEFAULT_COMMAND = 'rg --files'

Let’s have a look at the result now.

image.png

By The Way

If you perfer ag, try this:

1
let $FZF_DEFAULT_COMMAND = 'ag -g ""'

Tips with rg

If you use rg as default search engine in fzf, you will find all hidden files are excluded. You need to add --hidden to show them.

1
let $FZF_DEFAULT_COMMAND = 'rg --files --hidden'

And now, all hidden files which not ignored by .gitignore are shown. But wait a minute, all files in .git directory are shown too! Most of time, this is not our purpose. But only the way can solve it is adding .git into .gitignore directly. Please comment if you find a better way!

Filter By Content

If we try to search content in your project with fzf using :Rg. The result will like below.

image.png

But all results match the pattern are shown even though the results matching the filename. How can we get the results only match with content? Just use . in your pattern. The characters before . will be known as a pattern for filename and as content pattern after ..

Let’s have a try which filter only with content, such as .arg.

image.png

What about arg. for only filename?

image.png

Reference