bash shell zsh vi clipboard – How to Paste from Clipboard to vi-Enabled zsh or Bash Shell

bashclipboardshellvizsh

I'd like to be able to paste from the system clipboard (or text selection) into my "vi-like" shell prompt using the keyboard. I normally use zsh and sometimes bash. In both cases, I have the shell set up with vi-like behaviour (bindkey -v / set -o vi).

In vim, the behaviour I'm looking for is available with the key sequence "+p. This particular key sequence doesn't work as expected in a vi-enabled shell prompt, though. Is there any way to either enable this or a similar behaviour, using keyboard only, while remaining with vi-like keybindings in a zsh or bash shell prompt?

— edit —

Usage case: I often navigate between Firefox with the Pentadactyl addon, a terminal emulator and vim itself – using the Xmonad window manager with custom keys to move around. All three programs have vi-like keybindings, which is very efficient (for "finger memory") so it would be ideal communicate text between them using vim syntax (or a very similar syntax) only.

Best Answer

Zsh doesn't support anything but internal registers, and bash doesn't support register at all as far as I know. By and large, shells support vi commands, not vim commands.

In zsh, here's a proof-of-concept for accessing the X selection from command mode. For real use you'd want to elaborate on these techniques. I use the xsel program, you can use xclip instead; see How to copy from one vim instance to another using registers. You'll find the features I used in the zle manual.

vi-append-x-selection () { RBUFFER=$(xsel -o -p </dev/null)$RBUFFER; }
zle -N vi-append-x-selection
bindkey -a '^X' vi-append-x-selection
vi-yank-x-selection () { print -rn -- $CUTBUFFER | xsel -i -p; }
zle -N vi-yank-x-selection
bindkey -a '^Y' vi-yank-x-selection

The function vi-append-x-selection inserts the current X selection after the cursor (similar to p or P). The function vi-yank-x-selection copies the last killed or yanked text to the X selection. zle -N declares the functions as zle widgets (i.e. edition commands). bindkey -a sets bindings for vi command mode.

Related Question