Elisp: Wikipedia URL Linkify

By Xah Lee. Date:

Here's a command to change a Wikipedia URL into a HTML link.

For example:

http://en.wikipedia.org/wiki/Saint_Jerome_in_His_Study_(Dürer)

becomes:

<a class="wikipedia-69128" href="http://en.wikipedia.org/wiki/Saint_Jerome_in_His_Study_(D%C3%BCrer)" data-accessed="2015-09-14">Saint Jerome in His Study (Dürer)</a>

and this:

http://zh.wikipedia.org/wiki/文本编辑器

becomes:

<a class="wikipedia-69128" href="http://zh.wikipedia.org/wiki/%E6%96%87%E6%9C%AC%E7%BC%96%E8%BE%91%E5%99%A8" data-accessed="2015-09-14">文本编辑器</a>

The advantage of this command are:

Here's the code.

(defun xah-html-wikipedia-url-linkify ()
  "Change Wikipedia URL under cursor into a HTML link.
If there is a text selection, use that as input.

Example:
http://en.wikipedia.org/wiki/Emacs
⇒
<a class=\"wikipedia-69128\" href=\"http://en.wikipedia.org/wiki/Emacs\" data-accessed=\"2015-09-14\">Emacs</a>.

URL `http://ergoemacs.org/emacs/elisp_html_wikipedia_url_linkify.html'
Version 2015-09-14."
  (interactive)
  (let ($boundaries
        $p1 $p2
        $input-str
        $link-text
        $output-str
        )
    (if (use-region-p)
        (progn
          (setq $p1 (region-beginning))
          (setq $p2 (region-end)))
      (progn
        (let ($p0)
          (progn
            (setq $p0 (point))
            (skip-chars-backward "^ \t\n<>[]")
            (setq $p1 (point))
            (goto-char $p0)
            (skip-chars-forward "^ \t\n<>[]")
            (setq $p2 (point))))

        ;; (setq ξboundaries (bounds-of-thing-at-point 'url))
        ;; (setq ξp1 (car ξboundaries))
        ;; (setq ξp2 (cdr ξboundaries))
        ))
    (setq $input-str (buffer-substring-no-properties $p1 $p2))
    (require 'url-util)
    (setq $link-text
          (replace-regexp-in-string
           "_" " "
           (decode-coding-string (url-unhex-string (file-name-nondirectory $input-str)) 'utf-8)))
    (setq $output-str
          (format
           "<a class=\"wikipedia-69128\" href=\"%s\" data-accessed=\"%s\">%s</a>"
           (url-encode-url $input-str)
           (format-time-string "%Y-%m-%d")
           $link-text
           ))
    (progn
      (delete-region $p1 $p2)
      (insert $output-str))))

In Emacs: Xah HTML Mode

See also: Elisp: Word to Wikipedia HTML Link

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