Elisp: Calling External Command to Decode URL Percent Encoding

By Xah Lee. Date: . Last updated: .

Here's a example of calling external script from emacs lisp to transform current region.

Problem

We want to decode percent encoded URL. See: Elisp: URL Percent Decode/Encode.

Solution

JavaScript has a function decodeURIComponent that does exactly what we need. [see JavaScript Encode URL, Escape String]

Here's the JavaScript code:

// -*- coding: utf-8 -*-
// 2014-01-11

// take a URI from stdin, percent decode it to stdout
// called from emacs

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function(chunk) {
  process.stdout.write(decodeURIComponent(chunk));
});

You need Node.js installed to run JavaScript script.

Here's the emacs lisp wrapper command:

(defun xah-decode-uri (p1 p2)
  "percent decode URI for text selection

Requires a node.js script. See code."
  (interactive "r")
  (let ((scriptName "/usr/bin/node /home/xah/git/xahscripts/emacs_uri_decode.js"))
    (save-excursion
      (shell-command-on-region p1 p2 scriptName nil "REPLACE" nil t))))

For how to write a elisp wrapper in general, see: Elisp: Write Emacs Commands Using Python, Ruby, ….

For a pure emacs lisp solution to decode URL, see: Elisp: URL Percent Decode/Encode.

Liket it? Put $1 at patreon. Or Buy Xah Emacs Tutorial. Thanks.