'Mapping select-all, copy, paste in vim

I have the following map in my vimrc:

nnoremap <C-a> ggVG
nnoremap <C-c> "*yy (might be because I'm in visual mode here?)
nnoremap <C-v> "*p

The select-all (ctrl-a) and the paste (ctrl-p) works, but the (ctrl-c) does not work with that shortcut, though it works if I manually type in the command after doing ctrl-c.

What needs to be fixed here?

vim


Solution 1:[1]

The first issue I would like to address is that your mapping for copying the text, nnoremap <C-c> "*yy, will only work in normal mode. When you select text in Vim, you enter visual mode, and the first n of nnoremap makes the mapping work in normal mode only.

You can make your mapping work by using noremap (all modes), vnoremap (visual and select mode), or xnoremap (visual mode only), like this:

vnoremap <C-c> "*y

You can find more information about mappings in the documentation.

Another thing to note is that the default function of Ctrl-c is to cancel/interrupt the current command. For example, if you enter insert mode and press Ctrl-c, you will exit insert mode and go back to normal mode. With your original mappings, it will cancel the selection (exits visual mode) without copying anything.

Solution 2:[2]

This works for me in Neovim but I believe it should also work in Vim as well. To yank all the content I have the following mapping in my configuration:

nnoremap <leader>ya ggVGy<C-O>

Details:

  1. gg: go to the first line
  2. V: select the first line
  3. G: go to the last line
  4. y: yank selection
  5. <C-O>: go to the previous cursor position

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 4awpawz