强曰为道

与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

15 - Telescope 模糊搜索

“Telescope is not just a fuzzy finder — it’s a framework for building pickers.”

15.1 Telescope 概览

15.1.1 架构

Telescope
├── Pickers(选择器)
│   ├── find_files      → 文件搜索
│   ├── live_grep       → 实时文本搜索
│   ├── buffers         → 缓冲区列表
│   ├── help_tags       → 帮助标签
│   ├── git_files       → Git 文件
│   ├── git_status      → Git 状态
│   ├── lsp_references  → LSP 引用
│   ├── lsp_definitions → LSP 定义
│   └── 自定义 Picker
├── Sorters(排序器)
│   ├── fzf             → FZF 算法
│   └── 内置排序器
└── Previewers(预览器)
    ├── buffer_previewer → 缓冲区预览
    └── terminal_previewer → 终端预览

15.1.2 与其他搜索工具对比

工具模糊搜索文件搜索文本搜索可扩展预览
Telescope
fzf.vim⚠️
CtrlP⚠️
LeaderF⚠️

15.2 安装与配置

15.2.1 基本安装

{ "nvim-telescope/telescope.nvim",
    cmd = "Telescope",
    dependencies = {
        "nvim-lua/plenary.nvim",
        { "nvim-telescope/telescope-fzf-native.nvim",
            build = "make",
            config = function()
                require("telescope").load_extension("fzf")
            end,
        },
    },
    keys = {
        { "<leader>ff", "<cmd>Telescope find_files<cr>", desc = "查找文件" },
        { "<leader>fg", "<cmd>Telescope live_grep<cr>", desc = "搜索文本" },
        { "<leader>fb", "<cmd>Telescope buffers<cr>", desc = "缓冲区" },
        { "<leader>fh", "<cmd>Telescope help_tags<cr>", desc = "帮助" },
        { "<leader>fo", "<cmd>Telescope oldfiles<cr>", desc = "最近文件" },
        { "<leader>fw", "<cmd>Telescope grep_string<cr>", desc = "搜索单词" },
        { "<leader>fd", "<cmd>Telescope diagnostics<cr>", desc = "诊断" },
        { "<leader>fs", "<cmd>Telescope lsp_document_symbols<cr>", desc = "文档符号" },
        { "<leader>fr", "<cmd>Telescope resume<cr>", desc = "恢复上次搜索" },
    },
    opts = {
        defaults = {
            prompt_prefix = "  ",
            selection_caret = " ",
            path_display = { "truncate" },
            layout_config = {
                horizontal = { prompt_position = "top", preview_width = 0.55 },
                vertical = { mirror = false },
                width = 0.87,
                height = 0.80,
                preview_cutoff = 120,
            },
            sorting_strategy = "ascending",
            file_ignore_patterns = { "%.git/", "node_modules/", "__pycache__/" },
        },
    },
}

15.3 内置 Picker

15.3.1 文件相关

Picker命令用途
find_filesTelescope find_files搜索文件名
git_filesTelescope git_filesGit 跟踪的文件
oldfilesTelescope oldfiles最近打开的文件
file_browser需要扩展文件浏览器

15.3.2 文本搜索

Picker命令用途
live_grepTelescope live_grep实时搜索文本
grep_stringTelescope grep_string搜索光标下的单词
current_buffer_fuzzy_find当前缓冲区搜索模糊搜索当前文件

15.3.3 Git

Picker命令用途
git_commitsTelescope git_commits提交历史
git_bcommitsTelescope git_bcommits当前文件提交历史
git_branchesTelescope git_branches分支列表
git_statusTelescope git_status文件变更状态

15.3.4 LSP

Picker命令用途
lsp_references引用查找引用
lsp_definitions定义跳转定义
lsp_implementations实现查找实现
lsp_document_symbols文档符号大纲
lsp_workspace_symbols工作区符号全项目搜索符号
diagnostics诊断查看诊断

15.4 Telescope 内操作

