Emacs Lisp: Writing a Wrap-URL Function

Advertise Here

, 2006-10, 2011-09-29

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:

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

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.

Solution

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."
(interactive)
(let (p1 p2 url)
    (search-backward " ")
    (forward-char)
    (setq p1 (point))
    (search-forward " ")
    (backward-char)
    (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 ".+/" "\\1" "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 wrap-url ()
  "Make thing at cursor point into a HTML link.
Example: http://en.wikipedia.org/wiki/Emacs
becomes
<a href=\"http://en.wikipedia.org/wiki/Emacs\">Emacs</a>"
  (interactive)
(let (p1 p2 url linkText)
  (progn
    (search-backward " ")
    (forward-char)
    (setq p1 (point))
    (search-forward " ")
    (backward-char)
    (setq p2 (point))
    (setq url (buffer-substring-no-properties p1 p2))
    (setq linkText (replace-regexp-in-string ".+/" "\\1" url) )
    )
  (delete-region p1 p2)
  (insert (concat "<a href=\"" url "\">" linkText "</a>"))
  )
)

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

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

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

blog comments powered by Disqus