A dialog to enter new search words in a saved search

Hello.

I found a script over at AppleScript Users forum that should work for Leopard. It didn’t for Snow Leopard, so I remade it. I find this easier than to go to the finder bar and and show the search criteria from there by ctrl-clicking on the context menu, and select “Show Search Criteria”. This one will show up the results in a finder window right behind the frontmost script editor window or whatever.

The more complex the other search criterions are, the better can you leverage the reuse of the saved searches of course.
Edit:
As per to day, the only queries that really work as intended is to enter one or several space delimited words.

You can enter expressions like “(before|after) script” for example. it works with the regular spotlight syntax which is further described in the link to Adam Bell’s tutorial below, and which you also get some traces of in the Boolean Operators section of the Spotlight help.

I don’t think this dialog will work with other things than simple searches for words in the contents.
That is: you can’t specify kMDItemAttributes in your search like author:tom or date <= 2010/08/14 for instance.
-I haven’t tried it yet, but I don’t think that will work. And that is because this query really only works on the kMDItemTextContent attribute.

You should not save any extra criterions added through the search field in the finder window of the saved search.

It now lets you select one of your saved searches, ironically I have to use spotlight to do that, in order to show the comments of the file beside it in a choose from list dialog. Some searches, at least some of mine doesn’t search for contents, so there is no use for me, as for you if you have such searches, to enter anything in the box, just hit enter, and then enter your criterion in the search field. Hopefully I will manage to fix this, so that one can enter criterions which goes for the different searches.
You may also have to set extension hidden to either all of your saved searches, or do the opposite in order to get a nice dialog.
And you should really have a look at the window coordinates of the finder window. I run 1200 by 1920 pixels.

try this to figure out what suits you:


tell application "Finder"
	activate
	copy position of its front window to {x, y} --result: {13, 47} 
	copy bounds of its front window to {x1, y1, x2, y2}
end tell
tell me
	activate
	set theText to "{" & x & "," & y & " } { " & x1 & "," & y1 & "," & x2 & "," & y2 & " }"
	set the clipboard to theText
	display alert "The window coordinates were : " & theText & "\nIt is pasted to the clipboard"
end tell

What goes well
b script[/b] goes well ( before or after and script ). A space in a spotlight query goes for and. | goes for or. ~ goes for and not. And you can nest parenthesis.

If this interests you then I would like to introduce you to Adam Bell’s article on Spotlight programming: Using Spotlight in your AppleScripts.

The intention by this way to program Spotlight:
This one leverages on the Finder Search window, because then I have access to quick look by hitting space on a script file for instance. -I can also sort the results to a certain extent.

If you already have a saved.search window open for that particular search, then it is good idea to close it before running the script, for now, while I figure what to do with that problem.


