Make new HTML document from template in AppleScript: How?

264 views
Skip to first unread message

Sonic Purity

unread,
Oct 4, 2021, 7:30:32 PM10/4/21
to BBEdit Talk
Greetings,
First, a big Thank You to everyone who’s participated in this group over the years. I’ve had at least half a dozen pressing questions answered via searching existing posts here, saving us all the trouble of me asking anew.

This one has me stumped, and searching here and generally on the WWW hasn't helped, nor has studying the BBEdit sample files.

I cannot figure out how to use AppleScript to create a new HTML document from an existing template file, as i easily do manually via ^⌘N then select my template then type in the title in the Title field and tap Create.

I did try Recording into a blank Script Editor window, performing the above steps: window remained totally empty, as though i’d done nothing.

How does one script this in AppleScript?

(BBEdit 11.6.8, macOS 10.12.6 Sierra, AppleScript 2.5 with Script Editor 2.9)

~ Thanks ~

Christopher Stone

unread,
Oct 4, 2021, 9:33:05 PM10/4/21
to BBEdit-Talk
On Oct 04, 2021, at 18:30, Sonic Purity <sonic...@gmail.com> wrote:
I cannot figure out how to use AppleScript to create a new HTML document from an existing template file, as i easily do manually via ^⌘N then select my template then type in the title in the Title field and tap Create.


Hey Sonic,

That's easy enough if you already know how, but not so much if you don't.

Recording is relatively useless – except for discovering the syntax for some things that are really difficult to suss out.  A recorded script very often takes a lot of editing to convert from a very verbose and literal recording of actions to something that rationally makes sense to user, computer, and task.

Here's a sample template.  Note the underlined bold tags – these are placeholders you can tab to in the open document.



<!DOCTYPE html>
<html>
<head>
<title><#TITLE#></title>
<meta name="generator" content="BBEdit Prerelease" />
</head>
<body>
<#HTML_BODY#>
</body>
</html>



You can use an AppleScript dialog to enter the title, but placeholders are easier.

This script uses the template-path defined with property templateFilePath.

It also contains code to demonstrate the use of an embedded template (commented-out).

--
Best Regards,
Chris



--------------------------------------------------------
# Auth: Christopher Stone
# dCre: 2021/10/04 20:07
# dMod: 2021/10/04 20:07 
# Appl: BBEdit
# Task: Create a New HTML Document Using a Template File.
# Libs: None
# Osax: None
# Tags: @Applescript, @Script, @ASObjC, @BBEdit, @Create, @HTML, @Document, @Template
--------------------------------------------------------
use AppleScript version "2.4" --» Yosemite or later
use framework "Foundation"
use scripting additions
--------------------------------------------------------
property templateFilePath : "~/Documents/BBEdit Documents/Templates/HTML_Template_01.txt"
property defaultWindowBounds : {202, 45, 1238, 900} --» {X1, Y1, X2, Y2} Upper-Left, Lower-Right
--------------------------------------------------------

set templateFilePath to ((current application's NSString's stringWithString:templateFilePath)'s stringByExpandingTildeInPath) as text
set templateText to read templateFilePath as «class utf8»

tell application "BBEdit"
    # Create from a template FILE.
    set newDoc to make new document with properties {text:templateText}

    

    # Create using embedded template TEXT in handler getTemplateText().
    # set newDoc to make new document with properties {text:my getTemplateText()}

    

    tell newDoc
        if its source language"HTML" then set its source language to "HTML"

        

        tell its window
            if its bounds ≠ defaultWindowBounds then
                set its bounds to defaultWindowBounds
            end if
        end tell

        

    end tell

    

end tell

--------------------------------------------------------
# Template Text
--------------------------------------------------------
on getTemplateText()
    return text 2 thru -1 of "
<!DOCTYPE html>
<html>
<head>
    <title><#TITLE#></title>
    <meta name=\"generator\" content=\"BBEdit Prerelease\" />
</head>
<body>
<#HTML_BODY#>
</body>
</html>
"
end getTemplateText
--------------------------------------------------------


jj

unread,
Oct 5, 2021, 2:28:28 AM10/5/21
to BBEdit Talk
Using AppleScript to create HTML templates is an option and Christopher's example is excellent in that regard.

BBEdit also offers some powerful tools to create/use customizable HTML templates with AppleScript placeholders.

Check the BBEdit manual for:

  • Chapter 11: BBEdit HTML Tools, Templates, p. 312
  • Appendix C: Placeholders and Include Files, p. 413 
  • Appendix C: Including AppleScripts, Including Unix Scripts, p. 421
  
Similar placeholder techniques can be used to create HTML Clippings, see the manual:

  • Chapter 12: Clipping Substitution Placeholders, p. 321
  
HTH

Jean Jourdain

Sonic Purity

unread,
Oct 6, 2021, 12:05:14 AM10/6/21
to BBEdit Talk

Thank you Chris and Jean for your responses. Jean’s in particular suggests to me it’s time to take a step or several back and share with you a big picture description of the overall automation project, since i may be going about things inefficiently due to my inexperience in some areas.

Here is an overview me and of what i’m doing, in English:


My Background

Despite my EECS degree, i’m more EE than CS. It was long enough ago that the languages i dealt with were Basic and Fortran. From those, i have an understanding of loops, conditional branches, variables, constants, etc. Apart from AppleScript, i haven’t dealt with object-oriented programming. I learned some Unix at UC Berkeley decades before Apple got into it, hence i’m comfortable on the command line. I’ve written some very simple, very short shell scripts.

I’m good with HTML and CSS, but for various reasons have avoided Javascript, having done almost no work with it. I haven’t used any other programming or scripting languages.

In terms of AppleScript, i’m at neophyte level, or just beyond. I’ve made a few short, basic ones on my own. This project is by far the most ambitious i’ve attempted. Even with resources like the BBEdit User Manual’s section on scripting the clipboard, i still can’t get a basic clipboard copy to work (for one example).


Project: Big Picture Overview

Convert my master fiction novel manuscripts into web pages for my personal site.


1) Write, edit, finalize story in TextEdit (TE). Result: master manuscript in RTF format.

