Another region-or-thing Example

In my last post on region-or-thing, I promised an example that uses the bounds information that region-or-thing returns. This example is much like the google-search function except that instead of looking up a word or phrase in Google, it turns the word or phrase into an Org-mode link to Wikipedia.

That requires a little explanation. Org-mode uses plain text for everything it does. You could, if you like, write your Org-mode files in any editor but then, of course, the display formatting that Org-mode does wouldn’t appear and you wouldn’t have the keyboard shortcuts. In its role as a markup language, it needs a way to encode links such as the link to the region-or-thing post above. The actual link is encoded as

[[http://irreal.org/blog/?p%3D50][region-or-thing]]

although Org-mode has a more convenient way of entering links than adding all the square brackets yourself. One other thing you should know is that for Wikipedia links, blanks are replaced by underscores.

With that information, it’s pretty easy to write our function

1:  (defun org-wp-linkify ()
2:    "Turn the region or word at the point into an org Wikipedia link"
3:    (interactive)
4:    (let* ((thing (region-or-thing 'word))
5:           (subject (replace-regexp-in-string " " "_" (elt thing 0))))
6:      (delete-region (elt thing 1) (elt thing 2))
7:      (insert (concat "[[http://en.wikipedia.org/wiki/" subject
8:                      "][" (elt thing 0) "]]"))))

On line 4, we call region-or-thing to get the vector describing the word or phrase and put it in the local variable thing. On line 5, we replace any spaces in the text with an underscore and store the result in subject. Next we delete the word or phrase from the Emacs buffer (line 6)—note how we use the bounds of the text to do that. Finally, we insert the link to Wikipedia in its place.

That’s a surprising amount of functionality for 8 lines of code (3 of which are boilerplate), but then it’s Lisp. Notice that some simple and obvious changes to lines 7–8 could make the function build a “normal” HTML link for use in non-Org files.

This entry was posted in Programming and tagged . Bookmark the permalink.