oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

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