AppleScript / Automator : use selected text as variable - applescript

I can't manage to find how to use the selected text as a variable for AppleScript and Automator.
Any ideas?

For Applescript, it works with other applications. To get the selected text of the front window in an app, Applescript has to use the language/syntax that this app understands/responds to. For very scriptable, text document based apps, there is much similarity, looking something like:
tell app "xyz" to get selection of document 1
However, there really is no standard. Many apps don't have a 'text selection' object in their scriptable dictionary, so you have to do all kinds of workarounds. See these examples:
tell application "Safari" to set selectedText to (do JavaScript "(''+getSelection())" in document 1)
tell application "System Events" to tell application process "TextEdit" to tell attribute "AXSelectedText" of text area 1 of scroll area 1 of window 1 to set selectedText to its value
tell application "Microsoft Word" to set selectedText to content of text object of selection
You can also script "System Events" to simulate the keystroke of command-c in order to copy text.
tell application "System Events" to keystroke "c" using {command down}
delay 1
set selectedText to the clipboard
If you need more specific help, post your code and indicate what app you are working with. If it is not a scriptable app, then you'll have to use the last method, calling System Events. Or, it's possible you can use an OS X Service, which you also asked about.
When you create a Service in Automator, you create a new Workflow of the type Service. Then, simply make sure that at the top of the window it says:
"Service receives selected text".
You can then use Automator actions to interact with the selected text that gets passed to the actions that follow.
Not all programs are compatible with Services, unfortunately.

To see how it works, try this very simple Automator service:
Create a Service in Automator and choose Text and Every application as input.
The first workflow step is Execute Applescript.
The Applescript's input parameter contains the selected text.
Set the Applescript to
on run {input, parameters}
display dialog (input as text)
return input
end run
After saving, you will have this action available in the context menu whenever you have selected text.
Maybe the naming is different, I don't know the English descriptions. But I hope this is a good starting point for you.
Have fun, Michael / Hamburg

Related

How to select file using AppleScript in Finder prompt?

