From 178f1c91844bb30ac7ebb3f8812040213ead8fd2 Mon Sep 17 00:00:00 2001 From: aliassar Date: Tue, 17 Nov 2026 09:55:34 +0100 Subject: [PATCH 1/7] fix(stringify): keep lists, nested emphasis and multi-line headings on round trip Co-Authored-By: Claude Opus 5.5 --- .../internal/stringify/handlers/emphesis.ts | 8 ++++- .../internal/stringify/handlers/heading.ts | 6 ++++ .../src/internal/stringify/handlers/li.ts | 15 ++++++--- .../src/internal/stringify/handlers/ol.ts | 12 ++++--- .../src/internal/stringify/handlers/ul.ts | 11 ++++--- .../comark/src/internal/stringify/list.ts | 33 +++++++++++++++++++ packages/comark/test/roundtrip-safety.test.ts | 20 +++++++++++ test/bundle.test.ts | 2 +- 8 files changed, 92 insertions(+), 15 deletions(-) create mode 100644 packages/comark/src/internal/stringify/list.ts diff --git a/packages/comark/src/internal/stringify/handlers/emphesis.ts b/packages/comark/src/internal/stringify/handlers/emphesis.ts index 3a8d449be..193e34ae7 100644 --- a/packages/comark/src/internal/stringify/handlers/emphesis.ts +++ b/packages/comark/src/internal/stringify/handlers/emphesis.ts @@ -5,13 +5,19 @@ import { comarkAttributes } from '../attributes.ts' export async function emphesis(node: ElementNode, state: State) { const [_, attrs, ...children] = node + // Emphasis inside emphasis alternates `*` and `_`: `**foo**` would read back as strong. + const marker = state.context.emphasisMarker === '*' ? '_' : '*' + const revert = state.applyContext({ emphasisMarker: marker }) + let content = '' for (const child of children) { content += await state.one(child, state, node) } content = content.trim() + state.applyContext(revert) + const attrsString = Object.keys(attrs).length > 0 ? comarkAttributes(attrs) : '' - return `*${content}*${attrsString}` + return `${marker}${content}${marker}${attrsString}` } diff --git a/packages/comark/src/internal/stringify/handlers/heading.ts b/packages/comark/src/internal/stringify/handlers/heading.ts index 4698507cc..4d165ecc3 100644 --- a/packages/comark/src/internal/stringify/handlers/heading.ts +++ b/packages/comark/src/internal/stringify/handlers/heading.ts @@ -42,5 +42,11 @@ export async function heading(node: ElementNode, state: State) { const attrs = comarkAttributes(id === undefined || id === autoId ? rest : { id, ...rest }) const suffix = attrs ? ` ${attrs}` : '' + // An ATX heading ends at the line break, so a multi-line h1/h2 (setext + // source) keeps its underline form. + if (level <= 2 && content.includes('\n')) { + return content + suffix + '\n' + (level === 1 ? '===' : '---') + state.context.blockSeparator + } + return '#'.repeat(level) + ' ' + content + suffix + state.context.blockSeparator } diff --git a/packages/comark/src/internal/stringify/handlers/li.ts b/packages/comark/src/internal/stringify/handlers/li.ts index 41156fa14..bb3859f60 100644 --- a/packages/comark/src/internal/stringify/handlers/li.ts +++ b/packages/comark/src/internal/stringify/handlers/li.ts @@ -4,14 +4,15 @@ import { indent } from '../../../utils/index.ts' import { comarkAttributes, userBlockAttrs } from '../attributes.ts' // Block elements that need explicit indentation in list items. -// Note: ol/ul are handled by their own handlers which manage indentation via listIndent context. +// Note: ol/ul are handled by their own handlers, which indent by the `listIndent` this item sets. const blockElements = new Set(['pre', 'blockquote', 'table']) export async function li(node: ElementNode, state: State) { const children = node.slice(2) as Node[] - const order = state.context.order - let prefix = order ? `${order}. ` : '- ' + const { order, listMarker } = state.context + const ordered = typeof order === 'number' + let prefix = ordered ? `${order}${listMarker || '.'} ` : `${listMarker || '-'} ` const className = (node[1].className as string) && Array.isArray(node[1].className) @@ -32,6 +33,10 @@ export async function li(node: ElementNode, state: State) { // Direct text children render sibling components inline. const hasInlineContent = children.some((child) => typeof child === 'string') + // A nested list must be indented to this item's content, whose column + // depends on the marker width (`1. ` vs `10. `). + const revert = state.applyContext({ listIndent: prefixWidth }) + let result = '' for (const child of children) { @@ -61,10 +66,12 @@ export async function li(node: ElementNode, state: State) { } result = result.trim() + state.applyContext(revert) + const attrs = comarkAttributes(userBlockAttrs('li', node[1] as Record)) const suffix = attrs ? ` ${attrs}` : '' - if (order) { + if (ordered) { state.applyContext({ order: order + 1 }) } diff --git a/packages/comark/src/internal/stringify/handlers/ol.ts b/packages/comark/src/internal/stringify/handlers/ol.ts index 6d1d576c9..65e61d9bd 100644 --- a/packages/comark/src/internal/stringify/handlers/ol.ts +++ b/packages/comark/src/internal/stringify/handlers/ol.ts @@ -2,15 +2,17 @@ import type { State } from 'comark/render' import type { ElementNode, Node } from 'comark' import { indent } from '../../../utils/index.ts' import { comarkAttributes, userBlockAttrs } from '../attributes.ts' +import { listMarker } from '../list.ts' -export async function ol(node: ElementNode, state: State) { +export async function ol(node: ElementNode, state: State, parent?: ElementNode) { const children = node.slice(2) as Node[] // `start` is carried by the native numbering; IMPLICIT_ATTRS drops it from user attrs. const start = Number((node[1] as Record).start) - const order = Number.isInteger(start) && start >= 1 ? start : 1 + const order = Number.isInteger(start) && start >= 0 ? start : 1 + const marker = listMarker(node, state, parent, ['.', ')']) - const revert = state.applyContext({ list: true, order, listIndent: 3 }) + const revert = state.applyContext({ list: true, order, listMarker: marker }) let result = '' for (const child of children) { @@ -25,13 +27,13 @@ export async function ol(node: ElementNode, state: State) { const attrs = comarkAttributes(userBlockAttrs('ol', node[1] as Record)) if (attrs) { if (revert.list) { - return '\n' + indent(`::ol${attrs}\n${result}\n::`, { width: (revert.listIndent as number) || 2 }) + return '\n' + indent(`::ol${attrs}\n${result}\n::`, { width: (state.context.listIndent as number) || 2 }) } return `::ol${attrs}\n${result}\n::` + state.context.blockSeparator } if (revert.list) { - result = '\n' + indent(result, { width: (revert.listIndent as number) || 2 }) + result = '\n' + indent(result, { width: (state.context.listIndent as number) || 2 }) } else { result = result + state.context.blockSeparator } diff --git a/packages/comark/src/internal/stringify/handlers/ul.ts b/packages/comark/src/internal/stringify/handlers/ul.ts index b6d00f125..1e623d060 100644 --- a/packages/comark/src/internal/stringify/handlers/ul.ts +++ b/packages/comark/src/internal/stringify/handlers/ul.ts @@ -2,11 +2,14 @@ import type { State } from 'comark/render' import type { ElementNode, Node } from 'comark' import { indent } from '../../../utils/index.ts' import { comarkAttributes, userBlockAttrs } from '../attributes.ts' +import { listMarker } from '../list.ts' -export async function ul(node: ElementNode, state: State) { +export async function ul(node: ElementNode, state: State, parent?: ElementNode) { const children = node.slice(2) as Node[] - const revert = state.applyContext({ list: true, order: false, listIndent: 2 }) + const marker = listMarker(node, state, parent, ['-', '*']) + + const revert = state.applyContext({ list: true, order: false, listMarker: marker }) let result = '' for (const child of children) { @@ -21,13 +24,13 @@ export async function ul(node: ElementNode, state: State) { const attrs = comarkAttributes(userBlockAttrs('ul', node[1] as Record)) if (attrs) { if (revert.list) { - return '\n' + indent(`::ul${attrs}\n${result}\n::`, { width: (revert.listIndent as number) || 2 }) + return '\n' + indent(`::ul${attrs}\n${result}\n::`, { width: (state.context.listIndent as number) || 2 }) } return `::ul${attrs}\n${result}\n::` + state.context.blockSeparator } if (revert.list) { - result = '\n' + indent(result, { width: (revert.listIndent as number) || 2 }) + result = '\n' + indent(result, { width: (state.context.listIndent as number) || 2 }) } else { result = result + state.context.blockSeparator } diff --git a/packages/comark/src/internal/stringify/list.ts b/packages/comark/src/internal/stringify/list.ts new file mode 100644 index 000000000..689bd1102 --- /dev/null +++ b/packages/comark/src/internal/stringify/list.ts @@ -0,0 +1,33 @@ +import type { State } from 'comark/render' +import type { ElementNode, MarkdownDocument, Node } from 'comark' +import { comarkAttributes, userBlockAttrs } from './attributes.ts' + +/** + * Pick the marker of a `ul` (`-` or `*`) or `ol` (`.` or `)`) node. + * + * Two lists of the same kind that follow each other merge into one list on + * re-parse unless the second uses a different bullet or delimiter, so the + * marker alternates along a run of adjacent lists. + */ +export function listMarker( + node: ElementNode, + state: State, + parent: ElementNode | undefined, + markers: [string, string] +) { + const siblings = parent + ? (parent.slice(2) as Node[]) + : ((state.context.tree as MarkdownDocument | undefined)?.nodes ?? []) + let alternate = false + for (let index = siblings.indexOf(node); index > 0 && isNativeList(siblings[index - 1], node[0]); index--) { + alternate = !alternate + } + return markers[alternate ? 1 : 0] +} + +// A list with user attrs renders as a `::ul` / `::ol` component, which ends the run. +function isNativeList(node: Node | undefined, tag: string): boolean { + return ( + Array.isArray(node) && node[0] === tag && !comarkAttributes(userBlockAttrs(tag, node[1] as Record)) + ) +} diff --git a/packages/comark/test/roundtrip-safety.test.ts b/packages/comark/test/roundtrip-safety.test.ts index b376c14cd..67c7a5594 100644 --- a/packages/comark/test/roundtrip-safety.test.ts +++ b/packages/comark/test/roundtrip-safety.test.ts @@ -159,6 +159,26 @@ describe('component after a list', () => { }) }) +describe('lists, emphasis and headings', () => { + it.each([ + ['an ordered list that starts at 0', '0. zero\n1. one\n'], + ['adjacent bullet lists', '- a\n- b\n\n+ c\n\n* d\n'], + ['adjacent ordered lists', '1. a\n\n1) b\n'], + ['adjacent nested lists', '- a\n - b\n\n * c\n'], + ['a list nested under item 10', '10. ten\n - nested\n'], + [ + 'a list nested under the tenth item', + '1. a\n2. b\n3. c\n4. d\n5. e\n6. f\n7. g\n8. h\n9. i\n10. j\n - nested\n', + ], + ['emphasis inside emphasis', '*_foo_*\n'], + ['a multi-line heading', 'Foo\nbar\n===\n'], + ['a multi-line level 2 heading with attributes', 'Foo\nbar {.c}\n---\n'], + ])('keeps %s', async (_, md) => { + const { t1, t2 } = await roundTrip(md) + expect(t2.nodes).toEqual(t1.nodes) + }) +}) + describe('link and image serialization', () => { const doc = (node: unknown) => ({ frontmatter: {}, meta: {}, nodes: [['p', {}, node]] }) as unknown as MarkdownDocument diff --git a/test/bundle.test.ts b/test/bundle.test.ts index aac8fcb86..4395f96ce 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -77,7 +77,7 @@ describe('package bundle size', { timeout: 60_000 }, () => { "@comark/react": "42.9k (83 files)", "@comark/svelte": "50.3k (91 files)", "@comark/vue": "62.6k (89 files)", - "comark": "440k (171 files)", + "comark": "442k (173 files)", } `) }) From 11da380185d5ad99d5d1e54588a71d3260afb6eb Mon Sep 17 00:00:00 2001 From: aliassar Date: Wed, 18 Nov 2026 19:47:56 +0100 Subject: [PATCH 2/7] fix(stringify): pick list markers in one pass per sibling collection Mark which lists in a sibling collection take the second marker in a single pass per render instead of an `indexOf` and backward scan for each list. A list that a `transformNode` hook copied is looked up by the node it was copied from, so adjacent lists stay apart. Co-Authored-By: Claude Opus 5.5 --- .../comark/src/internal/stringify/list.ts | 36 ++++++++++++++----- .../comark/src/internal/stringify/state.ts | 15 +++++++- packages/comark/test/roundtrip-safety.test.ts | 7 ++++ 3 files changed, 48 insertions(+), 10 deletions(-) diff --git a/packages/comark/src/internal/stringify/list.ts b/packages/comark/src/internal/stringify/list.ts index 689bd1102..5e1d82104 100644 --- a/packages/comark/src/internal/stringify/list.ts +++ b/packages/comark/src/internal/stringify/list.ts @@ -1,6 +1,10 @@ import type { State } from 'comark/render' -import type { ElementNode, MarkdownDocument, Node } from 'comark' +import type { ElementNode, MarkdownDocument } from 'comark' import { comarkAttributes, userBlockAttrs } from './attributes.ts' +import { sourceNode } from './state.ts' + +// Per render and per sibling collection, the lists that take the second marker. +const alternateLists = new WeakMap>>() /** * Pick the marker of a `ul` (`-` or `*`) or `ol` (`.` or `)`) node. @@ -15,18 +19,32 @@ export function listMarker( parent: ElementNode | undefined, markers: [string, string] ) { - const siblings = parent - ? (parent.slice(2) as Node[]) - : ((state.context.tree as MarkdownDocument | undefined)?.nodes ?? []) - let alternate = false - for (let index = siblings.indexOf(node); index > 0 && isNativeList(siblings[index - 1], node[0]); index--) { - alternate = !alternate + const siblings: readonly unknown[] = parent ?? (state.context.tree as MarkdownDocument | undefined)?.nodes ?? [] + let byCollection = alternateLists.get(state.context) + if (!byCollection) alternateLists.set(state.context, (byCollection = new WeakMap())) + let alternates = byCollection.get(siblings) + if (!alternates) byCollection.set(siblings, (alternates = findAlternateLists(siblings, parent ? 2 : 0))) + return markers[alternates.has(sourceNode(node)) ? 1 : 0] +} + +// One pass over the siblings: a list alternates when the one before it is a +// native list of the same kind that did not. +function findAlternateLists(siblings: readonly unknown[], start: number): Set { + const alternates = new Set() + let previousAlternates = false + for (let index = start; index < siblings.length; index++) { + const node = siblings[index] + const tag = Array.isArray(node) ? node[0] : undefined + const alternate: boolean = + (tag === 'ul' || tag === 'ol') && index > start && isNativeList(siblings[index - 1], tag) && !previousAlternates + if (alternate) alternates.add(node) + previousAlternates = alternate } - return markers[alternate ? 1 : 0] + return alternates } // A list with user attrs renders as a `::ul` / `::ol` component, which ends the run. -function isNativeList(node: Node | undefined, tag: string): boolean { +function isNativeList(node: unknown, tag: string): boolean { return ( Array.isArray(node) && node[0] === tag && !comarkAttributes(userBlockAttrs(tag, node[1] as Record)) ) diff --git a/packages/comark/src/internal/stringify/state.ts b/packages/comark/src/internal/stringify/state.ts index 986bbe285..cb2b5b7ec 100644 --- a/packages/comark/src/internal/stringify/state.ts +++ b/packages/comark/src/internal/stringify/state.ts @@ -26,6 +26,17 @@ function findHandler(ctx: Context, node: ElementNode): NodeHandler | undefined { return userHandler } +// The tree node each `transformNode` copy was made from. +const sourceNodes = new WeakMap() + +/** + * The tree node `node` was rendered from: handlers get a copy when a + * `transformNode` hook changed it, and only the original is in its parent. + */ +export function sourceNode(node: ElementNode): ElementNode { + return sourceNodes.get(node) ?? node +} + /** * Render a single node. When `atLineStart` is true, leading block markers in * text nodes are escaped. @@ -86,7 +97,9 @@ export async function one(node: Node, state: State, parent?: ElementNode, atLine hasOwnAttrs = true props = transformed.props } - node = [transformed.tag, attrs, ...(node.slice(2) as Node[])] + const copy: ElementNode = [transformed.tag, attrs, ...(node.slice(2) as Node[])] + sourceNodes.set(copy, node) + node = copy } } if (hasOwnAttrs) state.renderData = { ...prevRenderData, props } diff --git a/packages/comark/test/roundtrip-safety.test.ts b/packages/comark/test/roundtrip-safety.test.ts index e5c29ba42..e30ab7cdd 100644 --- a/packages/comark/test/roundtrip-safety.test.ts +++ b/packages/comark/test/roundtrip-safety.test.ts @@ -177,6 +177,13 @@ describe('lists, emphasis and headings', () => { const { t1, t2 } = await roundTrip(md) expect(t2.nodes).toEqual(t1.nodes) }) + + it('keeps adjacent lists apart when a transformNode hook copies them', async () => { + const t1 = await parseMarkdown('- a\n\n* b\n') + const rendered = await renderMarkdown(t1, { transformNode: ({ props }) => ({ props: { ...props } }) }) + const t2 = await parseMarkdown(rendered) + expect(t2.nodes).toEqual(t1.nodes) + }) }) describe('link and image serialization', () => { From 0bcea8a2f2884162e83e11eb55dc1576fbf69fa4 Mon Sep 17 00:00:00 2001 From: aliassar Date: Wed, 18 Nov 2026 19:48:08 +0100 Subject: [PATCH 3/7] fix(stringify): keep `*` for emphasis that does not touch its parent's `_` cannot open or close emphasis inside a word, so `_foo *bar*baz_` came back as literal underscores. Nested emphasis now switches to `_` only where `*` would sit next to the enclosing `*` and read as strong. Co-Authored-By: Claude Opus 5.5 --- .../src/internal/stringify/handlers/emphesis.ts | 11 ++++++++--- packages/comark/test/roundtrip-safety.test.ts | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/comark/src/internal/stringify/handlers/emphesis.ts b/packages/comark/src/internal/stringify/handlers/emphesis.ts index 193e34ae7..030af8354 100644 --- a/packages/comark/src/internal/stringify/handlers/emphesis.ts +++ b/packages/comark/src/internal/stringify/handlers/emphesis.ts @@ -1,12 +1,17 @@ import type { State } from 'comark/render' import type { ElementNode } from 'comark' import { comarkAttributes } from '../attributes.ts' +import { sourceNode } from '../state.ts' -export async function emphesis(node: ElementNode, state: State) { +export async function emphesis(node: ElementNode, state: State, parent?: ElementNode) { const [_, attrs, ...children] = node - // Emphasis inside emphasis alternates `*` and `_`: `**foo**` would read back as strong. - const marker = state.context.emphasisMarker === '*' ? '_' : '*' + // Emphasis that opens or closes emphasis around it alternates `*` and `_`: + // `**foo**` would read back as strong. Elsewhere it keeps `*`, since `_` + // cannot open or close inside a word (`*foo *bar*baz*`). + const source = sourceNode(node) + const atEdge = parent !== undefined && (parent[2] === source || parent[parent.length - 1] === source) + const marker = state.context.emphasisMarker === '*' && atEdge ? '_' : '*' const revert = state.applyContext({ emphasisMarker: marker }) let content = '' diff --git a/packages/comark/test/roundtrip-safety.test.ts b/packages/comark/test/roundtrip-safety.test.ts index e30ab7cdd..e26eefe49 100644 --- a/packages/comark/test/roundtrip-safety.test.ts +++ b/packages/comark/test/roundtrip-safety.test.ts @@ -171,6 +171,7 @@ describe('lists, emphasis and headings', () => { '1. a\n2. b\n3. c\n4. d\n5. e\n6. f\n7. g\n8. h\n9. i\n10. j\n - nested\n', ], ['emphasis inside emphasis', '*_foo_*\n'], + ['emphasis that ends inside a word within emphasis', '_foo *bar*baz_\n'], ['a multi-line heading', 'Foo\nbar\n===\n'], ['a multi-line level 2 heading with attributes', 'Foo\nbar {.c}\n---\n'], ])('keeps %s', async (_, md) => { From d794f31e29732a793acb375d2f3db2355e808823 Mon Sep 17 00:00:00 2001 From: aliassar Date: Wed, 18 Nov 2026 19:48:09 +0100 Subject: [PATCH 4/7] fix(stringify): escape the first line of a multi-line heading A setext heading's text starts its line, so a leading `#`, `>` or list marker in it needs the escape the ATX `# ` prefix made unnecessary. Co-Authored-By: Claude Opus 5.5 --- .../comark/src/internal/stringify/handlers/heading.ts | 10 ++++++++-- packages/comark/src/internal/stringify/state.ts | 2 +- packages/comark/test/roundtrip-safety.test.ts | 1 + 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/comark/src/internal/stringify/handlers/heading.ts b/packages/comark/src/internal/stringify/handlers/heading.ts index ed72ff047..01428337f 100644 --- a/packages/comark/src/internal/stringify/handlers/heading.ts +++ b/packages/comark/src/internal/stringify/handlers/heading.ts @@ -3,6 +3,7 @@ import type { ElementNode, HeadingIdsOption } from 'comark' import { textContent } from '../../../utils/index.ts' import { createHeadingIdTracker, nextHeadingId, reserveHeadingId, type HeadingIdTracker } from '../../heading-id.ts' import { comarkAttributes } from '../attributes.ts' +import { escapeLeadingBlock } from '../state.ts' // Replays the parser's id generation across one render so each heading's // implicit id is known (`null` when ids are disabled). @@ -34,7 +35,7 @@ export async function heading(node: ElementNode, state: State) { const level = Number(tag.slice(1)) - const content = await state.flow(node, state) + let content = await state.flow(node, state) // The auto-generated id is implicit in `# Heading` markdown; only echo a custom one. const { id, ...rest } = node[1] as Record @@ -43,8 +44,13 @@ export async function heading(node: ElementNode, state: State) { const suffix = attrs ? ` ${attrs}` : '' // An ATX heading ends at the line break, so a multi-line h1/h2 (setext - // source) keeps its underline form. + // source) keeps its underline form. Its text then starts the line, where a + // leading `#`, `>`, `-`... needs the escape the `# ` prefix made unnecessary. if (level <= 2 && content.includes('\n')) { + if (typeof node[2] === 'string' && node[2]) { + const end = content.indexOf('\n') + content = escapeLeadingBlock(content.slice(0, end)) + content.slice(end) + } return content + suffix + '\n' + (level === 1 ? '===' : '---') + state.context.blockSeparator } diff --git a/packages/comark/src/internal/stringify/state.ts b/packages/comark/src/internal/stringify/state.ts index cb2b5b7ec..dea751d19 100644 --- a/packages/comark/src/internal/stringify/state.ts +++ b/packages/comark/src/internal/stringify/state.ts @@ -389,7 +389,7 @@ function escapeInline(text: string): string { * heading. `*`, `_` and `~` based markers are already handled by * {@link escapeInline}; only the block-exclusive markers remain here. */ -function escapeLeadingBlock(line: string): string { +export function escapeLeadingBlock(line: string): string { // ATX heading: 1-6 `#` followed by a space/tab or the end of the line. if (/^#{1,6}([ \t]|$)/.test(line)) return `\\${line}` // Blockquote: `>` (a following space is optional). diff --git a/packages/comark/test/roundtrip-safety.test.ts b/packages/comark/test/roundtrip-safety.test.ts index e26eefe49..631bf6aaa 100644 --- a/packages/comark/test/roundtrip-safety.test.ts +++ b/packages/comark/test/roundtrip-safety.test.ts @@ -174,6 +174,7 @@ describe('lists, emphasis and headings', () => { ['emphasis that ends inside a word within emphasis', '_foo *bar*baz_\n'], ['a multi-line heading', 'Foo\nbar\n===\n'], ['a multi-line level 2 heading with attributes', 'Foo\nbar {.c}\n---\n'], + ['a multi-line heading that starts with an escaped marker', '\\# Foo\nbar\n===\n'], ])('keeps %s', async (_, md) => { const { t1, t2 } = await roundTrip(md) expect(t2.nodes).toEqual(t1.nodes) From 1186ba9a54b4808a98361281248ca12206f3534e Mon Sep 17 00:00:00 2001 From: aliassar Date: Wed, 18 Nov 2026 19:48:09 +0100 Subject: [PATCH 5/7] fix(stringify): separate a nested list that starts past 1 from the item text Only an ordered list that starts at 1 can interrupt a paragraph, so a nested list with any other start gets a blank line before it. Co-Authored-By: Claude Opus 5.5 --- packages/comark/src/internal/stringify/handlers/ol.ts | 4 +++- packages/comark/test/roundtrip-safety.test.ts | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/comark/src/internal/stringify/handlers/ol.ts b/packages/comark/src/internal/stringify/handlers/ol.ts index f24a0b565..2ac3a3df5 100644 --- a/packages/comark/src/internal/stringify/handlers/ol.ts +++ b/packages/comark/src/internal/stringify/handlers/ol.ts @@ -33,7 +33,9 @@ export async function ol(node: ElementNode, state: State, parent?: ElementNode) } if (revert.list) { - result = '\n' + indent(result, { width: (state.context.listIndent as number) || 2 }) + // Only a list that starts at 1 can interrupt the item's text: any other + // start needs a blank line before it. + result = (order === 1 ? '\n' : '\n\n') + indent(result, { width: (state.context.listIndent as number) || 2 }) } else { result = result + state.context.blockSeparator } diff --git a/packages/comark/test/roundtrip-safety.test.ts b/packages/comark/test/roundtrip-safety.test.ts index 631bf6aaa..afd4c08b6 100644 --- a/packages/comark/test/roundtrip-safety.test.ts +++ b/packages/comark/test/roundtrip-safety.test.ts @@ -170,6 +170,7 @@ describe('lists, emphasis and headings', () => { 'a list nested under the tenth item', '1. a\n2. b\n3. c\n4. d\n5. e\n6. f\n7. g\n8. h\n9. i\n10. j\n - nested\n', ], + ['a nested list that starts at 0 after text', '- parent\n\n 0. child\n'], ['emphasis inside emphasis', '*_foo_*\n'], ['emphasis that ends inside a word within emphasis', '_foo *bar*baz_\n'], ['a multi-line heading', 'Foo\nbar\n===\n'], From 32bea0e361f0ec7f80b7904094d35d054363a1af Mon Sep 17 00:00:00 2001 From: aliassar Date: Wed, 18 Nov 2026 19:49:11 +0100 Subject: [PATCH 6/7] test: update bundle size snapshot Co-Authored-By: Claude Opus 5.5 --- test/bundle.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/bundle.test.ts b/test/bundle.test.ts index d1a968385..bd669ab53 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -77,7 +77,7 @@ describe('package bundle size', { timeout: 60_000 }, () => { "@comark/react": "43.3k (87 files)", "@comark/svelte": "51.0k (95 files)", "@comark/vue": "62.7k (93 files)", - "comark": "451k (177 files)", + "comark": "453k (177 files)", } `) }) From 21e560ef561dc8590f69600179160eda795204da Mon Sep 17 00:00:00 2001 From: Farnabaz Date: Thu, 19 Nov 2026 11:58:00 +0100 Subject: [PATCH 7/7] fix(stringify): only alternate emphasis marker directly inside emphasis The `_` marker was picked for any emphasis at the edge of its parent while the `*` context was active, including when the parent was a link inside emphasis. `_x [a*b*](/u) y_` then stringified to `*x [a_b_](/u) y*`, which loses the inner emphasis on re-parse. The edge rule now applies only when the immediate parent is an `em` element. Adds a round-trip case for it. --- .../comark/src/internal/stringify/handlers/emphesis.ts | 7 ++++--- packages/comark/test/roundtrip-safety.test.ts | 1 + 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/comark/src/internal/stringify/handlers/emphesis.ts b/packages/comark/src/internal/stringify/handlers/emphesis.ts index 030af8354..7f988a189 100644 --- a/packages/comark/src/internal/stringify/handlers/emphesis.ts +++ b/packages/comark/src/internal/stringify/handlers/emphesis.ts @@ -6,11 +6,12 @@ import { sourceNode } from '../state.ts' export async function emphesis(node: ElementNode, state: State, parent?: ElementNode) { const [_, attrs, ...children] = node - // Emphasis that opens or closes emphasis around it alternates `*` and `_`: + // Emphasis that opens or closes its parent emphasis alternates `*` and `_`: // `**foo**` would read back as strong. Elsewhere it keeps `*`, since `_` - // cannot open or close inside a word (`*foo *bar*baz*`). + // cannot open or close inside a word (`*foo *bar*baz*`, `_x [a*b*](/u) y_`). const source = sourceNode(node) - const atEdge = parent !== undefined && (parent[2] === source || parent[parent.length - 1] === source) + const atEdge = + parent !== undefined && parent[0] === 'em' && (parent[2] === source || parent[parent.length - 1] === source) const marker = state.context.emphasisMarker === '*' && atEdge ? '_' : '*' const revert = state.applyContext({ emphasisMarker: marker }) diff --git a/packages/comark/test/roundtrip-safety.test.ts b/packages/comark/test/roundtrip-safety.test.ts index afd4c08b6..4df84695b 100644 --- a/packages/comark/test/roundtrip-safety.test.ts +++ b/packages/comark/test/roundtrip-safety.test.ts @@ -173,6 +173,7 @@ describe('lists, emphasis and headings', () => { ['a nested list that starts at 0 after text', '- parent\n\n 0. child\n'], ['emphasis inside emphasis', '*_foo_*\n'], ['emphasis that ends inside a word within emphasis', '_foo *bar*baz_\n'], + ['emphasis inside a link inside emphasis', '_x [a*b*](/u) y_\n'], ['a multi-line heading', 'Foo\nbar\n===\n'], ['a multi-line level 2 heading with attributes', 'Foo\nbar {.c}\n---\n'], ['a multi-line heading that starts with an escaped marker', '\\# Foo\nbar\n===\n'],