Applescript: copy the selected text and assign it to a var. Then replace the spaces inbetween with - - applescript

Here's a screenshot of my Mouse Gesture App.
I right-click and draw a gesture with my mouse, the app can execute an AppleScript that I put in the right-bottom box.
The scenario for the script is that:
I select a word or two on Chrome
I right-click and draw the gesture with my mouse to trigger the script. Then the script gets the selected word and edits it.
How can the script get the word?
My thought is:
"System COPY command" then "PASTE from Clipboard to a Variable in script"
If you have other better way, that would be great.
After getting the word, edit it by replacing spaces in between with "-" dashes.
i.e. "hook up" --> "hook-up"
Then open a new tab in Chrome where URL is :
https://dictionary.cambridge.org/dictionary/english-chinese-simplified/hook-up Here "hook-up" should be the selected keyword
script generated by ChatGPT, but it doesn't work.
set theText to (the clipboard as text)
set theText to replace_spaces(theText)
set theURL to "www.dictionary.com/" & theText
tell application "Google Chrome"
activate
set currentTab to the active tab of the first window
set URL of currentTab to theURL
end tell
on replace_spaces(theText)
set AppleScript's text item delimiters to " "
set theText to theText as text
set theText to theText's text items as string
set AppleScript's text item delimiters to "-"
set theText to theText as text
set AppleScript's text item delimiters to ""
return theText
end replace_spaces

There are several problems with ChatGPT's script (no surprises there!) The replace_spaces method was totally wrong. Other potential issues were not ensuring that Google Chrome was running and that it had at least one open window. Also, the format of the URL was not quite right to work with that site.
This works in my testing.
use AppleScript version "2.4"
use scripting additions
set theText to (the clipboard as text)
set theText to "hook up" -- for testing only, then comment this out
set theText to replace_spaces(theText)
set theURL to "https://www.dictionary.com/browse/" & theText
if application "Google Chrome" is not running then
launch application "Google Chrome"
delay 1
end if
tell application "Google Chrome"
activate
if (count of windows) is 0 then
make new window
end if
set currentTab to the active tab of the first window
set URL of currentTab to theURL
end tell
on replace_spaces(theText)
set savedTIDs to AppleScript's text item delimiters
set AppleScript's text item delimiters to " "
set theTextItems to theText's text items
set AppleScript's text item delimiters to "-"
set theText to theTextItems as text
set AppleScript's text item delimiters to savedTIDs
return theText
end replace_spaces

Related

How to get the application name for a window reference

When I get the reference to a window using for example:
tell application "Safari"
set theWindow to first window
end tell
log(process(theWindow)) -- # Safari
tell application "Terminal"
set theWindow to first window
end tell
log(process(theWindow)) -- # Terminal
to process(theWindow)
-- How to get app name from "theWindow"
end process
From the variable theWindow, is it possible to extract the app name "Safari"? I need to know this information from a handler because the handler can accept window reference of other application as well.
tell application "Safari"
set theWindow to first window
end tell
log (process(theWindow))
tell application "Terminal"
set theWindow to first window
end tell
log (process(theWindow)) -- # Terminal
to process(theWindow)
try
theWindow as text
on error errorMessage
end try
set ATID to AppleScript's text item delimiters
set AppleScript's text item delimiters to "\""
set appName to text item 2 of errorMessage
set AppleScript's text item delimiters to ATID
return appName
end process

AppleScript: How to extract numbers from a string?

