Emacs: URL Percent Decode/Encode

By Xah Lee. Date: . Last updated: .

Here's commands to percent encode/decode URL.

(defun xah-html-percent-encode-url (&optional Begin End)
  "Percent encode URL in current line or selection.

Example:
    http://example.org/(Dürer)
becomes
    http://example.org/(D%C3%BCrer)

Example:
    http://example.org/文本编辑器
becomes
    http://example.org/%E6%96%87%E6%9C%AC%E7%BC%96%E8%BE%91%E5%99%A8

URL `http://xahlee.info/emacs/emacs/emacs_url_percent_decode.html'
Version: 2022-04-08 2023-09-24"
  (interactive)
  (require 'url-util)
  (let (xp1 xp2 xinput xnewStr)
    (if Begin
        (setq xp1 Begin xp2 End)
      (if (region-active-p)
          (setq xp1 (region-beginning) xp2 (region-end))
        (setq xp1 (line-beginning-position) xp2 (line-end-position))))
    (setq xinput (buffer-substring-no-properties xp1 xp2)
          xnewStr (url-encode-url xinput))
    (if (string-equal xnewStr xinput)
        (message "no change")
      (progn
        (delete-region xp1 xp2)
        (insert xnewStr)))
    xnewStr
    ))

(defun xah-html-percent-decode-url (&optional Begin End)
  "Decode percent encoded URL of current line or selection.

Example:
 %28D%C3%BCrer%29
becomes
 (Dürer)

Example:
 %E6%96%87%E6%9C%AC%E7%BC%96%E8%BE%91%E5%99%A8
becomes
 文本编辑器

URL `http://xahlee.info/emacs/emacs/emacs_url_percent_decode.html'
Version: 2022-04-08 2023-09-24"
  (interactive)
  (let (xp1 xp2 xinput xnewStr)
    (if Begin
        (setq xp1 Begin xp2 End)
      (if (region-active-p)
          (setq xp1 (region-beginning) xp2 (region-end))
        (setq xp1 (line-beginning-position) xp2 (line-end-position))))
    (setq xinput (buffer-substring-no-properties xp1 xp2))
    (require 'url-util)
    (setq xnewStr (url-unhex-string xinput))
    (if (string-equal xnewStr xinput)
        (message "percent-decode no change")
      (progn
        (delete-region xp1 xp2)
        (insert (decode-coding-string xnewStr 'utf-8))))))

Emacs, Percent Encode/Decode Url