开发者

Prevent Vim from clearing the clipboard on exit

开发者 https://www.devze.com 2023-03-15 08:41 出处:网络
When I open Vim from a terminal, copy some text to 开发者_开发技巧the system clipboard, and exit Vim, the system clipboard gets cleared.

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?


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

autocmd VimLeave * call system("xsel -ib", getreg('+'))


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

Restart your computer or run it manually.

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


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

autocmd VimLeave * call system('echo ' . shellescape(getreg('+')) . 
            \ ' | xclip -selection clipboard')


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.


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.


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消