// Copied from Equipo's EquipoKit (oficina/equipo 00d09aa7, // native/apple/Sources/EquipoKit/Markdown/ChatMarkdown.swift). Base's changes are // marked "Base:"; keep the rest in step with Equipo's. import Foundation import cmark_gfm /// The rendered subset, shared by fixtures and both native transcripts. struct ChatMarkdownNode: Codable, Equatable, Sendable { // Source anchors survive appended chunks and a fence's closing line. var sourceOffset = 0 enum CodingKeys: String, CodingKey { case kind, text, target, label, copy, copied, wrap, copyEnabled, start, children } static func == (lhs: Self, rhs: Self) -> Bool { lhs.kind == rhs.kind && lhs.text == rhs.text && lhs.target == rhs.target && lhs.label == rhs.label && lhs.copy == rhs.copy && lhs.copied == rhs.copied && lhs.wrap == rhs.wrap && lhs.copyEnabled == rhs.copyEnabled && lhs.start == rhs.start && lhs.children == rhs.children } var kind: String var text: String? var target: String? var label: String? var copy: String? var copied: String? var wrap: Bool? var copyEnabled: Bool? /// Base: an ordered list's first number, when it isn't 1. var start: Int? var children: [ChatMarkdownNode] = [] } enum ChatMarkdown { static func parse(_ source: String, draft: Bool) -> [ChatMarkdownNode] { let source = draft ? MarkdownDraft.steady(source) : source let prepared = MarkdownInput.prepare(source) return prepared.source.withCString { _ in guard let parser = cmark_parser_new(CMARK_OPT_SOURCEPOS) else { return [] } defer { cmark_parser_free(parser) } // Observe each parser transition before EOF finalizes open fences. // An explicit closing fence returns current to the code's parent; // ending a surrounding list/quote does not count as closing it. var closedFences = Set>() var input = Array(prepared.source.utf8) var longFences: [UnsafeMutablePointer: Int] = [:] var lineStart = 0 for end in 0...input.count where end == input.count || input[end] == 10 { if Task.isCancelled { return [] } if end == input.count && lineStart == end { break } let old = parser.pointee.current let parent = old?.pointee.parent let wasFence = old.map { $0.pointee.type == CMARK_NODE_CODE_BLOCK.rawValue && $0.pointee.as.code.fenced != 0 } ?? false let length = end < input.count ? end - lineStart + 1 : end - lineStart if wasFence, let old, let required = longFences[old], required > 255 { let marker = old.pointee.as.code.fence_char var cursor = lineStart while cursor < end { guard input[cursor] == marker else { cursor += 1; continue } let begin = cursor while cursor < end, input[cursor] == marker { cursor += 1 } // cmark stores fence lengths in one byte. Keep a shorter // run as content instead of letting that truncation close // the block; the retained input restores its literal. if cursor - begin >= 255, cursor - begin < required { input[begin] = 1 } } } input.withUnsafeBytes { raw in cmark_parser_feed(parser, raw.baseAddress!.assumingMemoryBound(to: CChar.self).advanced(by: lineStart), length) } if end == input.count, input.last != 13 { cmark_parser_feed(parser, "\n", 1) } if wasFence, let old, parser.pointee.current == parent, old.pointee.flags & UInt16(CMARK_NODE__OPEN.rawValue) == 0 { closedFences.insert(old) } if let current = parser.pointee.current, current.pointee.type == CMARK_NODE_CODE_BLOCK.rawValue, current.pointee.as.code.fenced != 0, longFences[current] == nil { let marker = current.pointee.as.code.fence_char let line = Array(prepared.originalLines[max(0, Int(current.pointee.start_line) - 1)].utf8) if let first = line.firstIndex(of: marker) { longFences[current] = line[first...].prefix { $0 == marker }.count } } lineStart = end + 1 } let consumed = MarkdownInput.Prepared(source: String(decoding: input, as: UTF8.self), original: source) var openFences = Set>() var blockSources: [UnsafeMutablePointer: [UInt8]] = [:] if let root = parser.pointee.root, let iterator = cmark_iter_new(root) { while cmark_iter_next(iterator) != CMARK_EVENT_DONE { guard let node = cmark_iter_get_node(iterator) else { continue } if blockSources[node] == nil, node.pointee.type == CMARK_NODE_PARAGRAPH.rawValue || node.pointee.type == CMARK_NODE_HEADING.rawValue { let held = Array(UnsafeBufferPointer(start: node.pointee.content.ptr, count: Int(node.pointee.content.size))) let raw = consumed.block(held, startLine: Int(node.pointee.start_line)) blockSources[node] = raw let input = MarkdownInput.forCMark(raw) input.withUnsafeBufferPointer { cmark_strbuf_set(&node.pointee.content, $0.baseAddress, Int32($0.count)) } } if node.pointee.type == CMARK_NODE_CODE_BLOCK.rawValue, !closedFences.contains(node) { openFences.insert(node) } } cmark_iter_free(iterator) } guard let root = cmark_parser_finish(parser) else { return [] } defer { cmark_node_free(root) } var projection = MarkdownProjection(source: source, draft: draft, root: root, openFences: openFences, blockSources: blockSources, prepared: consumed) return projection.tree(root) } } @concurrent static func parseInBackground(_ source: String, draft: Bool) async -> [ChatMarkdownNode] { assert(!Thread.isMainThread) guard !Task.isCancelled else { return [] } return parse(source, draft: draft) } static func allowsLink(_ destination: String) -> Bool { // Base: only absolute http(s) links, as ask.js's webURL and // equipo.WebURL (Equipo's MarkdownLinks also allows its own paths // and mailto). BaseJSON.webURL(destination) != nil } } private struct MarkdownProjection { let source: String let draft: Bool let bytes: [UInt8] let lines: [String] let starts: [Int] let openFrom: Int? let linkHidden: [Range] let openFences: Set> let references: [String: String] let blockSources: [UnsafeMutablePointer: [UInt8]] let prepared: MarkdownInput.Prepared var projected: [UnsafeMutablePointer: [ChatMarkdownNode]] = [:] struct InlineSource { let bytes: [UInt8] let starts: [Int] let originalStarts: [Int] } var inlineSources: [UnsafeMutablePointer: InlineSource] = [:] var inlineOwners: [UnsafeMutablePointer: UnsafeMutablePointer] = [:] static let referencePattern = try! NSRegularExpression(pattern: #"(?m)^ {0,3}\[([^\]]+)\]:[ \t]*(<[^>]*>|\S+)"#) static func normalized(_ value: String) -> String { value.split(whereSeparator: { $0.isWhitespace }).joined(separator: " ").lowercased() } init(source: String, draft: Bool, root: UnsafeMutablePointer, openFences: Set>, blockSources: [UnsafeMutablePointer: [UInt8]], prepared: MarkdownInput.Prepared) { self.prepared = prepared self.blockSources = blockSources self.openFences = openFences var refs: [String: String] = [:] for match in Self.referencePattern.matches(in: source, range: NSRange(source.startIndex..., in: source)) { guard let key = Range(match.range(at: 1), in: source), let value = Range(match.range(at: 2), in: source) else { continue } let label = Self.normalized(String(source[key])) if refs[label] == nil { refs[label] = String(source[value]) } } references = refs self.source = source; self.draft = draft let bytes = Array(source.utf8) self.bytes = bytes lines = source.components(separatedBy: "\n") var offsets = [0] for (index, byte) in bytes.enumerated() where byte == 10 { offsets.append(index + 1) } starts = offsets func offset(_ line: Int32, _ column: Int32) -> Int { guard line > 0, Int(line) <= offsets.count else { return bytes.count } return min(bytes.count, offsets[Int(line) - 1] + max(0, Int(column) - 1)) } var last = root while let child = cmark_node_last_child(last), ["document", "block_quote", "list", "item", "paragraph", "heading", "code_block", "html_block", "thematic_break"].contains(Self.kind(child)) { last = child } let end = offset(cmark_node_get_end_line(last), cmark_node_get_end_column(last) + 1) let breaks = bytes[end...].filter { $0 == 10 }.count if draft, ["paragraph", "heading"].contains(Self.kind(last)), breaks <= 1, !(Self.kind(last) == "heading" && breaks > 0) { openFrom = offset(cmark_node_get_start_line(last), cmark_node_get_start_column(last)) } else { openFrom = nil } if let from = openFrom { let line = max(from, offsets.last ?? 0) let tail = String(decoding: bytes[line...], as: UTF8.self) let regex = try! NSRegularExpression(pattern: #"(!?\[)[^\[\]\n`]*(\](?:\([^()\x09\x0a\x0c\x0d\x20]*)?)?\z"#) if let match = regex.firstMatch(in: tail, range: NSRange(tail.startIndex..., in: tail)), let first = Range(match.range(at: 1), in: tail) { let start = line + tail[..) -> String { String(cString: cmark_node_get_type_string(node)) } func literal(_ node: UnsafeMutablePointer) -> String { let value = cmark_node_get_literal(node).map(String.init(cString:)) ?? "" if ["code_block", "html_block"].contains(Self.kind(node)) { let skip = Self.kind(node) == "code_block" && node.pointee.as.code.fenced != 0 ? 1 : 0 return String(decoding: prepared.block(Array(value.utf8), startLine: Int(node.pointee.start_line) + skip), as: UTF8.self).replacingOccurrences(of: "\r", with: "\n") } return value } func offset(_ line: Int32, _ column: Int32) -> Int { guard line > 0, Int(line) <= starts.count else { return bytes.count } return min(bytes.count, starts[Int(line) - 1] + max(0, Int(column) - 1)) } // Inline columns are relative to the block's normalized content, not the // original continuation line. Map through that content before reading. func inlineRange(_ node: UnsafeMutablePointer) -> (UnsafeMutablePointer, [UInt8], Range)? { guard let parent = inlineOwners[node], let context = inlineSources[parent] else { return nil } let raw = context.bytes, offsets = context.starts let base = Int(parent.pointee.start_column - 1 + parent.pointee.internal_offset) func position(_ line: Int32, _ column: Int32, end: Bool) -> Int { let index = Int(line - parent.pointee.start_line) guard offsets.indices.contains(index) else { return raw.count } // Multiline code/HTML end columns omit the block offset in cmark. let adjustment = end && node.pointee.end_line != node.pointee.start_line && ["code", "html_inline"].contains(Self.kind(node)) ? 0 : base return min(raw.count, max(0, offsets[index] + Int(column) - 1 - adjustment)) } let lo = position(node.pointee.start_line, node.pointee.start_column, end: false) let hi = position(node.pointee.end_line, node.pointee.end_column + 1, end: true) return (parent, raw, lo..) -> String { guard let (_, content, span) = inlineRange(node) else { return literal(node) } return String(decoding: content[span], as: UTF8.self) } func range(_ node: UnsafeMutablePointer) -> Range { if let (block, _, span) = inlineRange(node) { func original(_ at: Int) -> Int { guard let context = inlineSources[block] else { return bytes.count } var lo = 0, hi = context.starts.count while lo + 1 < hi { let mid = (lo + hi) / 2 if context.starts[mid] <= at { lo = mid } else { hi = mid } } return min(bytes.count, context.originalStarts[lo] + at - context.starts[lo]) } let lo = original(span.lowerBound) return lo..) { guard let iterator = cmark_iter_new(root) else { return } defer { cmark_iter_free(iterator) } while true { let event = cmark_iter_next(iterator) if event == CMARK_EVENT_DONE { break } guard event == CMARK_EVENT_ENTER, let node = cmark_iter_get_node(iterator) else { continue } if ["paragraph", "heading"].contains(Self.kind(node)) { let content = node.pointee.content let held = blockSources[node] ?? Array(UnsafeBufferPointer(start: content.ptr, count: Int(content.size))) let raw = Array(held.suffix(Int(content.size))) var offsets = [0] for (i, b) in raw.enumerated() where b == 10 { offsets.append(i + 1) } var originals: [Int] = [] for (line, start) in offsets.enumerated() { let end = line + 1 < offsets.count ? offsets[line + 1] - 1 : raw.count let index = Int(node.pointee.start_line) - 1 + line guard lines.indices.contains(index) else { originals.append(bytes.count); continue } let normalized = String(decoding: raw[start..) -> [ChatMarkdownNode] { prepareInlineSources(root) // Postorder on an explicit heap stack. Quotes can be thousands deep. var stack: [(UnsafeMutablePointer, Bool)] = [(root, false)] while let (node, visited) = stack.popLast() { if Task.isCancelled { return [] } if !visited { stack.append((node, true)) var child = cmark_node_last_child(node) while let current = child { stack.append((current, false)); child = cmark_node_previous(current) } } else { var nodes = project(node) if nodes.count == 1, !["document", "block_quote", "image"].contains(Self.kind(node)) { nodes[0].sourceOffset = range(node).lowerBound } projected[node] = nodes var child = cmark_node_first_child(node) while let current = child { projected.removeValue(forKey: current); child = cmark_node_next(current) } } } return projected[root] ?? [] } func children(_ node: UnsafeMutablePointer) -> [ChatMarkdownNode] { var out: [ChatMarkdownNode] = [] var child = cmark_node_first_child(node) while let current = child { for next in projected[current] ?? [] { if next.kind == "text", next.text == nil || next.text == "" || next.text == "\n" && ["document", "list", "item"].contains(Self.kind(node)) { continue } if next.kind == "text", out.last?.kind == "text" { out[out.count - 1].text! += next.text ?? "" } else { out.append(next) } } child = cmark_node_next(current) } return out.map { value in var value = value if value.kind == "text" { value.text = value.text?.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") } return value } } func leaf(_ kind: String, _ text: String = "") -> ChatMarkdownNode { ChatMarkdownNode(kind: kind, text: text.isEmpty ? nil : text) } func project(_ node: UnsafeMutablePointer) -> [ChatMarkdownNode] { switch Self.kind(node) { case "text": var value = draftText(node) if let next = cmark_node_next(node), ["linebreak", "softbreak"].contains(Self.kind(next)) { while value.last == " " || value.last == "\t" { value.removeLast() } } return [leaf("text", value)] case "softbreak": return [leaf("text", "\n")] case "linebreak": return [leaf("break")] case "code": var raw = inlineRaw(node) // cmark caps code-span delimiter runs at 80. The inline adapter // pads longer paired delimiters without changing source columns. if node.pointee.backtick_count == 80 { while raw.first == "`" { raw.removeFirst() } while raw.last == "`" { raw.removeLast() } } // Goldmark keeps internal line breaks; cmark replaces them with spaces. var code = raw if code.contains(where: { $0 != " " && $0 != "\n" }), let first = code.first, let last = code.last, (first == " " || first == "\n"), (last == " " || last == "\n") { code = String(code.dropFirst().dropLast()) } return [leaf("code", code.replacingOccurrences(of: "\r", with: "\n"))] case "html_inline": return [leaf("text", inlineRaw(node))] case "html_block": var value = literal(node) if Int(node.pointee.end_line) == lines.count, bytes.last != 10, bytes.last != 13, value.hasSuffix("\n") { value.removeLast() } return [leaf("text", value)] case "thematic_break": return [] // Render has no rule output. case "code_block": var length: Int32 = 0, indent: Int32 = 0 var character: CChar = 0 guard cmark_node_get_fenced(node, &length, &indent, &character) != 0 else { return [leaf("codeBlock", literal(node))] } let opening = Array(lines[max(0, Int(node.pointee.start_line) - 1)].utf8) var info: [UInt8] = [] var infoLength = 0 if let first = opening.firstIndex(of: UInt8(bitPattern: character)) { var at = first while at < opening.count, opening[at] == UInt8(bitPattern: character) { at += 1 } infoLength = opening.count - at while at < opening.count, [9, 10, 11, 12, 13, 32].contains(opening[at]) { at += 1 } var end = opening.count while end > at, [9, 10, 11, 12, 13, 32].contains(opening[end - 1]) { end -= 1 } info = Array(opening[at..= lines.count, value.hasSuffix("\n") { value.removeLast() } var box = leaf("paste", value) switch lower { case "prompt": box.label = BaseText.text("chat.paste.prompt") case "text": box.label = BaseText.text("chat.paste.text") case "bash", "sh", "zsh", "shell", "console": box.label = BaseText.text("chat.paste.command") default: box.label = lang.isEmpty ? nil : lang } box.wrap = ["prompt", "text"].contains(lower) ? true : nil box.copy = BaseText.text("chat.paste.copy") box.copied = BaseText.text("chat.paste.copied") box.copyEnabled = !draft || !openFences.contains(node) return [box] case "paragraph": if let item = cmark_node_parent(node), Self.kind(item) == "item", let list = cmark_node_parent(item), cmark_node_get_list_tight(list) != 0 { return children(node) } return [ChatMarkdownNode(kind: "paragraph", children: children(node))] case "heading": return [ChatMarkdownNode(kind: "paragraph", children: children(node))] case "emph": return [ChatMarkdownNode(kind: "emphasis", children: children(node))] case "strong": return [ChatMarkdownNode(kind: "strong", children: children(node))] case "list": // Base: an ordered list keeps its first number. let ordered = cmark_node_get_list_type(node) == CMARK_ORDERED_LIST let start = Int(cmark_node_get_list_start(node)) return [ChatMarkdownNode(kind: ordered ? "ordered" : "unordered", start: ordered && start != 1 ? start : nil, children: children(node))] case "item": return [ChatMarkdownNode(kind: "item", children: children(node))] case "link": // Goldmark's AutoLink is outside Render's vocabulary. if range(node).lowerBound < bytes.count, bytes[range(node).lowerBound] == 60 { return [] } let target = linkTarget(node) guard ChatMarkdown.allowsLink(target) else { return children(node) } return [ChatMarkdownNode(kind: "link", target: target, children: children(node))] default: return children(node) // Quotes/images keep only their children. } } /// Render resolves HTML entities in destinations but keeps punctuation /// escapes. cmark's destination has already removed those backslashes. func linkTarget(_ node: UnsafeMutablePointer) -> String { let raw = inlineRaw(node) func destination(_ tail: Substring) -> String { let trimmed = tail.drop(while: { " \t\n\r\u{000B}\u{000C}".contains($0) }) if trimmed.first == "<", let end = trimmed.dropFirst().firstIndex(of: ">") { return String(trimmed[trimmed.index(after: trimmed.startIndex)..) -> String { var raw = inlineRaw(node) let actual = literal(node) // cmark leaves the original source span on partially consumed // delimiter leaves. Their surviving delimiter count is in the literal. for marker: Character in ["*", "_"] { if raw.first == marker, actual.first == marker { let old = raw.prefix(while: { $0 == marker }).count let kept = actual.prefix(while: { $0 == marker }).count if old > kept { raw.removeFirst(old - kept) } } if raw.last == marker, actual.last == marker { let old = raw.reversed().prefix(while: { $0 == marker }).count let kept = actual.reversed().prefix(while: { $0 == marker }).count if old > kept { raw.removeLast(old - kept) } } } return MarkdownDraft.decodeText(raw) } func draftText(_ node: UnsafeMutablePointer) -> String { guard let from = openFrom else { return textValue(node) } let segment = range(node) guard segment.lowerBound >= from, !segment.isEmpty else { return textValue(node) } let partiallyConsumed = literal(node).allSatisfy { $0 == "*" || $0 == "_" } && literal(node).utf8.count < inlineRaw(node).utf8.count var hidden = linkHidden var firstBacktick: Int? var at = segment.lowerBound while at < segment.upperBound { let char = bytes[at] // The watched fallback text is extended up to the next inline // parser trigger, even if that parser ultimately finds no node. var startsLinkLabel = false if let firstBacktick, [33, 42, 60, 91, 93, 95, 96].contains(char) { var escapes = 0, previous = at while previous > 0, bytes[previous - 1] == 92 { escapes += 1; previous -= 1 } if escapes % 2 == 0 { hidden.append(firstBacktick.. 0, bytes[before - 1] == 92 { slashes += 1; before -= 1 } if slashes % 2 == 1 { at = start + 1; continue } if char == 96 { // Goldmark coalesces watched fallback text through the next // unmatched code opener; its draft hides that entire span. firstBacktick = firstBacktick ?? start hidden.append(firstBacktick!.. Bool { c.map { CharacterSet.whitespacesAndNewlines.contains($0) } ?? true } func punct(_ c: Unicode.Scalar?) -> Bool { c.map { CharacterSet.punctuationCharacters.union(.symbols).contains($0) } ?? false } let lf = !space(right) && (!punct(right) || space(left) || punct(left)) let rf = !space(left) && (!punct(left) || space(right) || punct(right)) let canOpen = char == 42 ? lf : lf && (!rf || punct(left)) let canClose = char == 42 ? rf : rf && (!lf || punct(right)) // Goldmark creates a delimiter even when it cannot open or // close. Removing that first unmatched delimiter merges it into // the watched backtick text; later text is a separate segment. if let firstBacktick { hidden.append(firstBacktick..= 2) || at == bytes.count && !partiallyConsumed { hidden.append(start.. cursor { kept.append(contentsOf: bytes[cursor..