Replace selected text and retain formatting

I have some series of characters that are difficult to memorize (such as s¿r&t$tr) and I want a script for each of these series to replace selected text in Pages documents with these characters while retaining the font family, font style and font size of the previous selected text.

I tried to accomplish this with this script. In Pages 5 this script works and retains the formatting of the previous selected text. In Pages 09 and TextEdit formatting is lost.

How can I replace selected text and keep formatting?

Thanks for your help.

set the clipboard to "s¿r&t$tr"
get the clipboard
tell application "System Events" to keystroke "v" using {command down}

This code works here when called from the Scripts Editor.
If I don’t explicitly state which is the target process the script pastes in the editor.

set the clipboard to "s¿r&t$tr"
get the clipboard
tell application "System Events" to tell process "Pages" # or TextEdit
	set frontmost to true
	keystroke "v" using {command down, option down, shift down}
end tell

Yvan KOENIG running El Capitan 10.11.4 in French (VALLAURIS, France) samedi 14 mai 2016 18:29:18

Thanks a lot, Yvan, works like a charm.

Thanks for the feedback.

The command with three modifiers apply also to Pages 5.x, Numbers 2.x, and Numbers 3.x

Yvan KOENIG running El Capitan 10.11.4 in French (VALLAURIS, France) samedi 14 mai 2016 18:53:56

Hi.

In Pages '09, it’s:

set hardToRememberText to "s¿r&t$tr"

tell application "Pages"
	set selection of document 1 to hardToRememberText
end tell

TextEdit’s scripting dictionary doesn’t offer a selection property, but the following currently works for me using GUI Scripting:

set hardToRememberText to "s¿r&t$tr"

tell application "System Events"
	set value of attribute "AXSelectedText" of text area 1 of scroll area 1 of window 1 of application process "TextEdit" to hardToRememberText
end tell

Thank you Nigel,

the script for TextEdit works very well. The script for Pages 09 doesn’t work here on El Capitan. Will try it later on Mac OS 10.8.5.

Thanks

Hmmm. :confused: It works for me in El Capitan ” provided that there is actually a front document and text selected in it (not, say, a text box or some other object). A production number of the script could perhaps include checks for things like that.