Wednesday, October 17, 2012

GNU screen clipboard to X11 clipboard integration

Now that we have Clipboard cut-and-paste working in remote vim, let's get GNU screen to interact with the X Clipboard. This is useful when copying a large scrollback buffer into a browser app or email client. I can now copy from my screen session to my local OSX client and back!
  1. Install xsel
    sudo aptitude install xsel
  2. Add to .screenrc:
    # read and write screen clipboard to X clipboard.
    bind > eval writebuf "exec sh -c 'xsel -bi </tmp/screen-exchange'"
    bind < eval "exec sh -c 'xsel -bo >/tmp/screen-exchange'" readbuf
    
  3. ...
  4. profit

How it works

GNU screen has a built-in cut-and-paste metaphor. We leverage two new keybindings C-A > and C-A < to exchange screen data with the X11 Clipboard. The OSX X11 app then pushes the clipboard changes into the local OSX clipboard.

C-A > dumps the current screen paste buffer to /tmp/screen-exchange, and then uses xsel to push the contents of /tmp/screen-exchange to the X11 Clipboard.

C-A < uses xsel to pull the X11 Clipboard contents to /tmp/screen-exchange and then populates the screen paste buffer with the contents of /tmp/screen-exchange. At this point, the normal C-A ] will paste the data.

xsel needs a valid DISPLAY configured to interact with X. If using a remote a screen session, you'll need to forward your X connection and make sure your DISPLAY var is valid inside of your screen session. For more details, see my OSX Remote VIM Clipboard post.

See the commit to my screenrc in my config repository.

Update:

Remove the -n flag from xsel -bi.