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/MarkdownInput.swift). Base's changes are
3// marked "Base:"; keep the rest in step with Equipo's.
4import Foundation
5import cmark_gfm
6
7/// Goldmark's delimiter classification includes Unicode symbols and NEL.
8/// Adapt only the inline parser's private block buffer, preserving byte widths.
9/// All projected text and targets come from the retained original block buffer.
10enum MarkdownInput {
11 struct Prepared {
12 let source: String
13 let original: String
14 let preparedLines: [String]
15 let originalLines: [String]
16 init(source: String, original: String) {
17 self.source = source; self.original = original
18 preparedLines = source.components(separatedBy: "\n")
19 originalLines = original.components(separatedBy: "\n")
20 }
21 func block(_ bytes: [UInt8], startLine: Int) -> [UInt8] {
22 var result: [UInt8] = []
23 var line = max(0, startLine - 1)
24 for part in bytes.split(separator: 10, omittingEmptySubsequences: false).dropLast(bytes.last == 10 ? 1 : 0) {
25 // Block content has one entry for each physical LF line,
26 // including empty lines. Never search into a later block.
27 if line < preparedLines.count {
28 let candidate = preparedLines[line]
29 var suffix = part[...]
30 var restored: [UInt8]?
31 while !suffix.isEmpty {
32 let wanted = String(decoding: suffix, as: UTF8.self)
33 if let range = candidate.range(of: wanted, options: .backwards) {
34 let offset = candidate[..<range.lowerBound].utf8.count
35 restored = Array(part.prefix(part.count - suffix.count)) + Array(originalLines[line].utf8.dropFirst(offset).prefix(suffix.count))
36 break
37 }
38 // cmark can expand the remainder of an indentation tab
39 // into spaces. Those generated spaces precede the
40 // verbatim suffix, whose byte mapping is unchanged.
41 guard suffix.first == 32 else { break }
42 suffix = suffix.dropFirst()
43 }
44 result += restored ?? Array(part)
45 } else { result += part }
46 line += 1
47 result.append(10)
48 }
49 if bytes.last != 10, !result.isEmpty { result.removeLast() }
50 return result
51 }
52 }
53 static func prepare(_ source: String) -> Prepared {
54 var bytes = Array(source.utf8)
55 // Goldmark splits lines on LF and treats preceding CRs as whitespace.
56 // cmark also splits lone CRs; preserve widths while preventing an extra
57 // CR before CRLF from inventing a blank line or a loose list.
58 for i in bytes.indices where bytes[i] == 13 {
59 if i + 1 < bytes.count, bytes[i + 1] != 10 { bytes[i] = 32 }
60 }
61 // The reference-definition block parser runs before the inline phase.
62 // Adapt angle destinations here too; the retained block restores bytes.
63 if let placeholder = (Array(UInt8(1)...UInt8(8)) + [127]).first(where: { !bytes.contains($0) }) {
64 var i = 0
65 while i + 2 < bytes.count {
66 if bytes[i] == 93, bytes[i+1] == 40 || bytes[i+1] == 58 {
67 var j = i + 2
68 while j < bytes.count, [32,9,10,13].contains(bytes[j]) { j += 1 }
69 if j < bytes.count, bytes[j] == 60 {
70 j += 1
71 while j < bytes.count, bytes[j] != 62, bytes[j] != 10 {
72 if bytes[j] == 60 { bytes[j] = placeholder }
73 j += 1
74 }
75 }
76 }
77 i += 1
78 }
79 }
80 return Prepared(source: String(decoding: bytes, as: UTF8.self), original: source)
81 }
82
83 static func destinationForParser(_ value: String, angled: Bool) -> String {
84 var bytes = forCMark(Array(value.utf8))
85 if angled { bytes = bytes.map { $0 == 60 ? 1 : $0 } }
86 var buffer = cmark_strbuf()
87 cmark_strbuf_init(cmark_get_default_mem_allocator(), &buffer, 0)
88 defer { cmark_strbuf_free(&buffer) }
89 bytes.withUnsafeBufferPointer { houdini_unescape_html_f(&buffer, $0.baseAddress, Int32($0.count)) }
90 cmark_strbuf_unescape(&buffer)
91 return String(decoding: UnsafeBufferPointer(start: buffer.ptr, count: Int(buffer.size)), as: UTF8.self)
92 }
93
94 static func forCMark(_ bytes: [UInt8]) -> [UInt8] {
95 var out: [UInt8] = []
96 for scalar in String(decoding: bytes, as: UTF8.self).unicodeScalars {
97 let replacement: String
98 if scalar.value == 13 { replacement = " " }
99 else if scalar.value == 0x85 { replacement = "\u{a0}" }
100 else if scalar.value == 0x2028 || scalar.value == 0x2029 { replacement = "\u{2000}" }
101 else if scalar.value == 11 { replacement = "\u{000C}" }
102 else if scalar.value > 127, CharacterSet.punctuationCharacters.union(.symbols).contains(scalar), cmark_utf8proc_is_punctuation(Int32(scalar.value)) == 0 {
103 switch scalar.utf8.count {
104 case 2: replacement = "¡"
105 case 3: replacement = "‼"
106 default: replacement = "\u{10100}"
107 }
108 } else { replacement = String(scalar) }
109 out.append(contentsOf: replacement.utf8)
110 }
111 // Goldmark allows a '<' inside an angle destination. cmark rejects it.
112 // A same-width placeholder lets cmark recognize the link structure;
113 // the original destination is retained and validated before linking.
114 var at = 0
115 while at + 2 < out.count {
116 if out[at] == 93, out[at + 1] == 40 || out[at + 1] == 58 {
117 var i = at + 2
118 while i < out.count, [32, 9, 10, 13].contains(out[i]) { i += 1 }
119 if i < out.count, out[i] == 60 {
120 i += 1
121 while i < out.count, out[i] != 62, out[i] != 10 {
122 if out[i] == 60 { out[i] = 1 }
123 i += 1
124 }
125 }
126 }
127 at += 1
128 }
129 // cmark's inline backtick cache has 80 slots. Preserve source widths
130 // while presenting longer matching runs as an 80-tick delimiter.
131 var runs: [(start: Int, end: Int)] = []
132 var cursor = 0
133 while cursor < out.count {
134 guard out[cursor] == 96 else { cursor += 1; continue }
135 let start = cursor
136 while cursor < out.count, out[cursor] == 96 { cursor += 1 }
137 runs.append((start, cursor))
138 }
139 var next: [Int: Int] = [:], matching: [Int: Int] = [:]
140 for index in runs.indices.reversed() {
141 let length = runs[index].end - runs[index].start
142 matching[index] = next[length]
143 next[length] = index
144 }
145 var index = 0
146 while index < runs.count {
147 let run = runs[index]
148 var before = run.start
149 while before > 0, out[before - 1] == 92 { before -= 1 }
150 guard (run.start - before) % 2 == 0, let close = matching[index] else { index += 1; continue }
151 if run.end - run.start > 80 {
152 for at in (run.start + 80)..<run.end { out[at] = 1 }
153 for at in runs[close].start..<(runs[close].end - 80) { out[at] = 1 }
154 }
155 index = close + 1
156 }
157 return out
158 }
159}
160