Elisp: 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:

http://en.wikipedia.org/wiki/Emacs

becomes

<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"
  (interactive)
  (let ((xp0 (point)) xp1 xp2 xinput xnewStr )
    (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))
    (setq xnewStr
          (if (file-exists-p (replace-regexp-in-string "^file:///" "/" xinput t t))
              (file-relative-name xinput)
            xinput
            ))
    (delete-region xp1 xp2)
    (insert (format "<a href=\"%s\">%s</a>" xnewStr xnewStr ))))