Neovim 插件 —— folke/flash.nvim

Table of Contents

介绍

在 Neovim 中,我们每天都在进行大量的光标移动操作。 无论是使用 h/j/k/l 逐行移动,还是通过 w/e/b/f/t 等 Vim 原生 motion 定位光标,这些操作都已经足够高效。 但当我们需要跳转到屏幕中距离较远的位置,或者在一段代码中快速定位某个特定位置时,传统的移动方式多少还是显得有些繁琐。

这时候,flash.nvim 就能派上用场了。

flash.nvim 是由 folke 开发的一款 Neovim 插件,它的核心思想非常简单:通过搜索目标,并为搜索结果分配一个简短的标签,让我们可以直接跳转到想去的位置。

这篇博客不会介绍 flash.nvim 的全部功能(因为我用到的功能可能不足百分之一),而是准备介绍我是如何使用它的。

配置

在 vim.pack 中安装:

-- lua/config/pack.lua

{ src = "https://github.com/folke/flash.nvim" },

我的配置:

展开看全部
local function _format_labels(opts)
  if opts.match.label2 then
    return {
      { opts.match.label1, "FlashLabel" },
      { opts.match.label2, "FlashMatch" },
    }
  else
    return {
      { opts.match.label1, "FlashLabel" },
    }
  end
end

local function _filter_folded_matches(matches)
  for i = #matches, 1, -1 do
    local line = matches[i].pos[1]
    local fold_start = vim.fn.foldclosed(line)
    if fold_start ~= -1 and fold_start ~= line then
      table.remove(matches, i)
    end
  end
end

local function _second_phase_jump(match, state, format_fn, label_opts)
  label_opts = label_opts or {}
  local Flash = require("flash")
  state:hide()
  Flash.jump({
    search = { max_length = 0 },
    highlight = { matches = false },
    label = vim.tbl_deep_extend("force", { format = format_fn }, label_opts),
    matcher = function(win)
      return vim.tbl_filter(function(m)
        return m.label1 == match.label1 and m.win == win
      end, state.results)
    end,
    labeler = function(matches)
      for _, m in ipairs(matches) do
        m.label1 = m.label2
        m.label2 = nil
        m.label = m.label1
      end
    end,
  })
end

local function jump_to_a_line(direction)
  direction = direction or "up"
  local Flash = require("flash")

  -- calc the viable lines
  local top = vim.fn.line("w0")
  local bottom = vim.fn.line("w$")
  local visible = bottom - top

  -- calc the head char
  local h = visible <= 26 and 0 or math.min(26, math.ceil((visible - 26) / 25))

  Flash.jump({
    search = { mode = "search", max_length = 0, multi_window = false },
    label = { after = { 0, 0 }, uppercase = false, format = _format_labels },
    pattern = "^",
    action = function(match, state)
      if match.label2 then
        _second_phase_jump(match, state, _format_labels, { after = { 0, -1 } })
      else
        state:hide()
        vim.api.nvim_win_set_cursor(match.win, { match.pos[1], match.pos[2] })
      end
    end,
    labeler = function(matches, state)
      _filter_folded_matches(matches)

      local labels = state:labels()
      local n = #matches
      local cursor_line = vim.fn.line(".")

      -- Build ordered indices: priority direction first (closest to cursor), then the rest
      local ordered = {}
      local primary = {} -- lines in the target direction
      local secondary = {} -- lines in the opposite direction

      if direction == "up" then
        for i = 1, n do
          if matches[i].pos[1] <= cursor_line then
            table.insert(primary, i)
          else
            table.insert(secondary, i)
          end
        end
        -- Reverse primary: closest to cursor first (matches are sorted ascending by line)
        for i = #primary, 1, -1 do
          table.insert(ordered, primary[i])
        end
        -- Secondary: below cursor, already in ascending order
        for _, idx in ipairs(secondary) do
          table.insert(ordered, idx)
        end
      else -- "down"
        for i = 1, n do
          if matches[i].pos[1] >= cursor_line then
            table.insert(primary, i)
          else
            table.insert(secondary, i)
          end
        end
        -- Primary: below cursor, already ascending (closest to cursor first)
        for _, idx in ipairs(primary) do
          table.insert(ordered, idx)
        end
        -- Reverse secondary: closest to cursor first (above cursor lines)
        for i = #secondary, 1, -1 do
          table.insert(ordered, secondary[i])
        end
      end

      -- Assign single-char labels to priority matches first
      local single_count = math.min(26 - h, n)
      for i = 1, single_count do
        local mi = ordered[i]
        matches[mi].label1 = labels[i]
        matches[mi].label2 = nil
        matches[mi].label = labels[i]
      end

      -- Assign double-char labels to remaining matches
      local idx = single_count + 1
      for header_i = 26 - h + 1, 26 do
        local header = labels[header_i]
        for second_i = 1, 26 do
          if idx > n then
            break
          end
          local mi = ordered[idx]
          matches[mi].label1 = header
          matches[mi].label2 = labels[second_i]
          matches[mi].label = header
          idx = idx + 1
        end
      end
    end,
  })
