0

I want to create a mapping in my neovim lua setup such that when I have a visual selection and hit <leader>ps, a telescope search is initiated with the selected text. Here is what I have for the moment:

local builtin = require('telescope.builtin')

local function get_visual_selection()
  local s_start = vim.fn.getpos("'<")
  local s_end = vim.fn.getpos("'>")
  local n_lines = math.abs(s_end[2] - s_start[2]) + 1
  local lines = vim.api.nvim_buf_get_lines(0, s_start[2] - 1, s_end[2], false)
  lines[1] = string.sub(lines[1], s_start[3], -1)
  if n_lines == 1 then
    lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3] - s_start[3] + 1)
  else
    lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3])
  end
  return table.concat(lines, '\n')
end

vim.keymap.set('n', '<leader>ps', function() -- works fine
    builtin.grep_string({ search = vim.fn.input("Grep > ") });
end)

vim.keymap.set('v', '<leader>ps', function() -- gets the same first value for sel everytime!
    local sel = get_visual_selection();
    builtin.grep_string({ search = vim.fn.input("Grep > " .. sel) });
end)

This code works on the first time; but then the first text retrieved from selection never changes! I get the first text I selected over and over. I don't understand what is causing that. It seems the function gets hit by some sort of caching mechanism from lua...?

1 Answer 1

0

I finally used a different and simpler way of doing this exact thing using a remap, yank and paste; I still don't know what's wrong in my question's lua script though.

Here is the working lua map:

vim.keymap.set('v', '<leader>ps', 'y<leader>ps<C-r>*', { remap = true });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.