Search code examples
luaneovim

Autocmd in visual mode neovim for syncing selection to X11 buffer


I want anything that I select in visual mode to go to the X11 buffer. My ideal workflow would be something like:

  1. I enter visual mode by pressing v (or V or ctrl V etc.)
  2. Select some text by some usual movements hjkl, wb or similar
  3. Outside of the terminal I do a middle click (click with the scroll-wheel) and the selection from 2 is pasted where I pressed

I can get something almost like this with e.g. a keymap: vim.keymap.set("v", "<leader>y", [["*ygv]]) and then adding a step between (2) and (3) where I press <leader>y.

My actual question is for how to make this yanking (while keeping visual selection (gv in my example keymap)) happen automatically.

Probably I would like something like an autocommand but I don't know the right events to be watching. Something that appears to kind-off work is:

vim.api.nvim_create_autocmd({"CursorMoved", "ModeChanged"}, {
    callback = function()
        local mode = vim.fn.mode(false)
        if mode == "v" or mode == "V" or mode == "^V" then
            vim.cmd([["*y]])
        end
    end,
})

but there are some problems:

  • it might be a bit aggressive in how often it runs
  • "^V" is not the right character to match against
  • it messes up :V as the the initial line selection is removed (but adding gv to the command didn't seem to work)

What would be a better approach?

I'm running nvim v0.9.4 on gnome.


Solution

  • If I understand correctly you want that standard X11 feature when any visual selection updates PRIMARY selection atom (while CLIPBOARD is used with control-c or similar). Btw. gvim built for gtk/X11 supports this feature natively (named autoselection or such).

    However, with nvim the situation is more complicated. The application is built for terminal and does not have any specific gtk or X11 code. The OS clipboard access is done usually by executing an external application such as xclip or xsel.

    So, technically, you maybe could trap CursorMoved event and then (while the current mode is visual, of course) keep updating "star" register per each invocation. But, honestly, I don't think that's a good idea.

    Such feature could possibly be implemented by some of nvim gui shells (nvim-qt, etc.) internally. But I'm not aware of anything like that done.

    Also, consider that analogue of PRIMARY selection was not included into Wayland core. So it exists only as an extra feature in Gnome/Wayland implementation.