Apple Event: May 7th at 7 am PT

Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Using Applescript to replace negative indent in HTML

I am playing with a script to take HTML from this forum window and remove the negative indent that this page adds when you paste an applescript copied from the editor into it. I have sumitted feedback to apple and if anyone cares I encourage them to do so.


What I want to do:

Starting with the focus in this window,

click the HTML button

find/replace "text-indent: -" with "text-indent: "

paste back into this window

click the "show full editor" button


FYI- I do believe that applescript is probalbly not the best approach for this task but my true mission is to learn more about scripting and a small detour to a shell script hasn't seemed too far.


So far I have:


tell application "Safari"


activateapplication "Safari"

tell application "System Events" to keystroke "a" using command down

delay 0.15

tell application "System Events" to keystroke "c" using command down

end tell


activateapplication "TextEdit"

tell application "TextEdit"


makedocument

set text of front document to the clipboard

set fdText to "text-indent: -"

set rplText to "text-indent: "




activateapplication "TextEdit"


set the clipboard tofdText

tell application "System Events" to keystroke "f" using command down

tell application "System Events" to keystroke "v" using command down

delay 0.15


set the clipboard torplText

tell application "System Events" to keystroke "f" using [command down, option down]

tell application "System Events" to keystroke "v" using command down

delay 0.15


activateapplication "TextEdit"

tell application "System Events" to keystroke tab

delay 0.15

tell application "System Events" to keystroke space

delay 0.15

set sr to front document's text


set the clipboard tosr

end tell


activateapplication "Safari"

tell application "Safari"

tell application "System Events" to keystroke "v" using command down

end tell


This works for me as you see above but it is a bit of a kludge. Drew suggested in this thread here that I could do my find replace using a shell script and I am trying to implement that now.



set fdText to "text-indent: "

set rplText to "text-indent: "

set inputstring to the clipboard



-- use 'sed' to replace the '-' after the text-indent:

set cmd to "echo \"" & inputstring & "\" | sed -e 's/text-indent: /text-indent: /g' "

set outputstring to (do shell scriptcmd)


--see what we got

display dialog "inputstring: " & return & inputstring & return & return & "outputstring:" & return & outputstring

This script is stumbling when the clipboard has text with quotes in it. I have been copying this window after I click the HTML button.

My questions:

How do I get this shell script to work with the quotes?

How do I find and click the HTML button above and the "show full editor" button in the other window?

Thanks,

quinn

MacBook Pro, OS X Mavericks (10.9.5)

Posted on Jan 25, 2015 2:09 PM

Reply
Question marked as Best reply

Posted on Jan 25, 2015 6:22 PM

Hey 🙂


Turns out that the string should be 'escaped' via the quoted form of and remove the wrapped quotes I added earlier…


tell application "Safari"


activateapplication "Safari"

tell application "System Events" to keystroke "a" using command down

delay 0.15

tell application "System Events" to keystroke "c" using command down

end tell


set inputstring to the clipboard

-- use 'sed' to replace the '-' after the text-indent:

set cmd to "echo " & quoted form of (inputstring) & " | sed -e 's/text-indent: /text-indent: /g' "

set outputstring to (do shell scriptcmd)

set the clipboard tooutputstring

--display dialog "inputstring: " & return & inputstring & return & return & "outputstring:" & return & outputstring


It just fixed this post, 🙂

The cmd+a selection is a bit hit or miss.

NOTE: it's copying back to the clipboard.


VikingOSX posted a hint on Accessibility Inspector in the other thread. I don't think it inspects the webpage but it is a bit beyond me.



EDIT: forgot info about 'quoted form of'

https://developer.apple.com/library/mac/technotes/tn2065/_index.html

23 replies
Question marked as Best reply

Jan 25, 2015 6:22 PM in response to t quinn

Hey 🙂


Turns out that the string should be 'escaped' via the quoted form of and remove the wrapped quotes I added earlier…


tell application "Safari"


activateapplication "Safari"

tell application "System Events" to keystroke "a" using command down

delay 0.15

tell application "System Events" to keystroke "c" using command down

end tell


set inputstring to the clipboard

-- use 'sed' to replace the '-' after the text-indent:

set cmd to "echo " & quoted form of (inputstring) & " | sed -e 's/text-indent: /text-indent: /g' "

set outputstring to (do shell scriptcmd)

set the clipboard tooutputstring

--display dialog "inputstring: " & return & inputstring & return & return & "outputstring:" & return & outputstring


It just fixed this post, 🙂

The cmd+a selection is a bit hit or miss.

NOTE: it's copying back to the clipboard.


VikingOSX posted a hint on Accessibility Inspector in the other thread. I don't think it inspects the webpage but it is a bit beyond me.



EDIT: forgot info about 'quoted form of'

https://developer.apple.com/library/mac/technotes/tn2065/_index.html

