Prevent Vim from clearing the clipboard on exit
Asked Answered
F

8

59

When I open Vim from a terminal, copy some text to the system clipboard, and exit Vim, the system clipboard gets cleared.

How to keep the copied text in the clipboard?

Fatherinlaw answered 23/6, 2011 at 11:56 Comment(9)
Read the FAQ people voting to close. "Software tools commonly used by programmers" are not off topic.Curse
@TLP It must be Linux. If I am not mistaking, process is the following: 1. You copy text. 2. Vim tells X that it has data for clipboard («tells that it has data», not «puts data into clipboard»). 3. You exit vim. 4. X now has no idea where he can get data for clipboard: clipboard is «cleared».Grouch
So the workaround may be the following: create a daemon that when something tells X that it (something) has data for clipboard will obtain this data and in turn tell X that it (daemon) has this data. In this case when something exits, daemon will still be present and able to give this data. Search for «clipboard manager» in your repository, it should solve this issue.Grouch
This does not happen for me on OS X. I can access the contents of the data in clipboard even after quitting vim. Are you sure you're using the + register to copy?Velum
@yoda It should happen only if you use X (xorg-server, not OS X).Grouch
@zyx: I did not confuse X with OS X. I was merely stating that it works fine on OS X. BTW, I also tested on a Linux machine using X and it is still not reproducible.Velum
@yoda. It must be reproducible with * register and it started to work this way for + register after some update (if I am not mistaking, it was X update).Grouch
Its happening for me in ubuntu. In vim version I can see +xterm_clipboard. Yes I am using "+y for copying.Fatherinlaw
Related: superuser.com/q/299419/442991Sb
E
52

Synthesizing answers from superuser, just add the following to your .vimrc

autocmd VimLeave * call system("xsel -ib", getreg('+'))
Emory answered 21/2, 2012 at 17:2 Comment(8)
It does not do exactly what TS wants: it saves value of default register to clipboard, not clipboard register. You should have used getreg('+').Grouch
Thanks for the work around Matt and ZyX. It requires installing 'xsel' though. I used getreg('+').Fatherinlaw
@Mike Have you found the solution for gvim? I've faced with the same problem.Normative
@dmitmedv No I still haven't. I have no idea why this works for vim but doesn't work for gvim.Burnell
On Ubuntu 18.04, this sometimes causes vim to crash (seg fault) or hang on exitTon
I just want to add few lines from my experience. Remember that if you used this copy paste using sudo, you can use only in applications with sudo access. It took me an hour to realize why I was not able to paste in my terminal after copying something which I had opened as sudo.Aelber
@Normative see clipboard persistence bug. "The problem happens because Xorg takes a conservative approach to copying. It copies only a reference to the original data when the user performs a select or copy."Preece
If using a Wayland compositor, one can use autocmd VimLeavePre * call system("wl-copy -o", getreg('+')) In my case this also does not clear the clipboard in case getreg('+') returns nothing.Corral
M
11

Install Parcellite, or glipper for Gnome and klipper for KDE.

Restart your computer or run it manually.

see: https://wiki.ubuntu.com/ClipboardPersistence

Musician answered 27/11, 2012 at 3:7 Comment(3)
I don't understand why people would vote this answer down. It shows that the problem isn't just because of the way Vim behaves - it affects many applications. The link shows how to fix the issue for all affected applications. What more could you want?Bitterling
Some people, such as myself, don't actually want a full clipboard manager because we want the clipboard to go away as soon as it is no longer needed (e.g. because it contains sensitive data). Fortunately, Parcellite offers a daemon mode in which it will "just" keep the clipboard safe.Americium
I found that parcelite seems to mess with clipboard, overall not reliable enough.Cupped
G
10

Based on Matt's answer, the following uses xclip instead of xsel:

autocmd VimLeave * call system('echo ' . shellescape(getreg('+')) . 
            \ ' | xclip -selection clipboard')
Galinagalindo answered 7/8, 2017 at 18:16 Comment(3)
This mostly works for me, but every copied line includes a trailing backslash when pasted back. Do others have this issue / does anyone know a solution?Leach
Make that echo -n and it won't add a newline to your clipboard ;)Dome
Oh, just saw this answer after editing the other one. Still, xclip solution is probably less error prone using this: system("xclip -selection clipboard -i", getreg('+'))Circulate
Y
4

