@gotipe/markdown
v0.1.3
Published
Lossless GFM Markdown <-> GoTipe document codec: untouched blocks keep their source bytes
Maintainers
Readme
@gotipe/markdown
Lossless GFM Markdown ⇄ GoTipe document codec for editing Markdown files that live in Git.
- An unchanged file round-trips byte-for-byte (BOM, front matter, CRLF, missing trailing newline, odd spacing, HTML, footnotes, link definitions — everything).
- After an edit only the source of the changed top-level blocks is rewritten; every other fragment (and the gaps between untouched neighbours) is copied from the original text.
- Plain JS (ESM and CommonJS builds) without runtime dependencies: GoTipe's own CommonMark/GFM
grammar (
src/grammar). No side effects on import, no Node-only APIs, noeval/new Function, no WASM (CSP note below).
import { parseMarkdown, serializeMarkdown } from "@gotipe/markdown";
const { doc, snapshot } = parseMarkdown(fileText);
// ... the editor changes `doc` ...
const { text, snapshot: next, map } = serializeMarkdown(doc, snapshot);
// `text` differs from `fileText` only inside edited blocks; keep `next` for the next save.API
parseMarkdown(text: string, options?: {
previous?: MarkdownSnapshot; // re-parse after an external change: reuse block ids
previousDoc?: Doc; // same, when no snapshot is available (matches by fingerprint)
createId?: () => string; // default: UUID v7
}): { doc: Doc; snapshot: MarkdownSnapshot };
serializeMarkdown(doc: Doc, snapshot?: MarkdownSnapshot):
{ text: string; snapshot: MarkdownSnapshot; map: MarkdownMap };
blockToMarkdown(block: Block, eol?: string): string; // one block, canonical Markdown
isBlockEmpty(block: Block): boolean; // blocks the serializer skips
fingerprint(block: Block): string; // id-free canonical JSON of a block
mdOffsetToText(map, mdOffset, bias?: "before" | "after"): { blockId; offset } | null;
textOffsetToMd(map, blockId, offset, bias?: "before" | "after"): number | null; // at a mark's edge: past or before its delimiters
textRangeToMd(map, from, to): { start; end } | null; // a text range without delimiters at its edges
markdownRawNodeSpec // GoTipe NodeSpec of the `markdownRaw` block, for defineExtensionMarkdownSnapshot is plain JSON (store it next to the open file). It holds the original text,
BOM, front matter, EOL style, and per top-level block its id, source range, fingerprint, nested
block ranges and text segments, plus the gaps between blocks and the trailing text.
MarkdownMap.blocks lists every block (nested too) with its range in text;
MarkdownMap.segments maps ranges of a block's flat text (concatenated span texts, or the raw
string of a code/raw block) to Markdown ranges. exact: true segments map char by char;
escapes (\*), character references (&), soft breaks (a space of the text over a line
ending and the stripped prefix of the next line), <br> in cells etc. get their own non-exact
segment.
How serialization works
For each top-level block of doc:
- The snapshot has a block with the same id and the same fingerprint → its original source
slice is emitted verbatim. Fingerprints ignore ids and Markdown style attrs (
marker,delimiter,spread, andbreaksof older documents) and attrs the codec does not use (e.g. a calloutemoji). - Otherwise the block is serialized, re-parsed and compared with the input; the first rendering
strategy that round-trips wins (delimiters →
<url>autolinks →<strong>/<em>/<s>tags). A soft break is a space in the document, so the writer reads the block's old source from the snapshot again and writes a space back as the line ending it was while the words around it are still there (serialization/line-breaks.ts): an edit rewrites only the lines it touches.
Between two blocks that were adjacent in the original the original gap is kept (unless a block
changed type and the gap has no blank line); otherwise EOL EOL. BOM, front matter and the
leading gap are always kept; the trailing text is kept when the last block is the original last
one, otherwise the file ends with one EOL. Empty paragraphs/headings are skipped
(isBlockEmpty) unless they are preserved verbatim. Re-serialized blocks use the file's EOL.
Structural hazards are handled: adjacent lists that would merge get a different marker, a leading
--- divider is written as *** when it would be read as front matter, an indented code block
after a list is re-fenced, nested ordered lists not starting at 1 get a blank line.
Document model
| Markdown | Block |
| --- | --- |
| paragraph | paragraph: a soft line break is a space, a hard one (\ or two spaces) is "\n" |
| #…######, setext | heading {level} |
| -/*/+ list | bulletList {marker, spread} → listItem (rich text, nested lists only) |
| 1./1) list | orderedList {start, delimiter, spread} → listItem |
| task list (- [ ], - [x], also bare - [ ]) | todoList {marker, spread} → todoItem {checked} (nested lists, sub-tasks included) |
| quote with exactly one paragraph | blockquote |
| > [!NOTE] … (GFM alerts) | callout {type: "note"…, alert: "NOTE"…} |
| fenced / indented code | codeBlock {language, meta?} (content: string) |
| ---, ***, ___ | divider |
| paragraph with only  | image {src, alt, caption} |
| paragraph with only [name](relative/name) | file {url, name} |
| GFM table | table {align} → tableRow → tableHeader / tableCell |
| HTML blocks, definitions, footnote definitions, anything else | markdownRaw {kind} (exact source) |
Marks: bold, italic, strikethrough, code, link {href, title?}, and paired simple inline
tags <u> → underline, <mark> → highlight, <sup>, <sub>, <em>/<i>, <strong>/<b>,
<s>/<del>. Other inline HTML, footnote references, reference links/images and inline images
are kept verbatim as text with the mdRaw mark. Line breaks follow CommonMark: a soft break and
a line ending inside inline code read as a space, a hard break as "\n". The writer writes a
"\n" as a hard break (\ + EOL, at the start or end of the text); in table cells and
headings "\n" ⇄ <br>. Verbatim mdRaw text keeps the line endings of its source.
Register the raw block and the raw mark in the editor:
import { defineExtension } from "@gotipe/core";
import { markdownRawNodeSpec } from "@gotipe/markdown";
const MarkdownRaw = defineExtension({ name: "markdownRaw", nodes: [markdownRawNodeSpec] });
const MarkdownRawMark = defineExtension({
name: "mdRaw",
marks: [{ name: "mdRaw", attrs: {}, rank: 90 }],
});markdownRawNodeSpec has the type of NodeSpec from @gotipe/core. The type is repeated in
this package, because core depends on it and not the other way round.
Known limitations
- Plain text that GFM autolinks (
https://…,www.…, e-mail addresses) becomes a link when the file is parsed again: the GFM transform works on decoded text, escaping cannot prevent it. - Inline code: Markdown has no line break inside code;
"\n"is written as a line ending only where that is safe (otherwise a space), never in headings/cells, and reads back as a space. In table cells a backslash directly before|inside code cannot be expressed in GFM (it is written as\\\|and reads back with an extra backslash). fileblocks round-trip only whennameequals the decoded basename of a relativeurl; otherwise they read back as a paragraph with a link. Conversely a paragraph that is only such a link (or only an image) is read as afile(image) block.- Lists mixing task and normal items, items with several paragraphs/code/quotes and ordered
task lists are kept as one
markdownRawblock. Quotes with more than one paragraph likewise. Nested task lists and lists under a task are parsed as nestedtodoList/lists.<details>blocks are split by CommonMark into HTML / paragraph / HTML blocks (the inner paragraphs are editable). - Re-serialized blocks use canonical syntax (ATX headings, fenced code,
*/**/~~,| a |tables,<url>or bare autolinks); list markers, delimiters, start and spread are kept. When emphasis cannot be expressed with delimiters (** a**,x*(y)*), HTML tags are used. - Reference links and footnote references stay verbatim (
mdRaw), they are not editable as links. - Non-GFM callout types are mapped to alerts (
info→NOTE,success→TIP,error/danger→CAUTION). Unknown block types: string content is written verbatim, rich text as a paragraph. - Segments for named character references that decode to two code points use a heuristic.
Strict CSP / Trusted Types
The owned parser decodes named character references with a platform-independent data
table. Import and parsing do not create DOM elements, use innerHTML, or evaluate code.
No third-party parser or bundler alias is required. The entity data provenance and
license are included in the package's third-party notices. An application that embeds the
parser still runs its own CSP acceptance checks.
Development
pnpm --filter @gotipe/markdown test # Vitest (property test: 400 seeded documents)
pnpm --filter @gotipe/markdown typecheck
pnpm --filter @gotipe/markdown build