Through AppleScript, I would like to change the background color of a ‘word’ in ‘rich text’. I see that the property ‘background’ refers to the background color of the first character of text. This is probably simple and I’m just banging my head, but how would I set the background color of a ‘word’?
You will want your script to locate the appropriate “attribute runs” and modify the background property of the target text in the attribute run(s). The approach is tricky at first, but it will make sense if you look at a few examples. There are a number of scripts posted here and there in the forum that do this. Another example that uses attribute run scripting is the “Merge Highlights (Rich)” script that comes with DEVONthink. Another resource is the macscripter.net forum.
Ignoring my own advice , here is a script that might do what you want.
A “word” is just the selected text in a document. Read the notes in the script’s comments. Use the script carefully. If you do not select any text, then the script will highlight all the text, so if you ignore the warning, you will change the background color of everything – and there is no undo.
(*
Script to change the background ("highlight")
of selected text in a DEVONthink document window.
This will work on any selected text. To make a
discontiguous selection use command-click to select
each block of text in the selection.
Use at your own risk. This script will change your data.
*)
property my_color : {0, 0, 0}
tell application id "DNtp"
try
set theSelection to the first item of (the selection as list)
if the kind of theSelection is not "RTF" then error "Select text in an RTF file"
if selected text of think window 1 = rich text of theSelection then
display alert "Do you want to highlight ALL of the text" buttons {"OK", "Cancel"} as warning
if result = {button returned:"Cancel"} then error "You canceled this action"
end if
set my_color to choose color default color my_color
tell selected text of think window 1
set theCount to number of characters
set i to 0
repeat with thisCharacter in characters
set background of thisCharacter to my_color
set i to i + 1
end repeat
end tell
on error error_message
display alert error_message
end try
end tell
On Mountain Lion, the color picker dialog is not rendered exactly correctly by AppleScript. A bit ugly, but it works.