2020-11-23 Emacs and the X selection

One thing I have been reading about lately is the interaction between Emacs and the outside world via the clipboard. Of course, Emacs predates the clipboard by a lot, but it interacts with it pretty nicely. I have a blog post about that in the works, but it’ll need a bit more work, and I’m really busy now (again…), so for today I only have a short tip.

Instead of using the clipboard – at least on GNU/Linux and X Window – you can use the “primary X selection”, which works by first dragging a portion of text (which sets and activates the region in Emacs) and then clicking the middle mouse button where you want to paste it (in Emacs or somewhere else). This is very useful (and can be made even more useful with mouse-yank-at-point set to t, which see), but the “selection” (“active region” in Emacs lingo) is rather volatile (even if less so than in other software), as the manual asserts.

Enter the secondary X selection. It works basically like the primary one, with the following two differences.

  1. It seems to be more “stable” - apparently, it survives quite a lot of editing commands, to the point some people don’t know how to turn it off.
  2. It is created with the Meta key and usual mouse actions (more or less – again, see the manual for details).

This makes it potentially useful to e.g. repeatedly paste some text even if the clipboard or the primary selection is changed. The drawback is that it is mouse-based, but if you use the mouse, this can sometimes be a nice alternative to using e.g. text registers (which are my go-to feature if I need to paste more than one text repeatedly).

Interestingly, there is a way to create a secondary selection without using the mouse. The function secondary-selection-from-region sets it to the active region. For some reason it is not interactive – I have no idea why. I might be tempted to write some functions to be able to use the secondary selection with only keyboard… (There is the second-sel.el package which might also be helpful, though it might also be overkill, depending on your taste and needs.)

OK, so that’s it for today – expect more about copying/pasting in the future!

CategoryEnglish, CategoryBlog, CategoryEmacs