Emacs: URL to Link Command

By Xah Lee. Date: . Last updated: .

Here's a command that wraps a anchor tag (link) at the cursor position.

For example, you have under cursor:

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

Press a button, and it's changed to

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

Put this in your emacs init file:

(defun xah-html-url-linkify ()
  "Make the URL at cursor point into a HTML link.
Work on current non-whitespace char sequence or text selection.

URL `http://ergoemacs.org/emacs/wrap-url.html'

Version 2018-07-28"
  (interactive)
  (let ( $p1 $p2 $input $newStr )
    (if (use-region-p)
        (setq $p1 (region-beginning) $p2 (region-end))
      (save-excursion
        (let ($p0)
          (setq $p0 (point))
          ;; 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 (string-match "^http" $input )
              $input
            (progn (file-relative-name (replace-regexp-in-string "^file:///" "/" $input t t)))))
    (delete-region $p1 $p2)
    (insert (concat "<a href=\"" (url-encode-url $newStr) "\">" $newStr "</a>" ))))

Emacs HTML Topic

  1. Emacs HTML Tips
  2. Emacs: Xah HTML Mode
  3. Emacs: Insert HTML Tag
  4. Emacs: URL to Link Command
  5. Elisp: Replace HTML Entities
  6. Emacs: CSS Compressor
  7. Emacs: Working with CSS Color Values
  8. Emacs: View Image Thumbnails
  9. Emacs: HTML Image Path to Img Tag
  10. Emacs: Convert Image Files in Dired
Patreon me $5 patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

If you have a question, put $5 at patreon and message me.