Stop VSCodeVim, vim and neovim from replacing the system clipboard with deleted or changed text

If you use VSCodeVim with "vim.useSystemClipboard": true or vim/neovim with set clipboard+=unnamed, deleting text with d, dd, D, or changing it with c or C overwrites your system clipboard contents with the deleted or changed text.

It’s worth using a clipboard manager to resurrect old system clipboard contents. But you can also stop VSCodeVim/vim/neovim from sending deleted text to your clipboard in the first place:

VSCodeVim

  1. Open the Command Palette (⇧⌘P) and type “Preferences: Open Settings (JSON)”.
  2. Add these entries to your config to fix the behaviour in normal and visual mode by sending deleted text to the black hole register instead of the system clipboard:
  "vim.useSystemClipboard": true,
  "vim.normalModeKeyBindingsNonRecursive": [    
    // Don't use system clipboard when deleting or changing.
    {
      "before": ["d"],
      "after": ["\"", "_", "d"]
    },
    {
      "before": ["c"],
      "after": ["\"", "_", "c"]
    },
    {
      "before": ["D"],
      "after": ["\"", "_", "D"]
    },
    {
      "before": ["C"],
      "after": ["\"", "_", "C"]
    }
  ],
  "vim.visualModeKeyBindingsNonRecursive": [
    // Don't use system clipboard when deleting or changing.
    {
      "before": ["d"],
      "after": ["\"", "_", "d"]
    },
    {
      "before": ["c"],
      "after": ["\"", "_", "c"]
    },
    {
      "before": ["D"],
      "after": ["\"", "_", "D"]
    },
    {
      "before": ["C"],
      "after": ["\"", "_", "C"]
    }
  ],

Now, cutting with x or yanking/copying with y will still use the system clipboard as expected, but deleting with d, D, dd, or changing with c or C will not.

Vim

In vim add this to your init.vim:

nnoremap d "_d
nnoremap D "_D
nnoremap c "_c
nnoremap C "_C
vnoremap d "_d
vnoremap D "_D
vnoremap c "_c
vnoremap C "_C

" Uncomment next line to use the system clipboard for yanks/cuts.
" set clipboard+=unnamed

Neovim

Put this in your init.lua:

vim.keymap.set({'n', 'v'}, 'd', '"_d', { noremap = true })
vim.keymap.set({'n', 'v'}, 'D', '"_D', { noremap = true })
vim.keymap.set({'n', 'v'}, 'c', '"_c', { noremap = true })
vim.keymap.set({'n', 'v'}, 'C', '"_C', { noremap = true })

-- Uncomment next line to use the system clipboard for yanks/cuts.
-- vim.api.nvim_command('set clipboard+=unnamed')