0

I'm trying to create an autocmd that copies selected text in visual mode in Neovim (preferably when selecting text with the mouse and copy on mouse button release)

I've tried so far:

vim.api.nvim_create_autocmd({"ModeChanged"}, {
  pattern = "[vV\x16]*:*",
  callback = function()
    vim.cmd('"*y')
  end,
})

If I do a command ="echo 'test'" instead of callback I can see the text once selected then hitting Esc so the autocmd somewhat works.

1
  • Do you still have something open in your question? How can we help you further? Otherwise maybe could you accept one of the solutions using the v button next to the arrow voting buttons. It allow the question to rest :-)
    – Vivian De Smedt
    Commented Sep 13, 2024 at 17:03

1 Answer 1

0

Remark: "*y is not a command but a set of keystroke.

I would do:

vim.api.nvim_create_autocmd({"ModeChanged"}, {
  pattern = "[vV\x16]*:*",
  callback = function()
      text = ''
      for linenb=vim.fn.line("'<"), vim.fn.line("'>") do
          line = vim.fn.getline(linenb)

          first_col = 1
          first_line = linenb == vim.fn.line("'<")
          if first_line then
              first_col = vim.fn.col("'<")
          end

          last_col = -1
          last_line = linenb == vim.fn.line("'>")
          if last_line then
              last_col = vim.fn.col("'>")
          end
          line = string.sub(line, first_col, last_col)

          if last_col == -1 then
              line = line .. "\n"
          end

          text = text .. line
      end
      vim.fn.setreg('*', text)
  end,
})

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.