'Neovim lua copy and paste key mapping

I just started replacing my vim config with lua config and im trying to make a simple copy/paste to clipboard key mapping so I can select a text with "v" and then click Ctrl+c and Ctrl+v but i can't get it to work.

I want to do a "+y and a "+p

I tried this but its not working:

local keymap = vim.api.nvim_set_keymap
keymap("n", "<C-c>", '"+y', opts)
keymap("n", "<C-v>", '<ESC>"+pa', opts)

Any ideas?



Solution 1:[1]

Try this:

vim.api.nvim_set_keymap("n", "<c-c>", '"*y :let @+=@*<CR>', {noremap=true, silent=true})
vim.api.nvim_set_keymap("n", "<c-v>", '"+p', {noremap=true, silent=true})

Add i,v,x... to that first quotes for other modes.

I see you're doing some extra things like escape and appending, so maybe it isn't all the way there for your workflow - but this should get you going.

Solution 2:[2]

I have a map helper function:

-- ~/.config/nvim/lua/mappings.lua
-- in your init.lua use: require('mappings')
local function map(mode, lhs, rhs, opts)
    local options = { noremap = true }
    if opts then
        options = vim.tbl_extend("force", options, opts)
    end
    vim.api.nvim_set_keymap(mode, lhs, rhs, options)
end

By default options are used, just in case you use any option these are merged with options.

Now you can create mappings like this:

-- Update Plugins
map("n", "<Leader>u", ":PackerSync<CR>")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 SergioAraujo