# NanoMD Generation Guide (v2.0.16)

For agents writing code or Markdown for `@pardnchiu/nanomd`. Every rule was checked against `src/parser` at v2.0.16; a syntax or option not listed here is unsupported.

NanoMD is a parser only (`MDParser`): Markdown string in, AST and HTML string out. It has no editor, no DOM binding and no plugins; the 1.x editor is a separate, unmaintained line.

## Setup

```html
<script src="https://cdn.jsdelivr.net/npm/@pardnchiu/nanomd@2.0.16/dist/parser.js"></script>
```

```js
import { MDParser } from "https://cdn.jsdelivr.net/npm/@pardnchiu/nanomd@2.0.16/dist/parser.esm.js";
```

```js
import { MDParser } from "@pardnchiu/nanomd";
import "@pardnchiu/nanomd/parser.css";
```

The script tag defines `window.MDParser` and inserts `parser.css` from the same directory (`<script data-nanomd-css="off">` turns that off). The ESM file also exports `Parse`, `Init`, `Refresh`, `OnCopyClick`, `ParseLines`, `DEFAULT_ENDPOINT` and `PARSE_OPTIONS`; it inserts the CSS relative to `import.meta.url`, which bundlers rewrite, so with a bundler import `@pardnchiu/nanomd/parser.css` yourself. There is no CommonJS build; Node 22+ can `require()` the ESM file.

## Render

```html
<article id="out" class="nanomd"></article>
<script>
  MDParser.Init({ enable: { highlight: true, mermaid: true } }).then(() => {
    const out = document.getElementById("out");
    out.innerHTML = MDParser.Parse(markdown).html();
    MDParser.Refresh(out);
  });
</script>
```

Always in this order: `await Init()`, `Parse(md).html()`, insert into the page, `Refresh(container)`.

- The container needs `class="nanomd"`: every style in `parser.css` is scoped to it.
- `Parse(md)` returns an AST with `.html()` (string) and `.json()` (plain array). There is no incremental update; parse again for new input.
- `Init()` sets parse options and loads optional libraries, returning a Promise. Options are global and every omitted option resets to its default, so call it once with the full set.
- `Refresh(container)` renders Mermaid, KaTeX, Chart.js and highlight.js and binds copy buttons and file links inside the container (default `document`). The container must already be in the document, otherwise it logs `[Invalid]` and does nothing. Call it again after every new insert.
- In Node, `Parse().html()` works without a DOM, `Init()` only sets parse options and `Refresh()` does nothing; run `Refresh` in the browser.

## Init Options

```js
await MDParser.Init(
  {
    enable: { mermaid: true, latex: true, highlight: true, chartjs: true },
    indent: 4,
    parseHeading: true,
    fileEndpoint: "/open?path={filepath}",
    hashtagEndpoint: "/tags/{tag}",
  },
  { mermaidjs: "/vendor/mermaid.min.js" },
);
```

- `enable.mermaid` / `latex` / `highlight` / `chartjs` (default `false`): loads that library from jsDelivr. Diagrams, maths, charts and highlighting appear only when enabled and after `Refresh()`.
- `indent` (default `4`): tab width for list nesting and footnote continuation; a non-positive or non-integer value falls back to `4`.
- `parseHeading` (default `false`): headings render as `<span class="md-h1">`; `true` renders real `<h1 class="md-h1">`, needed for SEO, anchors and screen readers.
- `fileEndpoint` (default `""`): must contain `{filepath}`, otherwise `[Invalid]` and ignored. Without it, file paths stay plain text.
- `hashtagEndpoint` (default `""`): must contain `{tag}`, otherwise `[Invalid]` and ignored. Without it, `#tag` stays plain text.
- The second argument overrides library URLs: `mermaidjs`, `katexjs`, `katexcss`, `highlightjs`, `chartjs`. A self-hosted KaTeX needs `fonts/` next to `katex.min.css`.

## Blocks

- `# Title` to `###### Title`, or a line followed by `===` / `---`: heading (`span.md-hN`, or `hN.md-hN` with `parseHeading`).
- A plain line: `span.md-line`. Consecutive lines join into one, the newline becoming a space; a line break inside a paragraph needs `<br>` (two trailing spaces stay as text).
- Blank lines: one `<br>` between blocks, however many there are.
- `---`, `***`, `___` on their own: `<hr>`. Directly under a text line, `---` turns that line into a heading, so leave a blank line before it.
- `> text`: `blockquote.md-quote`, its content parsed as Markdown.
- `> [!NOTE]` followed by at least one more `>` line: alert `blockquote.md-alert.md-alert-note`; also `TIP`, `IMPORTANT`, `WARNING`, `CAUTION`, case-insensitive. Without a body line it renders as a plain quote showing `[!NOTE]`. Alerts work at the top level only, not inside lists or quotes.
- `- a`, `* a`, `1. a`: `ul.md-list` / `ol.md-list`; an ordered list starting at N ≠ 1 gets `start="N"`. `+` is not a list marker, and switching between `-` and `1.` starts a new list. Indent a child item to the parent's content column (2 spaces after `- `, 3 after `1. `); a tab counts as `indent` columns.
- `- [ ] a`, `- [x] a`: `li.md-task` with a disabled checkbox.
- A table with a `|---|` separator row: `div.md-table-wrap > table.md-table`; `:-`, `-:`, `:-:` set `text-align`.
- A line starting with an HTML tag: kept as raw HTML (sanitized, see Security). Tags in the middle of a line are escaped as text, so `a <b>x</b>` shows the tags; use Markdown syntax there.
- Code blocks are fenced only; 4-space indented code is not supported.

