Is there a way to grep on files that are returned by Telescope's live_grep()?

281 Views Asked by At

I want to search files that contains "A" but also "B", like live_grep on live_grep result.

I know I could achieve similar by RegExp, but it would be easier for me to search "A" and then "B" separately, step by step.

What I want to achieve is something like below(from TypeScript React Project):

  1. live_grep() <Button> (from entire project directory)
  2. Returns files containing Button component
  3. live_grep() <Badge> (but only from files returned by 1.)
  4. Returns files that contain Badge component but also Button component
1

There are 1 best solutions below

2
ysjn On

I've managed to achieve the result by using telescope-live-grep-args.nvim extension and bit of lua coding.

  {
    "nvim-telescope/telescope.nvim",
    dependencies = { "nvim-telescope/telescope-live-grep-args.nvim" },
    config = function()
      require("telescope").setup({
        defaults = {
          mappings = {
            n = {
              ["<C-r>"] = {
                function(p_bufnr)
                  -- send results to quick fix list
                  require("telescope.actions").send_to_qflist(p_bufnr)
                  local qflist = vim.fn.getqflist()
                  local paths = {}
                  local hash = {}
                  for k in pairs(qflist) do
                    local path = vim.fn.bufname(qflist[k]["bufnr"]) -- extract path from quick fix list
                    if not hash[path] then -- add to paths table, if not already appeared
                      paths[#paths + 1] = path
                      hash[path] = true -- remember existing paths
                    end
                  end
                  -- show search scope with message
                  vim.notify("find in ...\n  " .. table.concat(paths, "\n  "))
                  -- execute live_grep_args with search scope
                  require("telescope").extensions.live_grep_args.live_grep_args({ search_dirs = paths })
                end,
                type = "action",
                opts = {
                  nowait = true,
                  silent = true,
                  desc = "Live grep on results",
                },
              },
            },
          },
        },
      })
      require("telescope").load_extension("live_grep_args")
    end,
  },