15.4.1 默认快捷键

按键模式功能
<C-n> / <Down>Insert/Normal下一项
<C-p> / <Up>Insert/Normal上一项
<CR>Insert/Normal选择
<C-x>Insert/Normal水平分割打开
<C-v>Insert/Normal垂直分割打开
<C-t>Insert/Normal标签页打开
<C-u>Insert清空搜索
<C-w>Insert删除前一个词
<Esc>Insert回到 Normal
qNormal关闭
<Tab>Normal切换选中
<S-Tab>Normal反向切换选中
<C-q>Normal发送到 quickfix

15.4.2 多选

" 在 Telescope 中多选文件并批量操作
<Tab>       " 选择/取消选择
<S-Tab>     " 反向选择
<C-q>       " 将所有选中项发送到 quickfix
" 然后使用 :cdo 批量操作

15.5 Telescope 扩展

15.5.1 常用扩展

-- fzf-native(更快的排序)
{ "nvim-telescope/telescope-fzf-native.nvim", build = "make" }

-- file-browser(文件管理)
{ "nvim-telescope/telescope-file-browser.nvim" }

-- ui-select(替换 vim.ui.select)
{ "nvim-telescope/telescope-ui-select.nvim" }

-- 加载扩展
require("telescope").load_extension("fzf")
require("telescope").load_extension("file_browser")
require("telescope").load_extension("ui_select")

15.5.2 ui-select

-- 用 Telescope 替换 vim.ui.select 选择菜单
require("telescope").setup({
    extensions = {
        ["ui-select"] = {
            require("telescope.themes").get_dropdown({}),
        },
    },
})
require("telescope").load_extension("ui_select")

15.6 自定义 Picker

local pickers = require("telescope.pickers")
local finders = require("telescope.finders")
local conf = require("telescope.config").values
local actions = require("telescope.actions")
local action_state = require("telescope.actions.state")

-- 自定义 Picker:搜索 Neovim 配置文件
local function config_files()
    pickers.new({}, {
        prompt_title = "Config Files",
        finder = finders.new_oneshot_job(
            { "find", vim.fn.stdpath("config"), "-type", "f" },
            {}
        ),
        sorter = conf.generic_sorter({}),
        attach_mappings = function(prompt_bufnr, map)
            actions.select_default:replace(function()
                local selection = action_state.get_selected_entry()
                actions.close(prompt_bufnr)
                vim.cmd("edit " .. selection[1])
            end)
            return true
        end,
    }):find()
end

vim.keymap.set("n", "<leader>fc", config_files, { desc = "配置文件" })

15.7 主题(Theme)

-- 使用 dropdown 主题
vim.keymap.set("n", "<leader>ff", function()
    require("telescope.builtin").find_files({
        theme = "dropdown",
        previewer = false,
    })
end, { desc = "查找文件" })

-- 使用 ivy 主题
vim.keymap.set("n", "<leader>fg", function()
    require("telescope.builtin").live_grep({
        theme = "ivy",
    })
end, { desc = "搜索文本" })

15.8 ripgrep 配置

defaults = {
    vimgrep_arguments = {
        "rg",
        "--color=never",
        "--no-heading",
        "--with-filename",
        "--line-number",
        "--column",
        "--smart-case",
        "--hidden",        -- 搜索隐藏文件
        "--glob=!.git/",   -- 排除 .git
    },
},

15.9 业务场景

场景Picker
打开文件find_files / git_files
搜索代码live_grep
搜索单词grep_string
查看引用lsp_references
跳转定义lsp_definitions
浏览符号lsp_document_symbols
查看诊断diagnostics
浏览提交git_commits
切换分支git_branches
最近文件oldfiles

15.10 总结

概念要点
Picker搜索行为的封装
Finder数据源(job/静态/动态)
Sorter排序算法
Previewer预览窗口
扩展fzf, file-browser, ui-select

下一步第 16 章 - Git 集成 → 在 Neovim 中高效使用 Git。


扩展阅读