2) Use TE to convert to HTML. Result: One HTML document which is syntactically-correct and validates, but is semantically a mess.

3) Process TE HTML document to make it semantic and have all the classes etc. i require for my CSS.

4) Create a new HTML document in BBEdit for each story chapter from a template, with all the header and navigation stuff.

5) Paste the chapter HTML from the TE HTML document into the body HTML area of the newly-created BBEdit individual chapter HTML document. Populate some navigation information.

6) Repeat 4 & 5 for each chapter.

7) Create a story main/TOC page from a different BBEdit HTML document template. Paste in Chapter titles and links from a document made around step 4.

8) Populate remaining navigation information in all the chapter HTML files from finalized information from the TOC document.


Note: i write my stories in TE—that’s non-negotiable. Having experimented with working with the original TE RTF in BBEdit, i quickly found that wholly unworkable. Having experimented with various options to get from TE RTF into HTML, i found TE’s “built in” Cocoa HTML Writer the least-worst option.


Project: Manual or Semi-Automated Processing

Step 1) above is straightforward and outside the scope of this discussion—no automation possible nor needed.

Step 2) above is one fast and straightforward menu command—no automation needed nor desired.


Step 3) is a Very Big Deal. I start with TE HTML that looks generally like this sample:

<p class="p1"><b>Dating Dilemmas</b></p>

<p class="p2"><br></p>

<p class="p4"><br></p>

<p class="p1">***** The Big Step *****</p>

<p class="p3">Nate was nervous—no question. […long paragraph text here…]</p>

<p class="p3">He wasn’t shy about his FAness and wasn’t shy at all behind a technology wall.[…long paragraph text here…]</p>

<p class="p4"><br></p>

<p class="p3">This was the 3rd. time he’d come out to the monthly Gravitational Goddesses Get-Together. […long paragraph text here…]</p>

… on and on for some 700,000 characters/130,000 words


Once i’m done, before splitting into chapters, this same sample looks like:

<h1>Dating Dilemmas</h1>

<div class="subhead">by Sonic Purity</div>

<hr>


<main>

<h2>The Big Step</h2>

<p class="narr">Nate was nervous—no question. […long paragraph text here…]</p>

<p class="narr">He wasn’t shy about his FAness and wasn’t shy at all behind a technology wall.[…long paragraph text here…]</p>


<p class="narr gap">This was the 3rd. time he’d come out to the monthly Gravitational Goddesses Get-Together.[…long paragraph text here…]</p>


There are about 34 steps in Step 3), covering all sorts of special CSS formatting not shown in my brief example. I’ve already automated what i can with Text Factories. A number of things have to be done manually.

When i’m done, there’s only one <h1> in the entire TE HTML document, which is the story title. Each chapter starts with <h2> and runs until the next opening <h2>—and Chris will be familiar with this from a question i asked here several weeks ago.


Steps 4-8 i’ve been doing manually/partially automated. They’re what i’m trying to more fully automate now, as most of it is repetitive work with predictable, repeatable actions. Here’s how i do it manually:


Somewhere between Steps 3 & 4: Find All chapter headings <h2>[content]</h2>, Extract to new document. Do some pre-processing for their eventual use on the TOC page and to get a story total chapter count from the line count. (This part is already automated.)


Step 4: New HTML document in BBEdit, selecting my individual story chapter template and entering the story title in the dialog. Using Includes, BBEdit fills in the current year (for copyright) and the story title in 3 locations.

I create a new folder in Finder for the new story (at a predictable location), using the story name adjusted to be URI-friendly (remove spaces and disallowed characters), sometimes shortened. (I’ve already successfully automated this part of the process [in this paragraph] in AppleScript.) I save the new HTML chapter document with the same name as the enclosing folder, other than C1.html appended at the end.