end

local function two_char_jump(opts)
  opts = opts or {}
  local target = opts.target or "start" -- "start" or "end"
  local Flash = require("flash")

  -- Patterns for word boundaries
  -- Beginnings: match the first char of each word segment, plus end of line
  -- Handles: start of line, after whitespace, after non-word chars, after underscore (snake_case), camelCase transitions
  local beginnings_pattern = [[\v((^|\s|\W)\zs\w|_\zs\w|\l\zs\u|$)]]
  -- Endings: match the last char of each word segment, plus end of line
  local endings_pattern = [[\v(\w\ze(\W|_)|\l\ze\u|$)]]
  local pattern = target == "end" and endings_pattern or beginnings_pattern

  Flash.jump({
    search = { mode = "search", multi_window = false },
    label = { after = false, before = { 0, 0 }, uppercase = false, format = _format_labels },
    pattern = pattern,
    action = function(match, state)
      _second_phase_jump(match, state, _format_labels)
    end,
    labeler = function(matches, state)
      _filter_folded_matches(matches)
      local labels = state:labels()
      for m, match in ipairs(matches) do
        match.label1 = labels[math.floor((m - 1) / #labels) + 1]
        match.label2 = labels[(m - 1) % #labels + 1]
        match.label = match.label1
      end
    end,
  })
end

require("utils.lazy").register({
  setup = function()
    vim.api.nvim_set_hl(0, "FlashLabel", { fg = "#ff007c", bold = true })
    vim.api.nvim_set_hl(0, "FlashMatch", { fg = "#7287fd" })
    require("flash").setup({
      labels = "asdghklqwertyuiopzxcvbnmfj",
      prompt = {
        prefix = { { " FlashSearch: ", "FlashPromptIcon" } },
      },
      search = {
        -- mode = "fuzzy"
      },
      jump = {
        pos = "end",
      },
    })
  end,
  -- stylua: ignore
  keys = {
    { { "n", "x", "o" }, "xx", function() require("flash").jump() end, { desc = "Flash" } },
    { { "n", "x", "o" }, "X", function() require("flash").treesitter() end, { desc = "Flash Treesitter" } },
    { "o", "r", function() require("flash").remote() end, { desc = "Remote Flash" } },
    { { "o", "x" }, "R", function() require("flash").treesitter_search() end, { desc = "Treesitter Search" } },
    { { "c" }, "<c-s>", function() require("flash").toggle() end, { desc = "Toggle Flash Search" } },
    { { "n", "v" }, "xh", function () two_char_jump({ target = "start" }) end, { desc = "Jump to word start" } },
    { { "n", "v" }, "xl", function () two_char_jump({ target = "end" }) end, { desc = "Jump to word end" } },
    { { "n", "v" }, "xj", function() jump_to_a_line("down") end, { desc = "Go to line below" } },
    { { "n", "v" }, "xk", function() jump_to_a_line("up") end, { desc = "Go to line above" } },
    { { "n", "v" }, "xw", function() require("flash").jump({ pattern = vim.fn.expand("<cword>") }) end, { desc = "Words" } },
    { { "n", "v" }, "xr", function() require("flash").jump({ continue = true }) end, { desc = "Resume" } },
  },
})

配置之所以这么长,是因为我自定义了一些辅助函数,来让 flash 的操作更加轻松。

因此先跳过开头定义的各种功能函数,直接看最下面的快捷键设置:

  keys = {
    { { "n", "x", "o" }, "xx", function() require("flash").jump() end, { desc = "Flash" } },
    { { "n", "x", "o" }, "X", function() require("flash").treesitter() end, { desc = "Flash Treesitter" } },
    { "o", "r", function() require("flash").remote() end, { desc = "Remote Flash" } },
    { { "o", "x" }, "R", function() require("flash").treesitter_search() end, { desc = "Treesitter Search" } },
    { { "c" }, "<c-s>", function() require("flash").toggle() end, { desc = "Toggle Flash Search" } },
    { { "n", "v" }, "xh", function () two_char_jump({ target = "start" }) end, { desc = "Jump to word start" } },
    { { "n", "v" }, "xl", function () two_char_jump({ target = "end" }) end, { desc = "Jump to word end" } },
    { { "n", "v" }, "xj", function() jump_to_a_line("down") end, { desc = "Go to line below" } },
    { { "n", "v" }, "xk", function() jump_to_a_line("up") end, { desc = "Go to line above" } },
    { { "n", "v" }, "xw", function() require("flash").jump({ pattern = vim.fn.expand("<cword>") }) end, { desc = "Words" } },
    { { "n", "v" }, "xr", function() require("flash").jump({ continue = true }) end, { desc = "Resume" } },
  },

这些快捷键就是我使用 flash 的全部入口。 flash 功能很多,但我实际在用的就这么几个。 不过它足够好用,已经覆盖了我编辑时的绝大部分场景。

输入,然后跳转

先看 flash 最核心的 jump 模式。以将触发键映射为 xx 为例:

{ { "n", "x", "o" }, "xx", function() require("flash").jump() end, { desc = "Flash" } },

按下 xx 后,屏幕会先“暗”下来:除搜索匹配之外的文本变灰,命令行出现 FlashSearch: 提示,等待你输入想找的字符。 这时只需要输入目标位置包含的字符,Flash 就会在当前可见区域内搜索所有匹配项,并为每一个匹配结果分配一个对应的字母标签。 匹配到的字符保持高亮,其余文本仍然灰着,目标位置旁边则会出现醒目的标签。

接下来,按下目标位置对应的标签,光标就会瞬间跳过去。

比如上面视频中:光标停在第 150 行,我想跳到第 168 行的 match 这个词上。 输入 match 后,Flash 会在当前窗口里找出所有匹配的 match,并给每个匹配项分配一个标签;只要按下目标 match 旁边对应的 g,光标就直接落过去了。

跳转到指定行

有时候,我们只想跳转到指定行,并不需要精确到单词粒度。这时可以按下 xj 或 xk:

{ { "n", "v" }, "xj", function() jump_to_a_line("down") end, { desc = "Go to line below" } },
{ { "n", "v" }, "xk", function() jump_to_a_line("up") end, { desc = "Go to line above" } },

比如上面的视频中:光标停在第 150 行,我想跳到第 177 行。输入 xj 后,每一行都会分配一个标签(单个或两个小写字符);按下对应标签,就能跳到目标行。 这个功能在可视模式下同样可用,复制或删除指定段落效率会高很多。

flash.nvim 其实在 README 中提供了 Jump to a line 的示例代码,但有一个问题:它的跳转标签可能会被分配为单个大写字符。 我个人觉得大写字符不好按,远不如两个小写字符顺手,所以专门写了 jump_to_a_line 和 two_char_jump 函数来实现这一功能。

它会优先从 asdghklqwertyuiopzxcvbnmfj 这个字符序列中按顺序分配标签; 当可跳转位点过多时,则启用两字符标签策略,且第一个字符固定为 f 或 j —— 这两个键正好位于左右手食指最舒适的位置。

这一习惯传承自 hop.nvim, 可惜它不能实现“先输入、再精准跳转”。 这一局,是 flash 胜了。:)

其他跳转方式

其他的一些跳转方式,我只会偶尔用一用,所以这里快速介绍:

{ { "n", "x", "o" }, "X", function() require("flash").treesitter() end, { desc = "Flash Treesitter" } },

按下 X 后,flash 会借助 Treesitter 为光标所在位置的各级语法节点(如表达式、语句、函数体)打上标签,按对应标签即可直接选中或跳转到该语法结构。

{ "o", "r", function() require("flash").remote() end, { desc = "Remote Flash" } },

在 operator pending 模式下按 r,可以先选中屏幕另一处的目标范围再执行待决操作(如删除、复制),完成后光标自动回到原位。

{ { "o", "x" }, "R", function() require("flash").treesitter_search() end, { desc = "Treesitter Search" } },

在 operator pending 或可视模式下按 R,先用 Treesitter 选中一个语法节点作为搜索模式,再为屏幕中所有同类节点打上标签,按标签即可跳转或对该语法结构执行操作。

{ { "n", "v" }, "xw", function() require("flash").jump({ pattern = vim.fn.expand("<cword>") }) end, { desc = "Words" } },

按下 xw 后,flash 会直接以光标当前所在单词为搜索模式,为屏幕中所有相同单词打上标签,按标签即可跳转,省去手动输入搜索字符的步骤。

{ { "n", "v" }, "xr", function() require("flash").jump({ continue = true }) end, { desc = "Resume" } },

在上一次搜索的基础上继续查找下一个匹配位置,而不必重新输入搜索字符,实现连续跳转。