Category Archives: emacs

2015-11-09 Emacs News

Links from, Hacker News,, Youtube, and the Emacs commit log.

Past Emacs News round-ups

Capturing links quickly with emacsclient, org-protocol, and Chrome Shortcut Manager on Microsoft Windows 8

UPDATE 2015-11-30: Well, that bitrotted quickly! Chrome Shortcut Manager is no longer available, but maybe Shortkeys will work instead.

Since I’ll be snipping lots of Emacs-related resources and organizing them into Emacs news roundups, I figured it was time to get org-protocol working.

Step 1: Get emacsclient to work

I was getting the error “No connection could be made because the target machine actively refused it.” I needed to change my Windows Firewall rules. From the Windows Firewall screen, I clicked on Advanced settings and chose Inbound Rules. On the Programs and Services tab, I confirmed that the right Emacs binary was selecI looked for the rules for GNU Emacs, consolidating them down to two rules (UDP and TCP). I limited the scope to local/remote On the advanced tab, I selected all the profiles and changed edge traversal to blocked.

I was still getting the error despite a fresh M-x server-start. After I deleted the contents of ~/.emacs.d/server and did another M-x server-start. When I ran emacsclient test.txt from the command-line, it correctly opened the file in my existing Emacs instance. Hooray!

Step 2: Load org-protocol

I added org-protocol to the org-modules variable so that Org would load it when Emacs reaches the (org-load-modules-maybe t) in my config. Since I didn’t want to restart Emacs, I also evaluated (load-library "org-protocol") to load it.

Step 3: Register the protocol

I ran an org-protocol.reg that set up the appropriate org protocol entry:

Windows Registry Editor Version 5.00

"URL Protocol"=""
@="URL:Org Protocol"



@="\"c:\\Program Files (x86)\\GNU Emacs 24.4\\bin\\emacsclientw.exe\"  \"%1\""

You can find a similar one in the org-protocol documentation.

Step 4: Add support to Chrome

I wanted something a bit different from the org-capture extensions available for Chrome. In particular, I wanted:

  • a keyboard-friendly way to quickly store a link
  • a keyboard-friendly way to capture a link with some notes

The Shortcut Manager extension for Chrome lets you specify your own keyboard shortcuts for running short Javascript. Inline Javascript doesn’t work on all sites. For example, Github blocks it with the following error: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src". Either the 'unsafe-inline' keyword, a hash ('...'), or a nonce ('nonce-...') is required to enable inline execution. Still, it works for many sites, so it’s a start. Here are the shortcuts I put together.

l Store link
L Store link (prompt for title, default to selection or document title)
c Capture link (prompt for template)

You can import them by going to Chrome’s More Tools > Extensions screen and choosing the Options link for Shortcut Manager. From there, use Import settings.

