# Converting a document into an AppletHub template

**This is the one guide to the template syntax** (KC, 2026-11-22). It serves a person writing a template and an AI model turning an existing document or form into one. It describes the syntax exactly as the service runs it, and Code T1 changes it in the same commit as any change to the engine; the syntax guide on the test page is a short form of it. The earlier Word guide and proposal are in `archive/` and are out of date.

---

## 1. What you are producing

A template is the original document with **markers** typed into its text where something changes from one use to the next. The service fills the markers from a JSON object of values and returns the finished document. It does no drafting of its own: every word in the output is either the template's own text or a value.

You produce three things:

1. **The template**: the document with markers. For a Word document, keep the original formatting (fonts, headings, numbering, tables) and change only the text. For text or Markdown, return the text.
2. **A `TEMPLATE:` comment at the top** describing each key for whoever (or whatever AI) will later fill in the values.
3. **A sample values file** (JSON) that fills every key with realistic, made-up data, so the template can be tested at once.

Then list what you could not convert, and why (section 9).

## 2. The workflow

1. **Read the whole document first.** Find every place that changes between uses: names, dates, amounts, addresses, numbers of parties, optional clauses, alternative clauses, tables of items, signature blocks, schedules.
2. **Make a key list before editing.** One key per distinct piece of information. Reuse the same key wherever the same information appears (the client's name in the header, the first paragraph and the signature block is one key, not three).
3. **Decide each key's kind** (text, number, date, yes/no; single value or list). See section 4.
4. **Mark up the document**, top to bottom, using the patterns in section 6.
5. **Write the `TEMPLATE:` comment** and the sample values.
6. **Check your work** with the checklist in section 10, ideally by uploading the template and the sample values to the test page (https://applethub-templates.vercel.app): click Find placeholders, paste the values in the JSON tab, Generate.

## 3. The syntax in one page

| Purpose | Write | Notes |
|---|---|---|
| Insert a value | `{{Client_Name}}` | Spaces inside the braces are allowed: `{{ Client_Name }}`. |
| Capitals | `[[{{Client_Name}} /case(upper)]]` | `upper`, `lower` or `title`. |
| Number | `[[{{Fee}} /number("#,##0.00")]]` | `0` required digit, `#` optional digit, a comma for thousands. |
| Percentage | `[[{{Share}} /number("0.##%")]]` | The value is a fraction: 0.6 shows as 60%. |
| Date | `[[{{Signing_Date}} /date("D MMMM YYYY")]]` | Codes: `YYYY YY MMMM MMM MM M DD D`. English month names. |
| Calculation | `[[({{Fee}} * {{Vat_Rate}}) /number("#,##0.00")]]` | `+`, `-`, `*` and parentheses. No division. |
| List, joined | `{{Names}}` → "A, B, C" | |
| List, own words | `[[{{Names}} /list(separator=";"; last="and")]]` → "A; B; and C" | `layout=none`, `space` (default) or `line`. |
| One paragraph or bullet per item | `[[{{Names}} /list(layout=paragraph; separator="")]]` | Only the item repeats (section 6.6). |
| One table row per item | `[[{{Names}} /list(layout=row)]]` in a cell | Section 6.8. |
| One table column per item | `[[{{Names}} /list(layout=column)]]` in a cell | Section 6.9. |
| Optional text | `[[DELIFNO({{Include_X}})@X]] … [[ENDDEL@X]]` | Deleted only when the answer is No. Section 6.4. |
| Text to drop on Yes | `[[DELIFYES({{Waived}})@W]] … [[ENDDEL@W]]` | Deleted only when the answer is Yes. |
| Optional paragraph or line | `[[DELIFNO({{X}}) /range(paragraph)]]`, `/range(line)` | Anywhere in it; no ENDDEL. Section 6.10. |
| Optional row / column / table | `[[DELIFNO({{X}}) /range(row)]]`, `/range(column)`, `/range(table)` | Anywhere in it; no ENDDEL. Section 6.10. |
| Note to the template author | `<!-- check the notice address -->` | Removed from the output. |
| Show a marker literally | `\{{Example}}` | |

Commands (`DELIFNO`, `ENDDEL`…), parameter names (`/number`) and fixed words (`row`, `upper`) may be in any case. Key names and labels are case-sensitive.

## 4. Keys: names and kinds

### Names
- Start with a letter; use letters, digits and underscores only: `Client_Name`, `Signing_Date`, `Fee_Amount`, `Include_Guarantee`.
- Use clear English nouns in `Title_Case_With_Underscores`. The name should tell someone who has never seen the document what to enter.
- Yes/no keys read as a question or a switch: `Include_Guarantee`, `Is_Draft`, `Has_Retainer`, `Retainer_Refundable`.
- Lists are plural: `Party_Names`, `Shareholders`, `Workstreams`.
- **One key per fact, reused everywhere.** If a list of parties has names and addresses, use two lists in the same order (`Party_Names`, `Party_Addresses`), not one list of mixed text.

### Kinds
The service works out each key's kind from how the template uses it. Make the usage say what you mean:

| Kind | How the template shows it | Value sent |
|---|---|---|
| text | plain `{{Key}}`, `/case`, or compared with quoted text | `"Acme Inc."` |
| number | `/number(...)` or used in a calculation or compared with a number | `25000` (digits only) |
| date | `/date(...)` or compared with `"YYYY-MM-DD"` | `"2026-11-21"` |
| yes/no | used alone as a condition: `DELIFNO({{Include_X}})` | `true` / `false` |
| list | `/list(...)` or used inside a repeated row, column or paragraph | `["A", "B"]` |

- **Format numbers and dates in the template, not in the value.** Write `USD [[{{Fee}} /number("#,##0.00")]]`, so the value is just `25000`.
- **Percentages are fractions.** `[[{{Interest_Rate}} /number("0.##%")]]` with the value `0.05` shows "5%".
- **Amounts in words are not supported** ("twenty-five thousand dollars"). Use a separate text key such as `Fee_In_Words`, or drop the words if the document allows it.

## 5. Rules that decide the result

These are how the engine behaves; design around them.

1. **Values are plain text.** Nothing inside a value is treated as markup; `{{X}}` inside a value prints as typed. A line break in a value becomes a line break in Word.
2. **Deletion only on a clear answer.** `DELIFYES` deletes only when the condition is Yes; `DELIFNO` only when it is No. If the answer is unknown (blank, null, missing, or anything that is not yes or no), **nothing is deleted** and only the markers are removed. Choose `DELIFNO` or `DELIFYES` so that keeping the text is the safe outcome when no one answered.
3. **Only what is inside `[[ ]]` repeats.** In a repeated paragraph, the text before the marker appears once (with the first item) and the text after it appears once (with the last item). Each item becomes its own paragraph or bullet.
4. **In a repeated row or column, the longest list decides** how many copies there are; shorter lists leave blanks.
5. **Nothing is calculated that you don't write as a calculation.** Totals, clause numbers in the text and cross-references stay as typed. Word's automatic numbering renumbers itself.
6. **Empty lines left by deletions are removed**, except blank lines that were already in the document.
7. **No grammar repair.** If removing an optional phrase would leave a double space or a stray comma, move the space or comma inside the deleted range (section 6.4).
8. **A document always comes back, and no template markup is ever shown in it.** Problems show in place and are listed in the report (with the key, label or location):
   - a value that is missing or null shows as **[Key Name]** (the key with spaces), e.g. `[Client Name]`; a blank value `""` is blank;
   - a value that cannot be read as the kind the template needs (e.g. "1.000,50" for a number) is shown as given;
   - a calculation that cannot be worked out shows **[ValueERROR!]** in bold;
   - a marker that cannot be read (a typo, an unclosed DELIF, a stray ENDDEL, a repeat the service cannot do) shows **[SyntaxERROR!]** in bold, and does nothing else.

   So test with the sample values and look for `[`…`ERROR!]` and `[Key Name]` in the result: each one is something to fix.

   The report that comes with a generated document (the `X-Template-Report` header; see `/openapi.yaml`) carries two flags: `ok` is false when the document holds an ERROR!; `complete` is true only when nothing is left to fill or decide, that is no `[Key Name]`, no clause kept because its condition was unknown, and no ERROR!. The test page shows "Generated" only when the document is complete; otherwise "Generated, with values still to fill" or "Generated with problems".

## 6. Patterns for common document features

### 6.1 Blanks and placeholders
Forms show blanks as `________`, `[name]`, `[●]`, `[insert date]`, `(the "Company")`. Replace each blank with a key:

> This Agreement is made on ______ between [NAME OF COMPANY] ("the Company") and …

becomes

> This Agreement is made on [[{{Agreement_Date}} /date("D MMMM YYYY")]] between {{Company_Name}} ("the Company") and …

Keep defined terms ("the Company") as text; they don't change.

### 6.2 Names, addresses, case
- Names: `{{Company_Name}}`. Capitals when the form shows them: `[[{{Company_Name}} /case(upper)]]`.
- Multi-line addresses: one text key, `{{Company_Address}}`; the value carries the line breaks.

### 6.3 Amounts and dates
- Money: `USD [[{{Purchase_Price}} /number("#,##0.00")]]`. Put the currency in the template if it never changes; otherwise add a `{{Currency}}` key.
- Totals that must add up: write the calculation, `[[({{Price}} * {{Quantity}}) /number("#,##0.00")]]`, or keep a separate key; the service never adds up a column.
- Dates: `[[{{Completion_Date}} /date("D MMMM YYYY")]]` (or the form's own style, e.g. `"MMMM D, YYYY"`).

### 6.4 Optional clauses
Wrap an optional sentence, clause or phrase in a labelled range. Use a short label that names the clause.

> We provide consulting services[[DELIFNO({{Include_Phone_Support}})@Phone]] and telephone support[[ENDDEL@Phone]].

- **Put the leading space (or comma) inside the range** and keep the final full stop outside, so the sentence reads correctly either way.
- A range may span several paragraphs, a heading and its clause, and even whole tables:

> [[DELIFNO({{Include_Guarantee}})@Guarantee]]
> 12. Guarantee
> 12.1 The Guarantor guarantees …
> 12.2 …
> [[ENDDEL@Guarantee]]

  Paragraphs left empty by the markers disappear.
- Ranges nest; each `ENDDEL@Label` closes the innermost open range with that label. Labels are unique in the template; a labelled opening needs a labelled closing.

### 6.5 Alternative clauses ("[A] / [B]", "delete as appropriate")
Use one key and two opposite ranges:

> [[DELIFNO({{Governing_Law}} = "England")@EN]]This Agreement is governed by English law.[[ENDDEL@EN]][[DELIFYES({{Governing_Law}} = "England")@NY]]This Agreement is governed by the laws of {{Governing_Law}}.[[ENDDEL@NY]]

For a yes/no choice:

> [[DELIFNO({{Is_Exclusive}})@Ex]]The appointment is exclusive.[[ENDDEL@Ex]][[DELIFYES({{Is_Exclusive}})@NonEx]]The appointment is non-exclusive.[[ENDDEL@NonEx]]

Remember rule 2: if the answer is unknown, **both** alternatives stay in. That makes a missing answer visible in the output.

Conditions you can write: `=`, `!=`, `>`, `<`, `>=`, `<=`, `AND`, `OR`, `NOT`, `CONTAINS`, `IS EMPTY`, `IS NOT EMPTY`, with brackets. Text in quotes; comparisons ignore capitals; dates as `"2026-01-01"`.

> [[DELIFYES({{Purchase_Price}} >= 1000000 AND NOT {{Board_Approved}})@Approval]]…[[ENDDEL@Approval]]

### 6.6 Lists in a sentence and bulleted lists
- In a sentence: `The Sellers are [[{{Seller_Names}} /list(last="and")]].` → "The Sellers are A, B, and C." With three or more items the separator also comes before the last word; use `separator=";"` for "A; B; and C".
- One bullet or numbered paragraph per item: put the marker in a bulleted (or numbered) paragraph of its own. In Word the bullet is the paragraph's formatting; in text or Markdown a typed `-`, `*`, `•` or `1.` at the start of the line is kept on every item:

> • [[{{Conditions}} /list(layout=paragraph; separator=";"; last="and")]]

  gives "• first condition;" / "• second condition; and" / "• third condition". Text before the marker stays only with the first item and text after it only with the last, so a lead-in like "The team:" belongs on its own line above the bullet.
- Lines inside one paragraph: `layout=line`.

### 6.7 Checkboxes
Turn each box into an optional phrase, or a yes/no condition:

> ☐ The Tenant may keep pets.

becomes

> [[DELIFNO({{Pets_Allowed}})@Pets]]The Tenant may keep pets.[[ENDDEL@Pets]]

or, when the box stands on a line of its own, simply `The Tenant may keep pets.[[DELIFNO({{Pets_Allowed}}) /range(paragraph)]]`.

Or, if the form must keep the box visible: `[[DELIFNO({{Pets_Allowed}})@P1]]☒[[ENDDEL@P1]][[DELIFYES({{Pets_Allowed}})@P2]]☐[[ENDDEL@P2]] The Tenant may keep pets.`

### 6.8 Tables with one row per item
Keep the heading row and any total row. Replace the example rows with **one** row of markers; the marker that makes the row repeat goes in its first cell:

| Name | Shares | Percentage |
|---|---|---|
| `[[{{Shareholder_Names}} /list(layout=row)]]` | `[[{{Share_Counts}} /number("#,##0")]]` | `[[{{Share_Percentages}} /number("0.##%")]]` |
| Total | `[[{{Total_Shares}} /number("#,##0")]]` | 100% |

- Every list in that row gives the item for its copy; a single value repeats unchanged in every copy.
- To drop some copies, put a row deletion anywhere in that row: `[[DELIFYES({{Share_Counts}} = 0) /range(row)]]`. Each copy decides for itself.
- Tables with merged or split cells cannot repeat rows or columns (the service refuses them with a message). Unmerge them, or keep the rows as fixed text.

### 6.9 Tables with one column per item (e.g. parties side by side)
Put `[[{{Party_Names}} /list(layout=column)]]` in one cell of the column to repeat; other cells of that column hold the matching lists (`{{Party_Jurisdictions}}`). One repeated column per table; not combined with repeated rows.

### 6.10 Optional paragraphs, lines, rows, columns and tables
Add `/range(...)` to a DELIFYES or DELIFNO to delete the whole part of the document around the marker. Put the marker **anywhere in that part**; no ENDDEL is needed:
- `[[DELIFNO({{Include_Clause}}) /range(paragraph)]]` – the paragraph (or bullet, or a paragraph in a cell) it sits in;
- `[[DELIFYES({{Attention}} IS EMPTY) /range(line)]]` – one line of a paragraph whose lines are separated by line breaks (Shift+Enter in Word), such as one line of an address; in a paragraph without line breaks, the whole paragraph;
- `[[DELIFNO({{Include_Legal_Fees}}) /range(row)]]` – the table row;
- `[[DELIFNO({{Show_Discount}}) /range(column)]]` – the whole column, heading included;
- `[[DELIFNO({{Include_Guarantee}}) /range(table)]]` – the table (the nearest one, if tables are nested).

Without `/range`, or with `/range(range)`, a DELIF deletes up to its ENDDEL (6.4). Labels (`@Label`) go only with that default. The same yes/no rule applies: only a clear answer deletes; otherwise only the marker is removed. Put the marker right after the text it follows (no space before it), so nothing is left over when it is removed.

Older templates may use `[[ROWDELIFNO(…)]]`, `[[COLDELIFNO(…)]]` and `[[TABLEDELIFNO(…)]]`; they still work and mean the same as `/range(row)`, `/range(column)` and `/range(table)`. Write the new form.

### 6.11 Headers and footers
Values and optional text work in headers and footers (`PRIVILEGED | [[{{Client_Name}} /case(upper)]]`, a "DRAFT" note in an optional range). Repeats do not; keep lists out of headers and footers.

### 6.12 Signature blocks
- One party: fixed text with keys (`Signed by {{Signatory_Name}}, {{Signatory_Title}}, for and on behalf of {{Company_Name}}`).
- A variable number of signatories: a table with one row per signatory (6.8), or a column per party (6.9). A multi-paragraph block per party cannot repeat as a unit.

### 6.13 Schedules and annexes
Optional schedules: wrap them (heading and all) in a range (6.4). Lists of items in a schedule: a repeated table (6.8) or repeated bullets (6.6).

### 6.14 Drafting notes and instructions in the form
Turn the form's own guidance ("[Note: delete if not applicable]", footnotes to the drafter) into conditions where they choose text, and into comments (`<!-- … -->`) where they only explain. Comments are removed from the output.

## 7. The `TEMPLATE:` comment

Put it at the very top of the document. It is removed from the output; it tells whoever fills the values what each key means. Use YAML with spaces (no tabs):

```
<!-- TEMPLATE:
  name: "Share Purchase Agreement (short form)"
  description: "Sale of shares in a private company by one or more sellers."
  instructions:
    - "Extract values from the term sheet and the parties' details."
    - "Do not invent missing information; use null."
    - "Keep list items aligned: the n-th name goes with the n-th address."
  keys:
    Company_Name:
      type: text
      description: "Full legal name of the company whose shares are sold."
    Purchase_Price:
      type: number
      description: "Total price in USD, digits only."
    Completion_Date:
      type: date
      description: "Date of completion, YYYY-MM-DD."
    Include_Guarantee:
      type: boolean
      description: "Whether a parent company guarantee is given."
    Seller_Names:
      type: list
      items: text
      description: "Sellers' full legal names, in the order they sign."
-->
```

Declare every key the template uses. The service reports keys declared but not used, and used but not declared.

## 8. The sample values

A JSON object with every key, realistic but invented (never real client data):

```json
{
  "Company_Name": "Example Holdings Ltd",
  "Purchase_Price": 1250000,
  "Completion_Date": "2026-12-15",
  "Include_Guarantee": true,
  "Seller_Names": ["Alice Chan", "Bob Smith"]
}
```

- Numbers as numbers (no currency signs or commas), dates as `YYYY-MM-DD`, yes/no as `true`/`false`, lists as arrays, unknown as `null`.
- Include at least one optional clause switched off and one list of two or more items, so the test shows the template working.

### Commas and quote marks

- **In the values (JSON):** a value is JSON text and a list is a JSON array, so commas and quote marks inside a value need nothing special: `["Smith, John \"JJ\"", "Lee"]` is two items. The service never splits text at commas.
- **In the test page's list box:** items are separated by commas, as in a spreadsheet (CSV). Put an item that contains a comma in quote marks, and inside it type a quote mark twice to get one: `"Smith, John ""JJ""", Lee` gives `Smith, John "JJ"` and `Lee`. A quote mark in an item that does not start with one stays as typed: `5" pipe`. Curly quotes (“ ”) work the same way.
- **In the markup (`[[ ]]`):** there is no escape character. To put a quote mark inside quoted text, use the other kind of quote around it: `'5" pipe'`, `"O'Brien"`, `‘5” pipe’`. Text in quotes ends at the next quote of the same kind.

## 9. What the service refuses (convert around it, or report it)

The service refuses a template that contains any of the following, with a message. Remove or flatten them before conversion, or list them in your report:

- review comments or tracked changes (accept or reject all changes and delete comments first);
- hidden text;
- embedded objects (pasted Excel tables, charts with data, ActiveX controls) – replace with an ordinary table or a picture;
- markup inside footnotes, endnotes, text boxes, content controls, hyperlinks, equations, charts or SmartArt, or in a paragraph that also holds a Word field (page numbers, cross-references) – the service cannot fill those places, and the finished document would otherwise show raw markup;
- macro-enabled files (`.docm`) and Word template files (`.dotx`) – save as `.docx`.

These do not stop the document but show **[SyntaxERROR!]** where the marker was, and the table or paragraph is left as it is: repeated rows or columns, or row/column deletion, in tables with merged or split cells; a repeat inside another repeat; a repeat in a header or footer.

Limits: 4 MB per file, 1,000 items per list, 15 seconds per document.

Not available at all: division, amounts in words, ordinal dates ("21st"), a group of several paragraphs repeated per item, page-width checks other than a warning.

## 10. Checklist before you hand it over

- [ ] Every blank, bracket and example value in the original has become a key or fixed text.
- [ ] The same fact uses the same key everywhere.
- [ ] Key names follow section 4; yes/no keys read as switches; lists are plural.
- [ ] Numbers and dates are formatted in the template, not in the values.
- [ ] Each optional range has its leading space or comma inside and its full stop outside.
- [ ] Every `[[DELIF…@Label]]` has a matching `[[ENDDEL@Label]]`; labels are unique.
- [ ] For every alternative, an unknown answer leaving both texts in is acceptable.
- [ ] Repeated tables have one marker row, no merged cells, and the repeat marker in the first cell.
- [ ] No lists in headers or footers; nothing inside footnotes, text boxes or fields.
- [ ] The `TEMPLATE:` comment declares every key with a description.
- [ ] The sample values fill every key and switch at least one option off.
- [ ] Tested on the test page: Find placeholders lists the keys you expect; Generate gives the expected document with no problems (warnings read and understood).

## 11. Worked example

**Original (a clause from a services agreement):**

> 4. FEES. The Client shall pay the Provider a fee of $[AMOUNT] per month [plus VAT at [RATE]%]. [If the Client is a new client: A one-off set-up fee of $[SET-UP FEE] is payable on signing.] Invoices are payable within [30/60] days.
>
> Services: [list each service as a bullet]

**Template:**

> 4. FEES. The Client shall pay the Provider a fee of USD [[{{Monthly_Fee}} /number("#,##0.00")]] per month[[DELIFNO({{Charge_Vat}})@Vat]] plus VAT at [[{{Vat_Rate}} /number("0.##%")]][[ENDDEL@Vat]].[[DELIFNO({{Is_New_Client}})@Setup]] A one-off set-up fee of USD [[{{Setup_Fee}} /number("#,##0.00")]] is payable on signing.[[ENDDEL@Setup]] Invoices are payable within {{Payment_Days}} days.
>
> Services:
>
> • [[{{Services}} /list(layout=paragraph; separator=";"; last="and")]]

**Sample values:**

```json
{
  "Monthly_Fee": 4500,
  "Charge_Vat": true,
  "Vat_Rate": 0.2,
  "Is_New_Client": false,
  "Setup_Fee": null,
  "Payment_Days": 30,
  "Services": ["bookkeeping", "payroll", "annual accounts"]
}
```

**Result:**

> 4. FEES. The Client shall pay the Provider a fee of USD 4,500.00 per month plus VAT at 20%. Invoices are payable within 30 days.
>
> Services:
>
> • bookkeeping;
> • payroll; and
> • annual accounts

Notes on the choices: the "[30/60]" choice became a number key rather than two alternatives (simpler, and any number works); the VAT phrase has its leading space inside the range and the full stop outside; `Setup_Fee` is null because its clause is switched off; "Services:" sits on its own line above the bulleted item, because text next to a repeat marker appears only once.

## 12. A prompt you can give an AI

> You are converting the attached document into a template for the AppletHub Template Service. Follow the attached conversion guide exactly. Keep the document's wording and formatting; only replace the parts that change between uses with markers. Return: (1) the template (if you can edit Word files, the .docx; otherwise the full text with markers, paragraph by paragraph, noting where tables and bullets are), (2) the `TEMPLATE:` comment for the top of the document, (3) a JSON file of realistic invented sample values for every key, and (4) a short list of anything you could not convert and why. Do not invent clauses that are not in the original.
