Emacs Lisp: Writing a Wrap-URL Function

Buy Xah Emacs Tutorial. Master emacs benefits for life.
, , …,

This page shows a example of writing a emacs lisp function that creates a HTML link on a URL string in the buffer. If you don't know elisp, first take a look at Emacs Lisp Basics.

Problem Description

Suppose you work in HTML a lot, and often need to make a URL into a link.

Suppose you have this URL text in your buffer:


and your cursor is on that line. You want to be able to, press a button, and have the text changed to

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

This page shows you how to write this function.


Here's the outline of steps:

Here's how to grab the text the cursor is on.

;; this snippet grabs the current block of text delimited by space.
;; It relies on the very useful search-backward and search-forward
;; and buffer-substring
(defun ff ()
"test. grabs the sequence of chars delimited by space."
(let (p1 p2 url)
    (search-backward " ")
    (setq p1 (point))
    (search-forward " ")
    (setq p2 (point))

    (setq url (buffer-substring p1 p2))
    (message "%s" url)

Now, if the URL “http://en.wikipedia.org/wiki/Green_tea”, we want the link text to be just “Green_tea”. We can do this with replace-regexp-in-string.

(replace-regexp-in-string ".+/" "" "http://en.wikipedia.org/wiki/Green_tea")

Now, we have the URL string and the linkText string. We need to concatenate them into one string. The key function is concat.

; concatenate strings
(concat "a" "b" "c")

Now we know how to code all the major steps for our wrap url function. We can put them together.

(defun tt ()
  "Make thing at cursor point into a HTML link.
Example: http://en.wikipedia.org/wiki/Emacs
<a href=\"http://en.wikipedia.org/wiki/Emacs\">Emacs</a>"
(let (p1 p2 url linkText)
    (search-backward " ")
    (setq p1 (point))
    (search-forward " ")
    (setq p2 (point))
    (setq url (buffer-substring-no-properties p1 p2))
    (setq linkText (replace-regexp-in-string ".+/" "" url) )
    (setq linkText (replace-regexp-in-string "_" " " linkText) )
  (delete-region p1 p2)
  (insert (concat "<a href=\"" url "\">" linkText "</a>"))

Now, we can test this. For example, here is a URL:

checkout this http://en.wikipedia.org/wiki/Emacs from Wikipedia

Put your cursor on the URL, and call wrap-url. The URL will become a link.

Like it?
Buy Xah Emacs Tutorial
or share
blog comments powered by Disqus