3
0
mirror of https://github.com/larvit/adf-codec.git synced 2026-11-18 22:25:44 +01:00

Read deep list items' blank lines and a directive's unclosed backtick runs in time linear in the markdown

This commit is contained in:
2026-10-18 11:15:30 +02:00
committed by Lillem4n
parent a9cdd70365
commit d82b7abb3f
11 changed files with 119 additions and 71 deletions
+3 -12
View File
@@ -1,12 +1,14 @@
import { runLength } from './emphasis-matching.ts'
export type CodeSpanCloser = (from: number, opener: number) => number | undefined
export function backtickRun(text: string, index: number): number {
return text.charAt(index) === '`' ? runLength(text, index) : 0
}
// Where the first run of exactly `opener` backticks at or after `from` begins, `from` never inside a run. Ask with
// `from` rising, so each length's cursor only moves forward and a walk stays linear; an earlier `from` rescans that length.
export function backtickCloser(text: string): (from: number, opener: number) => number | undefined {
export function backtickCloser(text: string): CodeSpanCloser {
const counts = new Map<number, number>()
eachRun(text, (_, length) => counts.set(length, (counts.get(length) ?? 0) + 1))
const firsts = new Map<number, number>()
@@ -35,17 +37,6 @@ export function backtickCloser(text: string): (from: number, opener: number) =>
}
}
// Where the run of exactly `opener` backticks closing a code span begins, `undefined` where none does.
export function closingBacktickRun(text: string, from: number, opener: number): number | undefined {
let cursor = from
while (cursor < text.length) {
const run = backtickRun(text, cursor)
if (run === opener) return cursor
cursor += run === 0 ? 1 : run
}
return undefined
}
export function fencedCodeBlock(info: string, body: string): string {
const fence = '`'.repeat(Math.max(3, longestBacktickRun(body) + 1))
return body === '' ? `${fence}${info}\n${fence}` : `${fence}${info}\n${body}\n${fence}`