Elisp: URL to HTML Link + Date

By Xah Lee. Date: . Last updated: .

Here's a command that change a URL into a HTML link, with access date.

example:

http://some.example.com/xyz.html

becomes:

<a href="http://example.com/x.html" data-accessed="2015-09-12">http://example.com/x.html</a>

Note that the date is automatically inserted. Access date in the URL link is useful, because when the content changed or becomes dead, a access date helps you find the original content. The data- are Custom Data Attribute introduced in HTML5. 〔see HTML5 Custom Data Attribute

Here's the code.

(defun xah-html-source-url-linkify ()
  "Change URL under cursor into a HTML link.
If there's a text selection, use the text selection as input.
Example: http://example.com/x.htm becomes <a href=\"http://example.com/x.htm\" data-accessed=\"2008-12-25\">http://example.com/x.htm</a>
URL `http://xahlee.info/emacs/emacs/elisp_html-linkify.html'
Version 2008-12-25 2021-07-31"
  (interactive)
  (let ((xp0 (point)) xp1 xp2 xinput )
    (if (use-region-p)
        (setq xp1 (region-beginning) xp2 (region-end))
      (save-excursion
        ;; chars that are likely to be delimiters of full path, e.g. space, tabs, brackets.
        (skip-chars-backward "^  \"\t\n'|[]{}<>〔〕“”〈〉《》【】〖〗〘〙«»‹›·。\\`")
        (setq xp1 (point))
        (goto-char xp0)
        (skip-chars-forward "^  \"\t\n'|[]{}<>〔〕“”〈〉《》【】〖〗〘〙«»‹›·。\\'")
        (setq xp2 (point))))
    (setq xinput (buffer-substring-no-properties xp1 xp2))
    (delete-region xp1 xp2)
    (insert (format
             "<a href=\"%s\" data-accessed=\"%s\">%s</a>"
             xinput (format-time-string "%Y-%m-%d") xinput
             ))))