Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

Google Search on Highlighted Text


  • Please log in to reply
41 replies to this topic
NakariaSan
  • Members
  • 50 posts
  • Last active: Apr 03 2011 04:12 PM
  • Joined: 25 Aug 2006
There was recently someone looking for a script in the "Ask For Help" section that would run a Google search on any words he had highlighted (if any). I did make something a while back just for myself, so I posted it for him. I didn't think to post it on the Scripts & Functions section before because it's relatively small, although I suppose it hasgrown in complexity as I've fine-tuned it. It has some smart analyzation of the highlighted string and can differentiate between a URL and just something you'd like to search for (a search query will have a Google Search run on it, in a new window, while a URL will be opened in a new window).

I use Ctrl+G for this, but that can easily be changed. Here's the code...

SendMode Input 
RegRead, OutputVar, HKEY_CLASSES_ROOT, http\shell\open\command 
StringReplace, OutputVar, OutputVar," 
SplitPath, OutputVar,,OutDir,,OutNameNoExt, OutDrive 
browser=%OutDir%\%OutNameNoExt%.exe 

^g:: 
{ 
   BlockInput, on 
   prevClipboard = %clipboard% 
   clipboard = 
   Send, ^c 
   BlockInput, off 
   ClipWait, 2 
   if ErrorLevel = 0 
   { 
      searchQuery=%clipboard% 
      GoSub, GoogleSearch 
   } 
   clipboard = %prevClipboard% 
   return 
} 

