Skip to content

Commit bced1c2

Browse files
authored
Merge pull request #492 from slara/master
add Telescope live_grep on Git root
2 parents 1c59dc2 + 5ce4f38 commit bced1c2

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

init.lua

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,39 @@ require('telescope').setup {
308308
-- Enable telescope fzf native, if installed
309309
pcall(require('telescope').load_extension, 'fzf')
310310

311+
-- Telescope live_grep in git root
312+
-- Function to find the git root directory based on the current buffer's path
313+
local function find_git_root()
314+
-- Use the current buffer's path as the starting point for the git search
315+
local current_file = vim.api.nvim_buf_get_name(0)
316+
-- If the buffer is not associated with a file, return nil
317+
if current_file == "" then
318+
print("Buffer is not associated with a file")
319+
return nil
320+
end
321+
-- Extract the directory from the current file's path
322+
local current_dir = vim.fn.fnamemodify(current_file, ":h")
323+
-- Find the Git root directory from the current file's path
324+
local git_root = vim.fn.systemlist("git -C " .. vim.fn.escape(current_dir, " ") .. " rev-parse --show-toplevel")[1]
325+
if vim.v.shell_error ~= 0 then
326+
print("Not a git repository")
327+
return nil
328+
end
329+
return git_root
330+
end
331+
332+
-- Custom live_grep function to search in git root
333+
local function live_grep_git_root()
334+
local git_root = find_git_root()
335+
if git_root then
336+
require('telescope.builtin').live_grep({
337+
search_dirs = {git_root},
338+
})
339+
end
340+
end
341+
342+
vim.api.nvim_create_user_command('LiveGrepGitRoot', live_grep_git_root, {})
343+
311344
-- See `:help telescope.builtin`
312345
vim.keymap.set('n', '<leader>?', require('telescope.builtin').oldfiles, { desc = '[?] Find recently opened files' })
313346
vim.keymap.set('n', '<leader><space>', require('telescope.builtin').buffers, { desc = '[ ] Find existing buffers' })
@@ -324,6 +357,7 @@ vim.keymap.set('n', '<leader>sf', require('telescope.builtin').find_files, { des
324357
vim.keymap.set('n', '<leader>sh', require('telescope.builtin').help_tags, { desc = '[S]earch [H]elp' })
325358
vim.keymap.set('n', '<leader>sw', require('telescope.builtin').grep_string, { desc = '[S]earch current [W]ord' })
326359
vim.keymap.set('n', '<leader>sg', require('telescope.builtin').live_grep, { desc = '[S]earch by [G]rep' })
360+
vim.keymap.set('n', '<leader>sG', ':LiveGrepGitRoot<cr>', { desc = '[S]earch by [G]rep on Git Root' })
327361
vim.keymap.set('n', '<leader>sd', require('telescope.builtin').diagnostics, { desc = '[S]earch [D]iagnostics' })
328362
vim.keymap.set('n', '<leader>sr', require('telescope.builtin').resume, { desc = '[S]earch [R]esume' })
329363

0 commit comments

Comments
 (0)