Replacing words in Applescript - macos

I'm back to writing Applescripts. I'm making a script that will Google things for you. Basically, I need to replace all of the spaces with %20. I know a little about text item delimiters, but I don't know how to implement them in this case.
Here's what I got so far:
if userInput contains "Google " then set {TID, text item delimiters} to {text item delimiters, {"Google "}}
if length of userInput is greater than or equal to 2 then set resultString to text item 2 of userInput
if userInput contains "Google " then set text item delimiters to TID
set openPage to (resultString as string)
if userInput contains "Google " then do shell script "open http://www.google.com/search?q=" & openPage
FYI, the userInput variable is the variable I use when dealing with textboxes.
Thanks

I think this script demonstrates the principle of what you’re trying to do:
tell application "Safari"
activate
display dialog "Search Google for:" default answer "" buttons {"Cancel", "OK"} default button "OK" with title (the name as text) with icon note giving up after 60
if the button returned of the result is equal to "OK" then
set theSearch to the text returned of the result
set AppleScript's text item delimiters to space
set theSearchList to every text item of theSearch
set AppleScript's text item delimiters to "+"
set theQuery to theSearchList as text
set AppleScript's text item delimiters to ""
set theLink to "http://www.google.com/search?hl=en&q=" & theQuery & "&btnG=Google+Search"
open location theLink
end if
end tell
However, it’s a lot easier if you just ask an app like BBEdit (or its free version, TextWrangler, which has the same AppleScript dictionary) to do the find and replace for you, because BBEdit is an expert at finding and replacing text, whereas AppleScript by itself is not. AppleScript is a “little language” — it deliberately lacks 95% of the functionality of most programming languages because the functionality is in the apps that you command with AppleScript. In other words, AppleScript expects you to have a text editor with which to process text, therefore AppleScript deliberately doesn’t have the built-in text processing ability of a language like Perl (which you can also use in your AppleScripts.)
So the above script gets a lot shorter, easier to write, easier to read, and easier to understand if you add BBEdit (or the free TextWrangler) into the mix:
tell application "Safari"
activate
display dialog "Search Google for:" default answer "" buttons {"Cancel", "OK"} default button "OK" with title (the name as text) with icon note giving up after 60
if the button returned of the result is equal to "OK" then
set theSearch to the text returned of the result
tell application "BBEdit"
set theQuery to replace " " using "+" searchingString theSearch
end tell
set theLink to "http://www.google.com/search?hl=en&q=" & theQuery & "&btnG=Google+Search"
open location theLink
end if
end tell
Also, notice that you don’t have to run a shell script to open a link in a browser. So this line in your script:
if userInput contains "Google " then do shell script "open http://www.google.com/search?q=" & openPage
… can be written like this:
if userInput contains "Google " then open location "http://www.google.com/search?q=" & openPage
… or like this:
if userInput contains "Google " then
open location "http://www.google.com/search?q=" & openPage
end if
… and you can use the “open location” command with any app, not just Safari. If you tell Finder to “open location” the link will open in your default browser, which might be Chrome.

Related

Removing a word from a variable in Applescript

