Miscellaneous ephemera…

w3m, Surfraw and Yanking URLs


I posted a couple of weeks ago about how much I was enjoying Surfraw, to the point of writing a couple of my own elvi. As part of the ongoing tweaking of my Surfraw experience, I have been experimenting with different text-based browsers, to see which one best fits my workflow.

I have previously been using both links and it’s homophone, lynx. While these have been perfectly acceptable, they weren’t quite providing the level of functionality —and integration with my vim-oriented workflow— that I was looking for. Enter w3m.

w3m is a text-based web browser as well as a pager like `more’ or `less’. With w3m you can browse web pages through a terminal emulator window (xterm, rxvt or something like that). Moreover, w3m can be used as a text formatting tool which typesets HTML into plain text.

w3m is a step up from the other two for a variety of reasons. It supports tables, frames, SSL connections, color and inline images. It also renders pages in a form as true to their original layout as possible. The killer features on top of that are, for me, the above mentioned rendering of HTML as text (meaning you can save content easily), and the customizable keybinds.

There was however, one significant sticking point. After countless hours fruitlessly searching, I was unable to find a way to yank URLs to the clipboard. As I have been spending a little time of late on Unix & Linux Stack Exchange, I thought I would ask the good folk there…

Less than fourty hours later, I had an answer so simple and elegant, that I was literally grinning when I read it. It deserves quoting in full. It is that ingenious.

Set the “External Browser” option to sh -c 'echo "$0" | xsel'

You can use xsel -b to use the clipboard instead of the primary selection. An alternative to xsel is xclip (xclip for the primary selection, xclip -selection CLIPBOARD for the clipboard).

In ~/.w3m/config, that’s the extbrowser setting. Then press M to copy (yank) the URL of the current page, or ESCM to copy the URL of the link under the cursor.

You can use the second or third external browser for that instead; then the key combination is 2M or 3M or 2ESCM or 3ESCM. Gilles on Unix & Linux Stack Exchange

This simple hack means that it is now trivial to yank either the URL of the current page, or of the link under the cursor to primary selection. It was just a matter then of adding some intuitive keybinds – as the M and EscapeM combination are redolent of the unamed editor:

keymap y EXTERN

The perfect UNIX solution

Updated 8/5/11

Gilles has edited and updated his answer with a slight change:

sh -c 'printf %s "$0" | xsel'

This prevents a new line being appended.