Jan 25, 2015 7:49 PM in response to Drew Reece

The Accessibility Inspector knows about anything that the mouse pointer passes over. I shows the UI hierarchy where the Use advanced editor link lives, and the UI element that represents the HTML button in this editor's toolbar. The challenge with GUI scripting is that Apple can make changes to the elements behind the scenes, and though things appear as they did previously, the GUI scripting code breaks. Just happened with me between Pages v5.2.2 and v5.5.1. Would not recommend it for that reason alone.

Jan 25, 2015 9:05 PM in response to Drew Reece

,Ok Drew,


It looks like it is mostly working for you. Mostly here too.


I was having trouble with the front end (keystroke "a", etc). It just didn't seem to be taking. Whatever is on the clipboard was what was used.

The back end- ...keystroke "v"... - no problem. Except that I have to keep repairing the /text-indent: -/ part of the script.😮


Starting with activate seems to have fixed things. The following seems to work starting from the HTML screen and ending back there.


activateapplication "Safari"

tell application "Safari"

tell application "System Events" to keystroke "a" using command down

delay 0.15

tell application "System Events" to keystroke "c" using command down

end tell

set inputstring to the clipboard

-- use 'sed' to replace the '-' after the text-indent:

set cmd to "echo " & quoted form of (inputstring) & " | sed -e 's/text-indent: -/text-indent: /g' "

set outputstring to (do shell scriptcmd)

set the clipboard tooutputstring


activateapplication "Safari"

tell application "Safari"

tell application "System Events" to keystroke "v" using command down

end tell

I love this shorter script.


quinn

Jan 25, 2015 9:26 PM in response to t quinn

It's surprisingly handy 🙂

How about a bit more delay, it seems to help the cmd + a you may want to tweak the timing…


tell application "Safari"


activate

delay 0.5

tell application "System Events" to keystroke "a" using command down

delay 0.15

tell application "System Events" to keystroke "c" using command down

end tell

You can do the activate within Safari's tell block too (I'm not sure if it alters much).


P.S.

For exercises in improving it…

  • Backup the clipboard & restore it so the user doesn't lose any changes they may already have in the pasteboard.
  • Convert it to a service via Automator, then use it Safari via a right click, Services > 'your service here' (note: services can have shortcuts via System Prefs > Keyboard…)
  • World domination

🙂


Step 2 help: http://macgrunt.com/2012/07/31/turn-an-applescript-into-a-service/

Jan 25, 2015 9:30 PM in response to VikingOSX

Hi VikingOSX,


I hear what you are saying about using the Accessability Inspector. Impermanent Info. But it seems the only option. Is that true? Still a useful tool. Would you help me translate its info into a button click?

This is what I get when I hang my cursor over the HTML button:

<AXApplication: “Safari”>

<AXWindow: “Reply to 'Re: Using Applescript to replace nega... | Apple Support Communities”>

<AXGroup>

<AXGroup>

<AXGroup>

<AXScrollArea: “”>

<AXWebArea: “”>

<AXGroup: “”>

<AXGroup: “”>

<AXButton: “”>


Attributes:

AXRole: “AXButton”

AXSubrole: “(null)”

AXRoleDescription: “button”

AXChildren: “<array of size 0>”

AXHelp: “Toggle HTML mode”

AXParent: “<AXGroup: “”>”

AXPosition: “x=-9051 y=-9860”

AXSize: “w=10033 h=10022”

AXTitle: “”

AXDescription: “Toggle HTML mode”

AXFocused (W): “0”

AXEnabled: “1”

AXWindow: “<AXWindow: “Reply to 'Re: Using Applescript to replace nega... | Apple Support Communities”>”

AXSelectedTextMarkerRange (W): “(null)”

AXStartTextMarker: “<AXTextMarker 0x608000243840 [0x7fff7a9faf00]>{length = 24, bytes = 0x8e010000000000009847de0e010000000000000001000000}”

AXEndTextMarker: “<AXTextMarker 0x6180000579d0 [0x7fff7a9faf00]>{length = 24, bytes = 0x940100000000000020014414010000000000000001000000}”

AXVisited: “0”

AXLinkedUIElements: “(null)”

AXSelected: “0”

AXBlockQuoteLevel: “0”

AXTopLevelUIElement: “<AXWindow: “Reply to 'Re: Using Applescript to replace nega... | Apple Support Communities”>”

AXTitleUIElement: “(null)”

AXAccessKey: “(null)”

AXARIABusy: “0”


Actions:

AXPress - press

AXShowMenu - show menu

AXScrollToVisible - AXScrollToVisible

How do I use this to click it?


quinn

Jan 26, 2015 4:12 AM in response to t quinn

Hello


FWIW, this is not about how to replace text in html but about how to avoid text-indent property in data source.


