Category Archives: geek

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

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

Python + sewing: Making basic shapes and splitting up larger patterns

More Python and sewing. =) The first step was to make parameterization even easier by allowing command-line specification of measurements. I refactored some code from and modified mkpattern to accept the new arguments, splitting up the name and value based on regular expressions (commit). That way, I could quickly generate patterns based on different dimensions, like so:

python ../mkpattern --client=../customer/Sacha/sacha-cm.json \
   --pattern=../patterns/ \
   --styles=../tests/test_styles.json \
   -m height=4in -m width=7.5in -m seam_allowance=0.5in \
   -m depth=7.5in -m strap_width=1in -m strap_length=10in -m hem_allowance=1in \

I sketched basic patterns for cylindrical and box-type containers the other day, so I wanted to try them out. It turned out that the Python framework I used for sewing patterns didn’t yet support arcs. Adding the arc element to the SVG was straightforward. I initially faked the bounding box for the arc, but since that made the code misbehave a little, I looked around for a better implementation. I translated the code from this post from 2011 to Python and added it to the code (git commit). That allowed me to make a simple cylinder pattern generator. I haven’t tested it yet, but it looks reasonable.

2015-10-27 20_30_11-foo.svgThe box tote was interesting to work on. When I did the math, I couldn’t believe that the calculations were that simple. I was waiting for a sqrt or a cos to show up, I think. Still, the small-scale paper version I taped up looks like it makes sense, and I’ll sew a full-size version soon. J- asked for a light blue lunch bag that would fit our standard containers, and I’ve been meaning to make a casserole carrier for a while now. It would be handy to be able to make bags that are the right size. Too small and things don’t lie flat, too big and they move around too much.

2015-10-27 20_31_54-foo.svg - Inkscape

I spent most of my time making a flexible circle skirt pattern, pretzeling my brain around circumferences, angles, multiple pieces, and fullness multipliers. I’m happy with the way it turned out. It can generate patterns for quarter-circle skirts, half-circle skirts, full-circle skirts – even an arbitrary fraction of skirt fullness split into an arbitrary number of pieces, with optional seam allowance, waist seam allowance, and hem allowance. If you give it the fabric width, it will split the pattern into however many pieces are needed. If you specify a seam allowance and you want a full-circle skirt in a single piece (maybe for dolls), it’ll leave room for the seam allowances by adjusting the inner radius. We’re heading into snow pants season, so I probably won’t get around to testing it in fabric for a while. Caveat netrix, I guess.

I also got around to writing a tool for splitting up large patterns so that I could print them on a regular printer. I had tried Posterazor and a few other tools for splitting up large images into smaller pages, but I wanted something that would add cutting lines and page numbers. It turns out that all you need to do is change the SVG’s height, width, and viewPort. I added a rectangle for the cutting line and some text for the page numbers. I haven’t figured out how to use pysvg to replace the contents of an existing text element, but since the tool prints out non-overlapping regions, I just keep adding more text elements. My script creates a numbered sequence of SVGs. I haven’t found a convenient way to print multiple SVGs in one go, but I can select multiple PNGs and print those, and I can use Inkscape’s command line to convert SVGs to PNGs like so:

inkscape -z -e output-01.png -d 300 output-01.svg

There’s supposed to be a -p command to output Postscript ready for printing, but command-line printing on Windows doesn’t seem to be as much of a thing as it is on Linux. Something to figure out another time, maybe. Anyway, now that I have a conversion pipeline, I can write a Bash script or Emacs Lisp to process things automatically.

I’ll probably move from all this theoretical script-writing to more hands-on sewing during the rest of the week. My fabric order has arrived, so I’ve got a bit of cutting and sewing ahead of me.

Hmm. With the command-line measurement and scaling overrides, it might be interesting to use this framework for papercraft and laser-cutting too. Someday!

Programmatically rescaling and manipulating the darts in sewing patterns