I am working with Selenium on macOS to automate sending images using WhatsApp web in Google Chrome. The task involves uploading the image, and for that a system(Finder) prompt comes up to select the file. It's done in Windows using AutoIt.
I tried looking up how to automate this task in macOS, and I believe AppleScript can be used for it. Since I have no experience in GUI scripting, any help would be appreciated.
Thanks.
I was able to find the answer on another post on Stack Overflow. I have added the answer for anyone who comes across the same problem.
tell application "System Events"
keystroke "G" using {command down, shift down}
delay 1
keystroke "/path/to/file"
delay 1
keystroke return
delay 1
keystroke return
delay 1
end tell
I don't advocate GUI scripting any more than the burning down of the Amazon, but it seems to be necessary for this task, and I wanted to provide you with an example of a GUI script that tries its best to minimise the unpleasantness of the user experience, and aim for fewer weak points in the code where GUI scripts are most likely to falter.
If you know the path to your file—which I assume you do in these sorts of situations, as your script keystrokes the filepath—then you might find the following technique saves a few steps, and feels a bit more graceful in how it gets executed:
set filepath to "/path/to/image.jpg"
-- Copy file object to clipboard
set the clipboard to filepath as «class furl»
-- Make sure Chrome is in focus and the
-- active tab is a WhatsApp tab
tell application id "com.google.Chrome"
activate
if the URL of the active tab in the front window ¬
does not contain "web.whatsapp.com" then return
end tell
-- Paste the clipboard contents
-- and hit return (send)
tell application id "com.apple.SystemEvents"
tell (process 1 where it is frontmost) to tell ¬
menu bar 1 to tell menu bar item "Edit" to tell ¬
menu 1 to tell menu item "Paste" to set Paste to it
if (click Paste) = Paste then keystroke return
end tell
The if (click Paste) = Paste check should negate the need for a delay, as it explicitly forces AppleScript to evaluate the click command before going on to issue a keystroke. However, I can't test this under all possible conditions, and if there are other factors, like CPU usage, or process freezes, that are likely to give the script a chance to jump ahead, then just insert a small delay after then and move keystroke return down onto its own line.
If you wish to remove the file object from the clipboard afterwards, then simply add as the final line set the clipboard to (and just leave it blank after the word "to", which will clear the clipboard's contents). Of course, this won't affect any clipboard history data you might have if you use a clipboard managing app, only the system clipboard's current item.

How to set clipboard with value of selected cell in Numbers using AppleScript

I am trying to automate a repeating task between Numbers and Quicken 2017 using AppleScript.
I would like to take the contents of the currently selected cell in Numbers, set the clipboard with that numeric value, and paste that value into the search field in Quicken.
How can one go about doing that with AppleScript?
Example pseudo code to illustrate intent:
tell application "Numbers"
activate
set myCellsValue to value of currently selected cell
set the clipboard to myCellsValue
end tell
tell application "Quicken 2017"
activate
tell application "System Events"
keystroke "f" using {command down}
delay 0.1
keystroke "v" using {command down}
end tell
end tell
You got it 90% correct. I don't use Quicken, but this worked with Microsoft Word:
tell application "Numbers"
activate
tell active sheet to tell application "System Events" to keystroke "c" using command down
end tell
tell application "Quicken 2017"
activate
tell application "System Events"
keystroke "f" using command down
delay 0.1
keystroke "v" using command down
end tell
end tell
I generally like to minimise the amount by which I employ System Events to issue keystrokes or mouse clicks if there’s another way.
Numbers is very much AppleScript-able. I don’t use it personally, but with the help of this site, I’ve pieced together this example script that I wholly admit is untested (I’d appreciate your feedback if you try it out):
tell application "Numbers"
tell the front document to ¬
tell the active sheet to ¬
set CurrentTable to the first table whose class of selection range is range
tell the CurrentTable to get the value of the first cell in the selection range
if the result is not missing value then set the clipboard to the result
end tell
Quicken is also AppleScript-able, but I can’t find a downloadable copy of Quicken’s AppleScript dictionary in order to piece together an equivalent sample of code. However, your Quicken tell block is exactly right for employing System Events to issue a Cmd+V.
However, if you fancy uploading a PDF of the AppleScript dictionary, I can use it to try and draft something more robust.

Automator To "Get Specified Text" then select text and then input keystroke

OK total newb here but this should be pretty simple.
I want to make a little automator script to make a "new day one entry" in my services menu on mac.
So I have text, I need to select this text and then have automator run the keystroke Command+D
Please help!
So far I have the code for the keystroke, I just can't figure out how to make the Automator function "Get Specified text" text to become "selected" so that I can run the applescript.
Here is my automator script so far
You should follow the instructions here: https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/MakeaSystem-WideService.html
First problem I see is that you don't seem to have chosen a document type of "Service" (in Automator). (You should see 'Service receives selected ...' in the title bar.)
You'll need this structure for your AppleScript even though you are not processing the input (the text you have already selected which is picked-up by the system as selected not as a specific parameter for the script).
on run {input, parameters}
tell application "System Events"
keystroke "d" using command down
end tell
end run
I don't have Day One, so I can't tell you what's correct, but it does not appear that Cmd-D is the correct code for a new entry from what I have found on the web.
Finally, if you are substituting a service to select from a contextual menu is that quicker than just doing the keyboard shortcut?

Using Applescript to Change desktop icon size

I am currently using applescript to setup various parameters of the desktops at my university. So far my script successfully changes the desktop background and the dock size.
The problem at hand is when I run the script, majority of the time, the icons on the desktop never change.
Here is the script I wrote to alter the desktop icon's size and grid spacing:
tell application "System Events"
set finderPrefsFile to property list file "~/Library/Preferences/com.apple.Finder.plist"
tell finderPrefsFile
tell property list item "DesktopViewSettings"
tell property list item "IconViewSettings"
set value of property list item "gridSpacing" to "100"
set value of property list item "iconSize" to "32"
set value of property list item "arrangeBy" to "none"
end tell
end tell
end tell
end tell
#Restart Finder for changes to take effect.
do shell script "killall Finder"
How should I go about altering the script to make it work all the time (I would like to eventually share this script with some of my classmates).
P.s.
Here is the full script
I didn't get your script work reliable. I played around with timeouts but didn't get the Finder to refresh using the new settings.
But I found to set some view options directly using vanilla AppleScript:
tell application "Finder"
activate
set iconViewOptions to desktop's window's icon view options
tell iconViewOptions
set arrangement to not arranged
set icon size to 32
set shows item info to false
set shows icon preview to false
end tell
quit
end tell
delay 1
tell application "Finder" to activate
The AppleScript quit-handler works more reliable then do shell script "killall Finder", maybe the killall is too hard...
The delay 1 does the magic to give the Finder the time to breath before get up again and using it the Script works each time...
But one thing is AFAIK not possible in Finder scripting: Setting the grid space :-/
Greetings, Michael / Hamburg

Creating an AppleScript to do a find in a replace in a given document

I'm looking to create aAppleScript that when run will:
Search the document for a given string
Replace that string with another given string
The strings will always be the same
Search for
This will be used in textmate - I was trying to do this in textmate
I know I can use textmate's find and replace functionality - I'm just trying to automate a little.
This should only make changes on the current page.
Is this possible?
UPDATE:
So I've found some code that has got me started...
tell application "TextMate" to activate
tell application "System Events"
keystroke "f" using {command down}
tell process "TextMate"
keystroke "<?"
keystroke tab
keystroke "<?php"
click button "Replace All"
end tell
keystroke "esc"
end tell
but I get the following error:
error "System Events got an error: Can’t get button \"Replace All\" of process \"TextMate\"." number -1728 from button "Replace All" of process "TextMate"
On the find and replace dialog of Textmate the button is labeled "Replace All" Am I missing something here?
You'll have to send the keystroke to the proper window. Something like tell window "find dialog" (or whatever). You have to be completely specific, so it might be
tell tab 1 of pane 1 of window "find and replace" of app textmate...
User interface scripting is so hackalicious you should only do it as a last resort.
Looks like you need sed.
on a command line, or with do shell script:
cat /path/to/your/file.php|sed "s_<?_<?php_g">/path/to/your/newfile.php
or for a whole folder's worth
cd /path/to/your/folder
for file in *.php; do cat "$file"|sed "s_<?_<?php_g">"${file/.php/-new.php}"; done
You're better off looking at MacScripter; there are lots of examples and solutions for find and replacing with or without a texteditor using Applescripts delimiters: MacScripter / Search results, like this:
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
It's all very well sending folks to do search/replace within AppleScript strings, or sending them to Mac OS X's underlying Unix tools, like sed and Perl, but those are often no real substitue for searching/replacing text directly in the target application.
I had the exact same problem, albeit in Dragon Dicate rather than TextMade. Google led me here, where I was dismayed to find no direct solution. So let me share the one I came up with:
set find to "the"
set replace to "THE"
tell application "Dragon Dictate"
activate
tell application "System Events"
tell process "Dragon Dictate"
keystroke "f" using {command down}
keystroke find
keystroke tab
keystroke replace
tell window "Find"
click button "Replace All"
end tell
end tell
end tell
end tell
The key difference is addressing the Find window, which knows about the "Replace All" button. You will also have to change the "Dragon Dicate" target app to "TextMate" of course. (AppleScript seems to require knowing EXACTLY what app a script is being fired against, unless you want to fall back into some truly ugly low-level message sending. When dealing with AppleScript, that's just the 337th sigh of the day!)
If you want to write an AppleScript to manipulate text, there is nothing better than to use an AppleScriptable text editor. That is the right tool for the job. Then you can write just a few lines of code and get the job done.
For example, in TextMate, go Edit > Select All and Edit > Copy to copy the contents of your document to the clipboard. Then run this AppleScript:
tell application "TextWrangler"
activate
set theSearchString to the clipboard
set theResultString to replace "old term" using "new term" searchingString theSearchString
set the clipboard to theResultString
end tell
Then go back into TextMate and go Edit > Paste.
TextWrangler is available for free in Mac App Store.
You may be able to expand this script so that the TextMate work is automated with GUI scripting, but since it is just selecting all and copying and pasting, that is a fairly small task.

Resources