Monday, August 8, 2011

Emacs lisp functions for word lookup using web services

2011-08-08 Mon 19:47

Without any commentary about Xah Lee besides this preemptory caveat that there is alot of commentary about him, there are some useful functions from his website\_lookup\_ref.html. The two used here are both lookups based on the word under the cursor for either a definition or wikipedia.

In the original definition of his function lookup-word-definition the web service is hard-coded. In preparation for making the particular web service configurable we need to know what might be available and a sense of the API. Xah Lee also had a list of online dictionaries (\_dir/Vocabulary\_dir/dictionary\_tools.html) along with an example for the word 'curlicue'.

American Heritage Dictionary (AHD)
AHD, Random House, …
Merriam Webster Collegiate
Compact Oxford English Dictionary\_oed/curlicue
Oxford Advanced Learner's Dictionary
Open Source Dictionaries*&Query=curlicue
Google dictionary
  • "Google Dictionary is no longer available."

First we declare a new variable, tcb/lookup-word-definition-dictquery, that points to the dictionary and prepares the query under the assumption that the word to be found is the very last part of the string.

(defcustom tcb/lookup-word-definition-dictquery
  "Dictionary and query API used in lookup-word-definition."

Now we define the function itself using the new variable.

(defun lookup-word-definition ()
  "Look up the current word's definition in a browser.
If a region is active (a phrase), lookup that phrase."
 (let (myword myurl)
   (setq myword
         (if (and transient-mark-mode mark-active)
             (buffer-substring-no-properties (region-beginning) (region-end))
           (thing-at-point 'symbol)))

  (setq myword (replace-regexp-in-string " " "%20" myword))
  (setq myurl (concat tcb/lookup-word-definition-dictquery myword))

  (browse-url myurl)
  ;; (w3m-browse-url myurl) ;; if you want to browse using w3m

Another useful function is a wikipedia lookup.

(defun lookup-wikipedia ()
  "Look up the word under cursor in Wikipedia.
If there is a text selection (a phrase), use that

This command switches you to your browser."
 (let (myword myurl)
   (setq myword
         (if (and transient-mark-mode mark-active)
             (buffer-substring-no-properties (region-beginning) (region-end))
           (thing-at-point 'symbol)))

  (setq myword (replace-regexp-in-string " " "_" myword))
  (setq myurl (concat "" myword))
  (browse-url myurl)