Search and replace text in Pages

Hi all,

I’m new to Applescript
I need to search and replace some text in a Pages document then save it as a new file
If any one can help me get started, it would be greatly appreciated

Thanks,
Kevin

You may use :


set avant to "12 - missing value
13 - " & quote & "Afficher les règles de format conditionnel" & quote & "
14 - missing value
15 - " & quote & "Créer un format de cellule personnalisé." & quote & "
16 - " & quote & "Gérer les formats de cellule personnalisés." & quote & "
17 - missing value
18 - " & quote & "Masquer" & quote & "
"

set |après| to "just for see"

tell application "Pages" to tell document 1
	if body text contains avant then
		set body text to my remplace(body text, avant, |après|)
	end if
end tell

--=====
(*
replaces every occurences of d1 by d2 in the text t
*)
on remplace(t, d1, d2)
	local oTIDs, l
	set oTIDs to AppleScript's text item delimiters
	set AppleScript's text item delimiters to d1
	set l to text items of t
	set AppleScript's text item delimiters to d2
	set t to "" & l
	set AppleScript's text item delimiters to oTIDs
	return t
end remplace

--=====

Yvan KOENIG (VALLAURIS, France) jeudi 31 mai 2012 19:00:52

Thanks

The code works but it messes up the document formatting
Any ideas why that happens?

It’s a bit logical.
It apply upon the raw text.

As far as I know, to keep the formatting, you must drive the Find & Replace dialog with GUI scripting.
I will look at this track tomorrow.

Yvan KOENIG (VALLAURIS, France) jeudi 31 mai 2012 22:33:04

Here it is.


--[SCRIPT]

my activateGUIscripting()

set avant to "12 - missing value
13 - " & quote & "Afficher les règles de format conditionnel" & quote & "
14 - missing value
15 - " & quote & "Créer un format de cellule personnalisé." & quote & "
16 - " & quote & "Gérer les formats de cellule personnalisés." & quote & "
17 - missing value
18 - " & quote & "Masquer" & quote & "
"

set |après| to "just for see"

tell application "Pages" to tell document 1
	my ReplaceAll("Pages", avant, |après|)
end tell

--=====

on activateGUIscripting()
	(* to be sure than GUI scripting will be active *)
	tell application "System Events"
		if not (UI elements enabled) then set (UI elements enabled) to true
	end tell
end activateGUIscripting

--=====

on ReplaceAll(theApp, old, new)
	activate application theApp
	tell application "System Events" to tell application process theApp
		keystroke "f" using {command down}
		delay 0.5
		name of first window whose subrole is "AXFloatingWindow"
		tell window result to tell first tab group
			set value of first text area of first scroll area to old
			set value of first text area of last scroll area to new
			click last button
		end tell -- window.
	end tell -- System Events.
end ReplaceAll

--=====
--[/SCRIPT]

Yvan KOENIG (VALLAURIS, France) vendredi 1 juin 2012 13:58:38

It works perfectly
You are the man! :smiley:

Thanks