I'm pretty newbie at Applescript and I can't work out how to remove a word from a variable if the word contains a “#” in it.
My script gets this error -> "Can’t make word into type integer." number -1700 from word to integer
Here's my script so far:
activate application "Grids"
delay 2
tell application "System Events"
keystroke "a" using command down
delay 0.25
keystroke "c" using command down
delay 0.25
set Description to the clipboard
if any word in Description contains "#" then delete that word
return Description
end tell
Any pointers?
Cheers,
Chris
To get text out of the clipboard, use (clipboard as text). The clipboard can contain almost anything, even multiple objects, in multiple formats, so as text gives you a string to work with.
And watch out: 'Description' appears to be part of some existing appleScript 'terminology', at least on the Mac I have right here, so I am changing your identifier to desc here:
activate application "Grids"
delay 2
tell application "System Events"
keystroke "a" using command down
delay 0.25
keystroke "c" using command down
delay 0.25
set desc to the clipboard as text
end tell
set out to {}
set tids to AppleScript's text item delimiters
set AppleScript's text item delimiters to " "
repeat with anItem in (text items of desc)
set str to (anItem as string)
if (str does not contain "#") then
set end of out to str
end if
end repeat
set outStr to out as string
set AppleScript's text item delimiters to tids
return outStr
This code just returns the text you are looking for. It does not re-insert the groomed string, or do anything else interesting.
I assume you're going to tell System Events to paste it via cmd-v. (Remember to set the clipboard to outStr before you paste!)
AppleScript's text item delimiters allows the string to be split and reassembled using a space (or any other token you wish). For code hygiene reasons, it's wise practice to store it before changing it, then reset it to its original value afterwards, as shown here, otherwise odd things might happen in scripts which expect it to have the default value.

Applescript & GarageSale Find & Replace on Selected Items

I found this script for search and find in GS. Its from 2008 so it was likely wirtten for the earlier version 6 as opposed to the current version 7. Its suppose to find text in the description of any current selected template and change it to whatever the user types it. It displays the search and replace boxes correctly and runs without any errors; however, no text is changed.
I have tried the publisher's forum & documentation; macscripter; and Apple's forum. I have tried modifying it multiple times however these changes produce errors that prevent it from running or it runs but does not do anything.
I am using GS 7.0.16 on OS 10.13.6.
The code appears to originate at this
https://macscripter.net/viewtopic.php?id=26963
Any idea of how to modify it?
set theReply1 to (display dialog "Enter text to replace" default answer "text" buttons {"Cancel", "Continue"} default button "Continue")
set origtext to text returned of theReply1
set theReply2 to (display dialog "Enter new replacement text" default answer "text" buttons {"Cancel", "Continue"} default button "Continue")
set replacetext to text returned of theReply2
to searchReplace(thisText, searchTerm, replacement)
set AppleScript's text item delimiters to searchTerm
set thisText to thisText's text items
set AppleScript's text item delimiters to replacement
set thisText to "" & thisText
set AppleScript's text item delimiters to {""}
return thisText
end searchReplace
tell application "GarageSale"
repeat with aTemplate in every selected template
set origline to get the description of aTemplate
set the description of aTemplate to my searchReplace(origline, origtext, replacetext)
end repeat
end tell
UPDATE:
I downloaded the latest beta of version 8 here:
enter link description here
The above code was written for 6. The publisher apparently made a lot of changes to the scripting language from 6 to 7. The publisher includes documentation on its website for the current 7 and beta 8. These more closely match so I decided to import my data to 8 and use Applescript with that.
I modified the above code to that below by exmining some examples in the beta 8 documentation. This script will find a replace a single continous line of text. You must switch from the Preview mode to the Edit mode and copy the html you want to replace. It will not work by copying the styled text form the Preview mode.
The publisher finally added a bulk find and replace to beta 8, but its currently is having problems with finding strings with html in it.
You can use the built in search of the latest beta 8 to find "This is some text". but it will not find "This is some text""More text". The above script will fidn this text.
The script below also works in GS 7.0.16. Simply load into Apple's script editor and compile as an application on your desktop. Select one listing in GS or one or more folders full of listings and run the compiled script. If I am replacing a large string with another large string I find it helpful to place these into two new TextEdit documents so that I can easily copy and paste them into the two dialog boxes shown by the script.
set theReply1 to (display dialog "Enter text to replace" default answer "text" buttons {"Cancel", "Continue"} default button "Continue")
set origtext to (text returned of theReply1)
set theReply2 to (display dialog "Enter new replacement text" default answer "text" buttons {"Cancel", "Continue"} default button "Continue")
set replaceText to text returned of theReply2
to searchReplace(thisText, searchTerm, replacement)
set AppleScript's text item delimiters to searchTerm
set thisText to thisText's text items
set AppleScript's text item delimiters to replacement
set thisText to "" & thisText
set AppleScript's text item delimiters to {""}
return thisText
end searchReplace
tell application "GarageSale"
repeat with theListing in (get selected ebay listings)
set origline to get the description of theListing
set the description of theListing to my searchReplace(origline, origtext, replaceText)
end repeat
end tell

