I have multiple Pages documents in which I need to replace special set of characters - in our language we have one-character prepositions (e.g. v, s, k, u, a), that can't be orphaned at the end of lines, so I need to replace the preposition and the next space with preposition and non-breakable space. Have been trying to use AppleScript (am quite newbie to programming) like this one:
set findList to {"v ", "s "}
set replaceList to {"v ", "s "}
set AppleScript's text item delimiters to ""
tell application "Pages"
activate
tell body text of front document
repeat with i from 1 to count of findList
set word of (words where it is (item i of findList)) to (item i of replaceList)
end repeat
end tell
end tell
return
This does not work as long as there are any spaces in the findList and replaceList parameters.
So I found, that text item delimiters might help me. I was able to make this script
set theText to "Some of my text with v in it"
set AppleScript's text item delimiters to "v "
set theTextItems to text items of theText
set AppleScript's text item delimiters to "v " --this is v with non-breakable space (alt+space)
set theText to theTextItems as string
set AppleScript's text item delimiters to {""}
theText
which works, but only with plain text set on the first line of the code (when I copy the result to Pages there is truly a non-breakable space).
But now I need to write a script, that works on the whole text of Pages document.
I have tried something like this:
tell application "Pages"
activate
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "v "
set textItems to body text of front document
set AppleScript's text item delimiters to "v " --again v with non-breakable space (alt+space)
tell textItems to set editedText to beginning & "v " & rest --again v with non-breakable space (alt+space)
set AppleScript's text item delimiters to astid
set text of document 1 to editedText
end tell
but I get the error
Can’t get beginning of "here is the whole text of the Pages document"." number -1728 from insertion point 1 of "and again the whole text of the document"
If I change the script to:
tell application "Pages"
activate
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "v "
set textItems to text items of body text of front document
set AppleScript's text item delimiters to "v "
tell textItems to set editedText to beginning & "v " & rest
set AppleScript's text item delimiters to astid
set text of document 1 to editedText
end tell
I get another error
Pages got an error: Can’t get every text item of body text of document 1." number -1728 from every text item of body text of document 1
Can anyone point me to the right direction how to properly script this?
Thanks.