513

Is there a way to copy a block of text to the system clipboard, so I can paste it in another program?

4
  • 15
    This has already been asked and answered on SO. You may find more and different information there.
    – bsmith89
    Commented Feb 4, 2015 at 0:47
  • 1
    I have been using this plugin on macvim christoomey/vim-system-copy and really love it. It works really well with motions cpip, cpi{.
    – filype
    Commented Jan 25, 2017 at 9:30
  • 3
    What you really need is EasyClip. It will do just that and so much more...
    – Scott Wade
    Commented Feb 25, 2017 at 5:56
  • I can not add answer but a comment. If you only want to copy a text you can also use sed :). sed -n 5p file; only 5th line. sed -n -e 5p -e 8p file; only 5th and 6th lines. sed -n 5,8p file; lines between 5th and 8th. It will print the lines in console. You can easily copy by selecting text. Commented Jan 28, 2020 at 10:24

15 Answers 15

576

For X11-based systems (ie. Linux and most other UNIX-like systems) there are two clipboards which are independent of each other:

  • PRIMARY - This is copy-on-select, and can be pasted with the middle mouse button.
  • CLIPBOARD - This is copied with (usually) ^C, and pasted with ^V (It's like MS Windows).

OS X and Windows systems only have one clipboard.

For X11 systems there are also number of tools that synchronize these clipboards for you; so if they appear to be the same, you may have one of them running.

Vim has two special registers corresponding to these clipboards:

  • * uses PRIMARY; mnemonic: Star is Select (for copy-on-select)
  • + uses CLIPBOARD; mnemonic: CTRL PLUS C (for the common keybind)

On Windows & OS X there is no difference between + and *, since these systems only have a single clipboard, and both registers refer to the same thing (it doesn't matter which one you use).

You can use these registers as any register. For example, using the PRIMARY clipboard * with the y and p commands:

  • "*yy
  • "*p

You could maybe use this as more convenient keybinds:

noremap <Leader>y "*y
noremap <Leader>p "*p
noremap <Leader>Y "+y
noremap <Leader>P "+p

If you want to "automatically" interface with the system's clipboard instead of referring to it manually all the time, you can set the clipboard variable:

  • Set it to unnamed to use * (PRIMARY, on select)
  • Set it to unnamedplus to use + (CLIPBOARD, ^C)

Now, just using yy will go to the system's clipboard, instead of Vim's unnamed register, and p will paste the system's clipboard.

You can also assign to these registers just like any register with let:

  • :let @+=42
  • :let @*=42

The clipboard setting has some more options (such as exclude filters); but these are the basics. See :help 'clipboard' for the full story ;-)

gVim

If you use gVim, you can get copy-on-select behaviour when using :set guioptions+=a.
This is enabled by default on X11 systems (copies to PRIMARY), but not on MS Windows & OSX (as selecting any text would override your clipboard).

No +clipboard?

Vim requires the +clipboard feature flag for any of this to work; you can check if your Vim has this by using :echo has('clipboard') from within Vim (if the output is 0, it's not present, if it's 1, it is), or checking the output of vim --version for +clipboard.

Most Linux distributions ship with a "minimal" Vim build by default, which doesn't have +clipboard, but you can usually install it:

  • Debian & Ubuntu: Install vim-gtk3.
  • Fedora: install vim-X11, and run vimx instead of vim (more info).
  • Arch Linux: install gvim (this will enable +clipboard for normal vim as well).

You could also use xclip, xcopy, or xsel to copy text to the clipboard; see the following questions for solutions:

SSH

You can also use a clipboard on remote machines if you enable X11 forwarding over SSH. This is especially useful with the above tip since you can then use xclip to access your desktop's clipboard. The Vim on the machine you're ssh-ing to will still need the +clipboard feature.

This requires the ForwardX11Trusted setting, and should only be done with trusted servers, as this gives the server almost complete control over your X11 session:

$ ssh -XY myhost

To make these settings persistent (so you don't need to add -XY every time), you could do something like this in your ~/.ssh/config:

# Do **NOT** set this globally; it gives the server complete control over
# your X11 session.
Host myhost
    ForwardX11 yes
    ForwardX11Trusted yes

Neovim

Neovim revamped the clipboard support. The built-in interface was removed and replaced with a system that call an external utility such as xclip, xsel, or pbcopy/pbpaste.

It should automatically pick up these utilities and use them. On OS X pbcopy and pbpaste should be available by default, on Linux you probably want to install xclip, as that's the most widely available (there are actually two versions of xsel with incompatible flags. This is really stupid).

Also see :help clipboard in Neovim.

19
  • 8
    ssh -Y implies -X so -X can be omitted.
    – hildred
    Commented Mar 16, 2015 at 20:52
  • 11
    A very interesting side effect of learning this (a few years ago) for me has been the realization that " can select many named registers. "+ is not magic, it's just register +. So for example, if you want to copy three things at the same time and paste each of them one by one, you can "1y, "2y and "3y and later "1p, "2p and "3p. This is really powerful and non-existent in almost any other editor. Another interesting usage is to look at stored macros. For example, if you record with qq, but you realize you need to fix it, you can: in a temp line "qp, fix it, and "qd.
    – Shahbaz
    Commented Feb 3, 2017 at 18:06
  • 1
    Just a note: OS X has two separate clipboards. One is accessed using Cmd-C and Cmd-V and the other using the emacs keybindings Ctrl-K and Ctrl-Y. Commented Feb 5, 2017 at 17:16
  • 6
    @shahbaz -- probably better to use the letter registers for such a purpose, since the numbered ones get changed whenever text is deleted.
    – evilsoup
    Commented Feb 26, 2017 at 10:17
  • 3
    Copy & paste as described in the question is meant for desktop. It is true that installing package gvim alongside vim gives you clipboard functionalities. but in file browsers you are then offered two text editors to open files! And this looks ugly. This is why it is better to install only packages vim and vim-gui-common. Later one provides the clipboard functionalities without the need for installing gvim. This is on Linux Debian 10.
    – 71GA
    Commented Jan 2, 2020 at 21:34
52

From http://vim.wikia.com/wiki/Accessing_the_system_clipboard

set clipboard=unnamedplus

This changes the default Vim register to the + register, which is linked to the system clipboard. From :h clipboard-unnamedplus:

                                        clipboard-unnamedplus
unnamedplus     A variant of the "unnamed" flag which uses the
                clipboard register '+' (quoteplus) instead of
                register '*' for all yank, delete, change and put
                operations which would normally go to the unnamed
                register.  When "unnamed" is also included to the
                option, yank operations (but not delete, change or
                put) will additionally copy the text into register
                '*'.
                Only available with the +X11 feature.
                Availability can be checked with: 
                        if has('unnamedplus')
2
  • 2
    Why does this not work for me when yank&paste between vim instances (each in a separate terminator terminal)?
    – thinwybk
    Commented Nov 30, 2018 at 9:43
  • 3
    If you are on Linux, and Vim has been compiled with the +X11 feature, and you have clipboard=unnamedplus set, then you should be able yank a line in one instance of vim and paste it in another instance of vim. You should also be able to paste it into any other application with CTRL+V or SHIFT+INSERT. You can use :version within Vim to see if +X11 appears in the list of included features. You can also check if the 'unnamedplus' feature is available with :if has('unnamedplus')⏎ echo 'yes'⏎ endif If you are not on Linux then you should use unnamed instead of unnamedplus. Commented Nov 30, 2018 at 15:49
28

On builds that support it, the register named * is the system clipboard. To copy text from Vim to the system clipboard, you can select the text using visual mode, then press "*y to copy it to the system clipboard.

Conversely, use "*p to paste text from the system clipboard into Vim.

0
22

The other answers cover how to copy text from your buffer into the system clipboard. Another common operation is to copy text from another register to the clipboard. For example, if you've already yanked some text into " (the default register), you might want to load that register into the clipboard.

You can do this with :let:

  • let @+=@" — copies the default register into the clipboard
  • let @*=@" — copies the default register into the X11 primary selection ("mouse clipboard")
  • let @+=@a — copy from register a to the clipboard
  • etc.

Note that this works for registers in general: let @a=@b copies register b to register a.

15

If you can't figure out how to get +clipboard to work, which I couldn't for some reason, then you can do this.

Assuming you only want to copy a section of the file, I do shift+v to go into visual mode and only highlight the lines I want to copy. Then I do this.

# Linux Wayland
:'<,'>w !wl-copy

# Linux Xorg
:'<,'>w !xclip -selection clipboard

Explanation

  • '<,'> - means you used visual mode to select a range (you don't type this)
  • w !{cmd} - write the range to the stdin of cmd, see more at :help w_c
  • wl-copy and xclip are programs that you can pipe text to and they'll add it to your system clipboard

Also, once this is in your history, you don't have to type the whole thing again. Just select with visual mode, type w then press up and the command should autocomplete. Also, also, you don't have to use visual mode. You can set whatever range you want.

2
  • 2
    Upvoting this (over the other similar answer) because this one gives explanation. By the way, a note to myself or other readers: when using xclip, you do NOT have to add that -selection clipboard parameter, which is too loooong to type. The default :'<,'>w !xclip would copy the content into the "primary" i.e. copy-on-select clipboard, which can be pasted with the middle mouse button.
    – RayLuo
    Commented May 8, 2020 at 17:18
  • Pros of this one is that you can use it with whatever VIM you have, but you did need xclip installed. I added the following to my .vimrc so I only have to type it the once: vnoremap <leader>y <esc>:'<,'>w !xclip -selection clipboard<cr><cr>
    – Todd Vanyo
    Commented Nov 1, 2021 at 21:59
6

This is the behavior I wanted when it came to the system clipboard:

  • Yanking a line with newline works
  • Yanking a line without newline works
  • Yanking whatever is visually selected works
  • Cut works
  • Cutting a line with newline works
  • Cutting a line without newline works

By works I mean: I'm still able to use p to paste while in vim and I can use the system clipboard also. Basically I want copy and paste to work as expected and I didn't want to clutter my system clipboard more than necessary.

My technique was to map the common yank, cut, and delete commands to use the system clipboard by adding these lines to my ~/.vimrc:

" use system clipboard
" https://anuragpeshne.github.io/essays/vim/7.html
noremap y "*y
noremap yy "*yy
noremap Y "*y$
noremap x "*x
noremap dd "*dd
noremap D "*D

The key insight from the https://anuragpeshne.github.io/essays/vim/7.html blog post is:

Recursive Mapping is evil, Always use non recursive mapping. (noremap)

2
  • 2
    What does the " do? The first answer already explained what * is for, (referring to the primary clipboard), but I don't see any explanation anywhere for what " is for and why that makes the command work. Commented May 29, 2020 at 16:23
  • 3
    It's not immediately obvious because you're probably used to the quote being used to go around words, like "foo"; however, for vim "* is actually the name of the "register" (a vim concept) that connects to the system clipboard. If you open vim and type :registers you can see the names of other registers like: "", "0, "1, and on. I found this article useful for learning about registers: brianstorti.com/vim-registers
    – mbigras
    Commented May 29, 2020 at 18:25
5

I recommend you use Gvim, and add this to your .vimrc:

source $VIMRUNTIME/mswin.vim
behave mswin

This enables support for CtrlC, CtrlX, CtrlV like notepad in Windows.

Note that this will also add some other common Windows shortcuts, such as CtrlS for :w, CtrlA for select all, etc.

5

I was struggling with the system clipboard and vim inside tmux.

It was solved by using xsel or xclip, like in this example:

1.) visually select a block text in normal mode: V<motionkey>

2.a) with xsel run ex: :'<,'>w !xsel -b

2.b) with xclip run ex: :'<,'>w !xclip -selection clipboard

