Ads by Google

Sunday, October 30, 2011

Searching the Internet from any buffer in Emacs

From the post here by Peter Munster, here's a method to search for any keyword that you're reading in the emacs buffer.

(defun pm/region-or-word (prompt)
  "Read a string from the minibuffer, prompting with PROMPT.
If `transient-mark-mode' is non-nil and the mark is active,
it defaults to the current region, else to the word at or before
point. This function returns a list (string) for use in `interactive'."
  (list (read-string prompt (or (and transient-mark-mode mark-active
                                     (buffer-substring-no-properties
                                      (region-beginning) (region-end)))
                            (current-word)))))
 
(defun pm/google (string)
  "Ask a WWW browser to google string.
Prompts for a string, defaulting to the active region or the current word at
or before point."
  (interactive (pm/region-or-word "Google: "))
  (browse-url (concat "http://google.com/search?num=100&q=" string)))

This will work if you have set

;;point to the appropriate browser
(setq browse-url-firefox-program "C:/Program Files/Mozilla Firefox/firefox.exe")

(setq browse-url-browser-function 'browse-url-firefox
          browse-url-new-window-flag nil
          browse-url-firefox-new-window-is-tab t)


Put this in your .emacs and when you see a word or highlight a region, issue a M-x pm/google (you can rename the function to a mnemonic, if you want to) and it will search for the word before point or region in google.  You probably would want to change the search engine if you want to some other search.

2 comments:

Justin said...

That's neat. Have you also seen webjump? You could conceivably add a drop down that lets you choose which webjump url to use, or base it on the major mode.

http://justinsboringpage.blogspot.com/2009/02/search-reddit-flickr-and-google-from.html

Ross Patterson said...

See also BrowseAproposURL:
http://www.emacswiki.org/emacs-se/BrowseAproposURL