Until last week I'd been using xclip to set and retrieve the X selection and X clipboard. But the syntax is a bit nasty -- to output the clipboard it's
xclip -selection clipboard -o. (I have since found out, thanks to the comments on this post, that it's not quite so bad, the options can be abbreviated as long as it's non-ambiguous.) I came across xsel and decided to give it a go. They both do roughly the same thing, but which is better?
Put simply, xsel is a little more advanced and has a nicer syntax.
They can both be installed easily in Ubuntu with
sudo aptitude install xclip and
sudo aptitude install xsel.
First of all, it's important to realize there are three selections X keeps track of: the primary X selection, the secondary X selection (but I've never actually seen this used) and the X clipboard.
The (primary) X selection is what is set when some text is selected and is usually retrieved when the middle mouse button is clicked.
The X clipboard is what most programs set when the copy command is used, and what they retrieve from the owner when the paste command is used.
I used the word "owner" there – in the X environment the program in which text is copied/selected takes "ownership" of the X clipboard or X selection. When another program asks for the contents of the clipboard or selection, X tells it which program is the owner and then the querying program asks the owning program for the contents directly. This means when the owning program exits the contents of the clipboard and selection are lost, unless something else takes over selection ownership. There exist system-tray type programs for this purpose.
Both xsel and xclip use the primary X selection by default. To set it:
some command | xsel
some command | xclip
The same so far. To retrieve it:
No output flag is required for xsel since it detects what stdin and stdout are and picks input or output mode automatically. See its manpage.
To set the X clipboard, xsel's command is much shorter:
some command | xsel -b
as compared to xclip's equivalent
some command | xclip -selection clipboard
And to retrieve the X clipboard
xclip -selection clipboard -o
I often want to put the contents of a file into the selection. I do that with
I've never found any of xclip's other features useful – it can be set to hold the selection until it has been retrieved n times and then delete it, for instance. On the other hand, some of xsel's options look very useful. Some examples:
some command | xsel -a appends text to the selection,
xsel -d deletes the selection and
xsel -k keeps (takes over) the selection so that it won't be lost when the program which set it exits.
Getting at the selection and clipboard from vim
In vim you can read and write to both of these by using the "+ (X clipboard) and "* (X selection) registers. For example, to copy the current line to the X clipboard type
"+yy or to paste from the X selection type