As far as I can tell, the negative text-indent property of the style generated from the rtf data copied from AppleScript Editor is result of its "indent wrapped lines" preference setting. Unchecking this option should yield style without text-indent property.


It appears the fora software strips the margin property accompanied with the text-indent property, which results in broken format of the copied text.


You may disable the said option via Preferences… menu item of AppleScript Editor application or by the following defaults command.


#!/bin/bash defaults write com.apple.ScriptEditor2 IndentsWrappedLines -bool false



Tested with AppleScript Editor 2.3 under OS X 10.6.8.


Regards,

H

Jan 26, 2015 6:41 AM in response to Hiroto

Hi Hiroto,


I had done a search (a while ago now) and dealing with the HTML seemed the only approach people had found.

This is a much better solution to the posting issue than running a script and it works for ApplescriptEditor 2.6.1 in OSX 10.9.5. Thanks!


I am still having fun playing with this script. I know you have a long history of scripting on these forums. Do you have advice for me regarding Clicking a button in a browser window? I would love to understand how to do that.

quinn

Jan 26, 2015 7:00 AM in response to Hiroto

Hiroto,


Your defaults write solution resolves pasting of AppleScript into regular, or advanced editor sessions in the ASC. Same OS X and editor version as t quinn reported.


I also adjusted the IndentWidth property from 4 to 6 in the AppleScript Editor plist, but this yielded no improvement to indent structure after the ASC paste.


You would think on a site focused on Apple, that the advanced editor session's Insert > Syntax highlighting would include AppleScript, and relevant formatting. 😉

Jan 27, 2015 8:59 AM in response to t quinn

Hello


After some experiments, I come to the following code. I avoided GUI scripting in Safari as far as possible and used javascript to click the HTML toggle button. I tried to get the html source by javascript as well but couldn't find a way to obtain it in DOM tree, for the relevant textarea remains empty for some reason, and resorted to some keystrokes.


By the way, it appears the HTML toggle button is present in both Full Editor and HTML modes and it is hidden in the latter. So I used it instead of "Show Full Editor" link to toggel the mode back to Full Editor from HTML mode.


The script will currently remove margin and text-indent properties from inline style of p elements.


Briefly tested with Safari 5.1.10 under OS X 10.6.8.


Hope this may help,

H



_main() on _main() set _delay to 0.3 -- adjust this as is needed tell application "Safari" activate my _toggle_html_mode(window 1's current tab) -- to html mode end tell delay _delay tell application "System Events" to keystroke "ac" using {command down} -- select all & copy delay _delay set the clipboard to _edit_html(the clipboard as text) -- edit html delay _delay tell application "System Events" to keystroke "v" using {command down} -- paste delay _delay tell application "System Events" to keystroke tab -- [1] delay _delay tell application "Safari" my _toggle_html_mode(window 1's current tab) -- to full editor mode end tell (* [1] required to remove focus from textarea so as to let focus be in textarea when html mode is entered next time *) end _main on _toggle_html_mode(doc) (* reference doc : reference of Safari document, tab or window *) tell application "Safari" tell doc do JavaScript "// click HTML toggle button function main() { var el = document.getElementById('wysiwygtext_html') || // HTML toggle button in advanced editor document.getElementById('wysiwygtext1_html') || // HTML toggle button in normal editor document.getElementById('wysiwygtext2_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext3_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext4_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext5_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext6_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext7_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext8_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext9_html'); // HTML toggle button in normal editor (alternative id) if (!el) { return null; } return clickElement(el); } function clickElement(el) { var e = document.createEvent('MouseEvent'); e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); return el.dispatchEvent(e); } main();" in it end tell end tell end _toggle_html_mode on _edit_html(t) (* string t : html source code return string : edited code *) do shell script "perl -CSDA -w <<'EOF' use strict; while (<DATA>) { s/ ( <p [^>]*? ) margin: [^;]+; \\s* /$1/ogx; # remove margin in (style of) p element s/ ( <p [^>]*? ) text-indent: [^;]+; \\s* /$1/ogx; # remove text-indent in (style of) p element s/ ( <p [^>]*? ) style=\"\" \\s* /$1/ogx; # remove emtpy style in p element print; } __END__ " & t & " EOF" end _edit_html

Jan 27, 2015 9:52 AM in response to VikingOSX

Hello VikingOSX,


Yes, advanced editor's insert > syntax highlighting could have been a handy way if it supported AppleScript syntax AND it preserved the text as the original. Sadly it puts extra spaces in front of each line (Firefox) and at the end of each line (Safari, Firefox) and these spaces break here-document and line continuation in shell. Unacceptable as source code formatter to say the least.


On the other hand, the coloured AppleScript script copied from (Apple)Script Editor in this forum results in script interleaved with blank line when copied by Firefox because Firefox inserts blank line after every p element. I always have to remove those extra blank lines when testing coloured AppleScript script posted here by others...



