grep whole word
Is it possible to grep the whole word under cursor? Or does the current "grep_string" picker support it already?
Do you mean something like this?
local function get_visual_selection()
vim.cmd('normal! "vy') -- Yank selection into the unnamed register
return vim.fn.getreg("v")
end
keys = {
{
"<leader>fw",
function()
require("telescope.builtin").live_grep({
default_text = vim.fn.expand("<cword>"),
initial_mode = "normal",
})
end,
desc = "Live Grep current word",
mode = "n",
},
{
"<leader>fw",
function()
require("telescope.builtin").live_grep({
default_text = get_visual_selection(),
initial_mode = "normal",
})
end,
desc = "Live Grep selected text",
mode = "x",
},
}
Yes, it does already. You can set up a shortcut like this:
vim.keymap.set('n', '<leader>sw', function()
require('telescope.builtin').grep_string()
end, { desc = '[S]earch current [W]ord' })
-- Or in lazy
{
'nvim-telescope/telescope.nvim',
-- ... other settings
config = function()
local builtin = require 'telescope.builtin'
vim.keymap.set('n', '<leader>sw', builtin.grep_string, { desc = '[S]earch current [W]ord' })
end,
},
I mean to grep the exact word under cursor, like the regex "\bsomeword\b". I work out with this:
vim.keymap.set('n', '<LEADER>fw',
function() require('telescope.builtin').grep_string { word_match = '-w' } end,
{ desc = 'telescope: search cursor string' }
)
But it's better to leave the search string on the input box of live_grep so I can modify it. When press the keymap (like <LEADER>fw), the behavior is just like open the live_grep window and type "\bsomeword\b". Does live_grep support any option like this?
Did you try my suggestion up above?
If you prefer you can remove the option initial_mode = "normal" to keep the default insert_mode behavior.
@thi-marques Thanks but your config cannot grep the exact word? Or should I add a pair of \b(I dont know what it should be in vim) around <cword>?
<cWORD>
WORD A WORD consists of a sequence of non-blank characters, separated with white space. An empty line is also considered to be a WORD.
word A word consists of a sequence of letters, digits and underscores, or a sequence of other non-blank characters, separated with white space (spaces, tabs, <EOL>). This can be changed with the 'iskeyword' option. An empty line is also considered to be a word.
@thi-marques I tried:
But it seems the grep result contains some word not match exactly:
My neovim version is v0.10.4 and telescope.nvim is 0.1.8 .
Sorry, I misunderstood. Now I see:
default_text = "\\b" .. vim.fn.expand("<cword>") .. "\\b"
@thi-marques Thanks!That will work.