2.c) :.w !xsel -b to copy arbitrary selection or the current line (see "additional tip" below)

3.) paste into another program

... and now assign this to your favorite key-mapping.

The options -b or -selection clipboard basically mean, that the program (xsel or xclip) is sent to the background and wait for another program to paste the content, so that it can "interfere".

(tested on manjaro with i3, xfce4-terminal, tmux)

additional tip: to copy the current line (where the cursor is located) very fast I map this command :.w !xsel -b to a key of choice - so copy works with and without a visual selection

2
  • please comment before downvote ( or after)
    – MacMartin
    Commented Sep 28, 2021 at 8:25
  • For me xclip didn't work, but xsel DID. As Brazilian we have ç key so I attached to it vnoremap ç <Esc>:'<,'>w !xsel -b<CR> Commented Aug 12, 2022 at 9:45
3

If your vim does not support +clipboard you can use the fakeclip plugin for Linux, Mac, Windows, tmux, screen, ...

2

MacVim Cmd + x/c/v for cut/copy/paste

If you use MacVim, the usual Cmd+x/c/v are defined in $VIMRUNTIME/macmap.vim which is sourced by default and hence are available without configuration:

vnoremap <special> <D-x> "+x

vnoremap <special> <D-c> "+y

cnoremap <special> <D-c> <C-Y>

