AppleScript - Remove First Three Lines of Text in Clipboard But Retain Styled Text?

57 Views Asked by At

I have a series of TextEdit documents saved as rich text files.

  • first line is three hyphens
  • second line is a title
  • third line is four hyphens
  • below the third line is various other styled text
---
Long Descriptive Title Here
----
Various Paragraphs of Text Here
Various Paragraphs of Text Here

After hitting Command + A then Command + C to copy the contents to the clipboard, I want to use an applescript to remove everything from the top down to the line with four hyphens, leaving only the various paragraphs of text.

The script below does that, but does not preserve the styled text.

How can I modify this to preserve the styled text but still remove the unwanted lines?

set theText to get the clipboard
set questionMarkOffset to offset of "----" in theText
set the clipboard to text (questionMarkOffset + 5) thru -1 of theText
1

There are 1 best solutions below

0
Mockman On
tell application "TextEdit"
    delete paragraphs 1 thru 3 of document 1
end tell

In case you are not certain ahead of time that the four hyphens will always be on line 3, here is a way to have the script look for the first line with only four hyphens and then delete it and any lines above.

tell application "TextEdit"
    set keepLine to "----" & linefeed
    set paraList to paragraphs of document 1

    repeat with c from 1 to length of paraList
        if contents of item c of paraList = keepLine then
            delete paragraphs 1 thru c of document 1
            exit repeat
        end if

    end repeat
end tell

The script creates a list of the document's paragraphs and then looks through them to see which contains four hyphens but nothing else.

Basically, it uses the '----' to identify the correct line but this is separate from the deletion process.

Notes:

  • A paragraph includes the linefeed (or return) at its end. This is why the & linefeed was added to keepLine.

  • In case the keepLine has additional characters following the four hyphens, then you would have to adjust the if statement to something like this:

    if contents of item c of paraList begins with keepLine then

  • The exit repeat command stops the repeat process once the first instance of four hyphens is found.

  • For applications that have good –or even half-decent– applescript support, you can generally manipulate items directly and avoid working with the clipboard.

  • If you look at the dictionary for textedit (File > Open Dictionary…) then you can look at the various commands and elements that are supported.