# md2html

`md2html` turns Markdown into HTML that can go in a page as it is, such as the posts and comments of a forum. It reads a subset of [CommonMark](https://spec.commonmark.org/0.31.2/) into a tree that an app may walk or change, and writes the tree as HTML. It is written in Agentica, with no C.

The output is safe by default: every text is escaped, raw HTML is shown as text and never passed through, a link is written only to `http`, `https` and `mailto` and always with a `rel`, images are off, the nesting stops at a depth limit, and the work grows in step with the text, whatever it holds.

## Install

Add it in a project with an `agentica.toml`, with its prefixed tag and its folder as `--subdir`:

```sh
agentica add md2html agentica-lang/packages --tag md2html-0.2.0 --subdir md2html
```

That writes this line of `agentica.toml`, and the entry of `agentica.lock`:

```toml
[dependencies]
md2html = { git = "https://github.com/agentica-lang/packages", tag = "md2html-0.2.0", subdir = "md2html" }
```

It needs Agentica 0.40.0 or later. It depends on [grammy](https://github.com/agentica-lang/agc-grammy) 0.2.0, which `agentica add` fetches with it.

## Example

```agentica
import Md2html from "pkg/md2html/md2html"

def main() -> Void
  puts(Md2html.to_html("# Hello\n\n- *one* <b>\n- [two](https://example.com)\n").strip)
end
```

```output
<h1>Hello</h1>
<ul>
<li><em>one</em> &lt;b&gt;</li>
<li><a href="https://example.com" rel="nofollow">two</a></li>
</ul>
```

## What it reads

The blocks of CommonMark: paragraphs, ATX headings (`# Title`) and setext headings (a line of `=` or `-` under the text), thematic breaks (`***`, `---`, `___`), indented code blocks and fenced code blocks (`` ``` `` or `~~~`, with an info string whose first word becomes the class `language-WORD`), block quotes, and bullet and ordered lists, nested, tight or loose. Tabs count to the next multiple of 4 columns, as the spec says.

Inside a paragraph or a heading: emphasis and strong emphasis (`*` and `_`, with the CommonMark rules for runs inside and between words), code spans, inline links (`[text](url "title")`, with the destination in `<...>` or not), images (`![description](url)`), autolinks (`<https://...>` and `<name@example.com>`), backslash escapes, entities (named, decimal and hexadecimal), and hard line breaks (two spaces or a backslash at the end of a line).

The examples of the CommonMark spec for these sections pass, byte for byte, except those that need what is left out below. The tests list each skipped example with its reason.

## What is left out

- Raw HTML: an HTML block or tag is text, escaped (`<b>` is written `&lt;b&gt;`).
- Link reference definitions (`[ref]: /url`) and the reference links that use them (`[text][ref]`): they are text.
- A link to a relative URL or to a scheme other than `http`, `https` and `mailto`: the link is its text (see below).
- Unicode punctuation, which counts in the emphasis rules, is read from a table of the common ranges, not from the full Unicode data, so a rare symbol next to a `*` may count as a letter.

## Untrusted text

`to_html` is made for text that users write. Every text, URL, title and class is escaped (`&`, `<`, `>` and `"`), so the output has no tag or attribute that the text did not get from md2html. An entity is read and what it stands for is escaped again: `&lt;` in the Markdown is written `&lt;`, and `&#0;` or a number that is not a character is U+FFFD.

A link is written only when its destination starts with `http:`, `https:` or `mailto:` (in any case), after entities and backslash escapes are read, so `[x](&#106;avascript:...)` is the text `x`. Any other link, an autolink with another scheme and a relative URL are their text. A URL is percent-encoded where the spec says, so it cannot hold a space or a quote. Every link has `rel="nofollow"`, or the `rel` of the options.

Images are off by default: an image is written as its description. With `images: true`, an image is written only from `http:` or `https:`.

A block quote or list item past `max_depth` (32 by default) is text, and so is an emphasis, strong emphasis or link past it, so a deep text cannot build a deep tree or deep HTML. `render` holds to the same limit for the blocks of a tree built by hand: a block quote or a list nested past it is left out. It writes the inlines of a tree with a stack, not with calls, so a hand-built tree of any depth is written.

Each line is read once, and the work of a line is bound by its characters, however deep the text nests and whatever it holds: an unclosed `*`, `[`, backtick or `<` never makes md2html read the text again. The tests check it with 100,000 nested markers, long lines, many lines and 100,000 unclosed inline markers, and check that three times the text takes less than 3.5 times the work. The inlines are split into tokens by a [grammy](https://github.com/agentica-lang/agc-grammy) grammar with no backtracking, and the rest is written by hand; text costs some 350 steps of the VM for each character.

## API

### `Md2html.to_html(text, options = Options()) -> String`

The HTML of the Markdown `text`, the same as `render(parse(text, options), options)`. It never fails: any text is Markdown.

```agentica
import Md2html from "pkg/md2html/md2html"

def main() -> Void
  puts(Md2html.to_html("> <script>alert(1)</script>").strip)
end
```

```output
<blockquote>
<p>&lt;script&gt;alert(1)&lt;/script&gt;</p>
</blockquote>
```

### `Md2html.parse(text, options = Options()) -> List[Block]`

The blocks of the Markdown `text`. Only `max_depth` of the options counts here: a link or an image to any URL is in the tree, and `render` decides what it writes.

```agentica
import Md2html from "pkg/md2html/md2html"

def main() -> Void
  puts(Md2html.parse("## Title\n\ntext\n"))
end
```

```output
[Block.Heading(2, [Inline.Text("Title")]), Block.Paragraph([Inline.Text("text")])]
```

### `Md2html.render(blocks, options = Options()) -> String`

The HTML of `blocks`, which may come from `parse` or be built by hand. Each block ends with a newline. A block quote or a list nested past `max_depth` is left out, and a heading level below 1 or above 6 is written as 1 or 6.

```agentica
import Md2html from "pkg/md2html/md2html"

def main() -> Void
  blocks = [Md2html.Block.Heading(2, [Md2html.Inline.Text("Fish & chips")]), Md2html.Block.ThematicBreak]
  puts(Md2html.render(blocks).strip)
end
```

```output
<h2>Fish &amp; chips</h2>
<hr />
```

### `Md2html.Options`

How a text is read and written:

- `classes: Map[String, String] = {}` maps a tag name (`p`, `h1` to `h6`, `hr`, `pre`, `code`, `blockquote`, `ul`, `ol`, `li`, `em`, `strong`, `a`, `img`, `br`) to the `class` attribute of that element, so an app can style the output. A code block with an info string puts its `language-WORD` class first. A paragraph of a tight list has no `<p>`, so it takes no class.
- `rel: String = "nofollow"` is the `rel` of every link; a forum may want `"nofollow ugc"`. An empty `rel` writes none.
- `images: Bool = false` writes images from `http:` and `https:`; when false, an image is its description.
- `max_depth: Int = 32` bounds the nesting of block quotes and list items, counted together, and apart from them the nesting of emphasis, strong emphasis and links. A marker past it is text, and `render` leaves out a block quote or list nested past it. A value below 1 counts as 1, and one above 1000 as 1000.

```agentica
import Md2html from "pkg/md2html/md2html"

def main() -> Void
  options = Md2html.Options(classes: {"p": "body", "blockquote": "quote"}, rel: "nofollow ugc")
  puts(Md2html.to_html("> said [this](https://example.com) ![a cat](https://example.com/cat.png)", options).strip)
end
```

```output
<blockquote class="quote">
<p class="body">said <a href="https://example.com" rel="nofollow ugc">this</a> a cat</p>
</blockquote>
```

### `Md2html.Block`

A block of the document:

- `Paragraph(List[Inline])`
- `Heading(Int, List[Inline])`: the level, 1 to 6, and the text.
- `ThematicBreak`
- `Code(String, String)`: the info string (empty for an indented code block) and the text, each line ending with a newline.
- `Quote(List[Block])`
- `BulletList(Bool, List[List[Block]])`: tight or not, and the blocks of each item. In a tight list the paragraphs of the items have no `<p>`.
- `OrderedList(Int, Bool, List[List[Block]])`: the start number, tight or not, and the blocks of each item.

### `Md2html.Inline`

A piece of text inside a paragraph or a heading:

- `Text(String)`: text, escaped when written.
- `Code(String)`: a code span.
- `SoftBreak`: a line break of the source, written as a newline.
- `HardBreak`: a hard line break, written `<br />` and a newline.
- `Emphasis(List[Inline])`, written `<em>`.
- `Strong(List[Inline])`, written `<strong>`.
- `Link(String, String, List[Inline])`: the destination, the title (empty for none) and the text. It is written as a link only to `http:`, `https:` or `mailto:`, and otherwise as its text.
- `Image(String, String, List[Inline])`: the source, the title and the description. It is written as an image only with `images: true` and from `http:` or `https:`, and otherwise as its description; the `alt` is the description as plain text.

## Pages in this section