nnoremap <special> <D-v> "+gP
cnoremap <special> <D-v> <C-R>+
execute 'vnoremap <script> <special> <D-v>' paste#paste_cmd['v']
execute 'inoremap <script> <special> <D-v>' paste#paste_cmd['i']

However, using them can lead to vim user who do not know the vim way and are lost on a foreign computer/environment.

1

You can also use a global command to put some specific pattern on the clipboard. It can be useful in situations where you have information scattered in a file and manually coping is prone to errors and tiring.

First clean the register that will receive the information

:let @a=""

Then copy all the lines containing the pattern to it

:g/pattern/yank A

Finally tranfereing (copying ) the information to the system clipboard

:let @+=@a

if you try to copy every line containing a "pattern" directly to the clipboard it won't work because the clipboard does not have the capability of append new content, thus we are using here a normal vim register to store all the lines containing the pattern at once and then putting it on the clipboard.

OBS: It is necessary clining the register before using it, and the use of the UPPERCASE version of the register allows us to append content, otherwise it won't work either.

1

Below is an excerpt from my ~/.vimrc, which answers the OP's question in a slightly specific way. I came up with this for my own use, and it's a rather seamless solution when you get used to it a bit.

In a nutshell, pressing F4 in visual mode copies the current visual selection to two of the three X11 clipboards, and pressing F5 in insert mode pastes the contents of the primary X11 clipboard into the buffer at the current cursor position, or right below it if the cursor isn't in a blank line. Both operations include some neat additional tweaks to make them more convenient, and you can choose function keys other than F4 and F5 for these operations.

