Zsh copy and paste like emacs

clipboardzsh

I have noticed that zsh has a lot of things I see in emacs. I can make a selection with ctrl+space and selecting a region. I can make copies just like in emacs while I stay inside zsh. In emacs I'm able to use my system clipboard (previously with some additional configuration needed but this works out of the box now in emacs). In zsh I can't seem to paste from my clipboard using C-y and copying from zsh to my system cliipboard has the same issue. Is there a way around this?

Best Answer

Zsh's has a built-in clipboard that doesn't communicate with other applications. Since it's very scriptable, you can make it communicate with a few lines in your ~/.zshrc. You'll need xclip or xsel. See Pasting from clipboard to vi-enabled zsh or bash shell for a proof-of-concept in vi mode. Here's the corresponding code for emacs mode (you'll probably want to do something similar to other kill-* widgets).

x-copy-region-as-kill () {
  zle copy-region-as-kill
  print -rn $CUTBUFFER | xsel -i -b
}
zle -N x-copy-region-as-kill
x-kill-region () {
  zle kill-region
  print -rn $CUTBUFFER | xsel -i -b
}
zle -N x-kill-region
x-yank () {
  CUTBUFFER=$(xsel -o -b </dev/null)
  zle yank
}
zle -N x-yank
bindkey -e '\ew' x-copy-region-as-kill
bindkey -e '^W' x-kill-region
bindkey -e '^Y' x-yank

This uses the X11 clipboard (typically accessed with Ctrl+C/Ctrl+V); remove the -b option to use the X11 primary selection instead (automatic copy on select, and paste with the middle mouse button).

Related Question