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