I am writing a script to go to the NYT website on Corona, get the US data, extract numbers (total, death), and to send me a notification. I am close, but when I extract numbers and display them, they are put together (ie 700021 instead of 7000,21). My question is:
How do I extract the numbers so that they are delineated?
Here is the code:
set theURL to "https://www.nytimes.com/interactive/2020/world/coronavirus-maps.html?action=click&pgtype=Article&state=default&module=styln-coronavirus&variant=show&region=TOP_BANNER&context=storyline_menu"
tell application "Safari" to make new document with properties {URL:theURL}
tell application "System Events"
repeat until exists (UI elements of groups of toolbar 1 of window 1 of application process "Safari" whose name = "Reload this page")
delay 0.5
end repeat
end tell
to getInputByClass(theClass, num)
tell application "Safari"
set input to do JavaScript "
document.getElementsByClassName('" & theClass & "')[" & num & "].innerText;" in document 1
end tell
return input
end getInputByClass
set myVar to getInputByClass("g-body ", 5)
on returnNumbersInString(inputString)
set s to quoted form of inputString
do shell script "sed s/[a-zA-Z\\']//g <<< " & s
set dx to the result
set numlist to {}
repeat with i from 1 to count of words in dx
set this_item to word i of dx
try
set this_item to this_item as number
set the end of numlist to this_item
end try
end repeat
return numlist
end returnNumbersInString
set theNums to returnNumbersInString(myVar) as text
display notification "COVID-19 UPDATE" subtitle theNums sound name "glass"
tell application "Safari"
close its front window
end tell
You are getting a list of numbers from the returnNumbersInString handler, but just coercing the list to text doesn't normally provide any kind of formatting. One solution would be to use text item delimiters to specify the text to use when joining the list items. For example, when converting to text for the notification you could do something like:
set tempTID to AppleScript's text item delimiters
set AppleScript's text item delimiters to ", "
set theNums to returnNumbersInString(myVar) as text
set AppleScript's text item delimiters to tempTID
Similar to your other question I helped you with, the target data is already in a table and as such I'd use the table data to get the information as its structure layout is not likely to change where target 'g-body ' of 5 may not always be the United States.
I get my data a little different way:
set theURL to "https://www.nytimes.com/interactive/2020/world/coronavirus-maps.html?action=click&pgtype=Article&state=default&module=styln-coronavirus&variant=show&region=TOP_BANNER&context=storyline_menu"
tell application "Safari" to make new document with properties {URL:theURL}
tell application "System Events"
repeat until exists ¬
(UI elements of groups of toolbar 1 of window 1 of ¬
application process "Safari" whose name = "Reload this page")
delay 0.5
end repeat
end tell
tell application "Safari" to tell document 1 to set CountriesTable to ¬
do JavaScript "document.getElementsByClassName('svelte-f9sygj')[0].innerText;"
tell application "Safari" to close its front window
set awkCommand to ¬
"awk '/United States/{print $3,\"Cases &\",$4,\"Deaths\"}'"
set notificationMessage to ¬
do shell script awkCommand & "<<<" & CountriesTable's quoted form
display notification notificationMessage subtitle "US COVID-19 UPDATE" sound name "glass"
NOTE: The code used to determine when the page in Safari has finished loading works in macOS Mojave and later, however, for macOS High Sierra and some earlier versions, add the words buttons of in front of UI elements ... in the repeat until exists ¬ ... code.
Note: The example AppleScript code is just that and does not contain any 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.

Mac OS Script is supposed to paste a UNC path as SMB, but it keeps converting the colon to a semicolon and converts the capital letters to lower-case

I have a Script that was supposed to convert Windows UNC path to Mac SMB, but keep converting the colon to a semicolon and Upper case to lower case. Here is code. Help is appreciated.
set myClip to the clipboard
set mytext to searchReplace(myClip, "<", "")
set mytext to searchReplace(mytext, ">.", "")
set mytext to searchReplace(mytext, ">", "")
set findIt to "\\"
set replaceIt to "/"
set mylocation to searchReplace(mytext, findIt, replaceIt)
set mylocation to "smb:" & mylocation
set the clipboard to mylocation
do shell script "pbpaste |textutil -convert txt -stdin -stdout -encoding 30 |pbcopy"
tell application "System Events" to keystroke (the clipboard)
on searchReplace(theText, SearchString, ReplaceString)
set OldDelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to SearchString
set newText to text items of theText
set AppleScript's text item delimiters to ReplaceString
set newText to newText as text
set AppleScript's text item delimiters to OldDelims
return newText
end searchReplace
This line:
tell application "System Events" to keystroke (the clipboard)
simulates key presses. The characters in the string are converted to the corresponding key and "pressed" without modifiers like Shift (by default). You can specify a using <modifiers> phrase on the command to specify which modifiers to use, but then those are used for all of the simulated key presses. You can't cause it to simulate the Shift for some key presses (for the upper-case letters and colon) and not others based on the characters in the string.
This seems like a good candidate for a Service rather than a stand-alone script. A service will automatically receive the selected text in the active app and its output will automatically replace that selected text, without having to use the clipboard or simulating key presses. Use Automator.app to create a service, enable "Output replaces selected text", add the Run AppleScript action, and put the guts of your script into the handler.

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

Replacing words in Applescript

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.

Resources