I ran into this issue and a related problem where suspending vim with ctrl-z would also clear the clipboard. I've extended Matt's solution to fix both:

set clipboard=unnamedplus

if executable("xsel")

  function! PreserveClipboard()
    call system("xsel -ib", getreg('+'))
  endfunction

  function! PreserveClipboadAndSuspend()
    call PreserveClipboard()
    suspend
  endfunction

  autocmd VimLeave * call PreserveClipboard()
  nnoremap <silent> <c-z> :call PreserveClipboadAndSuspend()<cr>
  vnoremap <silent> <c-z> :<c-u>call PreserveClipboadAndSuspend()<cr>

endif

The if executable("xsel") guard is there to avoid errors if xsel is not installed. The nnoremap mapping preserves the clipboard when suspending from normal mode and the vnoremap mapping handles suspending from visual or select modes.

I've confirmed this works on vim 7.4 and 8.0.

Yearround answered 24/2, 2018 at 5:34 Comment(2)
Hi thank for your post! It works well. But if I use xclip like call system('echo ' . shellescape(getreg('+')) . \ ' | xclip -selection clipboard'). When I use ctrl+shift+v will freeze my terminal for a minutes after use <c-z> suspend vim.Sulphone
You can replace getreg('+') with @+Inappropriate
E
3

Use Neovim. It by default doesn't clear the clipboard on exit. You will still need to set clipboard=unnamedplus (typically in ~/.config/nvim/init.vim) and have xsel or xclip tools installed.

Keep in mind that some other defaults are different as well.

Epode answered 11/11, 2020 at 21:26 Comment(2)
Thank you! Adding the clipboard=unnamedplus did the trick for me. It even fixed the issue of the clipboard not carrying across tabs.Jillane
I use nvim v0.7.2 and it does clear the output. I have only xclip and not xsel. In the meantime i solved it with ``` vim.api.nvim_create_autocmd("VimLeave", { pattern = "*", command = "call system('xclip -selection c', getreg('+'))", }) ``` can you link some source how is it default and why both xsel and xclip should do? ThanksLilithe
O
1

Based on Matt's answer

When using his method copying multiple lines added slashes to the end of lines when pasting.

This should remedy that.

autocmd VimLeave * exe ":!echo " . shellescape(getreg('+')) . " | xclip -selection clipboard"

When i used "shellescape" with "system" newlines kept getting escaped. But that didn't happen when i used exe.

Don't know the real reason. but this worked.

Ostentation answered 4/12, 2019 at 6:44 Comment(0)
T
0

Please correct me if I'm wrong but from my understandings of Vim...
1) Vim uses registers instead of the clipboard to store copied/cut data.
2) These registers are preserved when exiting vim in a status file but are not accessible outside of the running process unless you manually open the file and inspect its contents
3) Saving stuff to the + registre while Vim runs allows you to paste to other applications.
4) By suspending vim (CTRL-Z) instead of closing it, these registers are still accessible.

Does that provide assistance?

Twentyfourmo answered 27/6, 2011 at 21:42 Comment(2)
I am able to paste to other window/terminal when vim is still running. Suspending vim with ctrl+z is clearing the copied text like exit.Fatherinlaw
Again, my experience is very limited as I usually work with vi through a PuTTY terminal. The gist of what I was able to learn is that the program uses local registers while running to store data to the clipboard, once the application is terminated the registers are cleared and data is unaccessable save the cache files it writes on close. If this effects the suspended state as well I can't suggest anything else. Good luck :DTwentyfourmo
H
0

Here's a solution for Neovim's init.lua, which also avoids this bug and its resulting error message, when exiting Neovim:

vim.api.nvim_create_autocmd({ "VimLeave" }, {
  callback = function()
    vim.fn.jobstart('echo "' .. vim.fn.getreg('+')  .. '" | xclip -selection clipboard -i', {detach=true})
  end,
})

I can't test a solution for Wayland currently (assuming Wayland has the same issue), but for wl-copy, it should be able to take the text to be copied as a list of strings after the command, so an approach like this should work:

vim.fn.jobstart({'wl-copy', vim.fn.getreg('+')}, {detach=true})

It does seem like it takes a second or two to actually get copied after exiting, though.

Hexachlorophene answered 3/3 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.