0

I have the following script that I want to use to change a single string in a Pages file to another, and it bombs with can't get alias. How do I fix this?

tell application "Pages"
    set MYTESTFILE to (choose file)
    set toFind to "Guy"
    set toReplace to "Gal"
    set theText to contents of MYTESTFILE
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to toFind
    set textItems to theText's text items
    set AppleScript's text item delimiters to toReplace
    tell textItems to set editedText to beginning & toReplace & rest
    set AppleScript's text item delimiters to astid
    set text of document 1 to editedText
end tell
1

Here you go. There were a few minor tweaks that needed to be made to get the script working, which you'll see when you read it.

The main thing to bear in mind is to get into the habit of only sending commands to an application that need to be sent to the application. The rest are often best performed outwith the tell block, so that terminologies don't get mixed up with each other. For instance, in this case, I'm pretty sure that Pages—along with other applications that use the iWork Suite of AppleScript commands—have their own object specifier called a text item, which is distinct from the one you're trying to employ in your script.

The original problem, however, was solved in a similar fashion by setting the variable to the alias returned by choose file outside of the Pages' tell block, but also not forgetting to use that alias inside the tell block to actually open the file, using the open command.

    set MYTESTFILE to (choose file)

    tell application "Pages"
        set MYTESTFILE to open MYTESTFILE
        properties of MYTESTFILE
        copy body text of MYTESTFILE to theText
    end tell

    set toFind to "Guy"
    set toReplace to "Gal"
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to toFind
    set textItems to theText's text items
    set AppleScript's text item delimiters to toReplace
    tell textItems to set editedText to beginning & toReplace & rest
    set AppleScript's text item delimiters to astid

    tell application "Pages" to set body text of MYTESTFILE to editedText

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .