Search code examples
htmltagsapplescriptstartswith

Applescript wrap lines with HTML tags and MarsEdit.app script problem


Im currently using a script in MarsEdit.app which has a flaw. It checks the HTML document for cases where paragraphs are wrapped with <p> tags as follows:

-- If already starts with <p>, don't prepend another one

if not {oneParagraph starts with "<p>"} then
           set newBodyText to newBodyText & "<p>"
end if
set newBodyText to newBodyText & oneParagraph

The problem here is that if the paragraph (or single line) is wrapped with any other HTML tag other than a <p> tag the script wraps <p> tags across the board.

Another portion of the script, which checks for ending tags at the end of the paragraph does pretty much the same thing.

-- If already ends with </p>, don't append another one

if not (oneParagraph ends with "</p>") then
    set newBodyText to newBodyText & "</p>"
end if

set newBodyText to newBodyText & return

Example:

<h5>Foobar </h5>

becomes

<p><h5>Foobar </h5></p>

In another question Applescript and "starts with" operator, @lri was kind enough to provide me a solution related to it.

on startswith(txt, l)
repeat with v in l
    if txt starts with v then return true
end repeat
false
end startswith

startswith("abc", {"a", "d", "e"}) -- true

and another of his recommendations can be found on this website as well Wrap lines with tags on applescript

Implementing these recommendations with MarsEdit.app is another issue for me.

I uploaded the entire script on pastebin. Pastebin: MarsEdit.app, wrap line with

tags script If anyone can help me edit the script to @lri's recommendations that would be great. Thanks in advance.


Solution

  • AppleScript:

    tell application "MarsEdit" to set txt to current text of document 1
    set paras to paragraphs of txt
    
    repeat with i from 1 to (count paras)
        set v to item i of paras
        ignoring white space
            if not (v is "" or v starts with "<") then
                set item i of paras to "<p>" & v & "</p>"
            end if
        end ignoring
    end repeat
    
    set text item delimiters to ASCII character 10
    tell application "MarsEdit" to set current text of document 1 to paras as text
    

    Ruby appscript:

    require 'appscript'; include Appscript
    
    doc = app('MarsEdit').documents[0]
    lines = doc.current_text.get.gsub(/\r\n?/, "\n").split("\n")
    
    for i in 0...lines.size
        next if lines[i] =~ /^\s*$/ or lines[i] =~ /^\s*</
        lines[i] = "<p>#{lines[i]}</p>"
    end
    
    doc.current_text.set(lines.join("\n"))
    

    These assume that anything starting with (white space and) < is a tag.