fzf是Linux終端下的一款模糊搜索神器,速度極快,還可以配合vim以及其他軟件使用,可以說是終端黨的必備神器。雖然它安裝起來比 較簡單,但是想要使用得比較好,還是需要一番配置的,但是我看網(wǎng)上配置的文章都寫得比較簡單,所以寫這篇文章記錄一下。
安裝
fzf可以單獨(dú)安裝,不過我推薦在vim中和fzf.vim一起安裝,比較方便而且簡單,我使用的vim plug管理插件,所以在vim配置文件里添加 以下兩行就可以了。
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
然后在vim下執(zhí)行:PlugInstall,它就開始安裝了,安裝過程中會問你幾個(gè)問題,都按y就好了。
安裝完成后就可以開始使用了,但是現(xiàn)在使用起來并不是很爽,因?yàn)闆]有預(yù)覽,不能搜索隱藏文件,而且只能搜索當(dāng)前目錄,還不能排除一些亂七八糟的文件夾,經(jīng)過配置之后這些都可以解決。
配置
在使用之前首先要安裝兩個(gè)軟件,fdfind(也有可能叫fd)和rg(ripgrep)還有 bat(一個(gè)文本 預(yù)覽工具,類似于cat,但是比它更強(qiáng)大)。然后在.zshrc文件下添加以下設(shè)置。
###
###FZF
###
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh
export FZF_DEFAULT_COMMAND='fdfind --hidden --follow -E ".git" -E "node_modules" . /etc /home'
export FZF_DEFAULT_OPTS='--height 90% --layout=reverse --bind=alt-j:down,alt-k:up,alt-i:toggle+down --border --preview "echo {} | ~/linux-config-file/fzf/fzf_preview.py" --preview-window=down'
# use fzf in bash and zsh
# Use ~~ as the trigger sequence instead of the default **
#export FZF_COMPLETION_TRIGGER='~~'
# Options to fzf command
#export FZF_COMPLETION_OPTS=''
# Use fd (https://github.com/sharkdp/fd) instead of the default find
# command for listing path candidates.
# - The first argument to the function ($1) is the base path to start traversal
# - See the source code (completion.{bash,zsh}) for the details.
_fzf_compgen_path() {
fdfind --hidden --follow -E ".git" -E "node_modules" . /etc /home
}
# Use fd to generate the list for directory completion
_fzf_compgen_dir() {
fdfind --type d --hidden --follow -E ".git" -E "node_modules" . /etc /home
}
- 前面有#號的是注釋
- FZF_DEFAULT_COMMAND是用來列出文件以供fzf搜索的命令
- --hidden:允許搜索隱藏文件
- -E:后面跟的目錄不會被搜索,用來排除一些沒什么用的目錄
- 最后的/etc和/home就是會在這兩個(gè)目錄里進(jìn)行搜索,你也可以添加其它目錄
- FZF_COMPLETION_OPTS是fzf搜索時(shí)的默認(rèn)參數(shù)
- --height:搜索窗口占屏幕的比例
- --layout=reverse:默認(rèn)搜索欄在底部,設(shè)置后搜索欄在上面
- --bind:用來更改默認(rèn)快捷鍵的,格式就是 快捷鍵:動作 設(shè)置之間用逗號分隔
- --preview:預(yù)覽命令,后面的python文件是我自己寫的Python腳本路徑,可以實(shí)現(xiàn)一些文件的預(yù)覽
- --preview-window:預(yù)覽窗口的位置,默認(rèn)在右邊,我設(shè)置到下邊
- FZF_COMPLETION_TRIGGER:在終端觸發(fā)fzf的快捷鍵,默認(rèn)是**
- 最下面兩個(gè)命令就是終端使用的時(shí)候的列出文件的命令,其實(shí)和上面的是一樣的,只是下面的那個(gè)是只列出文件夾,所以多了一個(gè)--type參數(shù)
下面是我自己寫的預(yù)覽腳本的內(nèi)容,你得把它復(fù)制到文件里,授予執(zhí)行權(quán)限,放到合適的路徑,然后用你的路徑替換上面我的路徑,大佬請忽略我亂七八糟的語法和謎一般的命名。
#! /usr/bin/python3
import os
import sys
def fzf_preview(rg_name):
rg_list = rg_name.split(':')
if len(rg_list) == 1:
bat_range = 0
else:
bat_range = rg_list[1].replace('\n', '')
file_path_list = rg_list[0].replace('\n', '').split('/')
for i,filep in zip(range(len(file_path_list)), file_path_list):
path_space = filep.find(' ')
if not path_space == -1:
file_path_list[i] = "'{}'".format(filep)
file_path = '/'.join(file_path_list)
preview_nameandline = [file_path, bat_range]
return preview_nameandline
if __name__ == "__main__":
rg_name = sys.stdin.readlines()[0]
preview_nameandline = fzf_preview(rg_name)
if os.path.isdir(preview_nameandline[0]):
os.system('ls -la {}'.format(preview_nameandline[0]))
elif preview_nameandline[0].replace("'", '').endswith(('.zip', '.ZIP')):
os.system('unzip -l {}'.format(preview_nameandline[0]))
elif preview_nameandline[0].replace("'", '').endswith(('.rar', '.RAR')):
os.system('unrar l {}'.format(preview_nameandline[0]))
elif preview_nameandline[0].replace("'", '').endswith('.torrent'):
os.system('transmission-show {}'.format(preview_nameandline[0]))
elif preview_nameandline[0].replace("'", '').endswith(('.html', '.htm', '.xhtml')):
os.system('w3m -dump {}'.format(preview_nameandline[0]))
else:
os.system('bat --style=numbers --color=always -r {}: {}'.format(
preview_nameandline[1], preview_nameandline[0]))
使用
終端中使用
- 在終端直接執(zhí)行
fzf,搜索到文件后會返回文件的絕對路徑