Step 5: I select some placeholder text in the just-saved document (which really ought to be just one Include-style placeholder word in the template). Switch back to the source TE HTML document. Select all the first chapter text (working great, Chris!), copy. Switch back to the new chapter document, paste and save.

Remaining in the new chapter HTML document: Fill in the current chapter number in one place, and the previous and upcoming chapter numbers (current - 1 and current +1) in 2 places, for navigation. For the first chapter, remove the 2 Previous chapter navigation links. For the last chapter remove the 2 Next chapter navigation links.


Step 6: Repeat all the above in Steps 4 & 5.


Step 7: Open New HTML document with template for story home/main/TOC (one entity—can’t decide what to call it) page. Finish formatting the extracted chapters document into list item entries, copy/paste into placeholder area of HTML list in this new document.

Manually update information that cannot be automated (e.g. exciting story synopsis that so far to this point is only in my head).

Do some more find/replace (which can be automated).

Manual work inserting a picture relevant to the story (because manual adjustments for visual aesthetics are needed).


Step 8: Do a bunch of multi-file Find/Replace in the individual chapter and TOC files to complete navigation links throughout. (This is partly automated and i look forward to making it fully so.)


*******************

That’s how i’ve been doing things manually/semi-automated. It’s clear to me that re-sequencing the steps is in some cases necessary for automation and in many other cases is more efficient. For example things can easily be re-jiggered to first complete all the automated parts of Steps 7 & 8, leaving all the manual stuff for me to do at one time at the end.


My Question, related to Jean’s suggestion to use AppleScripts called from BBEdit templates

Is there any point in doing that, with my initial conditions and this sort of workflow? How would that even work? To me, my mind jumps to doing as much as possible with a couple of AppleScripts (more than one because of some essential manual work that cannot be done at the start or end of automated processing), having those call the templates or otherwise plant template content into newly-created HTML documents.

Is my current approach to automation wrong-headed/inefficient? If so, what would be a more optimized approach?


I’ve read the AppleScript Language Guide all the way through. Problem is, until i tried to look up the use control statement, i didn’t realize there was anything newer than the 2008 version for 10.5 Leopard. I was looking for PDFs, because i get nervous with Apple-provided documentation online, since it sometimes vanishes when Apple decides no one needs it any more.

Chris: where does that impressive NSString's stringWithString stuff come from? I haven’t seen documentation on that anywhere.

Thanks in advance for any suggestions.

))Sonic((

jj

unread,
Oct 6, 2021, 1:49:50 AM10/6/21
to BBEdit Talk
Hi Sonic,

Thank you for your long overview. It helps understand the traveler and the road ahead.

I would just suggest that before you start the journey, you check the Markdown language: https://en.wikipedia.org/wiki/Markdown
and the BBEdit manual for Markdown.

BBEdit fully supports Markdown and has built-in Markdown-to-HTML preview and conversion.

Today, this is probably the most common way to produce textual content for the web and it's way easier to use than AppleScript.

Bon voyage.

Jean Jourdain

Jan Erik Moström

unread,
Oct 6, 2021, 3:35:18 AM10/6/21
to BBEdit Talk
On 6 Oct 2021, at 7:49, jj wrote:

Sonic,

While I read that

> i write my stories in TE—that’s non-negotiable

but should you decide to check out jj's suggestion and start using Markdown

> I would just suggest that before you start the journey, you check the Markdown language: https://en.wikipedia.org/wiki/Markdown and the BBEdit manual for Markdown.

I suggest that you add Marked to your toolbox, it's an excellent tool for converting Markdown into various other formats, combining separate markdown files into one document, etc, etc. I use BBEdit + Marked for a lot of my writing (non-fiction) and for me it's a very nice combination.

Unfortunately, I haven't used TextEdit for many years so I can't really offer any insight in how to use TE + BBEdit best in your case.

= jem

Sonic Purity

unread,
Oct 8, 2021, 12:11:17 AM10/8/21
to BBEdit Talk
Yeah, Markdown is interesting, but with over 1.8 million words across a couple dozen novels plus assorted novellas, novelettes, and a short story or two already written in TextEdit, i’m already invested in doing things as my odd personal mix of normal rich text formatting plus Sonic’s Quirky Markup.

The issue in this thread’s long resolved, and i’ve made excellent progress with my AppleScript, so i’ll start a new conversation on a new sticking point.

Thanks All!

Christopher Stone

unread,
Oct 11, 2021, 1:54:32 AM10/11/21
to BBEdit-Talk
On Oct 07, 2021, at 23:11, Sonic Purity <sonic...@gmail.com> wrote:
Note: i write my stories in TE—that’s non-negotiable.


Hey Sonic,

Agh...

At least take a look at Jedit Ω (1,840 Yen ~ $16.00 USD).


It will do what TextEdit will do and a whole lot more.

You have to tweak some of the keyboard shortcuts, but like BBEdit Jedit has preferences for that.


--
Best Regards,
Chris

Reply all
Reply to author
Forward
0 new messages