From 79cb5055a4c4f4c695e3f63368d60688f038c290 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:19:13 -0800 Subject: [PATCH 1/9] Add an option that makes a newline in a paragraph a line break Models often use a single newline as a line break. CommonMark makes it a space. Add newlinesAsLineBreaks to MarkdownStreamParser.init, MarkdownStreamParser.document(from:) and TranscriptStream.init. The default is false, so the parser follows CommonMark as before. With the option, the block parser puts a line break, not a space, between two lines of a paragraph or a heading. A line that ends in a backslash or two spaces still gives one line break. The text that text(in:) and copyText(in:) give has a newline at the break. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Markdown/BlockParser.swift | 31 +++-- .../Markdown/MarkdownStreamParser.swift | 16 ++- .../Stream/TranscriptStream.swift | 7 +- Tests/TranscriptKitTests/LineBreakTests.swift | 116 ++++++++++++++++++ 4 files changed, 157 insertions(+), 13 deletions(-) create mode 100644 Tests/TranscriptKitTests/LineBreakTests.swift diff --git a/Sources/TranscriptKit/Markdown/BlockParser.swift b/Sources/TranscriptKit/Markdown/BlockParser.swift index 4ef128f..f16a775 100644 --- a/Sources/TranscriptKit/Markdown/BlockParser.swift +++ b/Sources/TranscriptKit/Markdown/BlockParser.swift @@ -9,6 +9,8 @@ import Foundation /// Each leaf becomes one block that records the containers it sits in. /// HTML comment blocks are dropped. Not supported: other raw HTML blocks /// (they read as paragraphs) and link reference definitions. +/// A newline inside a paragraph is a space, as in CommonMark, or a line +/// break if `State` has `newlinesAsLineBreaks`. enum BlockParser { enum Kind: Equatable { case paragraph @@ -27,6 +29,9 @@ enum BlockParser { var kind: Kind let containers: [TranscriptBlock.Container] let marker: TranscriptBlock.ListMarker? + /// Paragraphs and headings: a newline between two lines is a line + /// break, not a space. + let newlinesAsLineBreaks: Bool /// Code blocks: the lines so far, joined by "\n". private(set) var code = "" private(set) var lineCount = 0 @@ -50,10 +55,12 @@ enum BlockParser { /// Where inline parsing of this block can resume. var checkpoint = InlineParser.Checkpoint() - init(kind: Kind, containers: [TranscriptBlock.Container], marker: TranscriptBlock.ListMarker?) { + init(kind: Kind, containers: [TranscriptBlock.Container], marker: TranscriptBlock.ListMarker?, + newlinesAsLineBreaks: Bool) { self.kind = kind self.containers = containers self.marker = marker + self.newlinesAsLineBreaks = newlinesAsLineBreaks } /// - Parameter units: `line` trimmed, as UTF-16, if the caller has it. @@ -82,7 +89,8 @@ enum BlockParser { lineCount += 1 case .paragraph, .heading: if let lastLine { - committedSource += BlockParser.contributionWhenFollowed(lastLineUnits, of: lastLine) + committedSource += BlockParser.contributionWhenFollowed(lastLineUnits, of: lastLine, + newlineIsLineBreak: newlinesAsLineBreaks) } lastLine = line lastLineUnits = units ?? BlockParser.utf16(BlockParser.trimmingSpaceAndTab(Substring(line))) @@ -157,6 +165,8 @@ enum BlockParser { struct State { /// The last block may still grow; the caller takes the others. var blocks: [RawBlock] = [] + /// A newline inside a paragraph is a line break, not a space. + let newlinesAsLineBreaks: Bool private var containers: [OpenContainer] = [] /// The last block is a paragraph with no blank line since. private var canContinue = false @@ -171,6 +181,10 @@ enum BlockParser { /// the first item's number, one up per item. private var lists: [ListCounter?] = [] + init(newlinesAsLineBreaks: Bool = false) { + self.newlinesAsLineBreaks = newlinesAsLineBreaks + } + private struct ListCounter { /// The bullet ("-", "+", "*") or the ordered delimiter ("." or ")"). let character: Character @@ -218,7 +232,8 @@ enum BlockParser { marker = containers[index].pendingMarker containers[index].pendingMarker = nil } - var block = RawBlock(kind: kind, containers: containers.map(\.kind), marker: marker) + var block = RawBlock(kind: kind, containers: containers.map(\.kind), marker: marker, + newlinesAsLineBreaks: newlinesAsLineBreaks) if let line { block.addLine(line, units: units) } blocks.append(block) endLists(from: containers.count) @@ -749,9 +764,11 @@ enum BlockParser { /// What a line adds to a block's inline source when another line /// follows it: its trimmed text and a space, or a line break if it ends /// in two spaces or a backslash (which is dropped, with the spaces - /// before it). `trimmed` is the line trimmed, as UTF-16; a line on its - /// own, with nothing after it, contributes just that. - fileprivate static func contributionWhenFollowed(_ trimmed: [UInt16], of line: String) -> [UInt16] { + /// before it), or if `newlineIsLineBreak` is true. `trimmed` is the line + /// trimmed, as UTF-16; a line on its own, with nothing after it, + /// contributes just that. + fileprivate static func contributionWhenFollowed(_ trimmed: [UInt16], of line: String, + newlineIsLineBreak: Bool) -> [UInt16] { let bytes = line.utf8 var units = trimmed var hardBreak = bytes.count >= 2 && bytes.suffix(2).elementsEqual([0x20, 0x20]) @@ -760,7 +777,7 @@ enum BlockParser { units.removeLast() while let last = units.last, last == space || last == tab { units.removeLast() } } - units.append(hardBreak ? newline : space) + units.append(hardBreak || newlineIsLineBreak ? newline : space) return units } diff --git a/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift b/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift index 39b6054..baca898 100644 --- a/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift +++ b/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift @@ -22,7 +22,7 @@ public struct MarkdownStreamParser: Sendable { /// Sum of the frozen blocks' UTF-16 lengths. private var frozenLength = 0 /// Blocks not frozen yet, after every complete line so far. - private var state = BlockParser.State() + private var state: BlockParser.State /// The unterminated last line. private var partial = "" /// `partial` as UTF-16, extended chunk by chunk. @@ -38,9 +38,15 @@ public struct MarkdownStreamParser: Sendable { /// distinct prefixes if several parsers feed one document. /// - tags: custom tags the text may use, and how they look; see /// `TranscriptTag`. Other tags show as written. - public init(idPrefix: String = String(UUID().uuidString.prefix(8)), tags: [TranscriptTag] = []) { + /// - newlinesAsLineBreaks: if true, a single newline inside a paragraph + /// or a heading is a line break, as models often intend. A line that + /// ends in a backslash or two spaces still gives one line break, not + /// two. If false (the default), the newline is a space, as in CommonMark. + public init(idPrefix: String = String(UUID().uuidString.prefix(8)), tags: [TranscriptTag] = [], + newlinesAsLineBreaks: Bool = false) { self.idPrefix = idPrefix self.tags = TranscriptTag.byName(tags) + state = BlockParser.State(newlinesAsLineBreaks: newlinesAsLineBreaks) } /// Adds the next piece of the stream. Chunks can split anywhere. @@ -68,8 +74,10 @@ public struct MarkdownStreamParser: Sendable { } /// Parses a complete Markdown string, with the custom `tags` it may use. - public static func document(from markdown: String, idPrefix: String = "md", tags: [TranscriptTag] = []) -> TranscriptDocument { - var parser = MarkdownStreamParser(idPrefix: idPrefix, tags: tags) + /// `newlinesAsLineBreaks` is as in `init`. + public static func document(from markdown: String, idPrefix: String = "md", tags: [TranscriptTag] = [], + newlinesAsLineBreaks: Bool = false) -> TranscriptDocument { + var parser = MarkdownStreamParser(idPrefix: idPrefix, tags: tags, newlinesAsLineBreaks: newlinesAsLineBreaks) parser.append(markdown) parser.finish() return parser.document diff --git a/Sources/TranscriptKit/Stream/TranscriptStream.swift b/Sources/TranscriptKit/Stream/TranscriptStream.swift index 4124486..348010f 100644 --- a/Sources/TranscriptKit/Stream/TranscriptStream.swift +++ b/Sources/TranscriptKit/Stream/TranscriptStream.swift @@ -54,8 +54,11 @@ public final class TranscriptStream { /// messages. It is parsed right away. Can be called from any thread. /// - tags: custom tags the text may use, and how they look; see /// `TranscriptTag`. Other tags show as written. - public nonisolated init(markdown: String = "", tags: [TranscriptTag] = []) { - var parser = MarkdownStreamParser(tags: tags) + /// - newlinesAsLineBreaks: if true, a single newline inside a paragraph + /// is a line break. If false (the default), it is a space, as in + /// CommonMark. See `MarkdownStreamParser.init`. + public nonisolated init(markdown: String = "", tags: [TranscriptTag] = [], newlinesAsLineBreaks: Bool = false) { + var parser = MarkdownStreamParser(tags: tags, newlinesAsLineBreaks: newlinesAsLineBreaks) if !markdown.isEmpty { parser.append(markdown) } diff --git a/Tests/TranscriptKitTests/LineBreakTests.swift b/Tests/TranscriptKitTests/LineBreakTests.swift new file mode 100644 index 0000000..ebefb49 --- /dev/null +++ b/Tests/TranscriptKitTests/LineBreakTests.swift @@ -0,0 +1,116 @@ +import Foundation +import Testing +@testable import TranscriptKit + +private func parse(_ markdown: String, newlines: Bool = true) -> [TranscriptBlock] { + MarkdownStreamParser.document(from: markdown, newlinesAsLineBreaks: newlines).blocks +} + +@Test func newlineInParagraphIsASpaceByDefault() { + #expect(parse("one\ntwo\nthree", newlines: false).map(\.text) == ["one two three"]) + #expect(MarkdownStreamParser.document(from: "one\ntwo").blocks.map(\.text) == ["one two"]) +} + +@Test func newlineInParagraphIsALineBreakWithTheOption() { + #expect(parse("one\ntwo\nthree").map(\.text) == ["one\ntwo\nthree"]) + #expect(parse("one\ntwo\nthree").map(\.kind) == [.paragraph]) + #expect(parse("one\n\ntwo").map(\.text) == ["one", "two"]) + #expect(parse("one \n two\t\nthree").map(\.text) == ["one\ntwo\nthree"]) + #expect(parse("one\r\ntwo\r\n").map(\.text) == ["one\ntwo"]) +} + +@Test func hardBreaksStayOneLineBreakWithTheOption() { + #expect(parse("one \ntwo").map(\.text) == ["one\ntwo"]) + for newlines in [false, true] { + #expect(parse("one\\\ntwo", newlines: newlines).map(\.text) == ["one\ntwo"]) + #expect(parse("one \\\ntwo", newlines: newlines).map(\.text) == ["one\ntwo"]) + } + #expect(parse("one
\ntwo").map(\.text) == ["one\n\ntwo"]) +} + +@Test func newlinesInContainersAreLineBreaksWithTheOption() { + let list = parse("- one\n two\n- three\nlazy") + #expect(list.map(\.text) == ["one\ntwo", "three\nlazy"]) + #expect(list.map(\.marker) == [.bullet, .bullet]) + let quote = parse("> one\n> two\nlazy\n\n> > nested\n> > line") + #expect(quote.map(\.text) == ["one\ntwo\nlazy", "nested\nline"]) + #expect(quote.map(\.containers) == [[.quote], [.quote, .quote]]) +} + +@Test func otherBlocksKeepTheirLinesWithTheOption() { + #expect(parse("Title\nmore\n===\nnext").map(\.text) == ["Title\nmore", "next"]) + #expect(parse("Title\nmore\n===\nnext").first?.kind == .heading(level: 1)) + #expect(parse("# Title\nbody").map(\.text) == ["Title", "body"]) + #expect(parse("```\na\nb\n```").map(\.text) == ["a\nb"]) + #expect(parse("| a | b |\n| - | - |\n| 1 | 2 |").map(\.text) == ["a\tb\n1\t2"]) + #expect(parse("a | b\nnext").map(\.text) == ["a | b\nnext"]) + #expect(parse("$$\nx\ny").map(\.text) == ["$$\nx\ny"]) + #expect(parse("$$\nx = 1\n$$").first?.spans.first?.math?.tex == "x = 1") +} + +@Test func inlineMarkupSpansLineBreaksWithTheOption() { + let emphasis = parse("*one\ntwo* and **three\nfour**")[0] + #expect(emphasis.text == "one\ntwo and three\nfour") + #expect(emphasis.spans.map(\.range) == [0..<7, 12..<22]) + #expect(emphasis.spans.map(\.traits) == [.italic, .bold]) + let bold = parse("one\n**two**")[0] + #expect(bold.text == "one\ntwo") + #expect(bold.spans.map(\.range) == [4..<7]) + let link = parse("see [the\nguide](https://x.y) now")[0] + #expect(link.text == "see the\nguide now") + #expect(link.spans.first?.link == "https://x.y") + #expect(parse("a \nb")[0].spans.first?.link == "https://x.y") + #expect(parse("a https://x.y\nb")[0].spans.first?.link == "https://x.y") + #expect(parse("one\ntwo")[0].spans.map(\.range) == [0..<7]) +} + +/// A code span keeps the newline as a line break, as the rest of the +/// paragraph does. +@Test func codeSpanKeepsTheLineBreakWithTheOption() { + let block = parse("a `b\nc` d")[0] + #expect(block.text == "a b\nc d") + #expect(block.spans.map(\.range) == [2..<5]) + #expect(block.spans.map(\.traits) == [.code]) + #expect(parse("a `b\nc` d", newlines: false)[0].text == "a b c d") +} + +@Test func copiedTextHasTheLineBreaks() { + let document = MarkdownStreamParser.document(from: "one\ntwo\n\n- item\n more\n\n> quote\n> line", + newlinesAsLineBreaks: true) + #expect(document.text(in: 0.. quote\n> line") + let plain = MarkdownStreamParser.document(from: "one\ntwo") + #expect(plain.copyText(in: 0.. \(parser.document.blocks.last?.text.debugDescription ?? "-")") + } + previous = parser.document + } + #expect(violations.isEmpty, "\(violations.joined(separator: "\n"))") + parser.finish() + #expect(parser.document.blocks.map(\.text) == ["One line\nanother line\nand a third\nwith bold that\nends", "item\nmore", "quote\nmore"]) +} From 7244af518eca24ae938e4ef58ba95c25201609f9 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:19:30 -0800 Subject: [PATCH 2/9] Read a link destination that starts after a line break The inline parser trimmed only spaces and tabs around a link destination. When a line break came after the "(", the destination was empty. This occurs for [a](\nurl) with the new option, and for a backslash line break without it. Trim newlines too. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/Markdown/InlineParser.swift | 2 +- Tests/TranscriptKitTests/LineBreakTests.swift | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Sources/TranscriptKit/Markdown/InlineParser.swift b/Sources/TranscriptKit/Markdown/InlineParser.swift index 58d3f28..a14a1f0 100644 --- a/Sources/TranscriptKit/Markdown/InlineParser.swift +++ b/Sources/TranscriptKit/Markdown/InlineParser.swift @@ -611,7 +611,7 @@ enum InlineParser { let opener = state.brackets.removeLast() if close != nil || open { let raw = String(decoding: units[(i + 2)..<(close ?? count)], as: UTF16.self) - .trimmingCharacters(in: .whitespaces) + .trimmingCharacters(in: .whitespacesAndNewlines) var destination = String(raw.prefix { !$0.isWhitespace }) if destination.hasPrefix("<"), destination.hasSuffix(">"), destination.count >= 2 { destination = String(destination.dropFirst().dropLast()) diff --git a/Tests/TranscriptKitTests/LineBreakTests.swift b/Tests/TranscriptKitTests/LineBreakTests.swift index ebefb49..e0b3c7e 100644 --- a/Tests/TranscriptKitTests/LineBreakTests.swift +++ b/Tests/TranscriptKitTests/LineBreakTests.swift @@ -114,3 +114,11 @@ private func parse(_ markdown: String, newlines: Bool = true) -> [TranscriptBloc parser.finish() #expect(parser.document.blocks.map(\.text) == ["One line\nanother line\nand a third\nwith bold that\nends", "item\nmore", "quote\nmore"]) } + +/// A link destination after a line break is still read. +@Test func linkDestinationCanStartOnTheNextLine() { + #expect(parse("[a](\nhttps://x.y)")[0].spans.first?.link == "https://x.y") + #expect(parse("[a](https://x.y\n\"title\")")[0].spans.first?.link == "https://x.y") + #expect(parse("[a](\nhttps://x.y)", newlines: false)[0].spans.first?.link == "https://x.y") + #expect(parse("[a](\\\nhttps://x.y)", newlines: false)[0].spans.first?.link == "https://x.y") +} From f55d3668c4e6f64e982bb63969072cb2930a2da7 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:19:30 -0800 Subject: [PATCH 3/9] Test streamed line breaks in chunks of any size Run the chunk-split test, the frozen-block test and the test that the shown text only grows with the option on and off. Add a text with single-newline paragraphs, hard breaks, lists, quotes, a setext heading, CRLF line ends and lines that could start other blocks. Check that the inline parse of a paragraph of many lines resumes near its end with the option. Co-Authored-By: Claude Opus 5.5 --- .../IncrementalParserTests.swift | 40 ++++++++++++++++--- Tests/TranscriptKitTests/MarkdownTests.swift | 19 +++++---- 2 files changed, 45 insertions(+), 14 deletions(-) diff --git a/Tests/TranscriptKitTests/IncrementalParserTests.swift b/Tests/TranscriptKitTests/IncrementalParserTests.swift index 6aeaeec..4dcc94c 100644 --- a/Tests/TranscriptKitTests/IncrementalParserTests.swift +++ b/Tests/TranscriptKitTests/IncrementalParserTests.swift @@ -34,6 +34,15 @@ let x = "a < b" // ** not bold ** Trailing paragraph with an unclosed `code span and *emphasis """ +/// Paragraphs whose lines end in a single newline, as models write them, +/// next to hard breaks and to lines that could start another block. +/// Written with explicit "\n" so that the trailing spaces stay. +let lineBreakMarkdown = "First line\nsecond line \nthird line\\\nfourth line \nfifth\t\n**bold** start\n" + + "`code\nspan` and [link\ntext](\nhttps://x.y) and *emphasis\nover lines*\r\nCRLF line\r\n\n" + + "- item one\n continued\nlazy line\n- item two\n\n> quote one\n> quote two\nlazy quote\n\n" + + "Setext title\nover two lines\n===\n\nA | B\nnot a table\n\n| a | b |\n| - | - |\n| 1 | 2 |\n\n" + + "$$\nx = 1\ny = 2\n\nafter math\n1. one\n two\n\n```\ncode\nlines\n```\nlast line\nends here" + /// The benchmark's answer text (Benchmark/TranscriptBench/Corpus.swift). func answerSection(_ index: Int) -> String { """ @@ -92,16 +101,16 @@ private func chunks(of text: String, size: Int?, seed: UInt64 = 1) -> [String] { return result } -@Test(arguments: [1, 2, 3, 5, 7, 13, nil] as [Int?]) -func incrementalParseMatchesParsingFromScratch(chunkSize: Int?) { - for markdown in [trickyMarkdown, (1...3).map(answerSection).joined()] { - var parser = MarkdownStreamParser(idPrefix: "md") +@Test(arguments: [1, 2, 3, 5, 7, 13, nil] as [Int?], [false, true]) +func incrementalParseMatchesParsingFromScratch(chunkSize: Int?, newlinesAsLineBreaks: Bool) { + for markdown in [trickyMarkdown, (1...3).map(answerSection).joined(), lineBreakMarkdown] { + var parser = MarkdownStreamParser(idPrefix: "md", newlinesAsLineBreaks: newlinesAsLineBreaks) var sent = "" var mismatches: [String] = [] for chunk in chunks(of: markdown, size: chunkSize, seed: 7) { parser.append(chunk) sent += chunk - var fresh = MarkdownStreamParser(idPrefix: "md") + var fresh = MarkdownStreamParser(idPrefix: "md", newlinesAsLineBreaks: newlinesAsLineBreaks) fresh.append(sent) if parser.document != fresh.document, mismatches.count < 5 { mismatches.append("after \(sent.count) characters: \(describe(parser.document.blocks.last)) vs \(describe(fresh.document.blocks.last))") @@ -109,7 +118,7 @@ func incrementalParseMatchesParsingFromScratch(chunkSize: Int?) { } #expect(mismatches.isEmpty, "\(mismatches.joined(separator: "\n"))") parser.finish() - #expect(parser.document == MarkdownStreamParser.document(from: markdown)) + #expect(parser.document == MarkdownStreamParser.document(from: markdown, newlinesAsLineBreaks: newlinesAsLineBreaks)) } } @@ -246,6 +255,25 @@ private func randomInline(length: Int, using generator: inout SeededGenerator) - #expect(mismatches.isEmpty, "\(mismatches.joined(separator: "\n"))") } +/// The inline parse of a paragraph of many single-newline lines resumes +/// near its end with the option too, so an update does not parse it whole. +@Test func checkpointKeepsUpWithLineBreaks() { + let lines = (0..<120).map { "Line \($0) with **bold**, `code` and a < b." } + for newlines in [false, true] { + var state = BlockParser.State(newlinesAsLineBreaks: newlines) + for line in lines { state.process(line) } + let source = state.blocks[0].inlineSource().units + #expect(source.contains(UInt16(UInt8(ascii: "\n"))) == newlines) + var checkpoint = InlineParser.Checkpoint() + var end = 0 + while end < source.count { + end = min(end + 7, source.count) + _ = InlineParser.parse(Array(source[.. Str // MARK: Streaming -/// Feeds `sample` in chunks of `size` characters and returns every intermediate document. -private func stream(chunkSize size: Int) -> (steps: [TranscriptDocument], final: TranscriptDocument) { - var parser = MarkdownStreamParser(idPrefix: "md") +/// Feeds `markdown` in chunks of `size` characters and returns every intermediate document. +private func stream(chunkSize size: Int, markdown: String = sample, + newlinesAsLineBreaks: Bool = false) -> (steps: [TranscriptDocument], final: TranscriptDocument) { + var parser = MarkdownStreamParser(idPrefix: "md", newlinesAsLineBreaks: newlinesAsLineBreaks) var steps: [TranscriptDocument] = [] - var rest = Substring(sample) + var rest = Substring(markdown) while !rest.isEmpty { parser.append(String(rest.prefix(size))) rest = rest.dropFirst(size) @@ -187,17 +188,19 @@ func streamingMatchesOneShotParse(chunkSize: Int) { #expect(stream(chunkSize: chunkSize).final == expected) } -@Test func frozenBlocksNeverChange() { - let steps = stream(chunkSize: 1).steps +@Test(arguments: [false, true]) +func frozenBlocksNeverChange(newlinesAsLineBreaks: Bool) { + let steps = stream(chunkSize: 1, newlinesAsLineBreaks: newlinesAsLineBreaks).steps for (previous, next) in zip(steps, steps.dropFirst()) { let settled = previous.blocks.dropLast() #expect(Array(next.blocks.prefix(settled.count)) == Array(settled)) } } -@Test func displayedTextOnlyGrowsWhileStreaming() { +@Test(arguments: [false, true]) +func displayedTextOnlyGrowsWhileStreaming(newlinesAsLineBreaks: Bool) { // Character by character is the worst case: every partial marker is seen. - let steps = stream(chunkSize: 1).steps + let steps = stream(chunkSize: 1, newlinesAsLineBreaks: newlinesAsLineBreaks).steps var violations: [String] = [] for (previous, next) in zip(steps, steps.dropFirst()) where !next.extends(previous) { violations.append("\(previous.blocks.last.map { "\($0.kind) \($0.text.suffix(24))" } ?? "-") -> \(next.blocks.last.map { "\($0.kind) \($0.text.suffix(24))" } ?? "-")") From 1ec0ff2aaf9afb3b59b5934d66594d155bef9cea Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:19:30 -0800 Subject: [PATCH 4/9] Time the parser on long paragraphs with newlines as line breaks Co-Authored-By: Claude Opus 5.5 --- Tests/TranscriptKitTests/ParserTimingTests.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Tests/TranscriptKitTests/ParserTimingTests.swift b/Tests/TranscriptKitTests/ParserTimingTests.swift index 1d907da..ce6ae57 100644 --- a/Tests/TranscriptKitTests/ParserTimingTests.swift +++ b/Tests/TranscriptKitTests/ParserTimingTests.swift @@ -53,13 +53,13 @@ private enum TimingText { } -private func timePerAppend(_ text: String, chunk: Int, tags: [TranscriptTag] = []) -> Double { +private func timePerAppend(_ text: String, chunk: Int, tags: [TranscriptTag] = [], newlinesAsLineBreaks: Bool = false) -> Double { var parts: [String] = [] var rest = Substring(text) while !rest.isEmpty { parts.append(String(rest.prefix(chunk))); rest = rest.dropFirst(chunk) } var best = Double.infinity for _ in 0..<(ProcessInfo.processInfo.environment["TIMING_LONG"] != nil ? 400 : 7) { - var parser = MarkdownStreamParser(idPrefix: "t", tags: tags) + var parser = MarkdownStreamParser(idPrefix: "t", tags: tags, newlinesAsLineBreaks: newlinesAsLineBreaks) let start = DispatchTime.now().uptimeNanoseconds for part in parts { parser.append(part) } let seconds = Double(DispatchTime.now().uptimeNanoseconds - start) / 1e9 @@ -118,6 +118,8 @@ func parserTiming() { .map { $0.offset % 12 == 11 ? $0.element + "\n" : $0.element + " " }.joined().prefix(15600)) print("TIMING very long paragraph: \(veryLongParagraph.count) chars, 2 per append: \(String(format: "%.1f", timePerAppend(veryLongParagraph, chunk: 2))) µs/append") print("TIMING long paragraph: \(longParagraph.count) chars in \(longParagraph.split(separator: "\n").count) lines, 2 per append: \(String(format: "%.1f", timePerAppend(longParagraph, chunk: 2))) µs/append") + print("TIMING long paragraph, newlines as line breaks: \(String(format: "%.1f", timePerAppend(longParagraph, chunk: 2, newlinesAsLineBreaks: true))) µs/append") + print("TIMING very long paragraph, newlines as line breaks: \(String(format: "%.1f", timePerAppend(veryLongParagraph, chunk: 2, newlinesAsLineBreaks: true))) µs/append") let mixed = "Café **crème**, 日本語の`コード` and [ссылка](https://x.y) 👩‍💻 éé. " let mixedParagraph = String(String(repeating: mixed, count: 70).split(separator: " ").enumerated() .map { $0.offset % 10 == 9 ? $0.element + "\n" : $0.element + " " }.joined().prefix(3000)) From 6382848071b8adc146f62d73649e73d96d721d31 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:19:30 -0800 Subject: [PATCH 5/9] Document the newlinesAsLineBreaks option in the README Co-Authored-By: Claude Opus 5.5 --- README.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 15e4433..4f60a92 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,8 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut - links, bare URLs and email addresses, and reference links; - images, drawn by a loader your app provides; - LaTeX math, drawn by a renderer your app provides; - - HTML entities and a few HTML tags. + - HTML entities and a few HTML tags; + - optionally, a single newline as a line break, as models often write it. - **Custom tags.** Define tags such as `@Ana` and how they look: font traits, colours, a link, padding, and shapes drawn behind or over the text. Pills and underlines (solid, dashed, dotted, wavy, marker) are built in, and you can draw shapes of your own, and animate a tag's letters and shapes when it @@ -90,6 +91,20 @@ let document = MarkdownStreamParser.document(from: markdown) TranscriptText(document, style: style) ``` +### Line breaks + +The parser follows CommonMark: a single newline inside a paragraph is a space. Models often use a single newline as +a line break. To show it as a line break, set `newlinesAsLineBreaks`: + +```swift +let stream = TranscriptStream(newlinesAsLineBreaks: true) +let document = MarkdownStreamParser.document(from: markdown, newlinesAsLineBreaks: true) +``` + +The option applies to paragraphs and headings, also inside lists and quotes. A blank line still starts a new +paragraph. A line that ends in a backslash or two spaces also gives one line break, not two. Selected and copied +text has a newline at each such line break. + ### Custom tags ```swift From 022c9a6fa77c2c510ff2e485c70b87f15eac62e6 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:22:29 -0800 Subject: [PATCH 6/9] Test that each line break starts a new laid-out line Co-Authored-By: Claude Opus 5.5 --- Tests/TranscriptKitTests/LineBreakTests.swift | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Tests/TranscriptKitTests/LineBreakTests.swift b/Tests/TranscriptKitTests/LineBreakTests.swift index e0b3c7e..9c98dda 100644 --- a/Tests/TranscriptKitTests/LineBreakTests.swift +++ b/Tests/TranscriptKitTests/LineBreakTests.swift @@ -122,3 +122,15 @@ private func parse(_ markdown: String, newlines: Bool = true) -> [TranscriptBloc #expect(parse("[a](\nhttps://x.y)", newlines: false)[0].spans.first?.link == "https://x.y") #expect(parse("[a](\\\nhttps://x.y)", newlines: false)[0].spans.first?.link == "https://x.y") } + +/// Each line break starts a new laid-out line, and the paragraph grows +/// by one line per break. +@Test func lineBreaksLayOutAsLines() { + let markdown = "one\ntwo\nthree" + let spaces = DocumentLayout(document: MarkdownStreamParser.document(from: markdown), width: 300) + let breaks = DocumentLayout(document: MarkdownStreamParser.document(from: markdown, newlinesAsLineBreaks: true), + width: 300) + #expect(spaces.entry(at: 0).layout.lines.count == 1) + #expect(breaks.entry(at: 0).layout.lines.count == 3) + #expect(breaks.height > spaces.height) +} From 1ad338044242efc1a4f8c09d2572dfd419d402fc Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:41:32 -0800 Subject: [PATCH 7/9] Apply the line break option to
, code spans and tags With newlinesAsLineBreaks, the inline parser now gets the option too. - A newline right after
adds no second line break. A line that ends in
gives one break, as a backslash or two spaces do. - A newline in a code span is a space, as in CommonMark. - A built-in tag such as or
can go over two lines. The output with the option off does not change. The streamed text corpus now has these cases, so the chunk-split tests cover them. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Markdown/InlineParser.swift | 44 ++++++++++++++----- .../Markdown/MarkdownStreamParser.swift | 10 +++-- .../IncrementalParserTests.swift | 1 + Tests/TranscriptKitTests/LineBreakTests.swift | 35 +++++++++++---- 4 files changed, 67 insertions(+), 23 deletions(-) diff --git a/Sources/TranscriptKit/Markdown/InlineParser.swift b/Sources/TranscriptKit/Markdown/InlineParser.swift index a14a1f0..77364b9 100644 --- a/Sources/TranscriptKit/Markdown/InlineParser.swift +++ b/Sources/TranscriptKit/Markdown/InlineParser.swift @@ -143,9 +143,11 @@ enum InlineParser { }() /// Parses a whole string. - static func parse(_ source: String, open: Bool, tags: [String: TranscriptTag] = [:]) -> Result { + static func parse(_ source: String, open: Bool, tags: [String: TranscriptTag] = [:], + newlinesAsLineBreaks: Bool = false) -> Result { var checkpoint = Checkpoint() - return parse(BlockParser.utf16(source), open: open, stableLength: 0, resumingFrom: &checkpoint, tags: tags) + return parse(BlockParser.utf16(source), open: open, stableLength: 0, resumingFrom: &checkpoint, tags: tags, + newlinesAsLineBreaks: newlinesAsLineBreaks) } /// Parses `units`, resuming from `checkpoint` and advancing it. @@ -157,8 +159,13 @@ enum InlineParser { /// source, or a fresh one. /// - tags: the app's custom tags, by name. The same in every call /// made with this checkpoint. + /// - newlinesAsLineBreaks: whether the block parser made each newline + /// between two lines a line break, not only a hard break. Then a + /// newline right after a `
` adds no second break, a newline in a + /// code span is a space, and a built-in tag can go over two lines. + /// The same in every call made with this checkpoint. static func parse(_ units: [UInt16], open: Bool, stableLength: Int, resumingFrom checkpoint: inout Checkpoint, - tags: [String: TranscriptTag] = [:]) -> Result { + tags: [String: TranscriptTag] = [:], newlinesAsLineBreaks: Bool = false) -> Result { let count = open ? visibleCount(of: units) : units.count if checkpoint.position > count { // Cannot happen if the caller keeps its promise; start over rather than misparse. @@ -170,12 +177,14 @@ enum InlineParser { let emails = units[checkpoint.position.. Bool { + tags: [String: TranscriptTag], newlinesAsLineBreaks: Bool) -> Bool { let i = state.position /// Whether a token whose decision looked at units up to `peek` /// (inclusive; `count` meaning it depended on where the text ends) may be taken. @@ -450,6 +459,10 @@ enum InlineParser { if close != nil || open { let contentEnd = close ?? count var content = units[contentStart..= 2, content.first == space, content.last == space, content.contains(where: { $0 != space }) { content = content.dropFirst().dropLast() @@ -678,7 +691,7 @@ enum InlineParser { // Custom tag names may have hyphens. while k < count, isASCIILetter(units[k]) || isASCIIDigit(units[k]) || units[k] == dash { k += 1 } let nameEnd = k - while k < count, units[k] == space { k += 1 } + while k < count, isBuiltInTagSpace(units[k], newlinesAsLineBreaks) { k += 1 } guard k < count, k - i < maximumTagLength else { if k >= count, count - i < maximumTagLength { outcome = .pending(show: false); peek = count } else { peek = k } break scan @@ -726,11 +739,15 @@ enum InlineParser { } guard htmlTags[name] != nil || name == "br" else { break scan } var k = j - while k < count, units[k] == space { k += 1 } + while k < count, isBuiltInTagSpace(units[k], newlinesAsLineBreaks) { k += 1 } if k < count, units[k] == slash { k += 1 } guard k < count else { outcome = .pending(show: false); peek = count; break scan } peek = k - if units[k] == greaterThan { outcome = .tag(name: name, closing: false, end: k + 1) } + if units[k] == greaterThan { + outcome = .tag(name: name, closing: false, end: k + 1) + // Whether a newline follows a "
" decides if it adds a second break. + if name == "br", newlinesAsLineBreaks { peek = k + 1 < count ? k + 1 : count } + } break scan } guard j - (i + 1) >= 2 else { break scan } @@ -770,7 +787,8 @@ enum InlineParser { let piece = state.appendSealedPiece(EmptyCollection()) state.tags.append(Tag(name: name, traits: traits, piece: piece)) } - state.position = end + let breakEndsLine = name == "br" && newlinesAsLineBreaks && end < count && units[end] == newline + state.position = breakEndsLine ? end + 1 : end case .customTag(let definition, let attributes, let end): let decoration = definition.decoration(for: attributes) let custom = InlineSpan.CustomTag(name: definition.name, attributes: attributes, decoration: decoration) @@ -959,6 +977,12 @@ enum InlineParser { unit == space || unit == tab || unit == newline } + /// A space in a built-in tag such as `
`. A newline counts only + /// with `newlinesAsLineBreaks`, which keeps the default output as before. + private static func isBuiltInTagSpace(_ unit: UInt16, _ newlinesAsLineBreaks: Bool) -> Bool { + unit == space || (newlinesAsLineBreaks && unit == newline) + } + private static func isAttributeNameStart(_ unit: UInt16) -> Bool { isASCIILetter(unit) || unit == underscore || unit == colon } diff --git a/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift b/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift index baca898..3eabdf1 100644 --- a/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift +++ b/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift @@ -40,8 +40,9 @@ public struct MarkdownStreamParser: Sendable { /// `TranscriptTag`. Other tags show as written. /// - newlinesAsLineBreaks: if true, a single newline inside a paragraph /// or a heading is a line break, as models often intend. A line that - /// ends in a backslash or two spaces still gives one line break, not - /// two. If false (the default), the newline is a space, as in CommonMark. + /// ends in a backslash, two spaces or `
` still gives one line + /// break, not two. A newline in a code span is still a space. If false + /// (the default), the newline is a space, as in CommonMark. public init(idPrefix: String = String(UUID().uuidString.prefix(8)), tags: [TranscriptTag] = [], newlinesAsLineBreaks: Bool = false) { self.idPrefix = idPrefix @@ -181,7 +182,8 @@ public struct MarkdownStreamParser: Sendable { paragraph.becomeParagraph() let text = paragraph.inlineSource() let result = InlineParser.parse(text.units, open: false, stableLength: text.units.count, - resumingFrom: ¶graph.checkpoint, tags: tags) + resumingFrom: ¶graph.checkpoint, tags: tags, + newlinesAsLineBreaks: raw.newlinesAsLineBreaks) return TranscriptBlock(id: id, kind: .paragraph, text: result.text, spans: result.spans, containers: raw.containers, marker: raw.marker) case .heading(let level): @@ -191,7 +193,7 @@ public struct MarkdownStreamParser: Sendable { } let source = raw.inlineSource() let result = InlineParser.parse(source.units, open: open, stableLength: source.stableLength, resumingFrom: &raw.checkpoint, - tags: tags) + tags: tags, newlinesAsLineBreaks: raw.newlinesAsLineBreaks) return TranscriptBlock(id: id, kind: kind, text: result.text, spans: result.spans, containers: raw.containers, marker: raw.marker) } diff --git a/Tests/TranscriptKitTests/IncrementalParserTests.swift b/Tests/TranscriptKitTests/IncrementalParserTests.swift index 4dcc94c..e21bb7b 100644 --- a/Tests/TranscriptKitTests/IncrementalParserTests.swift +++ b/Tests/TranscriptKitTests/IncrementalParserTests.swift @@ -38,6 +38,7 @@ Trailing paragraph with an unclosed `code span and *emphasis /// next to hard breaks and to lines that could start another block. /// Written with explicit "\n" so that the trailing spaces stay. let lineBreakMarkdown = "First line\nsecond line \nthird line\\\nfourth line \nfifth\t\n**bold** start\n" + + "a tag over lines, a break
\nafter it
\\\nand inside\n" + "`code\nspan` and [link\ntext](\nhttps://x.y) and *emphasis\nover lines*\r\nCRLF line\r\n\n" + "- item one\n continued\nlazy line\n- item two\n\n> quote one\n> quote two\nlazy quote\n\n" + "Setext title\nover two lines\n===\n\nA | B\nnot a table\n\n| a | b |\n| - | - |\n| 1 | 2 |\n\n" diff --git a/Tests/TranscriptKitTests/LineBreakTests.swift b/Tests/TranscriptKitTests/LineBreakTests.swift index 9c98dda..797b0b1 100644 --- a/Tests/TranscriptKitTests/LineBreakTests.swift +++ b/Tests/TranscriptKitTests/LineBreakTests.swift @@ -25,7 +25,22 @@ private func parse(_ markdown: String, newlines: Bool = true) -> [TranscriptBloc #expect(parse("one\\\ntwo", newlines: newlines).map(\.text) == ["one\ntwo"]) #expect(parse("one \\\ntwo", newlines: newlines).map(\.text) == ["one\ntwo"]) } - #expect(parse("one
\ntwo").map(\.text) == ["one\n\ntwo"]) + #expect(parse("one
\ntwo").map(\.text) == ["one\ntwo"]) + #expect(parse("one
\ntwo
\nthree").map(\.text) == ["one\ntwo\nthree"]) + #expect(parse("one
\\\ntwo").map(\.text) == ["one\ntwo"]) + #expect(parse("one

\ntwo").map(\.text) == ["one\n\ntwo"]) + #expect(parse("one\\
\ntwo").map(\.text) == ["one
\ntwo"]) + #expect(parse("one
\ntwo", newlines: false).map(\.text) == ["one\n two"]) +} + +@Test func builtInTagsCanSpanLinesWithTheOption() { + for newlines in [false, true] { + #expect(parse("a b", newlines: newlines).map(\.text) == ["a \nb"]) + let bold = parse("bold after", newlines: newlines)[0] + #expect(bold.text == "bold after") + #expect(bold.spans.map(\.range) == [0..<4]) + #expect(bold.spans.map(\.traits) == [.bold]) + } } @Test func newlinesInContainersAreLineBreaksWithTheOption() { @@ -64,14 +79,15 @@ private func parse(_ markdown: String, newlines: Bool = true) -> [TranscriptBloc #expect(parse("one\ntwo")[0].spans.map(\.range) == [0..<7]) } -/// A code span keeps the newline as a line break, as the rest of the -/// paragraph does. -@Test func codeSpanKeepsTheLineBreakWithTheOption() { - let block = parse("a `b\nc` d")[0] - #expect(block.text == "a b\nc d") +/// A newline in a code span is a space, as in CommonMark. +@Test func newlineInCodeSpanIsASpaceWithTheOption() { + let block = parse("a `b\nc` d\ne")[0] + #expect(block.text == "a b c d\ne") #expect(block.spans.map(\.range) == [2..<5]) #expect(block.spans.map(\.traits) == [.code]) + #expect(parse("`` a\n``")[0].text == "a") #expect(parse("a `b\nc` d", newlines: false)[0].text == "a b c d") + #expect(parse("a `b\\\nc` d", newlines: false)[0].text == "a b\nc d") } @Test func copiedTextHasTheLineBreaks() { @@ -95,11 +111,11 @@ private func parse(_ markdown: String, newlines: Bool = true) -> [TranscriptBloc #expect(plain.document.blocks.map(\.text) == ["one two"]) } - /// Each line of a paragraph only adds text at the end while it streams in: /// the line break before it does not appear first as a space. @Test func lineBreaksOnlyGrowTheTextWhileStreaming() { - let markdown = "One line\nanother line\nand **a third\nwith bold** that\nends\n\n- item\n more\n\n> quote\n> more" + let markdown = "One line\nanother line\nand **a third\nwith bold** that\nends\nwith `code\nspan` and
\nnext\n\n" + + "- item\n more\n\n> quote\n> more" var parser = MarkdownStreamParser(idPrefix: "g", newlinesAsLineBreaks: true) var previous = parser.document var violations: [String] = [] @@ -112,7 +128,8 @@ private func parse(_ markdown: String, newlines: Bool = true) -> [TranscriptBloc } #expect(violations.isEmpty, "\(violations.joined(separator: "\n"))") parser.finish() - #expect(parser.document.blocks.map(\.text) == ["One line\nanother line\nand a third\nwith bold that\nends", "item\nmore", "quote\nmore"]) + #expect(parser.document.blocks.map(\.text) == ["One line\nanother line\nand a third\nwith bold that\nends\nwith code span and\nnext", + "item\nmore", "quote\nmore"]) } /// A link destination after a line break is still read. From e97179eae0637339d2e7b40306ea2f9746618d4b Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:41:32 -0800 Subject: [PATCH 8/9] Describe the line break option the same way in each place The TranscriptStream doc now says "a paragraph or a heading", as the MarkdownStreamParser doc does. The README says that
at the end of a line gives one break, and that a newline in a code span is a space. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- Sources/TranscriptKit/Stream/TranscriptStream.swift | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4f60a92..6613024 100644 --- a/README.md +++ b/README.md @@ -102,8 +102,8 @@ let document = MarkdownStreamParser.document(from: markdown, newlinesAsLineBreak ``` The option applies to paragraphs and headings, also inside lists and quotes. A blank line still starts a new -paragraph. A line that ends in a backslash or two spaces also gives one line break, not two. Selected and copied -text has a newline at each such line break. +paragraph. A line that ends in a backslash, two spaces or `
` also gives one line break, not two. A newline in a +code span is still a space, as in CommonMark. Selected and copied text has a newline at each such line break. ### Custom tags diff --git a/Sources/TranscriptKit/Stream/TranscriptStream.swift b/Sources/TranscriptKit/Stream/TranscriptStream.swift index 348010f..905a9ff 100644 --- a/Sources/TranscriptKit/Stream/TranscriptStream.swift +++ b/Sources/TranscriptKit/Stream/TranscriptStream.swift @@ -55,7 +55,7 @@ public final class TranscriptStream { /// - tags: custom tags the text may use, and how they look; see /// `TranscriptTag`. Other tags show as written. /// - newlinesAsLineBreaks: if true, a single newline inside a paragraph - /// is a line break. If false (the default), it is a space, as in + /// or a heading is a line break. If false (the default), it is a space, as in /// CommonMark. See `MarkdownStreamParser.init`. public nonisolated init(markdown: String = "", tags: [TranscriptTag] = [], newlinesAsLineBreaks: Bool = false) { var parser = MarkdownStreamParser(tags: tags, newlinesAsLineBreaks: newlinesAsLineBreaks) From dfe1d73bee94560066726f971a5d94b3af4de85e Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:47:09 -0800 Subject: [PATCH 9/9] Skip a newline only after an opening br tag A closing
is a tag only when an app adds a custom tag named br. The parser does not look past it, so it must not drop the newline that follows it. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/Markdown/InlineParser.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/TranscriptKit/Markdown/InlineParser.swift b/Sources/TranscriptKit/Markdown/InlineParser.swift index 77364b9..3902cce 100644 --- a/Sources/TranscriptKit/Markdown/InlineParser.swift +++ b/Sources/TranscriptKit/Markdown/InlineParser.swift @@ -787,7 +787,7 @@ enum InlineParser { let piece = state.appendSealedPiece(EmptyCollection()) state.tags.append(Tag(name: name, traits: traits, piece: piece)) } - let breakEndsLine = name == "br" && newlinesAsLineBreaks && end < count && units[end] == newline + let breakEndsLine = name == "br" && !closing && newlinesAsLineBreaks && end < count && units[end] == newline state.position = breakEndsLine ? end + 1 : end case .customTag(let definition, let attributes, let end): let decoration = definition.decoration(for: attributes)