Search code examples
textapplescripttextedit

Apple Script : Cleaning textedit text


I want to clear some text from a textedit text but its only half working for me

tell application "TextEdit"

    set documentText to text of document 1
    set {oldTID, my text item delimiters} to {my text item delimiters, "Administration"}
    set textBits to text items of documentText
    set my text item delimiters to ""
    set text of document 1 to textBits as text
    set my text item delimiters to oldTID

    set documentText to text of document 1
    set {oldTID, my text item delimiters} to {my text item delimiters, "New Search"}
    set textBits to text items of documentText
    set my text item delimiters to ""
    set text of document 1 to textBits as text
    set my text item delimiters to oldTID

    set documentText to text of document 1
    set {oldTID, my text item delimiters} to {my text item delimiters, "Advanced"}
    set textBits to text items of documentText
    set my text item delimiters to ""
    set text of document 1 to textBits as text
    set my text item delimiters to oldTID


    set documentText to text of document 1
    set {oldTID, my text item delimiters} to {my text item delimiters, "Tips"}
    set textBits to text items of documentText
    set my text item delimiters to ""
    set text of document 1 to textBits as text
    set my text item delimiters to oldTID

end tell

For some reason "New Search" is still on the text document. Is that possible otherwise to only keep the text from the line 2 to 3 for example?

Kind regards.


Solution

  • Multiple text item delimiter calls can be tricky for AppleScript. Try this:

    tell application "TextEdit" to set documentText to text of document 1
    
    tell application "TextEdit" to set text of document 1 to my RemoveThis(documentText, {"Administration", "New Search", "Advanced", "Tips"})
    
    to RemoveThis(txt, termList)
        repeat with eachTerm in termList
            set {oldTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, (eachTerm as text)}
            set textBits to text items of txt
            set AppleScript's text item delimiters to oldTID
            set txt to (textBits as text)
        end repeat
        return txt
    end RemoveThis
    

    In this way, you can define a list of terms to be sifted through, and not worry about the coding details.