diff --git a/README.md b/README.md
index 5408c98..2a2666d 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, 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
```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/InlineParser.swift b/Sources/TranscriptKit/Markdown/InlineParser.swift
index 58d3f28..3902cce 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()
@@ -611,7 +624,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())
@@ -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" && !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)
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 39b6054..3eabdf1 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,16 @@ 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, 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
self.tags = TranscriptTag.byName(tags)
+ state = BlockParser.State(newlinesAsLineBreaks: newlinesAsLineBreaks)
}
/// Adds the next piece of the stream. Chunks can split anywhere.
@@ -68,8 +75,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
@@ -173,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):
@@ -183,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/Sources/TranscriptKit/Stream/TranscriptStream.swift b/Sources/TranscriptKit/Stream/TranscriptStream.swift
index 7d9d1bd..78ef97a 100644
--- a/Sources/TranscriptKit/Stream/TranscriptStream.swift
+++ b/Sources/TranscriptKit/Stream/TranscriptStream.swift
@@ -55,8 +55,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
+ /// 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)
if !markdown.isEmpty {
parser.append(markdown)
}
diff --git a/Tests/TranscriptKitTests/IncrementalParserTests.swift b/Tests/TranscriptKitTests/IncrementalParserTests.swift
index 6aeaeec..e21bb7b 100644
--- a/Tests/TranscriptKitTests/IncrementalParserTests.swift
+++ b/Tests/TranscriptKitTests/IncrementalParserTests.swift
@@ -34,6 +34,16 @@ 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"
+ + "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"
+ + "$$\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 +102,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 +119,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 +256,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[.. [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\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() {
+ 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 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() {
+ 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.. quote\n> more"
+ var parser = MarkdownStreamParser(idPrefix: "g", newlinesAsLineBreaks: true)
+ var previous = parser.document
+ var violations: [String] = []
+ for character in markdown {
+ parser.append(String(character))
+ if !parser.document.extends(previous) {
+ violations.append("\(previous.blocks.last?.text.debugDescription ?? "-") -> \(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\nwith code span and\nnext",
+ "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")
+}
+
+/// 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)
+}
diff --git a/Tests/TranscriptKitTests/MarkdownTests.swift b/Tests/TranscriptKitTests/MarkdownTests.swift
index 74fa31a..b7202c3 100644
--- a/Tests/TranscriptKitTests/MarkdownTests.swift
+++ b/Tests/TranscriptKitTests/MarkdownTests.swift
@@ -167,11 +167,12 @@ private func substring(_ result: InlineParser.Result, _ span: InlineSpan) -> 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))" } ?? "-")")
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))