Google Search from within Emacs

A quick and dirty eLisp function for searching on the internet from within Emacs. The default is to search using Google, but you can add to the *internet-search-urls* variable to setup additional search URLs.

By default, the search term is appended at end of the URL – however, you can also encode the specific search term insertion point in the URL by marking the position using the “%s” marker.

;;; The custom search URLs
(defvar *internet-search-urls*
 (quote ("http://www.google.com/search?ie=utf-8&oe=utf-8&q=%s"
         "http://en.wikipedia.org/wiki/Special:Search?search=")))

;;; Search a query on the Internet using the selected URL.
(defun search-in-internet (arg)
 "Searches the internet using the ARGth custom URL for the marked text.

If a region is not selected, prompts for the string to search on.

The prefix number ARG indicates the Search URL to use. By default the search URL at position 1 will be used."
 (interactive "p")

 ;; Some sanity check.
 (if (> arg (length *internet-search-urls*))
      (error "There is no search URL defined at position %s" arg))

  (let ((query                          ; Set the search query first.
    (if (region-active-p)
      (buffer-substring (region-beginning) (region-end))
    (read-from-minibuffer "Search for: ")))

  ;; Now get the Base URL to use for the search
  (baseurl (nth (1- arg) *internet-search-urls*)))

  ;; Add the query parameter
  (let ((url
    (if (string-match "%s" baseurl)
      ;; If the base URL has a %s embedded, then replace it
         (replace-match query t t baseurl)
    ;; Else just append the query string at end of the URL
      (concat baseurl query))))
 
   (message "Searching for %s at %s" query url)
   ;; Now browse the URL
   (browse-url url))))
Advertisement

2 thoughts on “Google Search from within Emacs

  1. Interesting! I did not know about Webjump. The usual Emacs adage seems to apply again … you do learn a new thing every day!

    This also triggers a thought that the ‘little’ packages in official Emacs are not quite well documented and are probably resulting in code/function rewrites by the dozen. The only reference I found in Emacs 23.1 for Webjump was in the Acknowledgements section of the info file.

    Next project for self: Scan the Emacs core elisp directories for new and hidden gems.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.