Search code examples
applescriptbbedit

BBEdit AppleScript for reformatting multiple files


I'm looking to write an Applescript which will utilize BBEdit — loop through a ton of HTML files and autoformat them (so the indentation is easier to read).

So far I have:

tell application "BBEdit"
    activate
    open {file "Macintosh HD:TEST DIRECTORY:testfile copy 2.html"} with LF translation
    (format mode hierarchical)
    beep 
    display alert "Finished!"
end tell

This applies the transformation to a single file, but has anyone got any suggestions how to apply this to an unknown number of HTML files?


Solution

  • You've almost got it; the trick is that you want to loop through the files returned by open. Thus, you need something like this:

    tell application "BBEdit"
        set docs to open LIST_OF_FILES with LF translation
        repeat with doc in docs
            -- format doc
            save doc
        end repeat
        beep -- Or even `say "Finished!" without waiting until completion`
             -- if you want your computer to talk to you
        display alert "Finished!"
    end tell
    

    As you can see, all you need to do is place your formatting code inside this loop (and don't forget to save the files!); the loop will set doc to each element of the list docs in turn, and run the body with that element. If you're not sure how to select the files, one way is choose file with multiple selections allowed; this will pop up a dialog box which will allow you to select as many files as you want. To use it, just replace LIST_OF_FILES with (choose file with multiple selections allowed).