# The document format

> A note's content as JSON: blocks with ids, text runs, parts; its canonical form, validation, merging and markdown

The format every note is stored in, and that the API, the CLI and agents read and write. Its machine-readable source is `spec/registry.json`; the block by block list is the [Reference](../specification/reference.md).

A Kribble document is a note's content: a list of blocks, as JSON. The format is closed and exact: it has exactly Kribble's blocks, no extension points, and one canonical serialization. The machine-readable half is the [registry](/files/attachments/01a13ff9-182c-762d-80a4-3216614b3a4c/registry.json); the [reference](../specification/reference.md) lists every block, part and run with its fields, and the [JSON Schema](/files/attachments/01a13ff9-182c-762d-80a4-3216614b3a4c/document.schema.json) is the canonical form as a schema.

MUST, SHOULD and MAY are as in RFC 2119.

## A document

```json
{
  "kribble": 2,
  "blocks": [
    { "id": "b1", "type": "heading", "level": 1, "text": [{ "text": "Release notes" }] },
    { "id": "b2", "type": "paragraph", "text": [
      { "text": "Read the " },
      { "text": "guide", "link": { "href": "https://getkribble.com" } },
      { "text": " first, and " },
      { "text": "don't", "bold": true, "italic": true },
      { "text": " skip it." }
    ]},
    { "id": "b3", "type": "list", "style": "task", "items": [
      { "id": "b4", "checked": true, "blocks": [{ "id": "b5", "type": "paragraph", "text": [{ "text": "Write it" }] }] }
    ]}
  ]
}
```