How to search itunes store for app with applescript?

How to search itunes store for app with applescript? I have been stuck on this and recording doesn't work in itunes.
I haven’t seen recording work in years. In this case, though, I’m not sure it could. While iTunes is scriptable, it doesn’t appear to have any direct means to perform a search of the Stores.
However, there is a means to perform a search using a URL and “open location”. It would look something like:
tell application "iTunes"
open location "itms://phobos.apple.com/WebObjects/MZSearch.woa/wa/search?WOURLEncoding=ISO8859_1&lang=1&output=lm&country=US&media=software&term=ia%20Writer"
end tell
Put the text you want to search for after &term=; here, that’s ia%20Writer (with the %20 meaning a space).
This combines info from Ars Technica and Doug’s AppleScripts.
Here's a way you can use an AppleScript display dialog to enter what App to search for in the iTunes Store using the answer provided by Jerry Stratton:
If the search has spaces in it, the script replaces it with %20 for you.
set theAppSearch to ""
set theAppSearch to text returned of (display dialog "App Search iTunes Store for:" default answer "" buttons {"Cancel", "OK"} default button 2)
if theAppSearch is not "" then
set theAppSearch to my replaceSpaces(theAppSearch)
tell application "iTunes"
activate
open location "itms://phobos.apple.com/WebObjects/MZSearch.woa/wa/search?WOURLEncoding=ISO8859_1&lang=1&output=lm&country=US&media=software&term=" & theAppSearch
end tell
end if
on replaceSpaces(theString)
set AppleScript's text item delimiters to {" "}
set theString to text items of theString
set AppleScript's text item delimiters to {"%20"}
set theString to theString as text
set AppleScript's text item delimiters to {""}
return theString
end replaceSpaces

How to open a folder containing a specific string? (Mac)

We got some folders with project IDs with the following Pattern: x123_projectname.
I use Alfred in my workflow and I need to find and open a specific folder by the ID.
It is possible to run applescripts from Alfred. I'm new to applescript and google helped me to create this this:
set theString to "/path/to/folder/containing/projects/"
display dialog "What is the ID?" default answer ""
set theID to the text returned of
(display dialog "What is the ID?" default answer "")
tell application "Finder"
activate
set x to theString & "theID" as alias
open x
end tell
but it didn't work - do you have any hints for me?
You have a couple problems with your script but in general you have the right idea. The main problem is that applescript doesn't work with slash delimited paths. Applescript paths are colon delimited. You can convert from slash to colon delimited using the "posix file" command. Give this a try. Good luck.
set theString to "/path/to/folder/containing/projects/"
display dialog "What is the ID?" default answer ""
set theID to the text returned of result
set macString to POSIX file theString
tell application "Finder"
activate
set theResult to every folder of macString whose name contains theID
open theResult
end tell

Get message in compose window from Mail.app