-- The Idea and implementation and any faults is totally mine. © McUsr 2010 and put in the Public Domain.
-- The usually guarrantees about nothing what so ever applies, use it at your own risk.
-- Read the documentation.
-- You are not allowed to post this code elsewhere, but may of course refer to the post at macscripter.net.
” macscripter.net/viewtopic.php?pid=131964#p131964
(*
TERMS OF USE. 
This applies only to posting code, as long as you don't post it, you are welcome to do
whatever you want to do with it without any further permission. 
Except for the following: Selling the code as is, or removing copyright statmentents and the embedded link in the code (without the http:// part) from the code. 

You must also state what you eventually have done with the original source. This obviously doesn't matter if you distribure AppleScript as read only. I do not require you to embed any properties helding copyright notice for the code.

Credit for having contributed to your product would in all cases be nice!

If you use this code as part of script of yours you are of course welcome to post that code with my code in it here at macscripter.net. If you then wish to post your code elsewhere after having uploaded it to MacScripter.net please email me and ask for permission.

The ideal situation is however that you then refer to your code by a link to MacScripter.net
The sole reason for this, is that it is so much better for all of us to have a centralized codebase which are updated, than having to roam the net to find any usable snippets. Which some of us probabaly originated in the first hand.

I'm picky about this. If I find you to have published parts of my code on any other site without previous permission, I'll do what I can to have the site remove the code, ban you, and sue you under the jurisdiction of AGDER LAGMANNSRETT of Norway. Those are the terms you silently agree too by using this code. 

The above paragraphs are also valid if you violate any of my terms.

If you use this or have advantage of this code in a professional setting, where professional setting means that you use this code to earn money by keeping yourself more productive. Or if you as an employee share the resulting script with other coworkers, enhancing the productivity of your company, then a modest donation to MacScripter.net would be appreciated.
*)

-- Originally made by Jaques Rioux From AppleScript Users Group for Leopard.
-- Reworked by  McUsr  for the public domain   see: macscripter.net/viewtopic.php?pid=131964#p131964  for reference
property u : {}
property mergedList : {}
property lengthlist : {}
global maxLen, spacesStr, tabsStr
set magniIcon to a reference to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/MagnifyingGlassIcon.icns"
set helpIcon to a reference to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/HelpIcon.icns"

set spacesStr to "         " -- 4 spaces
set tabsStr to "\t\t\t\t\t\t" -- 6 tabs

set {tids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, linefeed}

set lp to (POSIX path of ((path to "dlib" from user domain as text) & "Saved Searches:")) & "*.savedSearch"
set lp to swapText(lp, " ", "\\ ")
set mdStr to "/usr/bin/mdls -raw -name kMDItemDisplayName  -name kMDItemFinderComment " & lp & " |/usr/bin/xargs -0 /usr/bin/printf \"%s\\t%s\\n\""
set u to paragraphs of (do shell script mdStr)
set AppleScript's text item delimiters to tab
set u to u as text
set AppleScript's text item delimiters to ""
set u to swapText(u, "(null)", "Uncommented")
set AppleScript's text item delimiters to tab
set u to every text item of u
set {mergedList, lengthlist, maxLen} to {{}, {}, 0}
repeat with i from 1 to ((count u) - 2) by 2
	--	set AppleScript's text item delimiters to "."
	set nm to text item i of my u
	set end of mergedList to {nm, text item (i + 1) of my u}
	set nmLen to length of nm
	if nmLen > maxLen then set maxLen to nmLen
	set end of lengthlist to nmLen
end repeat
set AppleScript's text item delimiters to tids
set maxLen to maxLen + 8
set disply_tbl to {}
repeat with i from 1 to (count mergedList)
	-- set end of disply_tbl to contents of item i of names_list & numTabs(item i of len_tbl) & numSpaces(item i of len_tbl) & item i of desc_list
	set end of disply_tbl to contents of item 1 of item i of my mergedList & numTabs(item i of my lengthlist) & contents of item 2 of item i of my mergedList
end repeat

set choosedSearch to choose from list disply_tbl default items {item 1 of disply_tbl}

if choosedSearch is not false then
	set choosedSearch to choosedSearch as text
	set AppleScript's text item delimiters to tab
	set choosedSearch to every text item of choosedSearch
	set theF to text item 1 of choosedSearch
	set idx to indexOfItem(theF, u)
	tell application "Finder" to set names_list to every file in folder ((path to "dlib" from user domain as text) & "Saved Searches:") whose displayed name is (item idx of my u as text)
end if

set smartFolder to names_list as alias as text
set done to false
repeat until done
	set uiAction to (display dialog "Enter a phrase to search" default answer "" with title "Custom Spotlight Search" buttons {"Help", "Cancel", "Ok"} cancel button 2 default button 3 with icon magniIcon)
	if button returned of uiAction is "Ok" then
		set searchCrit to text returned of uiAction
		set done to true
	else
		display dialog "Syntax of Spotlight searches\n\nto|on\t\tto OR on\nto on\t\tto and on\n\"to on\"\t\t\"to on\" as one word\nto~on\t\tto AND NOT on\n(to|on)~in\tto OR on NOT in\n\nA space is like an inclusive AND.\n\nYou can group expressions with parenthesis." with title "Custom Spotlight Search" buttons {"Ok"} default button 1 with icon helpIcon
	end if
end repeat
if searchCrit contains "\"" then
	set searchCrit to swapText(searchCrit, "\"", "\\\"")
end if

tell application "System Events"
	set TheXML to property list file smartFolder
	
	repeat with i in (get (property list items of contents of TheXML))
		
		set t_name to name of i
		if t_name is "RawQuery" then
			try
				set OldVal to my oldSpotlightArgs(get value of i)
				tell i to set value to my swapText((get value), OldVal, searchCrit)
			end try
		else if t_name is "SearchCriteria" then
			tell property list item 2 of property list item "displayValues" of property list item 1 of property list item "FXCriteriaSlices" of i to set value to searchCrit
		else if t_name is "RawQueryDict" then
			try
				set OldVal to my oldSpotlightArgs(get value of property list item "RawQuery" of i)
				tell property list item "RawQuery" of i to set value to my swapText((get value), OldVal, searchCrit)
			end try
		end if
	end repeat
end tell

tell application "System Events"
	set frontmost to true
	open smartFolder
	set frontmost to false
end tell

tell application "Finder"
	launch
	tell its window 1
		set its toolbar visible to false
		set its sidebar width to 0
		set its bounds to {514, 44, 1227, 299}
		set its position to {514, 44}
		set its zoomed to true
	end tell
end tell


set AppleScript's text item delimiters to tids
on oldSpotlightArgs(theArgString)
	local oldArgs
	set {tids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "\""}
	set oldArgs to text item 2 of theArgString
	set AppleScript's text item delimiters to tids
	return oldArgs
end oldSpotlightArgs


on numTabs(txtLen)
	global maxLen, tabsStr
	return text 1 thru ((maxLen - txtLen) div 4) of tabsStr
end numTabs

on numSpaces(txtLen)
	global maxLen
	global tabsStr
	set tmp to ((maxLen - txtLen) mod 4)
	if tmp ≠ 0 then
		return text 1 thru 1 of spacesStr
	else
		return ""
	end if
end numSpaces

on indexOfItem(theItem, itemsList) -- credit to Emmanuel Levy but I modified it with the considering case statements
	local rs
	considering case
		set text item delimiters to return
		set itemsList to return & itemsList & return
		set text item delimiters to {""}
		try
			set rs to -1 + (count (paragraphs of (text 1 thru (offset of (return & theItem & return) in itemsList) of itemsList)))
		on error
			return 0
		end try
		rs
	end considering
end indexOfItem

to swapText(theTExt, swapOut, swapIn)
	(* This bit comes from Apple's own "Replace Text in Item Names" script
with some of the variables changed to make it a call-able handler *)
	if the theTExt contains the swapOut then
		-- replace target string using delimiters
		set AppleScript's text item delimiters to the swapOut
		set the text_item_list to every text item of theTExt
		set AppleScript's text item delimiters to the swapIn
		set the theTExt to the text_item_list as string
		set AppleScript's text item delimiters to ""
	end if
	return theTExt
end swapText

Hello.

Minor fixes: Brings the finder window totally in front. I discovered that it wasn’t feasible to save the saved search with new criterions from the search bar in the finder window of the saved search, and made the “documentation” reflect that. I have also added a help dialog over the most common search operators for spotlight in the search dialog through a button, and “custom icons”.

Hello.

It now lets you select one of your saved searches, ironically I have to use spotlight to do that, in order to show the comments of the file beside it in a choose from list dialog. Some searches, at least some of mine doesn’t search for contents, so there is no use for me, as for you if you have such searches, to enter anything in the box, just hit enter, and then enter your criterion in the search field. Hopefully I will manage to fix this, so that one can enter criterions which goes for the different searches.
You may also have to set extension hidden to either all of your saved searches, or do the opposite in order to get a nice dialog.
And you should really have a look at the window coordinates of the finder window. I run 1200 by 1920 pixels. There is a script in the post above together with the new code.

Hello.

What I have written about hyphens to make concatenate words in to one word as a search term was plain wrong.
They are then indeed interpreted as a filename as Adam Bell wrote in his article.article on Spotlight programming: Using Spotlight in your AppleScripts.

This is still a fragile piece of software. I have made a toolbar icon in finder out of the Saved Searches folder, so that I can have quick access to them, (for dragging them into the sidebar of finder, where I can edit the Search Criteria and look at what has been going on.

There are some issues here to be solved and resolved, but all in all: This makes me search a whole lot faster, when it is this fast to invoke a search directly from within the application I am, without having to resort to finder to find the search, and then maybe open it. I plan to have directed searches for mail and web history as well. And be able to add criterions to the query from the dialog.

Hello.

I have removed two errors of min relating to stuffing in a new kMdQuery which should make it a whole lot better to use.

  • It actually works with those changes. :slight_smile:

Hello.

What I wrote about using boolean operators in this kind of queries appears to be an outright lie! I’m sorry about that.
If I should make those operators work, then I will have to use a different kind of query, and it can be done, but the time does not permit that right now. I’ll let the documentation -at fault! Stand until I have fixed it.

As per to day, the only queries that really work as intended is to enter one or several space delimited words.