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>" ))))

HTML Topic

  1. Emacs HTML Tips
  2. Insert HTML Tag
  3. URL to Link Command
  4. Lines to HTML Table
  5. Replace HTML Entities
  6. CSS Compressor
  7. Color CSS Color Values
  8. View Image Thumbnails
  9. HTML Image Path to Img Tag
  10. Convert Image Files in Dired
  11. Xah HTML Mode

Elisp HTML Commands

  1. wrap-url
  2. URL to Link
  3. Link to Dead Link
  4. Make Image Links
  5. Extract URL
  6. Word to Wikipedia Linkify
  7. Wikipedia URL Linkify
  8. URL Percent Decode/Encode
  9. Lines to HTML Table
  10. Markup Function Names
  11. Color Source Code
  12. Transform Text Under Cursor
  13. Chinese Char Reference Linkify
  14. HTML make-citation
  15. update-title
  16. Google Map Linkify 🌐
  17. CSS Compressor
  18. Make Ruby Annotation
  19. Move Image File

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy a nice keyboard: Best Keyboards for Emacs

Emacs

Emacs Lisp

Misc