diff --git a/src/plain-text/adf-to-plain-text.test.ts b/src/plain-text/adf-to-plain-text.test.ts index 25206f7..1a33679 100644 --- a/src/plain-text/adf-to-plain-text.test.ts +++ b/src/plain-text/adf-to-plain-text.test.ts @@ -198,6 +198,12 @@ test('writes a code block ending in a line feed as one block, a blank line from assert.equal(plain(adfToPlainText(document({ content: [text('a\n')], type: 'codeBlock' }, line('b')))), 'a\n\nb') }) +test('writes the line feeds of consecutive code fragments as the one fragment holding them all', () => { + const split: AdfNode = { content: [text('a\n'), text('\n'), text('b')], type: 'codeBlock' } + const whole: AdfNode = { content: [text('a\n\nb')], type: 'codeBlock' } + assert.equal(plain(adfToPlainText(document(split))), plain(adfToPlainText(document(whole)))) +}) + test('writes a task item holding blocks as an item', () => { const tasks: AdfNode = { content: [{ attrs: { localId: 'a', state: 'TODO' }, content: [line('a'), line('b')], type: 'blockTaskItem' }], type: 'taskList' } assert.equal(plain(adfToPlainText(document(tasks))), '☐ a\n b') diff --git a/src/plain-text/adf-to-plain-text.ts b/src/plain-text/adf-to-plain-text.ts index 8c8a950..ad2dfca 100644 --- a/src/plain-text/adf-to-plain-text.ts +++ b/src/plain-text/adf-to-plain-text.ts @@ -32,26 +32,29 @@ export function adfToPlainText(document: AdfDocument): Result { }) } -// A stack rather than recursion (docs/decisions.md §Nothing recurses unbounded). Text is written the moment it is met: `gap` holds the line feeds it owes first, `lead` the marker of the item it opens, `indent` the margin of every line after that. +// A stack rather than recursion (docs/decisions.md §Nothing recurses unbounded). Text is written the moment it is met: `gap` holds the line feeds the layout owes first and `literal` those the text before ended in, of which the larger is written, `lead` the marker of the item it opens, `indent` the margin of every line after that. function writeText(content: readonly AdfNode[]): Result { const pieces: string[] = [] let length = 0 let gap = 0 let indent = '' let lead: string | undefined + let literal = 0 function emit(text: string): void { let end = text.length while (end > 0 && text[end - 1] === '\n') end -= 1 if (end > 0) { - const head = length === 0 || gap > 0 ? `${length === 0 ? '' : '\n'.repeat(gap)}${lead ?? indent}` : '' + const owed = Math.max(gap, literal) + const head = length === 0 || owed > 0 ? `${length === 0 ? '' : '\n'.repeat(owed)}${lead ?? indent}` : '' const body = text.slice(0, end).replaceAll(/\n(?=[^\n])/g, `\n${indent}`) pieces.push(head, body) length += head.length + body.length gap = 0 lead = undefined + literal = 0 } - gap = Math.max(gap, text.length - end) + literal += text.length - end } const pending: Step[] = childSteps(content, { level: 1, lines: 2 }, 0, undefined, () => undefined).reverse()