GoogleSearch: 
   StringReplace, searchQuery, searchQuery, `r`n, %A_Space%, All 
   Loop 
   { 
      noExtraSpaces=1 
      StringLeft, leftMost, searchQuery, 1 
      IfInString, leftMost, %A_Space% 
      { 
         StringTrimLeft, searchQuery, searchQuery, 1 
         noExtraSpaces=0 
      } 
      StringRight, rightMost, searchQuery, 1 
      IfInString, rightMost, %A_Space% 
      { 
         StringTrimRight, searchQuery, searchQuery, 1 
         noExtraSpaces=0 
      } 
      If (noExtraSpaces=1) 
         break 
   } 
   StringReplace, searchQuery, searchQuery, \, `%5C, All 
   StringReplace, searchQuery, searchQuery, %A_Space%, +, All 
   StringReplace, searchQuery, searchQuery, `%, `%25, All 
   IfInString, searchQuery, . 
   { 
      IfInString, searchQuery, + 
         Run, %browser% http://www.google.com/search?hl=en&q=%searchQuery% 
      else 
         Run, %browser% %searchQuery% 
   } 
   else 
      Run, %browser% http://www.google.com/search?hl=en&q=%searchQuery% 
return


ruddym
  • Members
  • 7 posts
  • Last active: Feb 05 2008 05:51 PM
  • Joined: 09 Jan 2008
Of the Google search selection scripts I've seen, this one is best of breed. Thanks very much NakariaSan.

I have 2 minor suggestions:

Change "prevClipboard = %clipboard%" to "prevClipboard = %ClipboardAll%" so formats are not lost.

Add "VarSetCapacity(prevClipboard, 0)" after "clipboard = %prevClipboard%" to release duplicate clipboard content from memory.

Cheers! :wink:

TotalBalance
  • Members
  • 211 posts
  • Last active: Sep 12 2015 03:17 AM
  • Joined: 22 Jan 2007
Removed previous post. Didn't realize this script can handle text in any app. I'll be using it after all. Thanks!!
Lars

NakariaSan
  • Members
  • 50 posts
  • Last active: Apr 03 2011 04:12 PM
  • Joined: 25 Aug 2006
Thanks, ruddym! :D Those are really good suggestions, I'll edit the previous post now! If you're interested, I also made something like the Google search box for Google Desktop Search (the one that you can bring up by double-clicking Ctrl), for a friend who liked the search box, but didn't want to have to install the whole desktop search program. It uses a lot of the same code and I'd be happy to dig it up for you, if you like (I can't find it now because I'm at work on my Ubuntu machine and all my Autohotkey scripts are, as you can imagine, on my Windows machine which is at home).

ruddym
  • Members
  • 7 posts
  • Last active: Feb 05 2008 05:51 PM
  • Joined: 09 Jan 2008
TotalBalance, it doesn't appear when I right-click in Firefox, so I'm thinking it came with Google Toolbar? I get a similar menu item to search Yahoo for the selected term, with the Yahoo toolbar installed. One of the things I like about the AHK script is it's easily adaptable to search Wikipedia or anywhere else.

NakariaSan, sure if you don't mind posting your Google search box code, I'll try it, thanks.

ruddym
  • Members
  • 7 posts
  • Last active: Feb 05 2008 05:51 PM
  • Joined: 09 Jan 2008
> One of the things I like about the AHK script is it's easily
> adaptable to search Wikipedia or anywhere else.

Oh, and more importantly, the other thing I like is that you can Google a selected term from any app, not just a web page.

  • Guests
  • Last active:
  • Joined: --
ok - i just shrinked down the origin script and am pretty sure that my ugly regex can be beautified, besides some minor issues changed like url recognition is based on protocol not on appearance of dots

this is why i did it, i might be wrong, but here's what i think:
- reading out the registry to have a handler for http is quite pointless, because when run command triggered, same key is being read from system
- if sendmode is input there is no need to blockinput since it'll be blocked anyways until send command is thru and all user input will be pushed afterwards, so why just dont use sendinput command directly, saves us the sendmode and wont possibly screw up the rest of script if integrated in a bigger one and used different there like sendmode play or something
- no need for putting OTB Style after hotkey definition - its not a bad thing, i just dont like it
- the new line to space and the trimming loop can be glued together like i did in my ugly regex
- the urlencode could be either done with a loop and exchanging every char thats not asci with its appopriate %hex value, but this can also be done from browser
- a 'cleaner' method to check for an url would be to check for occurence of http if no http then for at least one slash and if a slash found, then minimum length of chars bewteen last dot left of 1st slash and 1st slash - and still this method wont find a domainname as localhost, but this one can be excluded and checked seperate the quick and dirty method just checks for the protocol, so google can also be queried for the url itself :). checking for dots is not too wise, since these wont be urlencoded and might appear as part of search pattern itself - so using such method could result in calling a search pattern as URL
- exchanging spaces with plus makes IMHO no difference for query results of google

^g:: ; GoogleSearch or Show Link with CTRL+G
  prevClipboard := ClipboardAll
  SendInput, ^c 
  ClipWait, 1
  if !(ErrorLevel)  { 
    Clipboard := RegExReplace(RegExReplace(Clipboard, "\r?\n"," "), "(^\s+|\s+$)")
    If SubStr(ClipBoard,1,7)="http://"
      Run, % Clipboard
    else 
      Run, % "http://www.google.com/search?hl=en&q=" Clipboard
  } 
  Clipboard := prevClipboard
return

greets
derRaphaelh

derRaphael
  • Members
  • 872 posts
  • Last active: Mar 19 2013 04:42 PM
  • Joined: 23 Nov 2007
got kicked ... damn now i been posting as guest

All scripts, unless otherwise noted, are hereby released under CC-BY

ruddym
  • Members
  • 7 posts
  • Last active: Feb 05 2008 05:51 PM
  • Joined: 09 Jan 2008
LOL! Thanks derRaphaelh. Yours looks like very economical code, but I'm going to have to learn more AHK syntax to understand it. Care to add a comment to the RegExReplace line?

TotalBalance
  • Members
  • 211 posts
  • Last active: Sep 12 2015 03:17 AM
  • Joined: 22 Jan 2007
Not sure what the cause is but with both versions of this script, sometimes the search fails with the following msg.

Your search - Your search - SendMode Input RegRead, OutputVar, HKEY_CLASSES_ROOT, http\shell\open\command StringReplace, OutputVar, OutputVar, - did not match any documents. - did not match any documents.

Suggestions:

* Make sure all words are spelled correctly.
* Try different keywords.
* Try more general keywords.
* Try fewer keywords.


Usually the search is ok for the first couple, then the error msg. starts coming up. If I reload, the cycle seems to repeat.

Any ideas why this is happening.
I'm using Firefox.
Lars

ruddym
  • Members
  • 7 posts
  • Last active: Feb 05 2008 05:51 PM
  • Joined: 09 Jan 2008
TotalBalance, try omitting lines 2-5 of NakariaSan's code. I think they're an accidental inclusion.

ruddym
  • Members
  • 7 posts
  • Last active: Feb 05 2008 05:51 PM
  • Joined: 09 Jan 2008
Thanks again NakariaSan and DerRaphael, I have learned some seriously useful code from you two. Not that the world needs another AHK "Google highlighted text" script, but here's mine:

; ----------------------------------------------
;### Search Google for selection, or open URL ###
#space:: 
;Copy Clipboard to prevClipboard variable, clear Clipboard. 
  prevClipboard := ClipboardAll
  Clipboard = 
;Copy current selection, continue if no errors.
  SendInput, ^c 
  ClipWait, 2
  if !(ErrorLevel) {
;Convert Clipboard to text, auto-trim leading and trailing spaces and tabs.
    Clipboard = %Clipboard%
;Clean Clipboard: change carriage returns to spaces, change >=1 consecutive spaces to +
    Clipboard := RegExReplace(RegExReplace(Clipboard, "\r?\n"," "), "\s+","+")
;Open URLs, Google non-URLs. URLs contain . but do not contain + or .. or @
    if Clipboard contains +,..,@ 
      Run, %browser% www.google.com/search?q=%Clipboard%
    else if Clipboard not contains .
      Run, %browser% www.google.com/search?q=%Clipboard%
    else
      Run, %browser% %Clipboard%
  } 
;Restore Clipboard, clear prevClipboard variable.
  Clipboard := prevClipboard
  prevClipboard =
return

NakariaSan's code above works great, but I was intrigued by DerRaphael's use of RegExReplace. So, I learned a bit about Perl regular expressions and came up with my own mods. 8)

Note that my code requires a browser variable to be set elsewhere in the .ahk file, as in:

browser="%ProgramFiles%\Mozilla Firefox\firefox.exe"

or

browser="%ProgramFiles%\Internet Explorer\iexplore.exe"

Cheers!

derRaphael
  • Members
  • 872 posts
  • Last active: Mar 19 2013 04:42 PM
  • Joined: 23 Nov 2007

Clipboard := RegExReplace(RegExReplace(Clipboard, "\r?\n"," "), "(^\s+|\s+$)")


this line modifies the clipboard itself using regular expresions twice (nested)

first one - the inner, just checks for `r`n where the `r is not neccessary to make a match, thats the questionmark indicating and replaces any foundoccurences with a space, the outer expression checks for and leading whitespaces ^\s+ - bracket circumflex (^ indicates to search only at beginning in this case and the + searches for ONE or more occurences of the whitespace \s this is combined with a pipe symbol | to have a different case check: the \s+$ checks for ONE or MORE whitespaces \s+ at the end indicating by $
so this line can also be writte as two lines first the inner and after that the outer, but why bother? of cource one can say it being faster processed this way, which is quite true, but seriously we're talking about a few input chars being regexed, i dont care if user input being proccessed 5 mseconds faster this way, when i can put up compact code ... would look different in a loop and bigger textes to search

its would be usefull, when you set the autotrim parameter in your script and restore it later, since it not always set to ON when using the clipboard = %clipboard% line

using a predefined brower variable makes only sense when you have more than one browser installed and want to use your NOT preffered browser to make the search or lookup the snippet

in the other case system will look up the handler for http protocol itself and choose the proper programm being used

greets
derRaphael

All scripts, unless otherwise noted, are hereby released under CC-BY

silveredge78
  • Members
  • 499 posts
  • Last active: Mar 14 2014 03:19 AM
  • Joined: 25 Jul 2006
I have created an IE AutoOpen Function that can be applied for this purpose as well (in fact I do):

; IE AutoOpen Hotkeys
#w::IEAutoOpen("URL","")  ; WinKey+w				;;AutoOpen Link
#g::IEAutoOpen("Google","www.google.com/search?q=")  ; WinKey+g	;;AutoOpen Google and Search
#p::IEAutoOpen("Yahoo profiles","profiles.yahoo.com/")  ; WinKey+p	;;AutoOpen Yahoo Profiles Link
#u::IEAutoOpen("Free Dictionary search","http://www.thefreedictionary.com/")  ; Win+u	;;AutoOpen Free Dictionary

IEAutoOpen(Desc,URL)		; v1.0.2, 09/18/07
{
  ClipSaved := ClipboardAll	; Save the entire clipboard to a variable of your choice.
  Clipboard = %Clipboard%
  TextClip = %Clipboard%  
  Clipboard = 
  Send, ^c
  ClipWait, 1
  IEClip = %Clipboard%
  Clipboard = %TextClip%
  InputBox, URLString, %Desc%, Please enter the %Desc% string to be opened in IE:, , , , , , , , %IEClip%
  If (GetKeyState("Control")) And (URL = "")	; Suggested by Lexikos
    URLString = www.%URLString%.com		; Suggested by Lexikos
  Clipboard := ClipSaved	; Restore the original clipboard. Note the use of Clipboard (not ClipboardAll).
  ClipSaved =			; Free the memory in case the clipboard was very large.
  If ErrorLevel <> 0
    Return
  Run, iexplore.exe %URL%%URLString%
}
Basically, you can use this to open any IE window you want. You call the function passing the base string and the description of what it is. If it is a blank passthrough of the base string, you can hit Ctrl+Enter rather than just Enter to have it add on the www. and .com to the string in it. If you have any questions, feel free to ask. I use this 25+ times a day! :)

