diff --git a/src/markdown/emit/adf-to-markdown.ts b/src/markdown/emit/adf-to-markdown.ts index 49a461d..fda1bb9 100644 --- a/src/markdown/emit/adf-to-markdown.ts +++ b/src/markdown/emit/adf-to-markdown.ts @@ -24,7 +24,7 @@ export type SpellingMemo = Map type Walk = { blocks: readonly PlacedBlock[]; headroom: number } type WalkedItem = { node: AdfNode; walk: Walk } -const largestListMarker = 999999999 +export const largestListMarker = 999999999 // Bare because tryList admits no item carrying attributes, marks or text. const listItemOpener = spellDirectiveOpener('listItem', undefined, '') diff --git a/src/markdown/emit/inline-line.ts b/src/markdown/emit/inline-line.ts index 432fde4..796c8e1 100644 --- a/src/markdown/emit/inline-line.ts +++ b/src/markdown/emit/inline-line.ts @@ -35,7 +35,7 @@ type LineAttempt = { fallback: NodeRange | 'opening-link'; line?: undefined } | type LineFallbacks = { carried: Set; openingLinkAsDirective: boolean } -export type PlainLineFallback = { kind: 'claimed-line'; line: number } | { kind: 'opening-link' } | { kind: 'unspellable-run'; run: MarkRun } +export type PlainLineFallback = { kind: 'claimed-line'; line: number; text: string } | { kind: 'opening-link' } | { kind: 'unspellable-run'; run: MarkRun } export function emitInlineLine(nodes: readonly AdfNode[], container: LineContainer, path: ConvertErrorPath): Result { const emitted = emitLine(nodes, container, path) @@ -53,11 +53,8 @@ export function plainLineFallback(nodes: readonly AdfNode[], container: LineCont const emission = lineSegments(nodes, container, path, { carried: new Set(), openingLinkAsDirective: false }) if (!emission.ok) return emission if (emission.value.carry !== undefined) return failure('unsupported-node-shape', 'an inline node on a plain line has no spelling but the carry', path) - const assembled = assembleInlineLine(emission.value.segments, container) - if (assembled.openingLinkAsDirective) return success({ kind: 'opening-link' }) - if (assembled.unspellableRun !== undefined) return success({ kind: 'unspellable-run', run: assembled.unspellableRun }) - const claimed = claimedLine(assembled.line, container) - return success(claimed === undefined ? undefined : { kind: 'claimed-line', line: claimed }) + const verdict = lineVerdict(emission.value.segments, container) + return success(verdict.kind === 'line' ? undefined : verdict) } export function tryPipeCell(nodes: readonly AdfNode[], path: ConvertErrorPath): string | undefined { @@ -118,20 +115,21 @@ function lineSegments(nodes: readonly AdfNode[], container: LineContainer, path: } function attemptLine(segments: readonly InlineSegment[], container: LineContainer, path: ConvertErrorPath): Result { - const assembled = assembleInlineLine(segments, container) - if (assembled.openingLinkAsDirective) return success({ fallback: 'opening-link' }) - if (assembled.unspellableRun !== undefined) return success({ fallback: assembled.unspellableRun }) - const claimed = claimedLine(assembled.line, container) - if (claimed !== undefined) { - return failure('unspellable-line-start', `block parsing would claim the emitted line ${JSON.stringify(assembled.line.split('\n')[claimed])}`, path) - } - return success({ line: assembled.line }) + const verdict = lineVerdict(segments, container) + if (verdict.kind === 'opening-link') return success({ fallback: 'opening-link' }) + if (verdict.kind === 'unspellable-run') return success({ fallback: verdict.run }) + if (verdict.kind === 'claimed-line') return failure('unspellable-line-start', `block parsing would claim the emitted line ${JSON.stringify(verdict.text)}`, path) + return success({ line: verdict.text }) } -function claimedLine(line: string, container: LineContainer): number | undefined { - if (container !== 'paragraph') return undefined - const index = line.split('\n').findIndex((single, index) => claimsLine(single, index === 0 ? 'first' : 'later')) - return index === -1 ? undefined : index +// The fallbacks in the order a line takes them, or the line where it takes none. +function lineVerdict(segments: readonly InlineSegment[], container: LineContainer): PlainLineFallback | { kind: 'line'; text: string } { + const assembled = assembleInlineLine(segments, container) + if (assembled.openingLinkAsDirective) return { kind: 'opening-link' } + if (assembled.unspellableRun !== undefined) return { kind: 'unspellable-run', run: assembled.unspellableRun } + const lines = assembled.line.split('\n') + const claimed = container === 'paragraph' ? lines.findIndex((single, index) => claimsLine(single, index === 0 ? 'first' : 'later')) : -1 + return claimed === -1 ? { kind: 'line', text: assembled.line } : { kind: 'claimed-line', line: claimed, text: lines[claimed] ?? '' } } // spec/flavour.md, Inline nodes. diff --git a/src/markdown/emit/plain-inline.ts b/src/markdown/emit/plain-inline.ts index f4bd55e..401e561 100644 --- a/src/markdown/emit/plain-inline.ts +++ b/src/markdown/emit/plain-inline.ts @@ -87,7 +87,7 @@ function mediaLeaves(attrs: Readonly, marks: readonly AdfMark[], } function noteLeaves(name: string): AdfNode[] { - return [textLeaf(`(${name} not included)`, [{ type: 'em' }])] + return [textLeaf(`(${name.replace(/[\r\u0000]/g, '').replace(/\n/g, ' ')} not included)`, [{ type: 'em' }])] } function nonEmpty(value: unknown): string | undefined { diff --git a/src/markdown/emit/plain-reduction.ts b/src/markdown/emit/plain-reduction.ts index 2d1de39..1729ba3 100644 --- a/src/markdown/emit/plain-reduction.ts +++ b/src/markdown/emit/plain-reduction.ts @@ -1,7 +1,7 @@ import type { AdfDocument, AdfNode } from '../../adf/document.ts' import { adfDocumentFault, nodeAttrs, nodeContent } from '../../adf/document.ts' import { blockNodeModel } from '../../adf/block-nodes.ts' -import { commonMarkSpelling, type SpellingMemo } from './adf-to-markdown.ts' +import { commonMarkSpelling, largestListMarker, type SpellingMemo } from './adf-to-markdown.ts' import { failure, faulted, success, type ConvertErrorPath, type Result } from '../../result.ts' import { inlineLeaves, isBlockNodeType, reduceInline, writableHref } from './plain-inline.ts' import { inlineNodeModel } from '../../adf/inline-nodes.ts' @@ -107,26 +107,29 @@ function concatenated(results: readonly Result[]): Result return success(blocks) } -// A list or a table still taking the directive form gives way to its blocks. +// A list still taking the directive form gives way to its items' blocks. function plainSequence(blocks: readonly AdfNode[], reduction: Reduction): Result { let sequence = mergedLists(blocks.filter((block) => block.type !== 'paragraph' || nodeContent(block).length > 0)) for (let index = 0; index < sequence.length; index += 1) { - const block = sequence[index] - if (block === undefined || !['bulletList', 'orderedList', 'table'].includes(block.type)) continue + const listed = sequence[index] + if (listed === undefined || (listed.type !== 'bulletList' && listed.type !== 'orderedList')) continue + const block = numberedPastMarkers(listed) + sequence[index] = block if (commonMarkSpelling(block, reduction.path, reduction.depth, reduction.memo)?.ok === true) continue - sequence = mergedLists([...sequence.slice(0, index), ...heldBlocks(block), ...sequence.slice(index + 1)]) - index = Math.max(-1, index - 2) + const held = nodeContent(block).flatMap(nodeContent) + const from = Math.max(0, index - 1) + sequence = [...sequence.slice(0, from), ...mergedLists([...sequence.slice(from, index), ...held, ...sequence.slice(index + 1, index + 2)]), ...sequence.slice(index + 2)] + index = from - 1 } return success(sequence) } -function heldBlocks(node: AdfNode): AdfNode[] { - const blocks: AdfNode[] = [] - for (const child of nodeContent(node)) { - const held = ['listItem', 'tableCell', 'tableHeader', 'tableRow'].includes(child.type) ? heldBlocks(child) : [child] - for (const block of held) blocks.push(block) - } - return blocks +// A numbered list whose markers run past CommonMark's keeps its numbers as text in a bullet list. +function numberedPastMarkers(list: AdfNode): AdfNode { + const order = nodeAttrs(list)['order'] + const items = nodeContent(list) + if (list.type !== 'orderedList' || typeof order !== 'number' || order + items.length - 1 <= largestListMarker) return list + return { content: items.map((item, offset) => itemOf(marked(nodeContent(item), `${order + offset}.`))), type: 'bulletList' } } function mergedLists(blocks: readonly AdfNode[]): AdfNode[] { @@ -214,7 +217,8 @@ function listItem(blocks: Result): Result { // A list item's first line reads as no rule and holds no line of spaces alone: the rule and the spaces give way. function itemOf(blocks: readonly AdfNode[]): AdfNode { - const content = (blocks[0]?.type === 'rule' ? blocks.slice(1) : blocks).map((block) => (block.type === 'codeBlock' ? { ...block, content: nodeContent(block).map(blankedLines) } : block)) + const rules = blocks.findIndex((block) => block.type !== 'rule') + const content = blocks.slice(rules === -1 ? blocks.length : rules).map((block) => (block.type === 'codeBlock' ? { ...block, content: nodeContent(block).map(blankedLines) } : block)) return { content, type: 'listItem' } } @@ -241,10 +245,14 @@ function taskBlocks(child: AdfNode, at: Reduction): Result { } if (child.type !== 'blockTaskItem') return reduceStanding(child, at) const blocks = reduceBlocks(nodeContent(child), at) - if (!blocks.ok) return blocks - const [first, ...rest] = blocks.value - if (first?.type === 'paragraph') return success([paragraph([text(`${marker} `), ...nodeContent(first)]), ...rest]) - return success([paragraph([text(marker)]), ...blocks.value]) + return blocks.ok ? success(marked(blocks.value, marker)) : blocks +} + +// The marker leads the first paragraph, or stands as one where the blocks open with another. +function marked(blocks: readonly AdfNode[], marker: string): AdfNode[] { + const [first, ...rest] = blocks + if (first?.type === 'paragraph') return [paragraph([text(`${marker} `), ...nodeContent(first)]), ...rest] + return [paragraph([text(marker)]), ...blocks] } function reduceTable(node: AdfNode, reduction: Reduction): Result {