## Inline

- `**b**`, `__b__`: `span.md-bold`. `*i*`, `_i_`: `<em>`. `***bi***`, `___bi___`: `span.md-bold > em`.
- `~~del~~`: `<del>`. `==mark==`: `<mark>`. `H~2~O`, `x^2^`: `<sub>`, `<sup>`, with no spaces inside.
- `` `code` ``: `<code>`; to include a backtick, wrap in more backticks: ``` `` a`b `` ```.
- `$E=mc^2$`: inline KaTeX `span.md-math-inline`. No space right after the opening `$` or before the closing one, and no digit right after the closing `$`, so `$5 and $10` stays text.
- `\*`, `` \` ``, `\[`, `\|`: the literal character.
- `<br>`: `br.md-br`.

`_` and `__` do not apply inside words, so `snake_case_name` is safe; `*` does apply inside words.

## Links, Media and Embeds

- `[label](https://x.y "title")`: `a.md-link` opening in a new tab (`target="_blank" rel="noopener"`). `mailto:` and `tel:` open in the same tab. Relative links (`/path`, `./a.md`) are allowed; other schemes such as `javascript:` do not become links.
- `[label][ref]` with `[ref]: https://x.y "title"`: reference link, labels case-insensitive; an undefined ref stays text.
- `<https://x.y>` and bare `https://x.y`: auto link; trailing punctuation (`.`, `,`, `)`, `。` ...) stays outside.
- A YouTube or Vimeo URL used as a link also embeds an `iframe.md-embed`.
- `![alt](a.png "title")`: `img.md-img`. A size suffix right after `)` sets dimensions: `(300x200)`, `(50%x)`, `(x200)`, `(300)`; numbers are px, `%` is kept, and a single value sets both width and height.
- `![alt](a.mp4)` or `.mov`: `<video class="md-img" controls>`.
- Paths such as `~/notes/a.md`, `/Users/me/a.go` or `` `~/a.md` `` become `a.md-file-link` only when `fileEndpoint` is set; a click `fetch()`es the endpoint.
- `#tag` and `＃標籤` become links only when `hashtagEndpoint` is set; `a#b` and `&#123;` are not tags.
- Footnotes: `[^id]` with `[^id]: text`, numbered by first reference and collected into `section.md-footnotes` at the end. Continuation lines are indented by `indent`; definitions work at the top level only; an undefined id stays text.

## Code Blocks and Diagrams

````markdown
```js
const a = 1;
```

```mermaid
flowchart LR
  A --> B
```

```math
\int_0^1 x^2 \, dx
```

```chartjs
{ "type": "bar", "data": { "labels": ["A", "B"], "datasets": [{ "label": "n", "data": [3, 5] }] } }
```
````

- A fence is 3+ backticks or tildes with the language right after it, no space; close it with the same character, at least as long. An unclosed fence runs to the end of the document.
- Highlighting needs `enable.highlight`; the language name goes to highlight.js as written and unknown names stay plain.
- `mermaid` needs `enable.mermaid`; an invalid diagram falls back to a code block. The theme follows `prefers-color-scheme` at first render.
- `math` is display KaTeX and needs `enable.latex`; errors fall back to a code block.
- `chartjs` needs strict JSON (double-quoted keys, no comments, trailing commas or functions) with a string `type` and an object `data`. **Only `type` and `data` are used; `options` is dropped.** Invalid JSON renders as a plain code block.
- Every code block gets a copy button; `OnCopyClick((ok, pre) => ...)` adds your own feedback.

## Security

`Parse().html()` escapes text and attributes and filters raw HTML lines: it removes `script`, `style`, `iframe`, `object`, `embed`, `form`, `link`, `meta` and `base` with their content, every `on*` attribute, and `href` / `src` / `xlink:href` / `action` / `formaction` values using `javascript:`, `vbscript:` or `data:text/html`. This is a regex filter, not a DOM sanitizer: for untrusted user input, also run the HTML through a sanitizer such as DOMPurify, or drop lines starting with `<` before parsing.

## Styling

Theme by overriding CSS variables on `.nanomd`: `--text`, `--accent`, `--code-bg`, `--mark`, `--alert-note`, `--alert-tip`, `--alert-important`, `--alert-warning`, `--alert-caution`. Block font sizes are fixed in `rem` (lists, quotes and alerts `1rem`; tables and footnotes `0.875rem`) and ignore the parent's `font-size`; only paragraphs and inline marks follow `.nanomd`. Change `html { font-size }` or the selector itself to resize blocks. `text-size-adjust: 100%` stops mobile browsers from enlarging wide tables. `.nanomd` has `padding: 1rem 1rem 5rem`; override it in tight layouts.

## AST

`Parse(md).json()` returns plain block nodes: `text`, `heading` (`level`), `list` (`ordered`, `start?`, `children: listItem[]` with `checked?`), `table` (`align`, `tableRow` / `tableCell`), `blockquote` (`tag?`), `codeBlock` (`lang?`, `value`), `html` (`value`), `hr`, `break`, `footnotes`. Inline nodes: `text`, `code`, `math`, `link` (`href`, `tag?`: `youtube` / `vimeo` / `file` / `image` / `video` / `hashtag`, `title?`, `width?`, `height?`), `footnoteRef`, `br`, and the marks `b` / `em` / `del` / `mark` / `sub` / `sup`. The AST is output only; nothing renders an edited AST back to HTML.