It keeps your original clipboard, and gives you a stripped down text only version of what is in your original clipboard for you to paste in the inputbox, and then when it is done, its back to your original clipboard. :)
SilverEdge78

Morpheus
  • Members
  • 475 posts
  • Last active: Oct 21 2014 11:08 AM
  • Joined: 31 Jul 2008
I modified NakariaSan's code to work with IE7 and tabs. This will use the active tab if IE is already open, instead of a new instance.

Requires Sean's Com Standard Library: <!-- m -->http://www.autohotke...topic22923.html<!-- m -->

I think the GetWebBrowser() function is Sean's as well...

#singleInstance Force
SetTitleMatchMode, 2
SendMode Input

^g::
{
   BlockInput, on
   prevClipboard = %clipboard%
   clipboard =
   Sleep, 50
   Send, ^c
   BlockInput, off
   ClipWait, 2
   if ErrorLevel = 0
   {
      searchQuery=%clipboard%
      GoSub, GoogleSearch
   }
   clipboard = %prevClipboard%
   return
}

GoogleSearch:
   StringReplace, searchQuery, searchQuery, `r`n, %A_Space%, All
   Loop
   {
      noExtraSpaces=1
      StringLeft, leftMost, searchQuery, 1
      IfInString, leftMost, %A_Space%
      {
         StringTrimLeft, searchQuery, searchQuery, 1
         noExtraSpaces=0
      }
      StringRight, rightMost, searchQuery, 1
      IfInString, rightMost, %A_Space%
      {
         StringTrimRight, searchQuery, searchQuery, 1
         noExtraSpaces=0
      }
      If (noExtraSpaces=1)
         break
   }
   ;StringReplace, searchQuery, searchQuery, \, `%5C, All
   StringReplace, searchQuery, searchQuery, %A_Space%, +, All
   StringReplace, searchQuery, searchQuery, `%, `%25, All
   IfInString, searchQuery, .
   {
      IfInString, searchQuery, +
         Search := "http://www.google.com/search?hl=en&q=" . searchQuery
      else
         Search := searchQuery
   }
   else
      Search := "http://www.google.com/search?hl=en&q=" . searchQuery
   COM_CoInitialize()
   If Not   pweb := GetWebBrowser()
      Run, %Search%
   Else
   COM_Invoke(pweb, "Navigate", search)
   COM_Release(pweb)
   COM_CoUninitialize()
   WinActivate, Windows Internet Explorer
return

GetWebBrowser()
{
   ControlGet, hIESvr, hWnd, , Internet Explorer_Server1, ahk_class IEFrame
   If Not   hIESvr
      Return
   DllCall("SendMessageTimeout", "Uint", hIESvr, "Uint", DllCall("RegisterWindowMessage", "str", "WM_HTML_GETOBJECT"), "Uint", 0, "Uint", 0, "Uint", 2, "Uint", 1000, "UintP", lResult)
   DllCall("oleacc\ObjectFromLresult", "Uint", lResult, "Uint", COM_GUID4String(IID_IHTMLDocument2,"{332C4425-26CB-11D0-B483-00C04FD90119}"), "int", 0, "UintP", pdoc)
   IID_IWebBrowserApp := "{0002DF05-0000-0000-C000-000000000046}"
   pweb := COM_QueryService(pdoc,IID_IWebBrowserApp,IID_IWebBrowserApp)
   COM_Release(pdoc)
   Return   pweb
}