I’ve been playing with the tmtp project for programmatically generating SVGs based on body measurements in order to create basic blocks and sewing patterns (see my previous blog post). I’m not yet at the point of being able to look at an image and see if it will sew correctly. However, printing and taping up large patterns is frustrating and a waste of paper. Scaling the patterns down so that they fit on a single page of paper makes perfect sense. With the measurements I’m working with, a scale of 0.2 (1″ : 5″) makes things fit neatly on 8.5″x11″ paper. It’s easy enough to cut them out and tape them up into something that resembles the form.

Here’s the commit that adds the scaling factor, and the commit that adds a very useful --scale command-line option. This lets me do something like this:

python mkpattern --verbose \
  --client=customer/Sacha/sacha-cm.json \
  --pattern=patterns/ \
  --styles=tests/test_styles.json --scale=0.2 output.svg

I generated a bunch of SVGs using my measurements, printed and cut them, and taped them up. Tada! They look like they make sense. The easy-fitting bodice block from Metric Pattern Cutting is, as expected, looser than the close-fitting bodice block, and both are a little bit bigger than the basic bodice block from BurdaStyle.

2015-10-26 16.17.312015-10-26 16.20.17

The basic shirt pattern from Cal Patch’s Design-it-Yourself Clothes fits over the basic blocks, as expected. It looks a little boxy compared to the blocks, but it will probably be fine in cotton, since cotton won’t be as stiff as paper.

2015-10-26 16.18.49

If I end up doing this a lot, I’ll probably look into modifying the patterns to draw an outline on a separate layer. Then I can convert the SVG for use with Hacklab’s laser cutter (see my previous experiments and fun results), so I can easily test with paper or fabric.

I was thinking about the viability of printing a small, to-scale 3D model based on measurements. Doesn’t have to be a photorealistic 3D scan of me – apparently you can get photorealistic 3D prints for about ~$120 these days, but that’s still a bit much. If it’s not from a scan, though, there’s the challenge of generating a good model based on entered measurements, or creating/adjusting an existing model of a dress maker’s mannequin. Anyway, papercraft with basic blocks seems to be a decent starting point. =)

With the scaling factor in place, I did the math for dart manipulation. Darts help add shape to fabric, turning flat pieces into slightly conical structures. If you wanted to move a dart on paper, you could tape the dart closed, then cut a new line to the apex of the dart and spread the pattern until it’s flat again. (Wikipedia describes this as slash-and-spread.)

There’s an SVG rotate transformation that would probably make it easier to handle the rotation of complex shapes. I haven’t figured out how to add an SVG group in tmtp yet, though. Instead, I:

  1. Added a pair of points where my “cut” was going to be
  2. Calculated the existing dart angle
  3. Rotated one of the dart points, one of the new cut points, and the points in between – to make things easier, I specified which points to rotate
  4. Redrew the front bodice

I added a few library functions, so now the code to rotate a dart is pretty short. It takes an array defining the dart points (start, apex, end), and another array of the points to rotate around the apex by the calculated angle.

def rotateDart(self, dart_points, points_to_rotate):
    # Determine the angle of rotation
    angle = angleOfVectorP(dart_points[0], dart_points[1], dart_points[2])
    # Rotate the dart closed
    (dart_points[0].x, dart_points[0].y) = rotateP(dart_points[0], dart_points[1], angle)
    # Rotate the rest of the points
    for i in range(len(points_to_rotate)):
        (points_to_rotate[i].x, points_to_rotate[i].y) = rotateP(points_to_rotate[i], dart_points[1], angle)

When I printed out my test pattern and cut it, the new pattern matched the result of slashing and spreading the dart on the previous bodice. Hooray for paper testing!

2015-10-26 18.27.54

The next step would probably be to make an SVG slicer that converts large patterns into segments that can be printed on a home printer. It would probably move/clip the image, add cutting lines and labels for convenience, and export a series of SVGs. If I’m lucky, I might be able to find a Python library that will let me easily create a multi-page PDF.

