Find in all open TextEdit documents?
Is there any way to find a string in all open TextEdit documents (rather than just one document?) I have hundred plus such open documents, unsaved.
Solution 1:
The following example AppleScript code when run from Script Editor, or saved as an AppleScript application, will present a search string dialog box for you to type in the search string.
If a match is found, it then creates a new TextEdit document with the name(s) of the document(s) containing the search string. If no match is found, it displays a dialog box with a message.
if running of application "TextEdit" then
tell application "TextEdit"
set docCount to count documents
if docCount is greater than 0 then
set searchString to ""
repeat while searchString is ""
set searchString to my getSearchString()
end repeat
set documentNamesList to {}
repeat with i from 1 to docCount
if text of document i contains the searchString then
copy name of document i to end of documentNamesList
end if
end repeat
if documentNamesList is not {} then
set AppleScript's text item delimiters to linefeed
set documentNamesList to documentNamesList as string
set AppleScript's text item delimiters to ""
set docText to "The following TextEdit documents contain the search string: " & ¬
searchString & linefeed & linefeed & documentNamesList
make new document with properties {text:docText}
activate
else
display dialog "No documents found containing the search string: " & ¬
searchString buttons {"OK"} default button 1 with title "No Match Found"
end if
else
display dialog "There are no open documents to search..." buttons {"OK"} ¬
default button 1 with title "No Open Documents"
end if
end tell
else
display dialog "TextEdit is not open..." buttons {"OK"} default button 1
end if
on getSearchString()
return text returned of (display dialog ¬
"Enter the search string:" default answer ¬
"" buttons {"Cancel", "OK"} default button 2 ¬
with title "Search Open TextEdit Documents")
end getSearchString
Note: The example AppleScript code is just that and does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5
, with the value of the delay set appropriately.