- `kribble`: the format version, `2`. Required. (Version 1, a ProseMirror tree with `"type": "doc"` at the root, isn't read anymore.)
- `blocks`: the document's blocks, at least one. An empty document is one empty paragraph.

## Blocks

A block is an object with an `id`, a `type` and the fields of its type ([reference](../specification/reference.md)). Fields at their default are left out.

**Ids.** Every block has an `id`: a non-empty string without whitespace (characters with Unicode's White_Space property: U+0085 and U+00A0 are, U+FEFF isn't), unique in the document (writers use UUIDs). Ids are stable: a block keeps its id when it changes, a copy gets a new one. Comments, search, agents and editors address blocks by id.

**Parts.** Some blocks are made of parts: a list's items, a table's rows and cells, tabs, steps, columns, cards, a file tree's entries, a diagram's layout. A part is an object with the fields of its part type; it has no `type` (the field it's in says what it is). Parts that hold content (list items, rows, cells, tabs, steps, columns, cards) have ids like blocks, unique among all ids in the document. The others (a table's columns, a file tree's entries, a diagram's layout) have none: an `id` on one is an unknown field.

**Containers.** A field holding blocks (`blocks`) is never empty: an empty container holds one empty paragraph. When an editor deletes the last block of a list item, it removes the item (and the list with its last item); of a cell, tab, column, step, quote, callout or accordion, it leaves an empty paragraph. A reader repairing a document gives an empty container an empty paragraph.

**Numbers** are JSON numbers, read as IEEE 754 doubles. An integer field holds a whole number; readers MUST read whole numbers up to 2^53 exactly, and larger ones (a file `size` of `1e21`) as doubles. **Strings** are Unicode text: a document never holds a lone surrogate.

**Tables.** A table's `rows` hold `cells`, placed on a grid as HTML places them: a cell takes the next column its row hasn't filled (cells spanning down from rows above fill theirs first), and spans `colspan` columns and `rowspan` rows. The grid is as wide as the first row with its spans. A row that fills fewer columns is shown with empty cells after it; a row span past the last row ends there. Editors keep every row full. `columns` holds the widths someone set, as fractions of the table's width: when it's present, readers use one width per grid column (extra ones ignored, missing ones an equal share), scaled to add up to 1; when any width isn't positive, or `columns` is empty, the layout is automatic.

**Lists.** With `moveChecked`, checking a task item moves it, in the document, to the end of the list, and unchecking one moves it back to just before the first checked item; readers show items in their order.

**Accordions** are shown open. Whether one is open isn't stored; readers may let people close and open them.

## Where blocks go

| In | May hold |
| --- | --- |
| the document | everything |
| a tab | everything but `tabs` |
| a column, a step, an accordion | text, media, flow containers, tables and cards |
| a quote, a callout, a list item | text, media, flow containers |
| a table cell | `paragraph`, `heading`, `code`, `list`, `image`, `file`, `divider` |

The groups: **text** (`paragraph`, `heading`, `code`), **media** (`image`, `video`, `file`, `embed`, `divider`, `fileTree`, `drawing`, `diagram`), **flow** (`quote`, `callout`, `list`), **structure** (`table`, `cards`), **layout** (`tabs`, `columns`, `steps`, `accordion`). So layout never nests except inside tabs, tables and cards stay out of quotes, callouts and lists, and cells hold simple content. A list item's first block is a paragraph or a heading.

## Text

Text (a paragraph's, a heading's, an accordion's or a step's title) is a list of **runs**:

| Run | Fields |
| --- | --- |
| text | `text` (never empty), and its formatting: `bold`, `italic`, `underline`, `strike`, `code` (each `true` or absent), `link` (`{ href, title? }`) |
| note link | `note` (the note's id), `name` (its name when linked, for readers that can't look it up) |
| line break | `break: true` |

A run's kind follows from its fields. Note links and line breaks have no formatting: bolding a selection leaves them as they are. A link is `{ href, title? }`: `href` a URL, a `#heading` anchor or a relative path. Code blocks and cards hold plain strings, not runs.

**Offsets.** A position in text is an offset in **UTF-16 code units** (what browsers, Java, Apple's TextKit and Windows count natively), with a note link and a line break counting as one each; in a plain string (a code block's `code`) likewise, with `\n` counting one. An offset is never inside a surrogate pair, and editors never put a caret or a selection edge inside a grapheme cluster (an extended grapheme cluster, Unicode UAX #29: an emoji with its modifiers and joiners is one). Comments anchor to a block id and an offset into its text.

## Canonical form

A document has exactly one canonical serialization, so equal documents are equal bytes:

- `kribble` then `blocks` at the root; `id` and `type` first in a block (`id` first in a part), then fields in registry order.
- Fields at their default, and unknown fields, left out; so are empty text and empty optional parts.
- Runs: no empty text; formatting in the order bold, italic, underline, strike, code, link, `false` never written; a link's `title` only when non-empty; neighbouring text runs with the same formatting merged.
- Inside a drawing's or diagram's scene (whose fields aren't the registry's) and in a diagram's `layout.positions`, object keys are sorted by Unicode code point (which is UTF-8 byte order: `"10"` before `"9"`, U+E000 before U+1F600). JavaScript objects list keys that look like array indexes first, so a JavaScript writer can't take the order from the object.
- A box (a position in `layout.positions`) is `x`, `y`, then `w` and `h` when present.
- JSON without insignificant whitespace. Strings escaped as `JSON.stringify` escapes them: `"` and `\` with a backslash, control characters below U+0020 as `\b`, `\f`, `\n`, `\r`, `\t` or `\u00xx` (lowercase hex), and every other character, U+2028 and U+2029 among them, as itself.
- Numbers as JavaScript writes them (ECMAScript's Number::toString): the shortest digits that read back as the same double; plain from 1e-6 up to (not including) 1e21, with an exponent outside that (`1e+21`, `1e-7`); `-0` as `0`.

Readers accept any form; writers SHOULD write the canonical one (the server stores only canonical documents). fixtures/canonical has documents and their exact canonical bytes.

## Validation

Validators report problems with a severity, a code and a path (a JSON Pointer, RFC 6901, like `/blocks/2/items/0/blocks/1`). Errors: the document isn't as specified. Warnings: readers handle it.

| Code | Severity |  |
| --- | --- | --- |
| `not-object` | error | The document, a block or a part isn't a JSON object. (A run that isn't one is an `unknown-run`.) |
| `bad-version` | error | `kribble` isn't 2. Validation stops. |
| `missing-type` | error | A block without a type. |
| `unknown-type` | error | A block type that isn't in the registry. |
| `not-allowed-here` | error | A block where it can't be ([Where blocks go](#where-blocks-go)). |
| `missing-id` | error | A block, or a part that has ids, without one. |
| `duplicate-id` | error | An id used before in the document (on the later one). |
| `field-missing` | error | A required field missing (an image's `src`, a container's `blocks`). |
| `field-type` | error | A field of the wrong kind, or out of range. |
| `too-few` / `too-many` | error | Fewer or more parts or blocks than allowed. |
| `first-block` | error | A list item that doesn't start with a paragraph or a heading. |
| `empty-run` | error | A text run with empty text. |
| `unknown-run` | error | A run that's neither text, a note link nor a line break. |
| `field-unknown` | warning | A field the block, part or run doesn't have: readers ignore it. |
| `field-value` | warning | A value outside an enum's known values: readers read it as the default. |
| `scene-element` | warning | A scene element without an id or a type: readers skip it. |

A problem about an object as a whole (`not-object`, `missing-type`, `unknown-type`, `not-allowed-here`, `missing-id`, `duplicate-id`, `first-block`, `empty-run`, `unknown-run`, `scene-element`, and `field-unknown`, which names the field in its message) is reported at the object's path: `/blocks/0`, `/blocks/0/text/2`. A problem about a field's value (`field-missing`, `field-type`, `field-value`, `too-few`, `too-many`) is at the field's path, present or not: `/blocks/0/level`, `/blocks/0/text/2/bold`. Validators check fields' kinds and ranges, not the format of strings: a `src` or `url` that isn't a valid URL isn't a problem, and neither are table widths that don't add up to 1.

fixtures/checks has a case for each code, with the exact problems: a validator conforms when it reports those (severity, code and path), each once, in any order.

## Merging

When a note was saved elsewhere while it was edited here, an editor merges the two versions (`server` and `mine`) with the one both started from (`base`), by id. A merge only keeps what it can keep without losing anyone's work; anything else is a conflict, which the person resolves. Every editor MUST merge the same way, so that what survives doesn't depend on who saved last (fixtures/merge: base, server, mine and the result, `null` for a conflict).

All three are made canonical first, and compared as canonical JSON. A **node** is a block or a part with an id. A node's **children** are what its one field of blocks or of parts with ids holds (a quote's `blocks`, a list's `items`, a table's `rows`, a row's `cells`, a tab's `blocks`…); its **own fields** are all its other fields. A paragraph, a heading or a card has no children. A list of nodes merges like this:

1. If a node is missing an id, or the nodes common to `mine` and `base` aren't in the same order in both (a reorder here, which the server's order would lose), it's a conflict.
2. In the server's order, for each of the server's nodes:
   - new on the server: kept;
   - deleted here: dropped, unless the server changed it (a conflict);
   - changed on one side only: that side's;
   - changed on both sides the same way: kept;
   - changed on both sides differently: merged as a node (below).
3. A node deleted on the server that was changed here is a conflict.
4. Nodes new here go right after the node before them here that's in the result (first when there's none), in their order here.

Two changed versions of a node merge when it has children, when not both sides changed its own fields (or both changed them the same way), and when its children merge. The result has the changed side's own fields and the merged children. Anything else, two different changes to the same paragraph among them, is a conflict: text isn't merged.

The document's blocks merge as a list. A merged document that isn't valid is a conflict.

## Drawings and diagrams

A `drawing`'s `scene` is a [drawing scene](../specification/drawings.md): its elements in stacking order, `background` and `height`; an element's `text` as typed, and `wrapped` the lines as the editor laid them out, when wrapping broke a line. Renderers draw `wrapped` (else `text`) line by line, without measuring; editors that change an element's text or size wrap it again. (Markdown writes a scene in the drawing format's older [data form](../specification/drawings.md).)

A `diagram` is `kind`, `source` (the [diagram language](../specification/the-diagram-language.md), the source of truth), `layout` (positions of boxes the user moved, by element key, and `drawnFrom`, the text the scene was last laid out from) and `scene`: the generated elements (they have `key`s) and any drawn next to them by hand. A box in `layout.positions` is `{ x, y, w?, h? }`. Editors lay the scene out again from the source with the diagram engine; renderers may draw the scene as it is. A diagram's scene can be empty (a document read from markdown): readers lay it out, have the CLI do it (`kribble convert --layout`, `kribble drawings`), or show the source.

## Charts

A `code` block whose `language` is `chart` is a chart: its `code` is written in the [chart language](../specification/the-chart-language.md) (bar, line, area, pie and doughnut charts from a few lines of text). It's an ordinary code block to the format, so documents with charts are version 2 documents and readers that don't draw charts show the text. Renderers that do draw it; editors may edit it with a chart panel that writes the text back.

## Markdown

Documents convert to and from Kribble Markdown: CommonMark with GFM tables, strikethrough and task lists, plus directives for the blocks Markdown doesn't have. Markdown has no place for some things, which a round trip loses:

- ids, other than a drawing's. When markdown replaces a document, the server matches its blocks up with the old ones: unchanged blocks keep their ids, the comments on them and what markdown can't hold. `kribble convert --base OLD.json` does the same for files.
- text alignment, table column widths, and cell spans;
- whitespace at the edges of paragraphs, headings and table cells (a reader trims it; only whitespace other than spaces and tabs survives, written as a character reference), and formatting on whitespace at the edges of formatted text (`**word **` is written `**word** `);
- empty paragraphs, which write nothing;
- the blocks inside a table cell: a GFM cell is one line, so its blocks are joined into one paragraph;
- a diagram's scene and layout: only its text is written, and the scene is laid out again from it.

| Block | Markdown |
| --- | --- |
| `heading` | `#` to `###` (deeper headings read as `###`) |
| `quote` | `> …` |
| `code` | A fence: ` ```ts filename="a.ts" `; a ` ```mermaid ` fence is an ordinary code block, and a ` ```chart ` fence is a code block that renderers draw as a [chart](#charts) |
| `fileTree` | ` ```file-tree `, the entries as indented text: two spaces a level, `/` after a folder, ` *` after a highlighted entry |
| `diagram` | ` ```diagram `, ` ```diagram sequence `, ` ```diagram class `: the diagram text |
| `drawing` | `::drawing{drawingId="…" data="…"}`: its id, and its scene in the drawing format's data form (left out when empty) |
| `callout` | `:::callout{type="warning"}` … `:::` |
| `tabs` | `:::tabs{group="…"}`, `::tab{label="…"}` … `::`, `:::` |
| `accordion` | `:::accordion`, the title, a `---` line, the content, `:::` |
| `steps` | `:::steps`, `::step`, the title, `---`, the content, `::`, `:::` |
| `columns` | `:::columns`, `::column` … `::`, `:::` |
| `cards` | `:::cards`, `::card{title="…" cover="…" href="…" noteId="…" noteName="…"}`, the description, `::`, `:::` |
| `image` | `![alt](src)` on a line of its own |
| `video`, `file`, `embed` | `::video{src="…" name="…"}`, `::attachment{src="…" name="…" size="…"}`, `::embed{url="…"}` |
| `list` | `- …`, `1. …`; `- [x] …` for a task list, the item's other blocks indented under it |
| `table` | A GFM table; the first row is its header |
| `divider` | `---` |
| a note link run | `:note-link[name]{noteId="…"}` |
| a line break run | A backslash at the end of the line |

**Front matter.** A file may start with a YAML block that isn't part of the document: a `---` line, directly followed by a `key: value` line (a key of letters, digits, `_` and `-`), up to the next `---` line. Readers skip it (so a note that starts with a divider keeps it); tools that rewrite a file put it back unchanged.

**Repairs.** A reader repairs what doesn't fit the format (a block where it can't be, a heading deeper than `###`) and reports each repair with its line. Editors that read markdown SHOULD show those reports, since the next save writes the repaired document.

A directive with more colons can hold one with fewer, so blocks nest (`:::::columns` and `::::column` around a `:::callout`). A block written where it can't be ([Where blocks go](#where-blocks-go)) is repaired as it's read: a layout block is replaced by what it holds (its title becoming a bold paragraph), any other block moves out to just after the block it was in. Where CommonMark and GFM leave a choice, the dialect reads and writes so that what a writer writes reads back the same:

- A directive's attributes are `key="value"` or `key='value'` pairs, with backslash escapes in the value; anything else between the braces is skipped. A `::name` line is a block only for the names in the table above; any other (`::std::string`) is text.
- A title in an attribute or after the directive's name (`::step{title="1. Install"}`) is inline content, never a block.
- A directive's body ends at its closing fence, or where a list item or quote around it ends. A closing fence inside a fenced code block, or indented four spaces or more, isn't one; a code fence closes on a run of the same character at least as long as the one that opened it.
- A link or image to a `javascript:`, `vbscript:`, `file:` or `data:` URL is text (except images in `data:image/png`, `gif`, `jpeg` or `webp`), as in markdown-it. Renderers never write such a URL into an `href` or `src` at all: only `http:`, `https:`, `mailto:`, `tel:`, `kribble:` and relative URLs (and those raster images).
- Readers trim whitespace (as JavaScript's `trim` defines it) from the edges of paragraphs, headings and table cells. Writers write any such whitespace other than spaces and tabs as a character reference (`&#xA0;`), which survives.
- `<u>` and `</u>` pair up within the same span of emphasis, link or strikethrough; an unpaired tag is text. A task list item starts with `[ ]`, `[x]` or `[X]` followed by a space, a tab or the end of the line.
- A code block's language is the first word of the fence's info string: writers write whitespace in it as `-`, and use a `~~~` fence when the info string holds a backtick. Numbers in attributes are written out in full, never with an exponent (unlike in the JSON); an attribute that isn't a number reads as its default.
- In a table cell, paragraphs keep their text, code blocks become code spans, and other blocks their text, all on one line.
- Text that reads as a web or email address (`https://…`, `www.…`, `name@host`) is a link, as in GitHub's Markdown, so such text without a link comes back from markdown as a link.

The exact dialect is defined by its fixtures: fixtures/markdown holds markdown and its documents, and every converter MUST pass them:

- `*.md` with `*.json`: both ways. Writing the document gives exactly the markdown; reading the markdown gives the document, with ids `b1`, `b2`, … in document order (a drawing keeps its `drawingId`).
- `parse/`: reading only. Other ways of writing the same things (other Markdown dialects, older Kribble markdown) and input the reader must repair to fit the format.
- `render/`: writing only. Normalisations the writer applies.
- `corpus.json`: random documents and their markdown. Every converter must write each one the same way and read it back the same, ids aside.
- `parse-corpus.json`: short markdown inputs, one per corner of the rules above, and the documents they read as, ids aside.

## Versions and changes

Within version 2, the format only grows in ways version 2 readers handle: a new optional field whose default means what documents without it meant; a new value for an enum (old readers read the default). Anything else, a new block type among it, is a new version with a migration from this one.

## What isn't in the format

- **Rendering.** How a callout looks, what a table's automatic column widths are: the reference implementations (the editor, the server's HTML renderer, the static site generator) agree, but the format only says what the content is.
- **The note around the document.** Its name, icon, description, position and permissions are the note's, not the document's.
- **Comments.** They're stored beside the document and point into it by block id and text offset.
- **How an editor keeps it.** The reference editor holds a note as ProseMirror's JSON while it's open and converts at the edges, losing nothing; other editors keep whatever model suits them.
