neovimfzf

Configure LazyNvim to search only within lines containing a regex


I'd like to configure a keymap which searches within lines which start with the word "class".

When I was using fzf.nvim I used to have something like this:

# "[F]ind [A]nywhere [C]lass
nnoremap <leader>fac :Rg '^ *class '

This would launch a nice hover window with the results already filtered for lines which start with the word "class" (allowed for some initial whitespace). Then I could further filter the list by typing.

Is there an equivalent to that when using LazNvim? I've set things up to use fzf-lua but I can't see any option for starting with an initial regex.


Interestingly, AI suggests this to me, which actually seems not to work:

return {
  "ibhagwan/fzf-lua",
  config = function()
    local fzf = require("fzf-lua")

    -- Optional: call setup if you want to customize fzf-lua globally
    fzf.setup({})

    -- Keymap: Search for class definitions in the current buffer
    vim.keymap.set("n", "<leader>fac", function()
      fzf.grep_curbuf({
        search = "^ *class ",
        prompt = "Class definitions> ",
        regex = true,
      })
    end, { desc = "Find class definitions in current buffer (fzf-lua)" })
  end,
}

Solution

  • If found a solution buried in this GitHub issue:

    :lua FzfLua.live_grep({ search="^#+", no_esc=true })
    

    I don't know whether no_esc is documented anywhere, but I spent a while looking for this option and didn't find it.

    So in my case, my shortcut should look like this:

    return {
      "ibhagwan/fzf-lua",
      keys = {
        -- Remove LazyVim's default <leader>sa mapping
        { "<leader>sa", false },
        {
          "<leader>sac",
          function()
            require("fzf-lua").live_grep({
              search = "^ *class ",
              prompt = "Class definitions> ",
              no_esc = true,
            })
          end,
          desc = "[s]earch [a]nywhere [c]lass",
        },
        {
          "<leader>sad",
          function()
            require("fzf-lua").live_grep({
              search = "^ *def ",
              prompt = "Function definitions> ",
              no_esc = true,
            })
          end,
          desc = "[s]earch [a]nywhere [d]ef",
        },
        {
          "<leader>shc",
          function()
            require("fzf-lua").grep_curbuf({
              search = "^ *class ",
              prompt = "Class definitions> ",
              no_esc = true,
            })
          end,
          desc = "[s]earch [h]ere [c]lass",
        },
        {
          "<leader>shd",
          function()
            require("fzf-lua").grep_curbuf({
              search = "^ *class ",
              prompt = "Function definitions> ",
              no_esc = true,
            })
          end,
          desc = "[s]earch [h]ere [d]ef",
        },
      },
    }