diff --git a/packages/comark/src/internal/stringify/handlers/emphesis.ts b/packages/comark/src/internal/stringify/handlers/emphesis.ts index 3a8d449b..193e34ae 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 4698507c..4d165ecc 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 41156fa1..bb3859f6 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 6d1d576c..65e61d9b 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 b6d00f12..1e623d06 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 00000000..689bd110 --- /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 b376c14c..67c7a559 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 aac8fcb8..4395f96c 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)", } `) })