Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<mention id="ana">@Ana</mention>` 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
Expand Down Expand Up @@ -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 `<br>` 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
Expand Down
31 changes: 24 additions & 7 deletions Sources/TranscriptKit/Markdown/BlockParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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)))
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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])
Expand All @@ -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
}

Expand Down
46 changes: 35 additions & 11 deletions Sources/TranscriptKit/Markdown/InlineParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 `<br>` 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.
Expand All @@ -170,12 +177,14 @@ enum InlineParser {
let emails = units[checkpoint.position..<count].contains(atSign)
// Decisions that are final go into the checkpoint...
while checkpoint.position < limit,
step(&checkpoint, units, count: count, open: open, limit: limit, emails: emails, tags: tags) {}
step(&checkpoint, units, count: count, open: open, limit: limit, emails: emails, tags: tags,
newlinesAsLineBreaks: newlinesAsLineBreaks) {}
checkpoint.settle()
// ...and the rest is parsed on a copy, every time.
var state = checkpoint
while state.position < count {
_ = step(&state, units, count: count, open: open, limit: nil, emails: emails, tags: tags)
_ = step(&state, units, count: count, open: open, limit: nil, emails: emails, tags: tags,
newlinesAsLineBreaks: newlinesAsLineBreaks)
}
if open { closeAtEnd(&state, count: count) }
// An HTML tag left open styles the rest of the block, as in a browser.
Expand Down Expand Up @@ -383,7 +392,7 @@ enum InlineParser {
/// would need to look at a unit at or past it is left unparsed and the
/// result is false.
private static func step(_ state: inout Checkpoint, _ units: [UInt16], count: Int, open: Bool, limit: Int?, emails: Bool,
tags: [String: TranscriptTag]) -> 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.
Expand Down Expand Up @@ -450,6 +459,10 @@ enum InlineParser {
if close != nil || open {
let contentEnd = close ?? count
var content = units[contentStart..<contentEnd]
if newlinesAsLineBreaks, content.contains(newline) {
// As in CommonMark, a line end in a code span is a space.
content = ArraySlice(content.map { $0 == newline ? space : $0 })
}
if close != nil, content.count >= 2, content.first == space, content.last == space,
content.contains(where: { $0 != space }) {
content = content.dropFirst().dropLast()
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 "<br>" 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 }
Expand Down Expand Up @@ -770,7 +787,8 @@ enum InlineParser {
let piece = state.appendSealedPiece(EmptyCollection<UInt16>())
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)
Expand Down Expand Up @@ -959,6 +977,12 @@ enum InlineParser {
unit == space || unit == tab || unit == newline
}

/// A space in a built-in tag such as `<br />`. 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
}
Expand Down
22 changes: 16 additions & 6 deletions Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 `<br>` 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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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: &paragraph.checkpoint, tags: tags)
resumingFrom: &paragraph.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):
Expand All @@ -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)
}
Expand Down
7 changes: 5 additions & 2 deletions Sources/TranscriptKit/Stream/TranscriptStream.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
Loading
Loading