When you think about it, this is all you need to interact with the X11 clipboards, and it also doesn't tie the X11 clipboards to the vim's standard yank and paste operations and associated registers. As a result, you end up with more options by having, basically, two separate clipboards to use at the same time.

Here's the vimscript code:

" Use xclip(1) to interact with the X11 clipboards, to allow yanking
" and pasting lines of text in visual and insert modes, respectively,
" which makes interaction with the X11 clipboards independent of the
" "+clipboard" and "+xterm_clipboard" features;  also, make each chunk
" of the text pasted in insert mode separately undoable
"
" NOTE: Function "XclipYank()" invokes xclip(1) twice, to ensure that
"       the text selected in visual mode is read into both XA_PRIMARY
"       and XA_CLIPBOARD selections, which is redundant if some kind
"       of clipboard manager runs in the background to transparently
"       synchronize the contents of all three X11 selections
"
for s:maptype in ["n", "x", "i", "c"]
  execute s:maptype .. "noremap <F4> <Nop>"
  execute s:maptype .. "noremap <F5> <Nop>"
endfor
unlet s:maptype

if executable("xclip")
\  && &term !=? "console" && &term !=? "linux"
\  && strlen($DISPLAY) > 0
  function! s:XclipYank()
    let range   = join(sort([line("."), line("v")]), ",")
    let command = "silent " .. range .. "write !xclip -in -selection "
    for selection in ["clipboard", "primary"]
      execute command .. selection
    endfor
  endfunction

  function! s:XclipPaste()
    if !pumvisible()
      let range = line(".") - 1
      execute "silent " .. range .. "read !xclip -out -selection primary"
      call feedkeys("\<C-G>u", "nt")
    endif
  endfunction

  xnoremap <F4> <Cmd>call <SID>XclipYank()<CR>
  inoremap <F5> <Cmd>call <SID>XclipPaste()<CR>
endif

I hope that the vimscript code is self-descriptive and understandable.


I've improved this vimscript code even further, for example to handle both XA_PRIMARY and XA_CLIPBOARD X11 selections, but I'll provide further updates only if someone actually asks for them.