- 在終端使用快捷鍵觸發(fā),在任何需要使用路徑的地方都可以用
nvim **<tab>
- kill命令進(jìn)程搜索,這個(gè)是真的好用
kill -9 <tab>
在vim中使用
- 使用
:Files命令開始搜索文件,找到后回車打開

- 使用
:Rg對文本內(nèi)容進(jìn)行模糊搜索,厲害了

然后你可以將這兩個(gè)命令綁定到快捷鍵上,這樣你就可以享受fzf所帶來的便利了。
和ranger配合使用
ranger是一個(gè)終端下的文件瀏覽器,和它配合使用可以實(shí)現(xiàn)文件的尋找并快速跳轉(zhuǎn)。
ranger默認(rèn)安裝完成后沒有配置文件,需要執(zhí)行ranger --copy-config=all來生成默認(rèn)配置文件。文件路徑在~/.config/ranger?,F(xiàn)在可以開始添加配置到commands.py,官方的配置你可以在 這里 找到,但是官方的命令并不好用,所以我進(jìn)行了一些修改,如下:
# use fzf in ranger
class fzf_select(Command):
"""
:fzf_select
Find a file using fzf.
With a prefix argument select only directories.
See: https://github.com/junegunn/fzf
"""
def execute(self):
import subprocess
import os.path
if self.quantifier:
# match only directories
command='fdfind --type d --hidden --follow -E ".git" -E "node_modules" . /etc /home/tom | fzf +m'
else:
# match files and directories
command='fdfind --hidden --follow -E ".git" -E "node_modules" . /etc /home/tom | fzf +m'
fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE)
stdout, stderr = fzf.communicate()
if fzf.returncode == 0:
fzf_file = os.path.abspath(stdout.rstrip('\n'))
if os.path.isdir(fzf_file):
self.fm.cd(fzf_file)
else:
self.fm.select_file(fzf_file)
添加完成之后你就可以通過:fzf_select命令來在ranger中啟動fzf查找,并自動跳轉(zhuǎn)了。當(dāng)然你可以把這個(gè)命令綁定到一個(gè)快捷鍵上,通過在rc.conf中添加以下配置。
# 將fzf查找綁定到ctrl+f鍵,最好添加到注釋Searching后面,我之前添加到前面沒有生效,不知道為什么
map <C-f> fzf_select
目前尚未解決的問題,在nvim中使用Rg進(jìn)行文本內(nèi)容搜索時(shí)依然只能搜索當(dāng)前文件夾,并且無法搜索隱藏文件
問題解決
2020/9/14, 搜索隱藏文件的問題已解決, 在init.vim中加上以下內(nèi)容
command! -bang -nargs=* Rg
\ call fzf#vim#grep(
\ "rg --column --line-number --no-heading --color=always --smart-case --hidden -g '!**/.git/**' -- ".shellescape(<q-args>), 1, <bang>0)
# --hidden: 顯示隱藏文件
# -g '!**/.git/**': 排除所有.git文件夾