Hi all; I’m inexperienced with AppleScript but I’ve been working on something important: Mail Merge for Pages (since Apple has decided to remove this feature… :/). I’ve got the basics working but I’m guessing there are much better ways to do most of this. I’d love some help fixing this script up and doing things the “right” way. In particular, I despise the need for delays to wait for Pages to finish each step (it feels like it might break at any moment).
on waitIfNeeded()
delay 0.05
repeat while (do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/Pages$/ {print $1}'") > 1
delay 0.1
end repeat
end waitIfNeeded
on run
set fieldDelimiter to "%"
tell application "Numbers"
set entries to table 1 of sheet 1 of document 1
set fields to value of cells of row 1 of entries
set countOfEntries to count of rows of entries
end tell
tell application "Pages" to set pagesDocument to name of document 1
tell application "Numbers" to set numbersDocument to name of document 1
display dialog "Merging data from \"" & numbersDocument & "\" into \"" & pagesDocument & "\". Estimated merge time: " & (round (3 * countOfEntries / 60)) & " minutes."
tell application "Pages" to activate
tell application "System Events"
tell process "Pages"
-- Copy template and make new document
keystroke "a" using command down
my waitIfNeeded()
keystroke "c" using command down
my waitIfNeeded()
keystroke "s" using command down & shift down
my waitIfNeeded()
keystroke return
my waitIfNeeded()
key code 51 -- delete
my waitIfNeeded()
repeat with currentEntry from 2 to countOfEntries
-- Paste template and replace fields
keystroke "v" using command down
keystroke "f" using command down
repeat with currentField in fields
tell application "Numbers" to set currentValue to value of cell currentEntry of column currentField of entries
keystroke fieldDelimiter & currentField & fieldDelimiter
keystroke tab
keystroke currentValue
click button 4 of window 1
my waitIfNeeded()
keystroke tab
end repeat
keystroke "w" using command down
my waitIfNeeded()
-- Move insertion point to end of document
keystroke "a" using command down
key code 124 -- right arrow
-- Also scroll to end of document
key code 119 -- end
my waitIfNeeded()
end repeat
end tell
end tell
end run