I've made many AppleScript module for TextWrangler but this time I face a "stupid" problem:
The idea: if nothing is selected in the text, set the selection to all the text.
I've made many tests, without any succes. Here is the last one:
tell application "TextWrangler"
set my_selection to (get selection)
set nb_mot to count words of (my_selection)
if nb_mot < 1 then
tell application "System Events"
keystroke "a" using command down
display dialog "Select all"
delay 1
end tell
set my_selection to (get selection)
delay 2
set nb_new_mot to count words of (my_selection)
display dialog "After select all " & nb_new_mot
end if
set var_1 to (replace "(" using "(" searching in my_selection options {search mode:literal, starting at top:false, wrap around:false, backwards:false, case sensitive:false, match words:false, extend selection:false})
end tell
When I select a part of the text, it's okay. When nothing is selected, I enter the if
block, but this give me an empty selection.
Any idea how I can grab only the selected text when there is something and perform a select all and copy that if no text is selected?
Best Answer
The reason you get an empty selection, i.e. when nothing is selected and
set my_selection to (get selection)
returns, e.g.,insertion point before character 1 of text document 1
, theif
statement block fails with theportion of the code because TextWrangler doesn't have focus.
The
keystroke
command goes to whatever has focus, so before you have System Eventskeystroke
something,activate
the target first, e.g.:That said, you can omit the
activate
command and use the following example AppleScript code:Note for clarity, I've remove the
display dialog
anddelay
commands along with all of System Events code, and other unnecessary code, as the following line of code is all that's necessary if thenb_mot is < 1
:The Event Log and Result of this example AppleScript code is:
As you can see it replaces the three
(
in: