Tuesday, August 03, 2010

Handy Emacs Function: url-decode-region

Every once in a while I get the need to URL decode some text while hacking away in emacs. I always spend a few moments looking for a way to do this, but usually give up. Tonight, I dug just a little deeper and learned about url-uhex-string.

This function does the URL encoding, but isn't interactive by default. So here's a quick elisp function I wrote up to make it so:

(defun url-decode-region (start end)
  "Replace a region with the same contents, only URL decoded."
  (interactive "r")
  (let ((text (url-unhex-string (buffer-substring start end))))
    (delete-region start end)
    (insert text)))

Now, I can highlight a region, and type M-x url-decode-region, which is what my fingers wanted to do all along, anyway.

If the need arises, or anyone is interested, I can write up url-encode-region.

3 comments:

  1. Thank you, although I added a second parameter of t to url-unhex-string so it would handle newlines.

    And here is the inverse function:

    (defun url-encode-region (start end)
    "Replace a region with the same contents, only URL encoded."
    (interactive "r")
    (let ((text (url-hexify-string (buffer-substring start end))))
    (delete-region start end)
    (insert text)))

    ReplyDelete
  2. Thank you!

    ReplyDelete
  3. nice! saved me a tonne of time updating some urls that i did not encode properly

    ReplyDelete