I am trying to make a script that will get the contents of an email message that I'm composing in Mail, do something with the data, and then send the message. I know how to make and send a new message from scratch with AppleScript, but I can't find a way to get a message that I'm already writing. I don't care what language is used, and I would be open to trying a different email client. Thanks for your help!
Mail has huge limitations with regards to Applescript and dealing with its content area is a major one. The best bet is to use GUI scripting to tab to the content area, type cmd-C, and then work off the data in the clipboard.
Sadly from what I can see Applescript has not been improved at all in Lion.
It's actually pretty easy to do what you need.
If you want to run some kind of an inline processing (assigned to, say, a hotkey (in Mail, e.g. Cmd+D is not occupied), or "just" listed in the Services menu, accessible after selecting something), you can simply use Automator. A demo Automator script reading the current selection, making some changes (here, converting some ASCII char+number combinations to some accented characters) and, finally, returning the modified text is as follows:
on run {input, parameters}
set myText to replaceText("a1", "á", (input as text))
set myText to replaceText("e1", "é", myText)
set myText to replaceText("i1", "í", myText)
return myText
end run
on replaceText(find, replace, someText)
set prevTIDs to text item delimiters of AppleScript
set text item delimiters of AppleScript to find
set someText to text items of someText
set text item delimiters of AppleScript to replace
set someText to "" & someText
set text item delimiters of AppleScript to prevTIDs
return someText
end replaceText
Make sure you enable the "Replaces selected text", should you want to overwrite the original content with the returned one.
if you want to write an external script not invoked from the local Services menu (or via a hotkey), you'll also need to add clipboard handling. A solution similar to the above with additional clipboard copy/paste:
on replaceText(find, replace, someText)
set prevTIDs to text item delimiters of AppleScript
set text item delimiters of AppleScript to find
set someText to text items of someText
set text item delimiters of AppleScript to replace
set someText to "" & someText
set text item delimiters of AppleScript to prevTIDs
return someText
end replaceText
tell application "Mail"
activate
tell application "System Events"
tell process "Mail"
click menu item "Select All" of menu "Edit" of menu bar 1
click menu item "Copy" of menu "Edit" of menu bar 1
end tell
end tell
end tell
tell application "Mail"
set textclip to (the clipboard)
end tell
set myText to replaceText("a1", "á", textclip)
set myText to replaceText("e1", "é", myText)
set myText to replaceText("i1", "í", myText)
set the clipboard to myText
tell application "Mail"
activate
tell application "System Events"
tell process "Mail"
click menu item "Paste" of menu "Edit" of menu bar 1
end tell
end tell
end tell
Note that the latter script selects (and, then, overwrites) the entire window contents. It should be easy to work on the current selection only.
It's possible, but painful. Painful enough that I'm still trying to work out exactly how to do something similar but in Safari. I've gotten to the point where I can find the textarea, but the documentation I've found for getting the content isn't working. (Unfortunately, that's pretty much par for the course for AppleScript; every program does stuff just a little bit differently from the next program.)
EDIT: ok, have some horrible evil which hopefully can be adapted to work with Mail: http://www.ece.cmu.edu/~allbery/edit_textarea.script
This is striaghtforward if we make two reasonably weak assumptions: that the message you're working on is frontmost, and that the subject of all draft messages is unique. Then, before running the script, save the message you're working on; this will place it in the drafts mailbox. Then, since the subject of the message is the name of the window, we can easily access it; and since we can easily access the drafts mailbox, we can combine the two. This gives us:
tell application "Mail"
set msgs to messages of drafts mailbox ¬
whose subject is (name of window 1 as string)
if (count of msgs) = 1 then
-- Do whatever
else
-- Error, disambiguate, whatever
end if
end tell
It's probably possible to make the script save the frontmost window, and it wouldn't surprise me if a freshly-saved message is always the first item of the drafts mailbox, but these are left as an exercise for the reader :-)
So I came across this in 2020 and with this Apple Script it is (now?) possible (whenever its still a bit hacky since I have to use the clipboard for this):
activate application "Mail"
tell application "System Events"
tell process "Mail"
set initialClipboardContent to (the clipboard as text)
set composeWindow to (first window whose title does not contain "Inbox")
set value of attribute "AXFocused" of UI element 1 of scroll area 1 of composeWindow to true
delay 0.05
# CMD + A
key code 0 using command down
delay 0.1
# CMD + C
key code 8 using command down
delay 0.1
set message to (the clipboard as text) as string
log message
set the clipboard to initialClipboardContent
end tell
end tell
Here a proof of concept:

Resources