mirror of
https://github.com/larvit/adf-codec.git
synced 2026-11-19 06:35:44 +01:00
Answer architecture round 5: the builders keep main's spelling, each writer's result and the CommonMark ask's spelling are held to the bound once built, and the engines' own overflows refuse alike
This commit is contained in:
@@ -46,7 +46,7 @@ test('refuses a value that is not an ADF document, naming the check it failed',
|
||||
|
||||
const tooLong = 'unsupported-node-shape: spelled as markdown, this would be longer than 536870888 characters, the longest string V8 holds'
|
||||
|
||||
// A code block of 300 lines, two of them some 1000 characters short of V8's longest string, so only what their spelling adds passes it.
|
||||
// A code block of 300 lines; two of these together fall some 1000 characters short of V8's longest string, so only what their spelling adds passes it.
|
||||
function nearlyHalfTheBound(): AdfNode {
|
||||
return { attrs: {}, content: [{ text: `${'a'.repeat(894_782)}\n`.repeat(300), type: 'text' }], type: 'codeBlock' }
|
||||
}
|
||||
|
||||
@@ -5,14 +5,14 @@ import { adfDocumentFault, heldTextLength, holdsOnlyAttributes, isUnmarkedSpella
|
||||
import { alertMarker, flavourClaims, foldedAlertMarker, leadingMarker, readAlertMarker, readTaskMarker, taskMarker } from '../portable/conventions.ts'
|
||||
import { blockDirectiveForm, documentSpelling } from '../block-directive.ts'
|
||||
import { blockNodeModel, blockNodes, isTaskItem } from '../../adf/block-nodes.ts'
|
||||
import { boundedThen, joinedWithin, longestMarkdown, separatedBy, tooLong, withinEngineLimits } from '../length-bound.ts'
|
||||
import { carriedBlock } from '../opaque-carry.ts'
|
||||
import { emitInlineLine } from './inline-line.ts'
|
||||
import { failure, faulted, success, type ConvertErrorPath, type Result } from '../../result.ts'
|
||||
import { fencePieces } from '../commonmark/backtick-runs.ts'
|
||||
import { fencedCodeBlock } from '../commonmark/backtick-runs.ts'
|
||||
import { holdsNullCharacter, isBlankLine, isThematicBreak, markerInterruptsParagraph } from '../commonmark/grammar.ts'
|
||||
import { languageSlot, type LanguageSlot } from '../code-language.ts'
|
||||
import { largestNesting } from '../../nesting.ts'
|
||||
import { longestMarkdown, tooLong, withinEngineLimits, withinLongest } from '../length-bound.ts'
|
||||
import { spellBlockDirectiveOpener } from './block-directive-spelling.ts'
|
||||
import { spellDirectiveCloser, spellDirectiveOpener } from '../directive-syntax.ts'
|
||||
import { tryImage } from './image.ts'
|
||||
@@ -28,9 +28,9 @@ type PlacedBlocks = { blocks: readonly PlacedBlock[]; headroom: number }
|
||||
// CommonMark starts a new list where the marker changes, so every second list in a run of one kind takes `alternateText`.
|
||||
type SpelledBlock = { spelling: 'commonmark' | 'directive'; text: string } | { alternateText: string; spelling: 'list'; text: string }
|
||||
// Keyed by reference: only a caller building one object per position (the parse, the portable reduction) passes one; a consumer's document may share a node.
|
||||
// Holds the spelling of each node the CommonMark ask was put to, until the walk above reads it.
|
||||
export type SpellingMemo = Map<AdfNode, KeptSpelling>
|
||||
// inner: the item's blocks joined, for the list form; walk: the blocks themselves, for the directive form.
|
||||
type WalkedItem = { inner: string; node: AdfNode; walk: PlacedBlocks }
|
||||
type WalkedItem = { node: AdfNode; walk: PlacedBlocks }
|
||||
export type Writing = { flavour: WrittenFlavour; memo: SpellingMemo | undefined }
|
||||
|
||||
const bulletDelimiters: Delimiters = ['-', '*']
|
||||
@@ -52,8 +52,8 @@ export function writeMarkdown(document: AdfDocument, flavour: WrittenFlavour): R
|
||||
if (heldTextLength(document.content) > longestMarkdown) return tooLong()
|
||||
const walk = walkBlocks(document.content, [], 0, { flavour, memo: undefined })
|
||||
if (!walk.ok) return walk
|
||||
const text = joinedWithin(walk.value.blocks.length === 0 ? [] : [...blockPieces(walk.value.blocks, 'document'), '\n'])
|
||||
return boundedThen(text, success)
|
||||
const text = joinBlocks(walk.value.blocks, 'document')
|
||||
return withinLongest(text === '' ? '' : `${text}\n`)
|
||||
}
|
||||
|
||||
function walkBlocks(nodes: readonly AdfNode[], path: ConvertErrorPath, depth: number, writing: Writing): Result<PlacedBlocks> {
|
||||
@@ -73,18 +73,16 @@ function tooDeep(path: ConvertErrorPath): Result<never> {
|
||||
return failure('unsupported-nesting-depth', `the document nests deeper than the ${largestNesting} levels the emitter carries`, path)
|
||||
}
|
||||
|
||||
function joinBlocks(blocks: readonly PlacedBlock[], container: BlockContainer): string | undefined {
|
||||
return joinedWithin(blockPieces(blocks, container))
|
||||
}
|
||||
|
||||
function* blockPieces(blocks: readonly PlacedBlock[], container: BlockContainer): Generator<string> {
|
||||
function joinBlocks(blocks: readonly PlacedBlock[], container: BlockContainer): string {
|
||||
let text = ''
|
||||
let alternated = false
|
||||
for (const [index, block] of blocks.entries()) {
|
||||
const previous = blocks[index - 1]
|
||||
if (previous !== undefined) yield separationBetween(previous, block, container)
|
||||
if (previous !== undefined) text += separationBetween(previous, block, container)
|
||||
alternated = !alternated && previous !== undefined && sharesMarker(previous, block)
|
||||
yield alternated && block.spelling === 'list' ? block.alternateText : block.text
|
||||
text += alternated && block.spelling === 'list' ? block.alternateText : block.text
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// A task list is spelled as a bullet list.
|
||||
@@ -119,6 +117,8 @@ export function commonMarkSpelling(node: AdfNode, path: ConvertErrorPath, depth:
|
||||
else if (readable.ok) writing.memo.set(node, { block: readable.value, depth })
|
||||
if (readable === undefined) return undefined
|
||||
if (!readable.ok) return readable
|
||||
// V8 throws past the bound while building the spelling; an engine holding longer strings refuses here alike.
|
||||
if (readable.value.text.length > longestMarkdown) return tooLong()
|
||||
return readable.value.spelling === 'directive' ? undefined : success(null)
|
||||
}
|
||||
|
||||
@@ -139,15 +139,12 @@ function spellReadableBlock(node: AdfNode, path: ConvertErrorPath, depth: number
|
||||
if (portable !== undefined) return portable
|
||||
if (node.type === 'blockquote') return tryBlockquote(node, path, depth, writing)
|
||||
if (node.type === 'bulletList' || node.type === 'orderedList') return tryList(node, path, depth, writing)
|
||||
if (node.type === 'codeBlock') return tryCodeBlock(node, writing.flavour)
|
||||
if (node.type === 'codeBlock') return readableText(tryCodeBlock(node, writing.flavour))
|
||||
if (node.type === 'heading') return tryHeading(node, path, writing.flavour)
|
||||
if (node.type === 'mediaSingle') return readableText(tryImage(node))
|
||||
if (node.type === 'paragraph') return tryParagraph(node, path, writing.flavour)
|
||||
if (node.type === 'rule') return readableText(tryRule(node))
|
||||
if (node.type === 'table') {
|
||||
const table = tryPipeTable(node, path, writing.flavour)
|
||||
return table === undefined || !table.ok ? table : success(commonMarkText(table.value))
|
||||
}
|
||||
if (node.type === 'table') return readableText(tryPipeTable(node, path, writing.flavour))
|
||||
return undefined
|
||||
}
|
||||
|
||||
@@ -165,25 +162,15 @@ function spellPortableBlock(node: AdfNode, path: ConvertErrorPath, depth: number
|
||||
function quotedUnder(head: string, node: AdfNode, path: ConvertErrorPath, depth: number, writing: Writing): Result<EmittedBlock> {
|
||||
const inner = walkBlocks(nodeContent(node), path, depth + 1, writing)
|
||||
if (!inner.ok) return inner
|
||||
const text = joinedWithin(inner.value.blocks.length === 0 ? [head] : [head, '\n\n', ...blockPieces(inner.value.blocks, 'document')])
|
||||
return quotedBlock(text, inner.value.headroom)
|
||||
const body = joinBlocks(inner.value.blocks, 'document')
|
||||
return success(commonMarkText(quoted(body === '' ? head : `${head}\n\n${body}`), inner.value.headroom))
|
||||
}
|
||||
|
||||
function quotedBlock(text: string | undefined, headroom: number): Result<EmittedBlock> {
|
||||
const quoted = text === undefined ? undefined : joinedWithin(quotedPieces(text))
|
||||
return boundedThen(quoted, (spelled) => success(commonMarkText(spelled, headroom)))
|
||||
}
|
||||
|
||||
function* quotedPieces(text: string): Generator<string> {
|
||||
for (let start = 0; ; ) {
|
||||
const end = text.indexOf('\n', start)
|
||||
const line = text.slice(start, end === -1 ? text.length : end)
|
||||
yield line === '' ? '>' : '> '
|
||||
yield line
|
||||
if (end === -1) return
|
||||
yield '\n'
|
||||
start = end + 1
|
||||
}
|
||||
function quoted(text: string): string {
|
||||
return text
|
||||
.split('\n')
|
||||
.map((line) => (line === '' ? '>' : `> ${line}`))
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
function tryTaskList(node: AdfNode, path: ConvertErrorPath, depth: number, writing: Writing): Result<EmittedBlock> {
|
||||
@@ -199,21 +186,14 @@ function tryTaskList(node: AdfNode, path: ConvertErrorPath, depth: number, writi
|
||||
if (task || previous === undefined) items.push([...walk.value.blocks])
|
||||
else for (const block of walk.value.blocks) previous.push(block)
|
||||
}
|
||||
const inners = joinedItems(items.map((blocks) => blockPieces(blocks, 'list-item')))
|
||||
const list = spelledList(
|
||||
items.map((blocks) => joinBlocks(blocks, 'list-item')),
|
||||
() => '',
|
||||
bulletDelimiters,
|
||||
headroom,
|
||||
)
|
||||
// The portable reduction leaves no task a list item cannot hold: a directive here would break the flavour.
|
||||
const unspellable = failure<EmittedBlock>('unsupported-node-shape', 'a task holds blocks no list item spells', path)
|
||||
return boundedThen(inners, (spelled) => spelledList(spelled, () => '', bulletDelimiters, headroom) ?? unspellable)
|
||||
}
|
||||
|
||||
// Each item's text, or `undefined` where one would pass the bound.
|
||||
function joinedItems(items: readonly Iterable<string>[]): string[] | undefined {
|
||||
const inners: string[] = []
|
||||
for (const pieces of items) {
|
||||
const inner = joinedWithin(pieces)
|
||||
if (inner === undefined) return undefined
|
||||
inners.push(inner)
|
||||
}
|
||||
return inners
|
||||
return list === undefined ? failure('unsupported-node-shape', 'a task holds blocks no list item spells', path) : success(list)
|
||||
}
|
||||
|
||||
function placedBlock(node: AdfNode, path: ConvertErrorPath, depth: number, writing: Writing): Result<PlacedBlocks> {
|
||||
@@ -229,15 +209,13 @@ function taskBlocks(task: AdfNode, path: ConvertErrorPath, depth: number, writin
|
||||
const content = nodeContent(task)
|
||||
const line = content.length === 0 ? success('') : emitInlineLine(content, 'paragraph', path, writing.flavour)
|
||||
if (!line.ok) return line
|
||||
const text = joinedWithin(line.value === '' ? [marker] : [marker, ' ', line.value])
|
||||
return boundedThen(text, (spelled) => success({ blocks: [{ ...markerBlock, text: spelled }], headroom: Number.POSITIVE_INFINITY }))
|
||||
return success({ blocks: [{ ...markerBlock, text: line.value === '' ? marker : `${marker} ${line.value}` }], headroom: Number.POSITIVE_INFINITY })
|
||||
}
|
||||
const walk = walkBlocks(nodeContent(task), path, depth, writing)
|
||||
if (!walk.ok) return walk
|
||||
const [first, ...rest] = walk.value.blocks
|
||||
if (first?.node.type !== 'paragraph') return success({ blocks: [markerBlock, ...walk.value.blocks], headroom: walk.value.headroom })
|
||||
const text = joinedWithin([marker, ' ', first.text])
|
||||
return boundedThen(text, (spelled) => success({ blocks: [{ ...first, text: spelled }, ...rest], headroom: walk.value.headroom }))
|
||||
const blocks = first?.node.type === 'paragraph' ? [{ ...first, text: `${marker} ${first.text}` }, ...rest] : [markerBlock, ...walk.value.blocks]
|
||||
return success({ blocks, headroom: walk.value.headroom })
|
||||
}
|
||||
|
||||
function readableText(text: string | undefined): Result<EmittedBlock> | undefined {
|
||||
@@ -253,10 +231,8 @@ function commonMarkText(text: string, headroom: number = Number.POSITIVE_INFINIT
|
||||
return { headroom, spelling: 'commonmark', text }
|
||||
}
|
||||
|
||||
function directivePair(node: AdfNode, opener: string, body: string, headroom: number = Number.POSITIVE_INFINITY): Result<EmittedBlock> {
|
||||
const closer = spellDirectiveCloser(node.type)
|
||||
const text = joinedWithin(body === '' ? [opener, '\n', closer] : [opener, '\n', body, '\n', closer])
|
||||
return boundedThen(text, (spelled) => success({ headroom, spelling: 'directive', text: spelled }))
|
||||
function directivePair(node: AdfNode, opener: string, body: string, headroom: number = Number.POSITIVE_INFINITY): EmittedBlock {
|
||||
return { headroom, spelling: 'directive', text: `${opener}\n${body === '' ? '' : `${body}\n`}${spellDirectiveCloser(node.type)}` }
|
||||
}
|
||||
|
||||
function emitDirectiveBlock(node: AdfNode, model: BlockNodeModel, path: ConvertErrorPath, depth: number, walkBody: () => Result<PlacedBlocks>): Result<EmittedBlock> {
|
||||
@@ -274,12 +250,11 @@ function emitDirectiveBody(node: AdfNode, model: BlockNodeModel, opener: string,
|
||||
if (model.contentModel === 'inline') {
|
||||
const line = emitInlineLine(nodeContent(node), 'paragraph', path, 'lossless')
|
||||
if (!line.ok) return line
|
||||
return directivePair(node, opener, line.value)
|
||||
return success(directivePair(node, opener, line.value))
|
||||
}
|
||||
const walk = walkBody()
|
||||
if (!walk.ok) return walk
|
||||
const body = joinBlocks(walk.value.blocks, 'directive')
|
||||
return boundedThen(body, (spelled) => directivePair(node, opener, spelled, walk.value.headroom))
|
||||
return success(directivePair(node, opener, joinBlocks(walk.value.blocks, 'directive'), walk.value.headroom))
|
||||
}
|
||||
|
||||
function tryBlockquote(node: AdfNode, path: ConvertErrorPath, depth: number, writing: Writing): Result<EmittedBlock> | undefined {
|
||||
@@ -287,18 +262,17 @@ function tryBlockquote(node: AdfNode, path: ConvertErrorPath, depth: number, wri
|
||||
const inner = walkBlocks(nodeContent(node), path, depth + 1, writing)
|
||||
if (!inner.ok) return inner
|
||||
const text = joinBlocks(inner.value.blocks, 'document')
|
||||
const alert = text !== undefined && flavourClaims[writing.flavour].alerts && leadingMarker(text, readAlertMarker) !== undefined
|
||||
return quotedBlock(alert ? joinedWithin(['\\', text]) : text, inner.value.headroom)
|
||||
const alert = flavourClaims[writing.flavour].alerts && leadingMarker(text, readAlertMarker) !== undefined
|
||||
return success(commonMarkText(quoted(alert ? `\\${text}` : text), inner.value.headroom))
|
||||
}
|
||||
|
||||
function tryCodeBlock(node: AdfNode, flavour: WrittenFlavour): Result<EmittedBlock> | undefined {
|
||||
function tryCodeBlock(node: AdfNode, flavour: WrittenFlavour): string | undefined {
|
||||
if (!holdsOnlyAttributes(node, ['language'])) return undefined
|
||||
const slot = languageSlot(nodeAttrs(node)['language'], flavourClaims[flavour])
|
||||
if (slot.kind === 'attribute') return undefined
|
||||
const [only, ...others] = fencedTexts(node) ?? []
|
||||
if (only === undefined || others.length > 0) return undefined
|
||||
const text = joinedWithin(fencePieces(slot.kind === 'fence' ? slot.info : '', only))
|
||||
return boundedThen(text, (spelled) => success(commonMarkText(spelled)))
|
||||
return fencedCodeBlock(slot.kind === 'fence' ? slot.info : '', only)
|
||||
}
|
||||
|
||||
// spec/flavour.md, The CommonMark blocks: one fence per text node, the language on each; with no fence to carry it, the attribute does.
|
||||
@@ -310,8 +284,7 @@ function emitCodeDirective(node: AdfNode, model: BlockNodeModel, path: ConvertEr
|
||||
if (opener === undefined) return carriedFence(carriedBlock(node, path, depth))
|
||||
if (!opener.ok) return opener
|
||||
const info = slot.kind === 'fence' ? slot.info : ''
|
||||
const body = joinedWithin(separatedBy('\n', texts.map((text) => fencePieces(info, text))))
|
||||
return boundedThen(body, (spelled) => directivePair(node, opener.value, spelled))
|
||||
return success(directivePair(node, opener.value, texts.map((text) => fencedCodeBlock(info, text)).join('\n')))
|
||||
}
|
||||
|
||||
// The text of each fence, or `undefined` where a child holds what no fence keeps, so the block carry takes the node.
|
||||
@@ -349,55 +322,39 @@ function tryList(node: AdfNode, path: ConvertErrorPath, depth: number, writing:
|
||||
for (const [offset, item] of items.entries()) {
|
||||
const walk = walkBlocks(nodeContent(item), [...path, 'content', offset], depth + 1, writing)
|
||||
if (!walk.ok) return walk
|
||||
const inner = joinBlocks(walk.value.blocks, 'list-item')
|
||||
if (inner === undefined) return tooLong()
|
||||
headroom = Math.min(headroom, walk.value.headroom)
|
||||
walked.push({ inner, node: item, walk: walk.value })
|
||||
walked.push({ node: item, walk: walk.value })
|
||||
}
|
||||
const number = ordered ? (offset: number): string => `${start + offset}` : (): string => ''
|
||||
return spelledOrDirectiveList(node, walked, number, { depth, headroom, path, writing })
|
||||
}
|
||||
|
||||
// The list spelling where every item holds lines a list item spells, else the directive form.
|
||||
function spelledOrDirectiveList(node: AdfNode, walked: readonly WalkedItem[], number: (offset: number) => string, at: { depth: number; headroom: number; path: ConvertErrorPath; writing: Writing }): Result<EmittedBlock> {
|
||||
const ordered = node.type === 'orderedList'
|
||||
// GitHub reads a task marker opening any item's first paragraph as a checkbox, whatever its siblings hold.
|
||||
const escapesMarker = (inner: string): boolean => flavourClaims[at.writing.flavour].taskMarkers && leadingMarker(inner, readTaskMarker) !== undefined
|
||||
const inners = walked.map(({ inner }) => (escapesMarker(inner) ? `\\${inner}` : inner))
|
||||
const list = spelledList(inners, number, ordered ? orderedDelimiters : bulletDelimiters, at.headroom)
|
||||
if (list !== undefined) return list
|
||||
const inners = walked.map((item) => {
|
||||
const inner = joinBlocks(item.walk.blocks, 'list-item')
|
||||
// GitHub reads a task marker opening any item's first paragraph as a checkbox, whatever its siblings hold.
|
||||
return flavourClaims[writing.flavour].taskMarkers && leadingMarker(inner, readTaskMarker) !== undefined ? `\\${inner}` : inner
|
||||
})
|
||||
const list = ordered ? spelledList(inners, (offset) => `${start + offset}`, orderedDelimiters, headroom) : spelledList(inners, () => '', bulletDelimiters, headroom)
|
||||
if (list !== undefined) return success(list)
|
||||
// The directive form spends a level the walk did not count.
|
||||
if (at.headroom < 1) return tooDeep(at.path)
|
||||
return emitDirectiveBlock(node, ordered ? blockNodes.orderedList : blockNodes.bulletList, at.path, at.depth, () => directiveItems(walked, at.headroom - 1))
|
||||
if (headroom < 1) return tooDeep(path)
|
||||
return emitDirectiveBlock(node, ordered ? blockNodes.orderedList : blockNodes.bulletList, path, depth, () => success({ blocks: directiveItems(walked), headroom: headroom - 1 }))
|
||||
}
|
||||
|
||||
function spelledList(inners: readonly string[], number: (offset: number) => string, [usual, alternate]: Delimiters, headroom: number): Result<EmittedBlock> | undefined {
|
||||
const pieces = listLines(inners, number, usual)
|
||||
const alternatePieces = listLines(inners, number, alternate)
|
||||
if (pieces === undefined || alternatePieces === undefined) return undefined
|
||||
const withAlternate = (text: string): Result<EmittedBlock> => boundedThen(joinedWithin(alternatePieces), (alternateText) => success({ alternateText, headroom, spelling: 'list', text }))
|
||||
return boundedThen(joinedWithin(pieces), withAlternate)
|
||||
function spelledList(inners: readonly string[], number: (offset: number) => string, [usual, alternate]: Delimiters, headroom: number): EmittedBlock | undefined {
|
||||
const text = listLines(inners, number, usual)
|
||||
const alternateText = listLines(inners, number, alternate)
|
||||
return text === undefined || alternateText === undefined ? undefined : { alternateText, headroom, spelling: 'list', text }
|
||||
}
|
||||
|
||||
// `undefined` where an item holds a line no list item spells.
|
||||
function listLines(inners: readonly string[], number: (offset: number) => string, delimiter: string): Iterable<string> | undefined {
|
||||
const items: Iterable<string>[] = []
|
||||
function listLines(inners: readonly string[], number: (offset: number) => string, delimiter: string): string | undefined {
|
||||
const lines: string[] = []
|
||||
for (const [offset, inner] of inners.entries()) {
|
||||
const pieces = listItemPieces(inner, `${number(offset)}${delimiter} `)
|
||||
if (pieces === undefined) return undefined
|
||||
items.push(pieces)
|
||||
const line = tryListItemLines(inner, `${number(offset)}${delimiter} `)
|
||||
if (line === undefined) return undefined
|
||||
lines.push(line)
|
||||
}
|
||||
return separatedBy('\n', items)
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
function directiveItems(items: readonly WalkedItem[], headroom: number): Result<PlacedBlocks> {
|
||||
const blocks: PlacedBlock[] = []
|
||||
for (const item of items) {
|
||||
const pair = boundedThen(joinBlocks(item.walk.blocks, 'directive'), (body) => directivePair(item.node, listItemOpener, body))
|
||||
if (!pair.ok) return pair
|
||||
blocks.push({ ...pair.value, node: item.node })
|
||||
}
|
||||
return success({ blocks, headroom })
|
||||
function directiveItems(items: readonly WalkedItem[]): PlacedBlock[] {
|
||||
return items.map((item) => ({ ...directivePair(item.node, listItemOpener, joinBlocks(item.walk.blocks, 'directive')), node: item.node }))
|
||||
}
|
||||
|
||||
function listStart(node: AdfNode, items: number): number | undefined {
|
||||
@@ -407,25 +364,16 @@ function listStart(node: AdfNode, items: number): number | undefined {
|
||||
return start + items - 1 > largestListMarker ? undefined : start
|
||||
}
|
||||
|
||||
function listItemPieces(inner: string, marker: string): Iterable<string> | undefined {
|
||||
if (inner === '') return [marker.trimEnd()]
|
||||
const [first = '', ...rest] = inner.split('\n')
|
||||
if (rest.some((line) => line !== '' && isBlankLine(line)) || (first !== '' && isBlankLine(first))) return undefined
|
||||
function tryListItemLines(inner: string, marker: string): string | undefined {
|
||||
if (inner === '') return marker.trimEnd()
|
||||
const body = inner.split('\n')
|
||||
if (body.some((line) => line !== '' && isBlankLine(line))) return undefined
|
||||
const indent = ' '.repeat(marker.length)
|
||||
const lines = body.map((line, index) => (index === 0 ? `${marker}${line}` : line === '' ? '' : `${indent}${line}`))
|
||||
const first = lines[0] ?? ''
|
||||
if (!isThematicBreak(first)) return lines.join('\n')
|
||||
// An item opens with `*` only as text, a list there taking `- ` and a rule `---`; a backslash keeps a first line reading as a rule text.
|
||||
const rule = isThematicBreak(`${marker}${first}`)
|
||||
if (rule && !inner.startsWith('*')) return undefined
|
||||
return itemLinePieces(rule ? `${marker}\\` : marker, first, rest, ' '.repeat(marker.length))
|
||||
}
|
||||
|
||||
function* itemLinePieces(opening: string, first: string, rest: readonly string[], indent: string): Generator<string> {
|
||||
yield opening
|
||||
yield first
|
||||
for (const line of rest) {
|
||||
yield '\n'
|
||||
if (line === '') continue
|
||||
yield indent
|
||||
yield line
|
||||
}
|
||||
return inner.startsWith('*') ? [`${marker}\\${first.slice(marker.length)}`, ...lines.slice(1)].join('\n') : undefined
|
||||
}
|
||||
|
||||
function tryParagraph(node: AdfNode, path: ConvertErrorPath, flavour: WrittenFlavour): Result<EmittedBlock> | undefined {
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import type { AdfNode } from '../../adf/document.ts'
|
||||
import type { BlockNodeModel } from '../../adf/block-nodes.ts'
|
||||
import { attributeNestingMessage, nodeAttrs, nodeMarks } from '../../adf/document.ts'
|
||||
import { attributePieces, isBareToken, spellDirectiveOpener, spellJsonAttribute, spellVocabulary } from '../directive-syntax.ts'
|
||||
import { blockArgument, markValues, marksAttribute } from '../block-directive.ts'
|
||||
import { boundedThen, joinedWithin } from '../length-bound.ts'
|
||||
import { failure, success, type ConvertErrorPath, type Result } from '../../result.ts'
|
||||
import { isBareToken, spellAttributes, spellDirectiveOpener, spellJsonAttribute, spellVocabulary } from '../directive-syntax.ts'
|
||||
import { overNested } from '../../json-value.ts'
|
||||
import { spellEmptyKeys } from '../empty-keys.ts'
|
||||
import { vocabularyPairs } from '../../adf/attribute-vocabulary.ts'
|
||||
@@ -23,9 +22,7 @@ export function spellBlockDirectiveOpener(node: AdfNode, model: BlockNodeModel,
|
||||
if (overNested(values)) return failure('unsupported-nesting-depth', attributeNestingMessage(marksAttribute, node.type), path)
|
||||
spelledPairs.push([marksAttribute, spellJsonAttribute(values)])
|
||||
}
|
||||
const head = spellDirectiveOpener(node.type, slot.argument, '')
|
||||
const opener = joinedWithin(spelledPairs.length === 0 ? [head] : [head, ' ', ...attributePieces(spelledPairs)])
|
||||
return boundedThen(opener, success)
|
||||
return success(spellDirectiveOpener(node.type, slot.argument, spellAttributes(spelledPairs)))
|
||||
}
|
||||
|
||||
// `undefined` where the argument slot holds a value no bare token spells.
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import type { AdfNode } from '../../adf/document.ts'
|
||||
import type { ConvertErrorPath } from '../../result.ts'
|
||||
import type { WrittenFlavour } from '../portable/conventions.ts'
|
||||
import { boundedThen, joinedWithin, separatedBy } from '../length-bound.ts'
|
||||
import { delimiterCells, pipeRowPieces } from '../pipe-table-syntax.ts'
|
||||
import { holdsOnlyAttributes, nodeContent } from '../../adf/document.ts'
|
||||
import { success, type ConvertErrorPath, type Result } from '../../result.ts'
|
||||
import { spellPipeDelimiter, spellPipeRow } from '../pipe-table-syntax.ts'
|
||||
import { tryPipeCell } from './inline-line.ts'
|
||||
|
||||
export function tryPipeTable(node: AdfNode, path: ConvertErrorPath, flavour: WrittenFlavour): Result<string> | undefined {
|
||||
export function tryPipeTable(node: AdfNode, path: ConvertErrorPath, flavour: WrittenFlavour): string | undefined {
|
||||
const rows = pipeRows(node)
|
||||
if (rows === undefined) return undefined
|
||||
const spelled: string[][] = []
|
||||
const lines: string[] = []
|
||||
for (const [rowIndex, row] of rows.entries()) {
|
||||
const cells: string[] = []
|
||||
for (const [cellIndex, paragraph] of row.entries()) {
|
||||
@@ -18,17 +17,10 @@ export function tryPipeTable(node: AdfNode, path: ConvertErrorPath, flavour: Wri
|
||||
if (line === undefined) return undefined
|
||||
cells.push(line)
|
||||
}
|
||||
spelled.push(cells)
|
||||
}
|
||||
const text = joinedWithin(separatedBy('\n', tableRows(spelled)))
|
||||
return boundedThen(text, success)
|
||||
}
|
||||
|
||||
function* tableRows(rows: readonly string[][]): Generator<Iterable<string>> {
|
||||
for (const [index, cells] of rows.entries()) {
|
||||
yield pipeRowPieces(cells)
|
||||
if (index === 0) yield pipeRowPieces(delimiterCells(cells.length))
|
||||
lines.push(spellPipeRow(cells))
|
||||
if (rowIndex === 0) lines.push(spellPipeDelimiter(cells.length))
|
||||
}
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
function pipeRows(node: AdfNode): AdfNode[][] | undefined {
|
||||
|
||||
Reference in New Issue
Block a user