2
  • I think I never saw anybody put so much effort into any answer. Nine revisions over the course of three weeks is impressive. You might consider adding a link to a public repo where your code resides. Do a git push and don't worry about updating here.
    – Friedrich
    Commented Mar 5 at 7:24
  • 1
    @Friedrich Thank you very much! :) I'm actually considering to start a blog series about all the vim-related stuff I do. I'm doing all that for my own use, improving the existing features and adding new features as I need them, and fixing bugs as I spot them. Of course, I want to share all that for everyone's benefit, but I'm afraid that the additional explanations would be required to make it all more understandable. That's why I'm considering a blog series.
    – dsimic
    Commented Mar 6 at 1:13
0

Every other answer has covered all the important things about the registers. I would like to add one more thing that I use.

There is a way in Vim to directly copy the visually selected text in to the clipboard. Just put this in your vimrc file:

set guioptions+=a

And, with this whenever you visually select some text it will be copied to your clipboard. For more information on this, :help guioptions

BTW, this is only for gVim.

2
  • 3
    guioptions+=a is also mentioned in Carpetsmoker's answer.
    – muru
    Commented Feb 26, 2016 at 7:32
  • @muru Yeah, sorry. I didn't see that before. I just saw it. Commented Feb 26, 2016 at 8:26
0

Use Ctrl-c, Ctrl-v and Ctrl-x:

To get the most "usual", intuitive method of copy-pasting with Ctrlc, Ctrlx and Ctrlv, copy the following to your .vimrc:

" Paste system clipboard with Ctrl + v
inoremap <C-v> <ESC>"+gPi    
"nnoremap <C-v> "+gP<ESC>
vnoremap <C-v> d"+gP<ESC>
cnoremap <C-v> <C-r>+

" Cut to system clipboard with Ctrl + x
vnoremap <C-x> "+d
"nnoremap <C-x> "+dd
inoremap <C-x> <ESC>"+ddi

" Copy to system clipboard with Ctr + c
vnoremap <C-c> "+y
nnoremap <C-c> "+yy
inoremap <C-c> <ESC>"+yyi

What happens here is:

  1. Paste system clipboard with Ctrlv:
    a) inoremap <C-v> <ESC>"+gPi - insert mode: paste after cursor, put cursor to end of paste, stay in insert mode
    b) nnoremap <C-v> "+gP - normal mode: same as insert mode, stay in normal mode.
    Note: This overrides the default shortut for Visual Block mode, so be aware of this if you enable it.
    c) vnoremap <C-v> d"+gP<ESC> - visual mode: replace selection with clipboard content
    d) cnoremap <C-v> <C-r>+ - command mode (when you press : ): paste clipboard content

  2. Cut to system clipboard with Ctrlx:
    a) vnoremap <C-x> "+d - visual mode: cut selection to sys clipboard
    b) nnoremap <C-x> "+dd - normal mode: cut current line to clipboard.
    Note: This overrides the shortcut for Completion mode, so again, be aware.
    c) inoremap <C-x> <ESC>"+ddi - insert mode: same as normal mode, but stay in insert mode

  3. Copy to system clipboard with Ctrlc:
    Note: <C-c> is commonly used as an almost-equivalent of Esc, which is the default behaviour. Be aware if this. (I personally use CapsLock as Esc system-wide.)
    a) vnoremap <C-c> "+y - visual mode: copy selection to sys clipboard
    b) nnoremap <C-c> "+yy - normal mode: copy current line to clipboard
    c) inoremap <C-c> <ESC>"+yyi - insert mode: same as normal mode, but stay in insert mode

0

I noticed that on gvim for Windows that Ctrl+Ins copies (yanks), which goes nicely with Shift+Ins for pasting from the system clipboard and a lot quicker than "+y.

These keyboard shortcuts are part of the IBM Common User Access (CUA) of 1987, so I think it's quite nice that it's a sort of standard.

I made this mapping so that it also works on Linux vim/nvim/gvim and vim for Windows (terminal version) as well.

Currently I don't know if this can be done on Macs.

" Ctrl+Ins to yank to system clipboard
if has('unix') || has('win32') && !has('gui_running')
  vnoremap <C-Insert> "+y
endif

Not the answer you're looking for? Browse other questions tagged or ask your own question.