More thoughts on sewing and programming: it would be nifty to be able to easily program variable seam allowances, so that I could say that one seam has a 1/2″ allowance and the other has a 2″ hem allowance. Lines should be pretty straightforward – just offset a parallel line by the specified distance. Bezier curves might be a challenge. In “An offset algorithm for polyline curves” (Liu, Yong, Zheng, and Sun, 2006), the authors describe a algorithm involving trimming the offset curves of a polyline curve. I should check out the approximation algorithms mentioned in their literature review – might be an easier thing to start with, especially if I can wrap my head around the way the existing code’s curveLength function interpolates curves. Or I can leave the addition of variable allowances as a human step. It’s not that hard with a seam allowance ruler. Still, it would be neat to have laser-ready SVGs… =)

Anyway, now that I’ve got a simple way to test things on a small scale and a bit more of a handle on the math, I’m looking forward to playing around with generating actual patterns instead of just basic blocks. Whee!

2015-10-26 Emacs News

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

Decision review: Mid-range phone (Moto G), and thinking about how to get even more out of it

My Samsung Galaxy S3 started uncontrollably turning off in February. Even after I cleaned the switches and contacts, it wouldn’t reliably stay on.

On W-‘s recommendation, I switched to a Moto G (2nd gen) a few days after my old phone died. I bought the mid-range Android phone from Staples instead of getting it through a phone contract.

I was a little nervous about my Moto G’s storage limits (16GB, no external storage), but surprisingly enough, it’s been fine. I subscribe to a handful of podcasts, and I’ve given up on the desire to keep an offline copy of my sketches for easy flipping. I’ve picked a few Evernote notebooks and Dropbox folders to synchronize offline, and I leave the rest for online or desktop use.

W- recommended the Otter Commuter case, so I got that too. His is black and mine is purple. Since the phones and cases are identical, sometimes I accidentally pick up his instead of mine if I’m not looking. The case has been working out nicely as well. It’s nice not having to worry so much about dropping my phone (which I’ve done more than a few times) or cracking the screen (which I haven’t).

It’s been almost eight months with the phone. I’m happy with the decision to go with the Moto G instead of splurging on a higher-end phone or choosing something more basic. I mostly use it for alarms, activity tracking, reading, mail, calls, weather forecasts, timers, tethering, remote cheque deposits, and the occasional app or game.

I still haven’t gotten around to Android development, even though that was one of the things I was curious about. Web development is easier for me and more generally useful. I did get around to learning more about Tasker and Javascript, and the quick activity tracker I put together for my most frequently-used categories has been handy. I haven’t played around much with NFC either, since that activity tracker’s been convenient enough for quick interactions and it’s always available.

The recent Android OS update improved the power use. I’ve been okay in terms of battery life – enough to feel comfortable listening to podcasts or leave the pedometer app running in the background.

I’ll probably use my phone even more over the next year, so it might be good to think about how I can get even more value out of it.

  • I haven’t quite gotten into the habit of reading e-books on my phone, even though I have the Kindle and Overdrive apps installed. I think it’s a combination of being impatient with the low information-density-per-page-turn of non-fiction books and not building up a fiction backlog instead. I read a bit of fanfiction from time to time. Hmm, maybe I can slowly work my way through classic literature.
  • In terms of podcasts, I like listening to CBC’s Ideas program, and W- and I sometimes chat about the episodes. I also listen to podcasts about philosophy, and Stoicism in particular. I can look around for tech shows, like the one that Daniel Gopar is starting up around Emacs.
  • It would probably be good to take more pictures, too. Sewing, maybe?
  • If I trim my Feedly blog subscriptions a bit more and then add feeds in line with my current interests, that would help me get more out of blog reading.
  • Jotting quick ideas in Evernote worked well before, but I haven’t been doing it lately because I’ve been casually browsing the web instead. Since browsing has diminishing returns, perhaps I’ll shift more attention towards writing.
  • I wonder if the performance and accuracy of speech recognition has improved enough for it to be mostly usable. Hmm…
  • Time to get back to doing flashcards, too!

I’ve settled into comfortable routines, but there’s so much I haven’t explored yet. Looking forward to taking advantage of the phone’s capabilities!