// ==UserScript==
// @ShortcutManager
// @name Store link
// @namespace XPrUJhE4wRsC
// @key l
// @include *
// ==/UserScript==
var storeLink = function(){
  var selection = window.getSelection().toString();
  var uri = 'org-protocol://store-link://' +
        encodeURIComponent(window.location.href) + '/' +
        encodeURIComponent(selection || document.title);
  window.location = uri;
  return uri;

// ==UserScript==
// @ShortcutManager
// @name Capture link
// @namespace XPrUJhE4wRsC
// @key c
// @include *
// ==/UserScript==
var captureLink =function(){
  var uri = 'org-protocol://capture://' +
        encodeURIComponent(window.location.href) + '/' +
        encodeURIComponent(document.title) + '/' +
  window.location = uri;
  return uri;

// ==UserScript==
// @ShortcutManager
// @name Store link with prompt
// @namespace XPrUJhE4wRsC
// @key Shift+l
// @include *
// ==/UserScript==
var storeLinkWithPrompt = function(){
  var selection = window.getSelection().toString();
  var uri = 'org-protocol://store-link://' +
        encodeURIComponent(window.location.href) + '/' +
        encodeURIComponent(window.prompt('Title', selection || document.title));
  window.location = uri;
  return uri;

Shortcut Manager looks like a really useful extension. Here are some other shortcuts I set up:

x close the current tab
r reload (cacheless)
t open a new tab
n select the right tab
p select the left tab
b back
f forward

Step 5: Add shortcuts for managing stored links

I added my/org-insert-link and org-insert-last-stored-link to my main hydra, which is on my hh keychord. my/org-insert-link is like org-insert-link, except it adds a newline if the cursor is at an Org link so that we don’t trigger org-insert-link‘s behaviour of editing links.

(defun my/org-insert-link ()
  (when (org-in-regexp org-bracket-link-regexp 1)
    (goto-char (match-end 0))
    (insert "\n"))
  (call-interactively 'org-insert-link))

(key-chord-define-global "hh"
                         (defhydra my/key-chord-commands ()
                           ;; ...
                           ("L" my/org-insert-link)
                           ("l" org-insert-last-stored-link)
                           ;; ...

This lets me quickly insert a bunch of links with a key sequence like h h l l l l or select a link to insert with h h L. C-y (yank) pulls in the URL of the last stored link, too.

Let’s see how this works out!

2015-11-02 Emacs News

Previous roundup – Links from,, and Youtube

2015-10-26 Emacs News

Links were from,, and Youtube. Here’s last week’s round-up, too. Enjoy!

2015-10-18 Emacs link round-up

How do you find out about cool new packages? Reddit suggests /r/emacs,, Paradox or package-list-packages, @melpa_emacs, Emacs-related blogs, gnu.emacs.sources, rubikitch’s feed, the MELPA repository (also available as a feed), Emacsist, Awesome Emacs, and other sources. ericjmritz has also been posting overviews of recently released/updated Emacs packages together with suggested config and other resources. September features: eno or avy for navigation, modalka for modal editing, nameless for namespaces, and highlight-thing for seeing other instances of a keyword under point.)

Quite a few people posted navigation tweaks. Check out these Hydra-related blog posts about Paradox, navigation, and other packages. If you use isearch a lot, swiper might be a faster way to search (it now supports visual-line-mode too), and you might like this multiple-cursors extension for it too. Multiple-cursors is neat.

There were a couple of writing-related resources, too. Emacs for Writers was a talk by Jay Dixit at the New York Emacs Meetup. Also, /u/yamadpc asked about a focused mode for writing. Suggestions included focus, darkroom-mode, writeroom-mode, and olivetti. In terms of building your own from the ground up, Emacs, naked describes variables you can set and functions you can call in order to make your Emacs screen cleaner.



Also, just for fun: Pacman.

Links from,, Youtube.

Wow, literate devops with Emacs and Org does actually work on Windows

Since I persist in using Microsoft Windows as my base system, I’m used to not being able to do the kind of nifty tricks that other people do with Emacs and shell stuff.

So I was delighted to find that the literate devops that Howard Abrams described – running shell scripts embedded in an Org Mode file on a remote server – actually worked with Plink.

Here’s my context: The Toronto Public Library publishes a list of new books on the 15th of every month. I’ve written a small Perl script that parses the list for a specified category and displays the Dewey decimal code, title, and item ID. I also have another script (Ruby on Rails, part of that lets me request multiple items by pasting in text containing the item IDs. Tying these two together, I can take the output of the library new releases script, delete the lines I’m not interested in, and feed those lines to my library request script.

Instead of starting Putty, sshing to my server, and typing in the command line myself, I can now use C-c C-c on an Org Mode block like this:

#+begin_src sh :dir /[email protected]:~
perl Business

That’s in a task that’s scheduled to repeat monthly, for even more convenience, and I also have a link there to my web-based interface for bulk-requesting files. But really, now that I’ve got it in Emacs, I should add a #+NAME: above the #+RESULTS: and have Org Mode take care of requesting those books itself.

On a related note, I’d given up on being able to easily use TRAMP from Emacs on Windows before, because Cygwin SSH was complaining about a non-interactive terminal.

ssh -l sacha  -o ControlPath=c:/Users/Sacha/AppData/Local/Temp/tramp.13728lpv.%r@%h:%p -o ControlMaster=auto -o ControlPersist=no -e none && exit || exit
Pseudo-terminal will not be allocated because stdin is not a terminal.
ssh_askpass: exec(/usr/sbin/ssh-askpass): No such file or directory
Permission denied, please try again.
ssh_askpass: exec(/usr/sbin/ssh-askpass): No such file or directory
Permission denied, please try again.
ssh_askpass: exec(/usr/sbin/ssh-askpass): No such file or directory
Permission denied (publickey,password).

As it turns out, setting the following made it work for me.

(setq tramp-default-method "plink")

Now I can do things like the following:

(find-file "/[email protected]:~/")

… which is, incidentally, this file (edited to remove my credentials):

# Displays new books from the Toronto Public Library
# Author: Sacha Chua ([email protected])
# Usage:
# perl <category> - print books
# perl <file> <username> <password> - request books
use Date::Parse;

#!/usr/bin/perl -w
use strict;
use URI::URL;
use WWW::Mechanize;
use WWW::Mechanize::FormFiller;
use WWW::Mechanize::TreeBuilder;
use HTML::TableExtract;
use Data::Dumper;
sub process_account($$$);
sub trim($);
sub to_renew($$);
sub clean_string($);

# Get the arguments
if ($#ARGV < 0) {
    print "Usage:\n";
    print "perl <category/filename> [username] [password]\n";

my $agent = WWW::Mechanize->new( autocheck => 1 );
my $formfiller = WWW::Mechanize::FormFiller->new();
if ($#ARGV > 0) {
  my $filename = shift(@ARGV);
  my $username = "NOT ACTUALLY MY USERNAME";
  my $password = "NOT ACTUALLY MY PASSWORD";
  print "Requesting books\n";
  request_books($agent, $username, $password, $filename);
} else {
  my $category = shift(@ARGV);
  print_new_books($agent, $category);

## FUNCTIONS ###############################################

# Perl trim function to remove whitespace from the start and end of the string
sub trim($)
  my $string = shift;
  $string =~ s/^\s+//;
  $string =~ s/\s+$//;
  return $string;

sub request_books($$$$)
  my $agent = shift;
  my $username = shift;
  my $password = shift;
  my $filename = shift;

  # Read titles and IDs
  open(DATA, $filename) or die("Couldn't open file.");
  my @lines = <DATA>;

  my %requests = ();

  my $line;
  my $title;
  my $id;
  foreach $line (@lines) {
    ($title, $id) = split /\t/, $line;
    chomp $id;
    $requests{$id} = $title;

  # Log in
  log_in_to_library($agent, $username, $password);
  print "Retrieving checked-out and requested books...";
  # Retrieve my list of checked-out and requested books
  my $current_ids = get_current_ids($agent);

  # Retrieve a stem URL that I can use for requests
  my $base_url = '';
  my @already_out;
  my @success;
  my @failure;
  # For each line in the file
  while (($id, $title) = each(%requests)) {
    # Do I already have it checked out or on hold? Skip.
    if ($current_ids->{$id}) {
      push @already_out, $title . " (" . $current_ids->{$id} . ")";
    } else {
      # Request the hold
      my $url = $base_url . $id;
      if ($agent->content =~ /The hold was successfully placed/) {
        # print "Borrowed ", $title, "\n";
        ## Did it successfully get checked out? Save title in success list
        push @success, $title;
      } else {
        # Else, save title and ID in fail list
        push @failure, $title . "\t" . $id;
  # Print out success list
  if ($#success > 0) {
    print "BOOKS REQUESTED:\n";
    foreach my $title (@success) {
      print $title, "\n";
    print "\n";
  # Print out already-out list
  if ($#already_out > 0) {
    foreach my $s (@already_out) {
      print $s, "\n";
    print "\n";
  # Print out fail list
  if ($#failure > 0) {
    print "COULD NOT REQUEST:\n";
    foreach my $s (@failure) {
      print $s, "\n";
    print "\n";

sub get_current_ids($)
  my $agent = shift;
  my %current_ids = ();
  my $string = $agent->content;
  while ($string =~ m/TITLE\^([0-9]+)\^/g) {
    $current_ids{$1} = 'requested';
  while ($string =~ m/RENEW\^([0-9]+)\^/g) {
    $current_ids{$1} = 'checked out';
  return \%current_ids;

sub print_new_books($$)
  my $agent = shift;
  my $category = shift;
  $agent->follow_link(text_regex => qr/Our Newest Titles/);
  $agent->follow_link(text_regex => qr/$category/i);

  my $continue = 1;
  while ($continue) {
    if ($agent->form_with_fields('SCROLL^F')) {
    } else {
      $continue = 0;

# Print out all the entries on this page
sub print_titles_on_page($)
  my $agent = shift;
  my @titles = $agent->look_down(sub {
                                $_[0]->tag() eq 'strong' and
                                $_[0]->parent->attr('class') and
                                $_[0]->parent->attr('class') eq 'itemlisting'; });
  foreach my $title (@titles) {
    my $hold = $title->parent->parent->parent->parent->look_down(sub {
                                                          $_[0]->attr('alt') and
                                                          $_[0]->attr('alt') eq 'Place Hold'; });
    my $id = "";
    my $call_no = "";
    if ($hold && $hold->parent && $hold->parent->attr('href') =~ /item_id=([^&]+)&.*?callnum=([^ "&]+)/) {
      $id = $1;
      $call_no = $2;
    print $call_no . "\t" . $title->as_text . "\t" . $id . "\n";

sub clean_string($)
    my $string = shift;
    $string =~ s#^.*?(<form id="renewitems" [^>]+>)#<html><body>\1#s;
    $string =~ s#</form>.*#</form></html>#s;
    $string =~ s#<table border="0" bordercolor="red".*(<table border="0" bordercolor="blue" cellspacing="0" cellpadding="0">)#\1#s;
    $string =~ s#</table>.*</form>#</table></form>#s;
# Clean up for parsing
    $string =~ s#<!-- Print the date due -->##g;
    $string =~ s#<br> <!-- Displays Date -->##g;
    return $string;

sub log_in_to_library($$$) {
    my $agent = shift;
    my $username = shift;
    my $password = shift;
    $agent->current_form->value('userId', $username);
    $agent->current_form->value('password', $password);

Ah, Emacs!