oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import cmark_gfm
3
4/// The rendered subset, shared by fixtures and both native transcripts.
5struct ChatMarkdownNode: Codable, Equatable, Sendable {
6 // Source anchors survive appended chunks and a fence's closing line.
7 var sourceOffset = 0
8 enum CodingKeys: String, CodingKey { case kind, text, target, label, copy, copied, wrap, copyEnabled, children }
9 static func == (lhs: Self, rhs: Self) -> Bool {
10 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.children == rhs.children
11 }
12 var kind: String
13 var text: String?
14 var target: String?
15 var label: String?
16 var copy: String?
17 var copied: String?
18 var wrap: Bool?
19 var copyEnabled: Bool?
20 var children: [ChatMarkdownNode] = []
21}
22
23enum ChatMarkdown {
24 static func parse(_ source: String, draft: Bool) -> [ChatMarkdownNode] {
25 let source = draft ? MarkdownDraft.steady(source) : source
26 let prepared = MarkdownInput.prepare(source)
27 return prepared.source.withCString { _ in
28 guard let parser = cmark_parser_new(CMARK_OPT_SOURCEPOS) else { return [] }
29 defer { cmark_parser_free(parser) }
30 // Observe each parser transition before EOF finalizes open fences.
31 // An explicit closing fence returns current to the code's parent;
32 // ending a surrounding list/quote does not count as closing it.
33 var closedFences = Set<UnsafeMutablePointer<cmark_node>>()
34 var input = Array(prepared.source.utf8)
35 var longFences: [UnsafeMutablePointer<cmark_node>: Int] = [:]
36 var lineStart = 0
37 for end in 0...input.count where end == input.count || input[end] == 10 {
38 if Task.isCancelled { return [] }
39 if end == input.count && lineStart == end { break }
40 let old = parser.pointee.current
41 let parent = old?.pointee.parent
42 let wasFence = old.map { $0.pointee.type == CMARK_NODE_CODE_BLOCK.rawValue && $0.pointee.as.code.fenced != 0 } ?? false
43 let length = end < input.count ? end - lineStart + 1 : end - lineStart
44 if wasFence, let old, let required = longFences[old], required > 255 {
45 let marker = old.pointee.as.code.fence_char
46 var cursor = lineStart
47 while cursor < end {
48 guard input[cursor] == marker else { cursor += 1; continue }
49 let begin = cursor
50 while cursor < end, input[cursor] == marker { cursor += 1 }
51 // cmark stores fence lengths in one byte. Keep a shorter
52 // run as content instead of letting that truncation close
53 // the block; the retained input restores its literal.
54 if cursor - begin >= 255, cursor - begin < required { input[begin] = 1 }
55 }
56 }
57 input.withUnsafeBytes { raw in
58 cmark_parser_feed(parser, raw.baseAddress!.assumingMemoryBound(to: CChar.self).advanced(by: lineStart), length)
59 }
60 if end == input.count, input.last != 13 { cmark_parser_feed(parser, "\n", 1) }
61 if wasFence, let old, parser.pointee.current == parent, old.pointee.flags & UInt16(CMARK_NODE__OPEN.rawValue) == 0 { closedFences.insert(old) }
62 if let current = parser.pointee.current, current.pointee.type == CMARK_NODE_CODE_BLOCK.rawValue, current.pointee.as.code.fenced != 0, longFences[current] == nil {
63 let marker = current.pointee.as.code.fence_char
64 let line = Array(prepared.originalLines[max(0, Int(current.pointee.start_line) - 1)].utf8)
65 if let first = line.firstIndex(of: marker) { longFences[current] = line[first...].prefix { $0 == marker }.count }
66 }
67 lineStart = end + 1
68 }
69 let consumed = MarkdownInput.Prepared(source: String(decoding: input, as: UTF8.self), original: source)
70 var openFences = Set<UnsafeMutablePointer<cmark_node>>()
71 var blockSources: [UnsafeMutablePointer<cmark_node>: [UInt8]] = [:]
72 if let root = parser.pointee.root, let iterator = cmark_iter_new(root) {
73 while cmark_iter_next(iterator) != CMARK_EVENT_DONE {
74 guard let node = cmark_iter_get_node(iterator) else { continue }
75 if blockSources[node] == nil, node.pointee.type == CMARK_NODE_PARAGRAPH.rawValue || node.pointee.type == CMARK_NODE_HEADING.rawValue {
76 let held = Array(UnsafeBufferPointer(start: node.pointee.content.ptr, count: Int(node.pointee.content.size)))
77 let raw = consumed.block(held, startLine: Int(node.pointee.start_line))
78 blockSources[node] = raw
79 let input = MarkdownInput.forCMark(raw)
80 input.withUnsafeBufferPointer { cmark_strbuf_set(&node.pointee.content, $0.baseAddress, Int32($0.count)) }
81 }
82 if node.pointee.type == CMARK_NODE_CODE_BLOCK.rawValue,
83 !closedFences.contains(node) { openFences.insert(node) }
84 }
85 cmark_iter_free(iterator)
86 }
87 guard let root = cmark_parser_finish(parser) else { return [] }
88 defer { cmark_node_free(root) }
89 var projection = MarkdownProjection(source: source, draft: draft, root: root, openFences: openFences, blockSources: blockSources, prepared: consumed)
90 return projection.tree(root)
91 }
92 }
93
94 @concurrent static func parseInBackground(_ source: String, draft: Bool) async -> [ChatMarkdownNode] {
95 assert(!Thread.isMainThread)
96 guard !Task.isCancelled else { return [] }
97 return parse(source, draft: draft)
98 }
99
100 static func allowsLink(_ destination: String) -> Bool {
101 MarkdownLinks.allows(destination)
102 }
103}
104
105private struct MarkdownProjection {
106 let source: String
107 let draft: Bool
108 let bytes: [UInt8]
109 let lines: [String]
110 let starts: [Int]
111 let openFrom: Int?
112 let linkHidden: [Range<Int>]
113 let openFences: Set<UnsafeMutablePointer<cmark_node>>
114 let references: [String: String]
115 let blockSources: [UnsafeMutablePointer<cmark_node>: [UInt8]]
116 let prepared: MarkdownInput.Prepared
117 var projected: [UnsafeMutablePointer<cmark_node>: [ChatMarkdownNode]] = [:]
118 struct InlineSource {
119 let bytes: [UInt8]
120 let starts: [Int]
121 let originalStarts: [Int]
122 }
123 var inlineSources: [UnsafeMutablePointer<cmark_node>: InlineSource] = [:]
124 var inlineOwners: [UnsafeMutablePointer<cmark_node>: UnsafeMutablePointer<cmark_node>] = [:]
125 static let referencePattern = try! NSRegularExpression(pattern: #"(?m)^ {0,3}\[([^\]]+)\]:[ \t]*(<[^>]*>|\S+)"#)
126 static func normalized(_ value: String) -> String { value.split(whereSeparator: { $0.isWhitespace }).joined(separator: " ").lowercased() }
127
128
129 init(source: String, draft: Bool, root: UnsafeMutablePointer<cmark_node>, openFences: Set<UnsafeMutablePointer<cmark_node>>, blockSources: [UnsafeMutablePointer<cmark_node>: [UInt8]], prepared: MarkdownInput.Prepared) {
130 self.prepared = prepared
131 self.blockSources = blockSources
132 self.openFences = openFences
133 var refs: [String: String] = [:]
134 for match in Self.referencePattern.matches(in: source, range: NSRange(source.startIndex..., in: source)) {
135 guard let key = Range(match.range(at: 1), in: source), let value = Range(match.range(at: 2), in: source) else { continue }
136 let label = Self.normalized(String(source[key]))
137 if refs[label] == nil { refs[label] = String(source[value]) }
138 }
139 references = refs
140 self.source = source; self.draft = draft
141 let bytes = Array(source.utf8)
142 self.bytes = bytes
143 lines = source.components(separatedBy: "\n")
144 var offsets = [0]
145 for (index, byte) in bytes.enumerated() where byte == 10 { offsets.append(index + 1) }
146 starts = offsets
147 func offset(_ line: Int32, _ column: Int32) -> Int {
148 guard line > 0, Int(line) <= offsets.count else { return bytes.count }
149 return min(bytes.count, offsets[Int(line) - 1] + max(0, Int(column) - 1))
150 }
151 var last = root
152 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 }
153 let end = offset(cmark_node_get_end_line(last), cmark_node_get_end_column(last) + 1)
154 let breaks = bytes[end...].filter { $0 == 10 }.count
155 if draft, ["paragraph", "heading"].contains(Self.kind(last)), breaks <= 1,
156 !(Self.kind(last) == "heading" && breaks > 0) {
157 openFrom = offset(cmark_node_get_start_line(last), cmark_node_get_start_column(last))
158 } else { openFrom = nil }
159 if let from = openFrom {
160 let line = max(from, offsets.last ?? 0)
161 let tail = String(decoding: bytes[line...], as: UTF8.self)
162 let regex = try! NSRegularExpression(pattern: #"(!?\[)[^\[\]\n`]*(\](?:\([^()\x09\x0a\x0c\x0d\x20]*)?)?\z"#)
163 if let match = regex.firstMatch(in: tail, range: NSRange(tail.startIndex..., in: tail)),
164 let first = Range(match.range(at: 1), in: tail) {
165 let start = line + tail[..<first.lowerBound].utf8.count
166 if start == 0 || bytes[start - 1] != 92 {
167 linkHidden = (1...2).compactMap { group in
168 guard let range = Range(match.range(at: group), in: tail) else { return nil }
169 let start = line + tail[..<range.lowerBound].utf8.count
170 return start..<(start + tail[range].utf8.count)
171 }
172 } else { linkHidden = [] }
173 } else { linkHidden = [] }
174 } else { linkHidden = [] }
175 }
176
177 static func kind(_ node: UnsafeMutablePointer<cmark_node>) -> String { String(cString: cmark_node_get_type_string(node)) }
178 func literal(_ node: UnsafeMutablePointer<cmark_node>) -> String {
179 let value = cmark_node_get_literal(node).map(String.init(cString:)) ?? ""
180 if ["code_block", "html_block"].contains(Self.kind(node)) {
181 let skip = Self.kind(node) == "code_block" && node.pointee.as.code.fenced != 0 ? 1 : 0
182 return String(decoding: prepared.block(Array(value.utf8), startLine: Int(node.pointee.start_line) + skip), as: UTF8.self).replacingOccurrences(of: "\r", with: "\n")
183 }
184 return value
185 }
186 func offset(_ line: Int32, _ column: Int32) -> Int {
187 guard line > 0, Int(line) <= starts.count else { return bytes.count }
188 return min(bytes.count, starts[Int(line) - 1] + max(0, Int(column) - 1))
189 }
190 // Inline columns are relative to the block's normalized content, not the
191 // original continuation line. Map through that content before reading.
192 func inlineRange(_ node: UnsafeMutablePointer<cmark_node>) -> (UnsafeMutablePointer<cmark_node>, [UInt8], Range<Int>)? {
193 guard let parent = inlineOwners[node], let context = inlineSources[parent] else { return nil }
194 let raw = context.bytes, offsets = context.starts
195 let base = Int(parent.pointee.start_column - 1 + parent.pointee.internal_offset)
196 func position(_ line: Int32, _ column: Int32, end: Bool) -> Int {
197 let index = Int(line - parent.pointee.start_line)
198 guard offsets.indices.contains(index) else { return raw.count }
199 // Multiline code/HTML end columns omit the block offset in cmark.
200 let adjustment = end && node.pointee.end_line != node.pointee.start_line && ["code", "html_inline"].contains(Self.kind(node)) ? 0 : base
201 return min(raw.count, max(0, offsets[index] + Int(column) - 1 - adjustment))
202 }
203 let lo = position(node.pointee.start_line, node.pointee.start_column, end: false)
204 let hi = position(node.pointee.end_line, node.pointee.end_column + 1, end: true)
205 return (parent, raw, lo..<max(lo, hi))
206 }
207 func inlineRaw(_ node: UnsafeMutablePointer<cmark_node>) -> String {
208 guard let (_, content, span) = inlineRange(node) else { return literal(node) }
209 return String(decoding: content[span], as: UTF8.self)
210 }
211 func range(_ node: UnsafeMutablePointer<cmark_node>) -> Range<Int> {
212 if let (block, _, span) = inlineRange(node) {
213 func original(_ at: Int) -> Int {
214 guard let context = inlineSources[block] else { return bytes.count }
215 var lo = 0, hi = context.starts.count
216 while lo + 1 < hi {
217 let mid = (lo + hi) / 2
218 if context.starts[mid] <= at { lo = mid } else { hi = mid }
219 }
220 return min(bytes.count, context.originalStarts[lo] + at - context.starts[lo])
221 }
222 let lo = original(span.lowerBound)
223 return lo..<max(lo, original(span.upperBound))
224 }
225 let start = offset(cmark_node_get_start_line(node), cmark_node_get_start_column(node))
226 return start..<max(start, offset(cmark_node_get_end_line(node), cmark_node_get_end_column(node) + 1))
227 }
228 mutating func prepareInlineSources(_ root: UnsafeMutablePointer<cmark_node>) {
229 guard let iterator = cmark_iter_new(root) else { return }
230 defer { cmark_iter_free(iterator) }
231 while true {
232 let event = cmark_iter_next(iterator)
233 if event == CMARK_EVENT_DONE { break }
234 guard event == CMARK_EVENT_ENTER, let node = cmark_iter_get_node(iterator) else { continue }
235 if ["paragraph", "heading"].contains(Self.kind(node)) {
236 let content = node.pointee.content
237 let held = blockSources[node] ?? Array(UnsafeBufferPointer(start: content.ptr, count: Int(content.size)))
238 let raw = Array(held.suffix(Int(content.size)))
239 var offsets = [0]
240 for (i, b) in raw.enumerated() where b == 10 { offsets.append(i + 1) }
241 var originals: [Int] = []
242 for (line, start) in offsets.enumerated() {
243 let end = line + 1 < offsets.count ? offsets[line + 1] - 1 : raw.count
244 let index = Int(node.pointee.start_line) - 1 + line
245 guard lines.indices.contains(index) else { originals.append(bytes.count); continue }
246 let normalized = String(decoding: raw[start..<end], as: UTF8.self)
247 let original = lines[index]
248 let prefix = original.range(of: normalized, options: .backwards).map { original[..<$0.lowerBound].utf8.count } ?? 0
249 originals.append(starts[index] + prefix)
250 }
251 inlineSources[node] = InlineSource(bytes: raw, starts: offsets, originalStarts: originals)
252 } else if node.pointee.type & 0xc000 == 0xc000, let parent = cmark_node_parent(node) {
253 inlineOwners[node] = inlineSources[parent] != nil ? parent : inlineOwners[parent]
254 }
255 }
256 }
257 mutating func tree(_ root: UnsafeMutablePointer<cmark_node>) -> [ChatMarkdownNode] {
258 prepareInlineSources(root)
259 // Postorder on an explicit heap stack. Quotes can be thousands deep.
260 var stack: [(UnsafeMutablePointer<cmark_node>, Bool)] = [(root, false)]
261 while let (node, visited) = stack.popLast() {
262 if Task.isCancelled { return [] }
263 if !visited {
264 stack.append((node, true))
265 var child = cmark_node_last_child(node)
266 while let current = child { stack.append((current, false)); child = cmark_node_previous(current) }
267 } else {
268 var nodes = project(node)
269 if nodes.count == 1, !["document", "block_quote", "image"].contains(Self.kind(node)) { nodes[0].sourceOffset = range(node).lowerBound }
270 projected[node] = nodes
271 var child = cmark_node_first_child(node)
272 while let current = child { projected.removeValue(forKey: current); child = cmark_node_next(current) }
273 }
274 }
275 return projected[root] ?? []
276 }
277 func children(_ node: UnsafeMutablePointer<cmark_node>) -> [ChatMarkdownNode] {
278 var out: [ChatMarkdownNode] = []
279 var child = cmark_node_first_child(node)
280 while let current = child {
281 for next in projected[current] ?? [] {
282 if next.kind == "text", next.text == nil || next.text == "" || next.text == "\n" && ["document", "list", "item"].contains(Self.kind(node)) { continue }
283 if next.kind == "text", out.last?.kind == "text" { out[out.count - 1].text! += next.text ?? "" }
284 else { out.append(next) }
285 }
286 child = cmark_node_next(current)
287 }
288 return out.map { value in
289 var value = value
290 if value.kind == "text" { value.text = value.text?.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") }
291 return value
292 }
293 }
294 func leaf(_ kind: String, _ text: String = "") -> ChatMarkdownNode { ChatMarkdownNode(kind: kind, text: text.isEmpty ? nil : text) }
295 func project(_ node: UnsafeMutablePointer<cmark_node>) -> [ChatMarkdownNode] {
296 switch Self.kind(node) {
297 case "text":
298 var value = draftText(node)
299 if let next = cmark_node_next(node), ["linebreak", "softbreak"].contains(Self.kind(next)) { while value.last == " " || value.last == "\t" { value.removeLast() } }
300 return [leaf("text", value)]
301 case "softbreak": return [leaf("text", "\n")]
302 case "linebreak": return [leaf("break")]
303 case "code":
304 var raw = inlineRaw(node)
305 // cmark caps code-span delimiter runs at 80. The inline adapter
306 // pads longer paired delimiters without changing source columns.
307 if node.pointee.backtick_count == 80 {
308 while raw.first == "`" { raw.removeFirst() }
309 while raw.last == "`" { raw.removeLast() }
310 }
311 // Goldmark keeps internal line breaks; cmark replaces them with spaces.
312 var code = raw
313 if code.contains(where: { $0 != " " && $0 != "\n" }),
314 let first = code.first, let last = code.last,
315 (first == " " || first == "\n"), (last == " " || last == "\n") {
316 code = String(code.dropFirst().dropLast())
317 }
318 return [leaf("code", code.replacingOccurrences(of: "\r", with: "\n"))]
319 case "html_inline": return [leaf("text", inlineRaw(node))]
320 case "html_block":
321 var value = literal(node)
322 if Int(node.pointee.end_line) == lines.count, bytes.last != 10, bytes.last != 13, value.hasSuffix("\n") { value.removeLast() }
323 return [leaf("text", value)]
324 case "thematic_break": return [] // Render has no rule output.
325 case "code_block":
326 var length: Int32 = 0, indent: Int32 = 0
327 var character: CChar = 0
328 guard cmark_node_get_fenced(node, &length, &indent, &character) != 0 else { return [leaf("codeBlock", literal(node))] }
329 let opening = Array(lines[max(0, Int(node.pointee.start_line) - 1)].utf8)
330 var info: [UInt8] = []
331 var infoLength = 0
332 if let first = opening.firstIndex(of: UInt8(bitPattern: character)) {
333 var at = first
334 while at < opening.count, opening[at] == UInt8(bitPattern: character) { at += 1 }
335 infoLength = opening.count - at
336 while at < opening.count, [9, 10, 11, 12, 13, 32].contains(opening[at]) { at += 1 }
337 var end = opening.count
338 while end > at, [9, 10, 11, 12, 13, 32].contains(opening[end - 1]) { end -= 1 }
339 info = Array(opening[at..<end])
340 }
341 let candidate = Int(node.pointee.start_line) == lines.count && bytes.last != 10 && infoLength == 1 ? "" : String(decoding: info.prefix(while: { $0 != 32 }), as: UTF8.self)
342 let lang = MarkdownDraft.matches(#"^\.?[A-Za-z0-9][A-Za-z0-9_+#.-]{0,23}$"#, candidate) ? candidate : ""
343 let lower = lang.lowercased()
344 var value = literal(node)
345 if cmark_node_parent(node).map({ Self.kind($0) != "document" }) == true, bytes.last == 13, bytes.dropLast().last == 10, Int(node.pointee.end_line) >= lines.count, value.hasSuffix("\n") { value.removeLast() }
346 var box = leaf("paste", value)
347 switch lower {
348 case "prompt": box.label = String(localized: "chat.paste.prompt", bundle: .module)
349 case "text": box.label = String(localized: "chat.paste.text", bundle: .module)
350 case "bash", "sh", "zsh", "shell", "console": box.label = String(localized: "chat.paste.command", bundle: .module)
351 default: box.label = lang.isEmpty ? nil : lang
352 }
353 box.wrap = ["prompt", "text"].contains(lower) ? true : nil
354 box.copy = String(localized: "chat.paste.copy", bundle: .module)
355 box.copied = String(localized: "chat.paste.copied", bundle: .module)
356 box.copyEnabled = !draft || !openFences.contains(node)
357 return [box]
358 case "paragraph":
359 if let item = cmark_node_parent(node), Self.kind(item) == "item",
360 let list = cmark_node_parent(item), cmark_node_get_list_tight(list) != 0 { return children(node) }
361 return [ChatMarkdownNode(kind: "paragraph", children: children(node))]
362 case "heading": return [ChatMarkdownNode(kind: "paragraph", children: children(node))]
363 case "emph": return [ChatMarkdownNode(kind: "emphasis", children: children(node))]
364 case "strong": return [ChatMarkdownNode(kind: "strong", children: children(node))]
365 case "list": return [ChatMarkdownNode(kind: cmark_node_get_list_type(node) == CMARK_ORDERED_LIST ? "ordered" : "unordered", children: children(node))]
366 case "item": return [ChatMarkdownNode(kind: "item", children: children(node))]
367 case "link":
368 // Goldmark's AutoLink is outside Render's vocabulary.
369 if range(node).lowerBound < bytes.count, bytes[range(node).lowerBound] == 60 { return [] }
370 let target = linkTarget(node)
371 guard ChatMarkdown.allowsLink(target) else { return children(node) }
372 return [ChatMarkdownNode(kind: "link", target: target, children: children(node))]
373 default: return children(node) // Quotes/images keep only their children.
374 }
375 }
376
377 /// Render resolves HTML entities in destinations but keeps punctuation
378 /// escapes. cmark's destination has already removed those backslashes.
379 func linkTarget(_ node: UnsafeMutablePointer<cmark_node>) -> String {
380 let raw = inlineRaw(node)
381 func destination(_ tail: Substring) -> String {
382 let trimmed = tail.drop(while: { " \t\n\r\u{000B}\u{000C}".contains($0) })
383 if trimmed.first == "<", let end = trimmed.dropFirst().firstIndex(of: ">") {
384 return String(trimmed[trimmed.index(after: trimmed.startIndex)..<end])
385 }
386 return String(trimmed.prefix(while: { !" \t\n\r\u{000B}\u{000C}".contains($0) }))
387 }
388 let resolved = cmark_node_get_url(node).map(String.init(cString:)) ?? ""
389 // A title or the destination itself can contain "](". A candidate is
390 // accepted only when its parser-normalized value equals the URL cmark
391 // actually selected. Source syntax can never redirect another link.
392 var search = raw.startIndex
393 while raw.last == ")", let opener = raw.range(of: "](", range: search..<raw.endIndex) {
394 let tail = raw[opener.upperBound..<raw.index(before: raw.endIndex)]
395 let candidate = destination(tail)
396 let angled = tail.drop(while: { " \t\n\r\u{000B}\u{000C}".contains($0) }).first == "<"
397 let parserValue = MarkdownInput.destinationForParser(candidate, angled: angled)
398 if parserValue == resolved || angled && parserValue.trimmingCharacters(in: .whitespacesAndNewlines) == resolved { return MarkdownDraft.entities(candidate) }
399 search = opener.upperBound
400 }
401 // Reference definitions carry the original destination too.
402 let groups = raw.components(separatedBy: "[").dropFirst().compactMap { $0.split(separator: "]", omittingEmptySubsequences: false).first.map(String.init) }
403 let label = groups.last(where: { !$0.isEmpty }) ?? ""
404 if let target = references[Self.normalized(label)] { return MarkdownDraft.entities(destination(target[...])) }
405 return cmark_node_get_url(node).map(String.init(cString:)) ?? ""
406 }
407
408 func textValue(_ node: UnsafeMutablePointer<cmark_node>) -> String {
409 var raw = inlineRaw(node)
410 let actual = literal(node)
411 // cmark leaves the original source span on partially consumed
412 // delimiter leaves. Their surviving delimiter count is in the literal.
413 for marker: Character in ["*", "_"] {
414 if raw.first == marker, actual.first == marker {
415 let old = raw.prefix(while: { $0 == marker }).count
416 let kept = actual.prefix(while: { $0 == marker }).count
417 if old > kept { raw.removeFirst(old - kept) }
418 }
419 if raw.last == marker, actual.last == marker {
420 let old = raw.reversed().prefix(while: { $0 == marker }).count
421 let kept = actual.reversed().prefix(while: { $0 == marker }).count
422 if old > kept { raw.removeLast(old - kept) }
423 }
424 }
425 return MarkdownDraft.decodeText(raw)
426 }
427 func draftText(_ node: UnsafeMutablePointer<cmark_node>) -> String {
428 guard let from = openFrom else { return textValue(node) }
429 let segment = range(node)
430 guard segment.lowerBound >= from, !segment.isEmpty else { return textValue(node) }
431 let partiallyConsumed = literal(node).allSatisfy { $0 == "*" || $0 == "_" } && literal(node).utf8.count < inlineRaw(node).utf8.count
432 var hidden = linkHidden
433 var firstBacktick: Int?
434 var at = segment.lowerBound
435 while at < segment.upperBound {
436 let char = bytes[at]
437 // The watched fallback text is extended up to the next inline
438 // parser trigger, even if that parser ultimately finds no node.
439 var startsLinkLabel = false
440 if let firstBacktick, [33, 42, 60, 91, 93, 95, 96].contains(char) {
441 var escapes = 0, previous = at
442 while previous > 0, bytes[previous - 1] == 92 { escapes += 1; previous -= 1 }
443 if escapes % 2 == 0 {
444 hidden.append(firstBacktick..<at)
445 // A link/image opener starts its own text segment, even
446 // before its destination arrives. Its label is not part
447 // of the watched unmatched code opener.
448 if char == 91 || char == 33 && at + 1 < bytes.count && bytes[at + 1] == 91 { startsLinkLabel = true }
449 }
450 }
451 if startsLinkLabel { firstBacktick = nil }
452 guard [42, 95, 96].contains(char) else { at += 1; continue }
453 let start = at
454 while at < segment.upperBound, bytes[at] == char { at += 1 }
455 var slashes = 0, before = start
456 while before > 0, bytes[before - 1] == 92 { slashes += 1; before -= 1 }
457 if slashes % 2 == 1 { at = start + 1; continue }
458 if char == 96 {
459 // Goldmark coalesces watched fallback text through the next
460 // unmatched code opener; its draft hides that entire span.
461 firstBacktick = firstBacktick ?? start
462 hidden.append(firstBacktick!..<at)
463 continue
464 }
465 let left = String(decoding: bytes[max(0, start - 4)..<start], as: UTF8.self).unicodeScalars.last
466 let right = String(decoding: bytes[at..<min(bytes.count, at + 4)], as: UTF8.self).unicodeScalars.first
467 func space(_ c: Unicode.Scalar?) -> Bool { c.map { CharacterSet.whitespacesAndNewlines.contains($0) } ?? true }
468 func punct(_ c: Unicode.Scalar?) -> Bool { c.map { CharacterSet.punctuationCharacters.union(.symbols).contains($0) } ?? false }
469 let lf = !space(right) && (!punct(right) || space(left) || punct(left))
470 let rf = !space(left) && (!punct(left) || space(right) || punct(right))
471 let canOpen = char == 42 ? lf : lf && (!rf || punct(left))
472 let canClose = char == 42 ? rf : rf && (!lf || punct(right))
473 // Goldmark creates a delimiter even when it cannot open or
474 // close. Removing that first unmatched delimiter merges it into
475 // the watched backtick text; later text is a separate segment.
476 if let firstBacktick { hidden.append(firstBacktick..<at) }
477 // A closer that cannot open is removed during the forward
478 // delimiter pass. An adjacent surviving delimiter can then merge
479 // into that same watched text during the final reverse pass.
480 if !(canClose && !canOpen && at < bytes.count && [42, 95].contains(bytes[at])) { firstBacktick = nil }
481 if canOpen && (!canClose || at - start >= 2) || at == bytes.count && !partiallyConsumed { hidden.append(start..<at) }
482 }
483 if let firstBacktick, segment.upperBound < bytes.count,
484 [33, 42, 60, 91, 93, 95, 96].contains(bytes[segment.upperBound]) {
485 hidden.append(firstBacktick..<segment.upperBound)
486 }
487 let relevant = hidden.filter { $0.overlaps(segment) }
488 guard !relevant.isEmpty else { return textValue(node) }
489 var kept: [UInt8] = []
490 var cursor = segment.lowerBound
491 for span in relevant.sorted(by: { $0.lowerBound < $1.lowerBound }) {
492 let begin = max(segment.lowerBound, span.lowerBound)
493 if begin > cursor { kept.append(contentsOf: bytes[cursor..<begin]) }
494 cursor = max(cursor, min(segment.upperBound, span.upperBound))
495 }
496 if cursor < segment.upperBound { kept.append(contentsOf: bytes[cursor..<segment.upperBound]) }
497 return MarkdownDraft.decodeText(String(decoding: kept, as: UTF8.self))
498 }
499}
500