Pages '09 replace string and preserve style

I just finished a bunch of small scripts for my wive and one had to replace some strings in a Pages '09 document. I haven’t found a general text replacing solution for Pages so far, that’s why I post it here.


on replaceAll(thedoc, searchString, replaceString)
	tell application "Pages"
		set theText to body text of thedoc
	end tell
	
	set astid to AppleScript's text item delimiters
	considering case
		set AppleScript's text item delimiters to {searchString}
		set theTextParts to every text item of theText
	end considering
	set theText to missing value
	set AppleScript's text item delimiters to astid
	set slen to (length of searchString) - 1
	set rlen to (length of replaceString)
	
	set x to 1
	repeat with i from 1 to (count of theTextParts) - 1
		set x to x + (length of item i of theTextParts)
		tell application "Pages"
			tell thedoc
				(*
                                This works too but is much slower because the display is refereshed 
				select (characters x thru (x + slen))
				set selection to replaceString
				*)
				delete (characters (x + 1) thru (x + slen))
                                -- this looks strange but according to the AS Dictionary a character can contain text
                                -- and it works without scrolling the document the whole time
				set character x to replaceString
			end tell
		end tell
		set x to x + rlen
	end repeat
end replaceAll


tell application "Pages"
	my replaceAll(document 1, "var_firstname", "Hugo")
end tell

The basic Idea behind the script is quite simple. It uses AppleScript’s text item delimiters to break the text into parts at each occurrence of the search string. The length of these text parts are then used as an kind of index to actually replace the text directly in the document which preserves the style of the first character of the search string for the replacement string.

Hopefully you will find this little helper usefull too.
Stefan