How can control the paste of a string with AppleScript? - applescript

In BBEdit and AppleScript I can loop through a string and set the string to the clipboard with:
set the clipboard to jsonString
I can then make a new text document and save it with:
set jsonParseFile to (name of project window 1) as text
save text document jsonParseFile to file ("some:location") without saving as stationery
set jsonParseFile to (name of active document of project window 1) as string
but when I try to paste the contents of the string with paste I get an error indicating that paste is not understood:
BBEdit got an error: active document doesn’t understand the “paste”
message.
So when I remove:
set jsonParseFile to (name of active document of project window 1) as string
and use:
paste of active document
I get the same error but when I just use paste I'm returned the error of:
BBEdit got an error: Can't continue paste.
How can I paste the string into the file variable jsonParseFile which is the front most file without calling on:
tell active document of project window 1 to paste
but rather with something like:
tell active document of file jsonParseFile to paste
that passes jsonParseFile? When I search I haven't found anything beyond keystroke and I'm not wanting to use and when I check the dictionary for answers I'm not getting much:

This is a simple example how to paste a string into the active document
set the clipboard to "Hello World"
tell application "BBEdit"
tell active document of project window 1
paste
end tell
end tell

Related

Applescript alter text on clipboard

I have written an AppleScript to automate my work setup and just need the final touch. I copy something to clipboard in my script; I need to edit the text I copied to leave only the last line (preferably without opening an actual text editor application, as this would clutter my workspace) and just paste that line in the Google Chrome browser.
In the last step of my script so far I do something causing message text to be output to Terminal. Then I get the text visible in Terminal to be copied to the clipboard as follows:
tell application "Terminal"
tell front window
set the clipboard to contents of selected tab as text
end tell
end tell
Now I can for example paste it, and it's something like
...
[I 15:03:31.259 LabApp] Serving notebooks from local directory: /workspace
[I 15:03:31.259 LabApp] The Jupyter Notebook is running at:
[I 15:03:31.259 LabApp] http://1fw5c518af9:1932/?token=5e6d97b348fsy734gd
[I 15:03:31.259 LabApp] or http://88.0.0.1:1932/?token=5e6d97b348fsy734gd
[I 23:56:47.798 LabApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 23:56:47.803 LabApp]
To access the notebook, open this file in a browser:
file:///root/.local/share/jupyter/runtime-open.html
Or copy and paste one of these URLs:
http://1fw5c518af9:1932/?token=5e6d97b348fsy734gd
or http://88.0.0.1:1932/?token=5e6d97b348fsy734gd
This always ends with text of the format or *URL*, e.g. in the above example it would be or http://88.0.0.1:1932/?token=5e6d97b348fsy734gd. This is separated from the line above by a line delimiter plus some trailing white-space before "or".
What I need to do is grab that URL, start a Google Chrome browser and paste it in there.
For opening Google Chrome, it should be simple enough, the following code (from this tut) takes you to Instagram:
tell application "Google Chrome" to activate
tell application "System Events"
key code 37 using command down
delay 0.5
keystroke "https://www.instagram.com/instagram"
delay 1
key code 36
delay 1
end tell
and literally all I need is something which edits what's on the clipboard to just the *URL* (in the case of the above example, just http://88.0.0.1:1932/?token=5e6d97b348fsy734gd). After that I can paste it from the clipboard (where Instagram is typed in, in the tutorial).
After trying the lovely answer by #user3439894 below I found the situation is a bit more complicated:
there are an unpredictable number of blank lines "" after the final
link.
I'm also wondering whether there may be white-space at the end
as well
I already know the form of http://88.0.0.1 (it's always consistently this) so is there a way of maybe searching for that and then just grabbing it with the rest of the link that follows? (it would be great to be able to delimit the end by either " " or new-line)
Edit 2:
In case http://88.0.0.1... occurs multiple times, we would like to select just one of these URLs - they are probably generally the same, but selecting the last would be safest.
What I need to do is grab that URL, start a Google Chrome browser and paste it in there.
&
This always ends with text of the format or *URL*, e.g. in the above
example it would be or http://88.0.0.1:1932/?token=5e6d97b348fsy734gd. This is separated
from the line above by a line delimiter plus some trailing white-space
before "or".
&
In case http://88.0.0.1... occurs multiple times, we would like to
select just one of these URLs - they are probably generally the
same, but selecting the last would be safest.
If what you are trying to do is get the last URL that starts with http://88 from the contents of the selected tab of the front window in Terminal, then here is a way to do it without using the clipboard, and open it in Google Chrome, and also do it without having to use UI Scripting.
In other words, no need to alter the text on the clipboard or keystroke the URL as you can just tell Google Chrome what to use for the URL.
Example AppleScript code:
tell application "Terminal" to ¬
set theTextFromTerminal to ¬
the contents of ¬
the selected tab of ¬
the front window ¬
as text
set theURL to ¬
the last paragraph of ¬
(do shell script ¬
"grep -o 'http://88.*$' <<< " & ¬
theTextFromTerminal's quoted form & ¬
"; exit 0")
if theURL is "" then return
if theURL does not start with ¬
"http://88." then return
tell application "Google Chrome"
activate
delay 1
if exists front window then
make new tab at ¬
end of front window ¬
with properties {URL:theURL}
else
set URL of ¬
the active tab of ¬
(make new window) to theURL
end if
end tell
Note: The example AppleScript code is just that and sans any included error handling 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.

