In addition to creating new documents, scripts may be called upon to edit existing documents, including locating and replacing words in the main body text. The current Pages scripting dictionary does not contain a search command, so editing long text flows efficiently requires the use of a script sub-routine optimized for that purpose.
The sub-routine included in the following example script (replaceWordWithStringInBodyText) is designed to work with long documents, by targeting the search and replace process at the paragraph-level, reducing the amount of text a script processes at a time. In addition, the script works from the end of the document to the beginning, thereby avoiding any issues with possible script-triggered reflow of the document.
The Long Document Example
In this example, the script will find and replace all of the occurrences of “Alice” in the “Alice in Wonderland” book by Lewis Carroll.
DO THIS ►For use with this tutorial DOWNLOAD the example Alice in WonderlandPages document.
DO THIS ► For execution optimization, open the example script in the AppleScript Editor application, and then install (save) it into the system-wide Script Menu (instructions). Once installed, run the script from the Script Menu.
Here’s a script for demonstrating replacing a word with a text string, in a long document:
Find-Change Example
01
tellapplication "Pages"
02
activate
03
display dialog "This script will replace all occurences of “Alice” and “Alice's” with “Wanda” and “Wanda's” in the “Alice in Wonderland” example Pages document." with icon 1 buttons {"Cancel", "Download Document", "Begin"} default button 3
04
if thebutton returnedof theresultis "Download Document" then
05
open location "http://iworkautomation.com/pages/body-text-replace.html"
Mention of third-party websites and products is for informational purposes only and constitutes neither an endorsement nor a recommendation. MACOSXAUTOMATION.COM assumes no responsibility with regard to the selection, performance or use of information or products found at third-party websites. MACOSXAUTOMATION.COM provides this only as a convenience to our users. MACOSXAUTOMATION.COM has not tested the information found on these sites and makes no representations regarding its accuracy or reliability. There are risks inherent in the use of any information or products found on the Internet, and MACOSXAUTOMATION.COM assumes no responsibility in this regard. Please understand that a third-party site is independent from MACOSXAUTOMATION.COM and that MACOSXAUTOMATION.COM has no control over the content on that website. Please contact the vendor for additional information.