0

I would like to change the search directory of the current telescope picker in neovim.

Ideal workflow:

  1. I open telescope find files or telescope live grep, and then start typing something
  2. Realise that the current working directory (default telescope search directory) is too deep to find what I'm looking for
  3. Press CTRL-K to change my search directory to its parent directory
  4. Either, see the file I want, or keep pressing CTRL-K until the search directory is high enough to see the file I want.

Here's what I've written to try to accomplish this, but it has some limitations:

local builtin = require('telescope.builtin') local go_up_one_dir = function(prompt_bufnr) local current_picker = require'telescope.actions.state'.get_current_picker(prompt_bufnr) local query_text = current_picker.sorter._discard_state.prompt local col = vim.fn.col('.') local cols = vim.fn.col('$') local vstart_col = vim.fn.col('v') -- need to figure out how to restore local mode = vim.fn.mode() -- these two local old_cwd = current_picker.cwd local new_cwd = vim.fn.fnamemodify(old_cwd, ':h') require'telescope.actions'.close(prompt_bufnr) local find_files = builtin.find_files { cwd = new_cwd } vim.fn.feedkeys(vim.fn.escape(query_text, '\\'), 't') for _ = 1, cols - col do vim.cmd[[call feedkeys("\<Left>", "t")]] end end require("telescope").setup { pickers = { find_files = { mappings = { i = { ["<C-k>"] = go_up_one_dir, }, n = { ["<C-k>"] = go_up_one_dir, }, }, }, live_grep = { mappings = { i = { ["<C-k>"] = go_up_one_dir, }, n = { ["<C-k>"] = go_up_one_dir, }, }, }, }, } 

Issues:

  • It doesn't relaunch live_grep, even if I was in live_grep originally, it launches find_files (you can see find_files is hardcoded in there; that's because I couldn't find out how to get the current picker type)
  • It doesn't restore normal vs insert mode, and it doesn't restore the cursor position in the query

Can my issues be fixed, or even better, is there a more supported way to change the search directory live?

1 Answer 1

0

You can achieve this with telescope-file-browser and a custom function. (See this comment on telescope github issue) Video demo

local ts_select_dir_for_grep = function(prompt_bufnr) local action_state = require("telescope.actions.state") local fb = require("telescope").extensions.file_browser local live_grep = require("telescope.builtin").live_grep local current_line = action_state.get_current_line() fb.file_browser({ files = false, depth = false, attach_mappings = function(prompt_bufnr) require("telescope.actions").select_default:replace(function() local entry_path = action_state.get_selected_entry().Path local dir = entry_path:is_dir() and entry_path or entry_path:parent() local relative = dir:make_relative(vim.fn.getcwd()) local absolute = dir:absolute() live_grep({ results_title = relative .. "/", cwd = absolute, default_text = current_line, }) end) return true end, }) end