Emacs Lisp: URL to HTML Link

By Xah Lee. Date: . Last updated: .

Here's a command turns a URL at the cursor position into a HTML link.

For example, this:



<a href="http://en.wikipedia.org/wiki/Emacs">http://en.wikipedia.org/wiki/Emacs</a>

Put this in your Emacs Init File:

(defun xah-html-url-linkify ()
  "Make the URL at cursor point into a HTML link.
For example, http://example.org/t.html becomes <a href=\"http://example.org/t.html\">http://example.org/t.html</a>
If text under cursor is a file path, use relative path for href value.
URL `http://xahlee.info/emacs/emacs/wrap-url.html'
Version 2006-10-30 2021-05-18"
  (let (($p0 (point)) $p1 $p2 $input $newStr )
    (if (use-region-p)
        (setq $p1 (region-beginning) $p2 (region-end))
        ;; chars that are likely to be delimiters of full path, e.g. space, tabs, brakets.
        (skip-chars-backward "^  \"\t\n'|[]{}<>〔〕“”〈〉《》【】〖〗〘〙«»‹›·。\\`")
        (setq $p1 (point))
        (goto-char $p0)
        (skip-chars-forward "^  \"\t\n'|[]{}<>〔〕“”〈〉《》【】〖〗〘〙«»‹›·。\\'")
        (setq $p2 (point))))
    (setq $input (buffer-substring-no-properties $p1 $p2))
    (setq $newStr
          (if (file-exists-p (replace-regexp-in-string "^file:///" "/" $input t t))
              (file-relative-name $input)
    (delete-region $p1 $p2)
    (insert (format "<a href=\"%s\">%s</a>" $newStr $newStr ))))