Subscribe to this blog


For blind programmers using text editors like Vim, the command line is in most cases the most convenient work environment on GNU/Linux. On the other hand, some tasks are not possible on a virtual tty, like for instance, browsing complex web pages. The only alternative is to constantly switch to a graphical X session. Copying text between a tty and a X session is more or less a pain. In this short article, I'll describe xclip and some convenient ways to use it with Vim / ZSH / GNU screen.

First of all, you should install this handy little program, e.g. through using apt-get install xclip. If you are not using a Debian-derived distribution, you can have a look at http://xclip.sourceforge.net for the source code.

To copy the text hi to your clipboard, type:

echo "hi" | xclip -d :0

You can view the contents of your clipboard using

xclip -o :0 -i

The :0 denotes the X screen that the X server is running on. In 99 % of all cases, using :0 should be enough. In rare cases, :1 should be used, change to this if you get an error message.

You can of course also copy files into the clipboard. This is as easy as

xclip FILENAMe

where FILENAMe needs to be an existing file.

Using ZSH, you can define a handy middle-line alias which allows commands like:

echo "my text"  | CLIP

For this, open your ~/.zshrc and insert

alias -g CLIP='xclip -d :0 -selection clipboard'

This has the handy advantage that you can paste your data into stdin of xclip as well. Just type CLIP, paste your data and press ctl + d.

To paste text from the GUI to your local Vim instance, you can easily define a command in your ~/.vimrc like this:

com Paste  :call CopyX()
func! CopyX()
    exe ":s/$/\r/g"
    exe ":.!xclip -selection clipboard -d :0 -o"
endfunc

Executing :Paste will then paste text from the X clipboard to your Vim buffer below the current line.

You can also use the clipboard from GNU screen. The following is based on a blog article. and uses instead xclip. Put the following into your ~/.screenrc:

# read and write screen clipboard to X clipboard.
bind > eval writebuf "exec sh -c 'xclip -d :0 -selection clipboard < /tmp/.screen-exchange'"
bind < eval "exec sh -c 'xclip -selection clipboard -o >/tmp/.screen-exchange'" readbuf

Then you can use Ctl-A + > or < to easily get the contents into or out of the screen clipboard buffer.



Comments