Extend :Rg to support visual select mode

Also move away from using the telescope builtin grep for word under
cursor mapping by extending the `:Rg` command to work in the following
circumstances:

* `:Rg text to search for`
* `:Rg` word under cursor
* `'<,'>Rg` visual selection
This commit is contained in:
Kenneth Benzie 2024-05-25 11:03:06 +01:00
parent 1996e631a3
commit fcd5cfbd54
3 changed files with 24 additions and 6 deletions

View File

@ -36,7 +36,6 @@ return {
vim.keymap.set('n', '<leader>gF', builtin.find_files, opts)
vim.keymap.set('n', '<leader>gf', builtin.git_files, opts)
vim.keymap.set('n', '<leader>gg', builtin.live_grep, opts)
vim.keymap.set('n', '<leader>rg', builtin.grep_string, opts)
vim.keymap.set('n', '<leader>gb', builtin.buffers, opts)
vim.keymap.set('n', '<leader>gh', builtin.help_tags, opts)
vim.keymap.set('n', '<leader>bl', builtin.current_buffer_fuzzy_find, opts)

View File

@ -116,16 +116,31 @@ end, {
complete = 'file',
})
-- :Rg grep for the given string and fuzzy find the results, bang to enable
-- regex in given string
-- FIXME: Support visual select modes
-- :Rg grep for the given string, word under the cursor, or visual selection
-- then fuzzy find the results. Bang to enable regex in given string.
vim.api.nvim_create_user_command('Rg', function(opts)
local grep_opts = { search = opts.args }
print(vim.inspect(opts))
local search = opts.args
if opts.range == 2 then
local lines = vim.fn.getline(vim.fn.line("'<"), vim.fn.line("'>"))
local start_col = vim.fn.col("'<")
local end_col = vim.fn.col("'>")
if #lines == 1 then
lines[1] = string.sub(lines[1], start_col, end_col)
else
lines[1] = string.sub(lines[1], start_col)
lines[#lines] = string.sub(lines[#lines], 1, end_col)
end
search = table.concat(lines, "\n")
elseif #search == 0 then
search = vim.fn.expand('<cword>')
end
local grep_opts = { search = search}
if opts.bang then
grep_opts['use_regex'] = true
end
require('telescope.builtin').grep_string(grep_opts)
end, { bang = true, nargs = '*' })
end, { bang = true, range = true, nargs = '*' })
vim.api.nvim_create_user_command('PreProcIfWrap', function(opts)
local buffer = vim.api.nvim_get_current_buf()

View File

@ -43,3 +43,7 @@ vim.keymap.set('t', '<C-w><C-g>', '<C-\\><C-n>:Gdb<CR>:startinsert<CR>', opts)
vim.keymap.set('t', '<C-w><C-e>', '<C-\\><C-n>:Program<CR>', opts)
vim.keymap.set('t', '<C-w><C-s>', '<C-\\><C-n>:Source<CR>', opts)
vim.keymap.set('t', '<C-w><C-a>', '<C-\\><C-n>:Asm<CR>', opts)
-- Mappings to grep for then fuzzy find the word under the cursor or visual selection
vim.keymap.set('n', '<leader>rg', ':Rg<CR>', opts)
vim.keymap.set('v', '<leader>rg', ":'<,'>Rg<CR>", opts)