How do I add text to a new BBEdit document at creation?

I open a lot of new documents in Textwrangler/BBedit and I would like them to always have the date printed at the top. I would like this to be automatic so that I don't have to remember to run a script each time.
I'm new to BBEdit but I really like Textwrangler and have used it for years. I read some of the documentation on BB and I think that attaching some Applescript to an event might be the way to go. However, none of the listed events seem quite right, and I don't really want to add dates to existing documents.
I found the following page which was a good starting point:
http://bbeditextras.org/wiki/index.php?title=Scripting_and_Automation
I also found these relevant hooks from the BB docs:
App attachment points
applicationDidFinishLaunching: called when the application has completed
startup.
applicationShouldQuit: called when you choose the Quit (or the application
receives a ‘quit’ event for any other reason).
applicationDidQuit: called when the application has finished shutting down and is about to exit.
applicationDidSwitchIn: called when BBEdit has been brought to the foreground.
applicationWillSwitchOut: called when BBEdit is being put into the background.
Document attachment points
documentDidOpen: called when a document has been opened and is ready for use. (Since BBEdit supports multiple types of documents, your script should allow for the argument to be a document of any type.)
documentShouldClose: called when the application is preparing to close a
document.
documentDidClose: called when the application has closed a document.
documentShouldSave: called when the application is trying to determine whether a given document should be saved.
documentWillSave: called when the application is about to begin saving a
document. (note that this will only be called after a successful return from a
‘documentShouldSave’.
documentDidSave: called after a document has been saved successfully.
documentWillUnlock: called when BBEdit is going to make a document writeable. (For example, when you click the pencil to unlock a document)
documentDidUnlock: called when BBEdit has successfully made a document
writeable.
documentWillLock: called when BBEdit is going to make a document read-only.
documentDidLock: called when BBEdit has successfully made a document readonly.
I don't know if any of those really fit, though. I could also try adding some scripts into the startup folder, but I'm not sure how I would go about say, adding a date to all open documents. I've never done applescript before so it's a little trial and error.
I have this code that I've tried running by itself, and it works fine:
tell application "BBEdit"
tell text window 1
select insertion point after (last character)
set selection to ((current date) as string)
end tell
end tell
I'm just a little lost as to how to get the above code to execute on file creation.
Open Script Editor and paste the following code in a new script document:
use BBEdit : application "BBEdit"
use scripting additions
on documentDidOpen(doc)
set n to the doc's name
set t to the doc's text as string
if n does not start with "untitled text" then return
if t's length > 0 then return
set the contents of the doc to (the (current date) as text) ¬
& linefeed & linefeed
end documentDidOpen
Save it as type script (extension .scpt), and name it Document.documentDidOpen.scpt. Either save it directly, or move it subsequently, to the folder ~/Library/Application Support/BBEdit/Attachment Scripts/; if the folder doesn't exist, create it.
Restarting BBEdit ought not to be necessary, but also couldn't hurt. Now, whenever you create a new document (of any type), it will be headed with the current date and time.
Try using BBEdit's 'Attaching Scripts to Menu Items' feature (p 295 of the v11 User Manual). In a nutshell, if you save a script to the Menu Scripts folder with a name based on the menu/command, then this script will run when that menu item is selected. So in your scenario:
Save the script below to BBEdit's Menu Scripts folder with the filename 'New•Text Document'.
tell application "BBEdit"
set cDate to ((current date) as text)
make new document with properties {contents:cDate}
end tell
As an aside, you can generally avoid using selection with the insertion point, for example:
tell document 1 of application "BBEdit" to set text of ¬
first insertion point of text 1 to ((current date) as text)
In your second 'question' scenario, you could probably cycle through all existing windows with that, for example:
tell application "BBEdit"
set tdCount to count of text documents
repeat with i from 1 to tdCount
set text of first insertion point of text 1 of ¬
text document i to ((current date) as text) & linefeed
end repeat
end tell

Change the color of text by using applescript

I am writing some text in to word file i want to change the color of that text any one can help on that one plz.
I want to print the 'message' from following script in red color.
Here is the Script:
set message to "mostly these windows are popup in application"
on ResultCreationFuction(message)
try
set text_to_save to message as text
tell application "System Events"
tell application "Finder"
set sortedList to sort (get files of folder "SofTestAutomationResult" of desktop) by modification date
set FileCount to get count of sortedList
set theFile to (item FileCount of sortedList) as alias
end tell
set file_ref to open for access theFile with write permission
write (text_to_save & return) to the file_ref starting at eof
close access file_ref
delay 2
end tell
end try
end ResultCreationFuction
Some Details:
The file is word which is all ready present on above location having name "10.012.2014_17_4_20.doc" (the name of .doc file is not fix)
What you are attempting is the wrong way to do it.
To manipulate content like that, including formatted text (not plain
text), you need to work within, ideally, a well-scriptable app, like
Pages (or Word, perhaps, but I don't have that on the machine I'm
writing this from).
Don't use System Events if you don't need to. Use the apps with the appropriate AppleEvents/dictionary, etc. If you don't know what I'm talking about, you need to take advantage of the infinite resource known as the web.
"Fuction" is just bad form.
I would suggest doing a lot more reading up on how AppleScript works (or scripting in general), but to start you out, here is a script I just wrote in pages which sets the color of a specific word of the open document after putting text in there:
tell application "Pages"
set body text of document 1 to "hello there mister fancy pants"
set color of word 3 of body text of page 1 of document 1 to {64614, 0, 111}
end tell
If you have Pages, try this by starting with a blank page and running this script. Obviously, you could get rid of "word 3 of" in the 2nd line, and the whole body text will be red.
I hope this makes sense and is of help.
[edit]
I should mention that even TextEdit is scriptable and can open Word documents. Here's an example using TextEdit:
tell application "TextEdit"
set text of document 1 to "hello mister fancy pants"
set color of words 2 thru 3 of text of document 1 to {65535, 0, 0}
end tell
There is a little danger of non-Word apps losing formatting of Word files. But it just seems you are attempting something very simple, and I'm not sure if Word is really necessary here.
You can't add color using the write to eof. You should open the document in Word and then insert the line and add the color. Here's a script that should demonstrate how:
set text_to_add to "mostly these windows are popup in application"
set theFile to ((path to desktop folder) & "10.012.2014_17_4_20.doc") as string
tell application "Microsoft Word"
set theFile to theFile as string -- assuming theFile is an alias or :: path
open file theFile
tell active document
set endOfDoc to end of content of text object -- insert the text to end of document
set theRange to create range start (endOfDoc - 1) end endOfDoc
insert text text_to_add at theRange
set myRange to create range start endOfDoc end (endOfDoc + (length of text_to_add))
set color index of font object of myRange to red
save
end tell
end tell

AppleScript to get name of single selected file in finder

I want to get the name of the currently in the finder window selected file. I'm working under OS X 10.9.2.
Here's my code:
display dialog "test"
tell application "Finder"
set theItems to selection
display dialog number of theItems
repeat with itemRef in theItems
display dialog name of itemRef
end repeat
end tell
In the Finder I selected only one mp3 file.
If I run the script then the dialogbox with "test" and the dialogbox with "1" is displayed correctly. But then I got the error message that the file cannot be converted into a type string.
I hope you can help me to fix this bug and I thank you in advance for your reply!
The name property of a file is already a text (or string) type. You are not properly parenthesizing the dialog statement.
display dialog (get name of itemRef)
file cannot be converted into a type string.
Then convert it to a string.
display dialog (name of itemRef) as string
I'd suggest you to use log instead of display dialog for debugging purpose.
For instance, log name of itemRef will return (in your "Events" and "Replies" window):
(name of document file 123.jpg of folder Desktop of
folder Saturnix of folder Users of startup disk)
As you can see, this is much more complex than a simple string of test (like "123.jpg"). This is telling you that name of itemRef is not returning the actual name of the file itemRef but a reference to that name. Luckily enough, calling as string on that reference will return us the actual name of the file.

Copying .rtf text into the body of an email with AppleScript

I have an AppleScript application which creates an email (in Mail.app) with attachments from the options I choose through dialogs. The text templates are stored in .rtf format so non-programers can alter the text templates to their wishes.
I am able to create an email from a .txt plain text file, but when I import an .rtf text file it imports the formatting commands, which I don’t want in the mail.
Here is an example of a .rtf import into an email:
{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf360
{\fonttbl\f0\fswiss\fcharset0 Helvetica-Light;}
{\colortbl;\red255\green255\blue255;}
\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural\pardirnatural
\f0\fs24 \cf0 technology mail for english speakers\
Here is part of my script:
-- Import the .rtf file and store content in the mycontent variable
set mycontent to (read "/Users/kiara/Desktop/mailer/technology/tech-en-content.rtf")
…
…
-- create mail from values stored in variables
tell application "Mail"
set theMessage to make new outgoing message with properties {visible:true, subject:mysubject, content:mycontent}
tell content of theMessage
make new attachment with properties {file name:this_file} at after last paragraph
end tell
end tell
Is it possible to import formatted text from .rtf files into a new mail without the formatting codes (I choose rtf because mostly bold and color are used to format text)?
Here is another approach:
set the clipboard to (read "/Users/kiara/Desktop/mailer/technology/tech-en-content.rtf" as «class RTF »)
tell application "Mail"
activate
set theMessage to make new outgoing message with properties {visible:true, subject:"mysubject"}
end tell
tell application "System Events"
tell process "Mail"
repeat until focused of UI element 1 of scroll area 4 of window 1
keystroke tab
end repeat
keystroke "v" using command down
end tell
end tell
I think Mail sends an email as either plain text or html, not rtf. So you would need to send your email as html not rtf. Note there's a trick to sending a html email with Mail via applescript. For some reason you can't set the visible property of the new message to true. It won't work if you do.
Here's how this can help you. You can use the command line tool textutil to convert the rtf to html and then send it as an email. Notice I use "tidy" in the command to make sure the html code is clean.
So all you need to do is put the receiver's email address and a subject in this script and run it...
set emailAddress to "someone#somewhere.com"
set theSubject to "My converted rtf to html"
set rtfFile to choose file with prompt "Choose the RTF file to email as HTML:" without invisibles
set theHTML to do shell script "/usr/bin/textutil " & " -stdout -format rtf -convert html " & quoted form of POSIX path of rtfFile & " | /usr/bin/tidy -b -utf8"
tell application "Mail"
set newMessage to make new outgoing message at end of outgoing messages with properties {visible:false}
tell newMessage
make new to recipient at end of to recipients with properties {address:emailAddress}
set subject to theSubject
set html content to theHTML
send
end tell
end tell
adayzdone answer works for me - more or less.
under Mac os X 10.15.6 , Mail 13.4 the scroll area is at another position / index.
And instead of using keystroke tab to get the content-Area an alternative way is to
set value of attribute "AXFocused" of UI element of scroll area 1 of window 1 to true
if you need to find the scroll area or identify other UI elements - you might want to use
on FindScrollAreas()
set Indices to {}
set the clipboard to "hello World"
tell application "System Events"
tell process "Mail"
activate
set i to 1
repeat with UIElement in UI elements of front window
-- button, text field, scroll area, static text
if class of UIElement is scroll area then
set end of Indices to i
end if
set i to i + 1
end repeat
end tell
end tell
return Indices
end FindScrollAreas
and there is also the fantastic approach in using Automator watch me do to get the menu items:
see this post
(you have to copy-paste the Events from Automator to some text-Editor to get some corresponding applescript)
and there is Xcode -> Xcode(menu) -> Open Developer Tool -> Accessibility Inspector - but i find it hard to transfer info to applescript
hope that helps, best -tom

Resources