So I ended up with the following perl script as a service to put any selected source code in a pre element.



#!/bin/bash /usr/bin/perl -CSDA -w <<'EOF' - "$@" use strict; my $TS = 4; # tab stop width [char] for (@ARGV) { s/([^\n\r]*?)\t/$1 . ' ' x ($TS - length($1) % $TS)/ge; s/&/&amp;/og; s/</&lt;/og; s/>/&gt;/og; printf "<pre class='jive-pre' style='font-family:monospace;'>\n%s</pre>\n", $_; } EOF




It does not do syntax highlighting but I'm not a fan of text colouring in the first place. 🙂


All the best,

Hiroto

Jan 27, 2015 10:20 AM in response to Hiroto

Hiroto,


I enabled the 4 space indent in the AS Editor (to force outdent), and then copied/pasted it into a regular ASC editor session. Your above script was saved as an AS application (as2asc) and run against the outdented AS in the reply window. The outdent was removed, but the resulting AS code reflected virtually no indent structure. I believe that if you used margin: 0 0 0 1.6em; (right-margin) instead of, or in combination with text-indent, the outdent would be fixed, and visual code structure would be restored.


I did some testing with the Cocoa HTML Writer output from TextEdit, and noticed that only once in the output HTML code, that the span.Apple-tab-span style occurred. I used sed to add the above margin setting to this style. I also observed that Cocoa HTML Writer would inject a hard tab after each Apple-tab-span style usage. These were removed with a control+V and keyboard tab, as sed was not removing them with a \t character.


Once I updated the Apple-tab-span style, and removed the hard tabs, the HTML code appeared in Safari with proper coloration, and indent. This pasted directly into the ASC regular reply editor exactly as it appeared in Safari. Not automated, but looked close to the original AS editor indent.

Jan 27, 2015 1:07 PM in response to Hiroto

Oops. I tested the script with wrong data. I should have paid closer attention to the html code given in HTML mode so that I could notice the literal tabs with style="white-space:pre;" are replaced with double spaces in HTML editor.


The previous code assumed literal tabs are being preserved and thus won't work as expected without them. Please replace the _edit_html() handler with the following one.




on _edit_html(t) (* string t : html source code return string : edited code *) do shell script "perl -CSDA -w <<'EOF' use strict; while (<DATA>) { s/ ( <p [^>]*? ) ( margin: [^;]+; ) /$1margin: 0px;/ogx; # set margin to 0px in (style of) p element s/ ( <p [^>]*? ) ( text-indent: \\s* ) - ( [^;]+; ) /$1$2$3/ogx; # remove - from text-indent in (style of) p element print; } __END__ " & t & " EOF" end _edit_html




The whole script would be as follows.



_main() on _main() set _delay to 0.3 -- adjust this as is needed tell application "Safari" activate my _toggle_html_mode(window 1's current tab) -- to html mode end tell delay _delay tell application "System Events" to keystroke "ac" using {command down} -- select all & copy delay _delay set the clipboard to _edit_html(the clipboard as text) -- edit html delay _delay tell application "System Events" to keystroke "v" using {command down} -- paste delay _delay tell application "System Events" to keystroke tab -- [1] delay _delay tell application "Safari" my _toggle_html_mode(window 1's current tab) -- to full editor mode end tell (* [1] required to remove focus from textarea so as to let focus be in textarea when html mode is entered next time *) end _main on _toggle_html_mode(doc) (* reference doc : reference of Safari document, tab or window *) tell application "Safari" tell doc do JavaScript "// click HTML toggle button function main() { var el = document.getElementById('wysiwygtext_html') || // HTML toggle button in advanced editor document.getElementById('wysiwygtext1_html') || // HTML toggle button in normal editor document.getElementById('wysiwygtext2_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext3_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext4_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext5_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext6_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext7_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext8_html') || // HTML toggle button in normal editor (alternative id) document.getElementById('wysiwygtext9_html'); // HTML toggle button in normal editor (alternative id) if (!el) { return null; } return clickElement(el); } function clickElement(el) { var e = document.createEvent('MouseEvent'); e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); return el.dispatchEvent(e); } main();" in it end tell end tell end _toggle_html_mode on _edit_html(t) (* string t : html source code return string : edited code *) do shell script "perl -CSDA -w <<'EOF' use strict; while (<DATA>) { s/ ( <p [^>]*? ) ( margin: [^;]+; ) /$1margin: 0px;/ogx; # set margin to 0px in (style of) p element s/ ( <p [^>]*? ) ( text-indent: \\s* ) - ( [^;]+; ) /$1$2$3/ogx; # remove - from text-indent in (style of) p element print; } __END__ " & t & " EOF" end _edit_html




Sorry for confusions.

Hiroto

Using Applescript to replace negative indent in HTML

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.