Search code examples
applescriptbbedit

Applescripts. How do I add a text_object/code snippet to the end of certain lines in a text document?


I'm using an Applescript to find-and-replace certain characters or strings of characters in BBEdit to speed up the process of ripping content out of a Microsoft Word document and wrapping it in html before it goes into a CMS. Most of this is fine when it's a replace-all type of command. However, I can't figure out how to amend the end of a line with a closing H tag.

For instance, the following line does a great job of wrapping paragraphs in P tags: replace "\\n\\n" using "</p>\\n<p>" searching in text 1 of text document 1 options {starting at top:true}

And I have a solution for adding h tags to the front of the a line. However, I can't figure out how to amend the end of a line with a closing h tag, and that's what I'm hoping to get some help with.

I'm looking for something that follows this logic: "If a line begins with <h3>, add </h3> to the end of the line." OR "When a line begins with <h3>, replace the next \\n with </h3>\\n."

If there's something that works within the Applescript (rather than a shell), that would be ideal, as I am fairly new to this and haven't taught myself anything about shells just yet.


Solution

  • You can solve this efficiently using BBEdit's built in regular expressions support, like so:

    tell application "BBEdit"
        tell text window 1
            tell contents
                replace "^(\\<h3\\>)(.*)$" using "\\1\\2<\\\\h3>" options {search mode:grep, starting at top:true}
            end tell
        end tell
    end tell
    

    This adds closing tags for all h3 elements.