Sources/OrgHighlight/OrgHighlighter.swift
330 lines · 12643 bytes
28 symbols in this file
1/// Highlights org source for the editor: one `<div class="ln">` per source line, with
2/// `<span>` classes for markup. Line-oriented with block state; it does not parse the
3/// document, so it stays cheap enough to run on every keystroke.
4public enum OrgHighlighter {
5
6 /// The HTML of each source line, in order.
7 public static func lines(_ source: String) -> [String] {
8 var block: [UInt8]? = nil
9 var out: [UInt8] = []
10 return source.utf8.split(separator: UInt8(ascii: "\n"), omittingEmptySubsequences: false).map { line in
11 out.removeAll(keepingCapacity: true)
12 out.append(contentsOf: lineOpen)
13 highlightLine(Array(line), block: &block, into: &out)
14 out.append(contentsOf: lineClose)
15 return String(decoding: out, as: UTF8.self)
16 }
17 }
18
19 private static let lineOpen = Array("<div class=\"ln\">".utf8)
20 private static let lineClose = Array("\n</div>".utf8)
21
22 /// Blocks whose bodies are shown verbatim, without inline markup.
23 private static let verbatimBlocks: [[UInt8]] = ["src", "example", "export", "comment"].map { Array($0.utf8) }
24
25 private static func highlightLine(_ b: [UInt8], block: inout [UInt8]?, into out: inout [UInt8]) {
26 var w = Writer(b: b, out: out)
27 defer { out = w.out }
28 let start = indentEnd(b)
29
30 if let name = block {
31 if lowerHasPrefix(b, at: start, "#+end_") {
32 block = nil
33 w.span("meta", 0, b.count)
34 } else if verbatimBlocks.contains(name) {
35 w.span("blk", 0, b.count)
36 } else {
37 inline(&w, 0, b.count)
38 }
39 return
40 }
41
42 // Headings: stars at column 0 followed by a space.
43 var stars = 0
44 while stars < b.count && b[stars] == UInt8(ascii: "*") { stars += 1 }
45 if stars > 0 && stars < b.count && b[stars] == UInt8(ascii: " ") {
46 heading(&w, stars)
47 return
48 }
49
50 if lowerHasPrefix(b, at: start, "#+begin_") {
51 var e = start + 8
52 while e < b.count && !isSpace(b[e]) { e += 1 }
53 block = b[(start + 8)..<e].map(lower)
54 w.span("meta", 0, b.count)
55 return
56 }
57 if hasPrefix(b, at: start, "#+") {
58 var e = start + 2
59 while e < b.count && isKeyChar(b[e]) { e += 1 }
60 if e > start + 2 && e < b.count && b[e] == UInt8(ascii: ":") {
61 w.span("kw", 0, e + 1)
62 w.text(e + 1, b.count)
63 } else {
64 w.span("meta", 0, b.count)
65 }
66 return
67 }
68 if start < b.count && b[start] == UInt8(ascii: "#") && (start + 1 == b.count || isSpace(b[start + 1])) {
69 w.span("cmt", 0, b.count)
70 return
71 }
72 if start < b.count && b[start] == UInt8(ascii: "|") {
73 w.span("tbl", 0, b.count)
74 return
75 }
76 if start < b.count && b[start] == UInt8(ascii: ":") {
77 if start + 1 == b.count || b[start + 1] == UInt8(ascii: " ") {
78 w.span("fix", 0, b.count)
79 return
80 }
81 var e = start + 1
82 while e < b.count && isKeyChar(b[e]) { e += 1 }
83 if e > start + 1 && e < b.count && b[e] == UInt8(ascii: ":") && (e + 1 == b.count || isSpace(b[e + 1])) {
84 w.span("drw", 0, e + 1)
85 w.text(e + 1, b.count)
86 return
87 }
88 }
89 if b.count - start >= 5 && b[start...].allSatisfy({ $0 == UInt8(ascii: "-") || isSpace($0) })
90 && b[start..<(start + 5)].allSatisfy({ $0 == UInt8(ascii: "-") }) {
91 w.span("hr", 0, b.count)
92 return
93 }
94 if let bulletEnd = bullet(b, start) {
95 w.span("bul", 0, bulletEnd)
96 var i = bulletEnd
97 if i + 3 <= b.count && b[i] == UInt8(ascii: "[") && b[i + 2] == UInt8(ascii: "]")
98 && (b[i + 1] == UInt8(ascii: " ") || b[i + 1] == UInt8(ascii: "X") || b[i + 1] == UInt8(ascii: "x") || b[i + 1] == UInt8(ascii: "-")) {
99 w.span("cb", i, i + 3)
100 i += 3
101 }
102 inline(&w, i, b.count)
103 return
104 }
105 inline(&w, 0, b.count)
106 }
107
108 private static func heading(_ w: inout Writer, _ stars: Int) {
109 let b = w.b
110 let level = (stars - 1) % 3 + 1
111 w.open("h\(level)")
112 var i = stars + 1
113 w.text(0, i)
114 if let (word, cls) = todoKeyword(b, i) {
115 w.span(cls, i, word)
116 i = word
117 }
118 if i + 4 <= b.count && b[i] == UInt8(ascii: " ") && b[i + 1] == UInt8(ascii: "[") && b[i + 2] == UInt8(ascii: "#") && b[i + 4] == UInt8(ascii: "]") {
119 w.text(i, i + 1)
120 w.span("pri", i + 1, i + 5)
121 i += 5
122 } else if i + 3 <= b.count && b[i] == UInt8(ascii: "[") && b[i + 1] == UInt8(ascii: "#") && b[i + 3] == UInt8(ascii: "]") {
123 w.span("pri", i, i + 4)
124 i += 4
125 }
126 if let tags = tagsStart(b, from: i) {
127 inline(&w, i, tags)
128 w.span("tag", tags, b.count)
129 } else {
130 inline(&w, i, b.count)
131 }
132 w.close()
133 }
134
135 private static func todoKeyword(_ b: [UInt8], _ i: Int) -> (Int, String)? {
136 for (word, cls) in [("TODO", "todo"), ("DONE", "done")] {
137 let u = Array(word.utf8)
138 if hasPrefix(b, at: i, word) && (i + u.count == b.count || b[i + u.count] == UInt8(ascii: " ")) {
139 return (i + u.count, cls)
140 }
141 }
142 return nil
143 }
144
145 /// Start of a trailing `:tag1:tag2:` group preceded by whitespace, if any.
146 private static func tagsStart(_ b: [UInt8], from: Int) -> Int? {
147 var end = b.count
148 while end > from && isSpace(b[end - 1]) { end -= 1 }
149 guard end - from >= 3, b[end - 1] == UInt8(ascii: ":") else { return nil }
150 var s = end - 1
151 while s > from && (isTagChar(b[s - 1]) || b[s - 1] == UInt8(ascii: ":")) { s -= 1 }
152 while s < end && b[s] != UInt8(ascii: ":") { s += 1 }
153 guard s < end - 1, s > from, isSpace(b[s - 1]) else { return nil }
154 return s
155 }
156
157 /// End of a list bullet and its following space, if the line has one.
158 private static func bullet(_ b: [UInt8], _ start: Int) -> Int? {
159 guard start < b.count else { return nil }
160 var e = start
161 let c = b[start]
162 if c == UInt8(ascii: "-") || c == UInt8(ascii: "+") || (c == UInt8(ascii: "*") && start > 0) {
163 e += 1
164 } else {
165 while e < b.count && isDigit(b[e]) { e += 1 }
166 guard e > start, e < b.count, b[e] == UInt8(ascii: ".") || b[e] == UInt8(ascii: ")") else { return nil }
167 e += 1
168 }
169 if e == b.count { return e }
170 guard b[e] == UInt8(ascii: " ") else { return nil }
171 return e + 1
172 }
173
174 // MARK: - Inline
175
176 private static func inline(_ w: inout Writer, _ from: Int, _ to: Int) {
177 let b = w.b
178 var i = from
179 var plain = from
180 while i < to {
181 var match: (end: Int, cls: String)? = nil
182 let c = b[i]
183 if c == UInt8(ascii: "[") {
184 if i + 1 < to && b[i + 1] == UInt8(ascii: "["), let e = find(b, "]]", i + 2, to) {
185 match = (e + 2, "lnk")
186 } else if hasPrefix(b, at: i, "[fn:"), let e = find(b, "]", i + 4, to) {
187 match = (e + 1, "fn")
188 } else if isDate(b, i + 1, to), let e = find(b, "]", i + 1, to) {
189 match = (e + 1, "ts")
190 }
191 } else if c == UInt8(ascii: "<") && isDate(b, i + 1, to), let e = find(b, ">", i + 1, to) {
192 match = (e + 1, "ts")
193 } else if c == UInt8(ascii: "h") && (i == from || !isWordChar(b[i - 1]))
194 && (hasPrefix(b, at: i, "https://") || hasPrefix(b, at: i, "http://")) {
195 var e = i
196 while e < to && !isSpace(b[e]) { e += 1 }
197 match = (e, "lnk")
198 } else if let cls = emphasisClass(c), let e = emphasisEnd(b, i, from, to) {
199 match = (e, cls)
200 }
201 if let m = match {
202 w.text(plain, i)
203 w.span(m.cls, i, m.end)
204 i = m.end
205 plain = i
206 } else {
207 i += 1
208 }
209 }
210 w.text(plain, to)
211 }
212
213 private static func emphasisClass(_ c: UInt8) -> String? {
214 switch c {
215 case UInt8(ascii: "*"): "b"
216 case UInt8(ascii: "/"): "i"
217 case UInt8(ascii: "_"): "u"
218 case UInt8(ascii: "+"): "s"
219 case UInt8(ascii: "="), UInt8(ascii: "~"): "v"
220 default: nil
221 }
222 }
223
224 /// End (past the closing marker) of an emphasis span opening at `i`, following org's
225 /// rules for the characters allowed around markers.
226 private static func emphasisEnd(_ b: [UInt8], _ i: Int, _ from: Int, _ to: Int) -> Int? {
227 let m = b[i]
228 if i > from && !isSpace(b[i - 1]) && !contains("-('\"{", b[i - 1]) { return nil }
229 guard i + 2 < to, !isSpace(b[i + 1]), b[i + 1] != m else { return nil }
230 var k = i + 2
231 while k < to {
232 if b[k] == m && !isSpace(b[k - 1]) && (k + 1 == to || isSpace(b[k + 1]) || contains("-.,;:!?')}[\"\\", b[k + 1])) {
233 return k + 1
234 }
235 k += 1
236 }
237 return nil
238 }
239
240 // MARK: - Output
241
242 private struct Writer {
243 let b: [UInt8]
244 var out: [UInt8]
245
246 mutating func text(_ from: Int, _ to: Int) {
247 var i = from
248 while i < to {
249 switch b[i] {
250 case UInt8(ascii: "&"): out.append(contentsOf: "&".utf8)
251 case UInt8(ascii: "<"): out.append(contentsOf: "<".utf8)
252 case UInt8(ascii: ">"): out.append(contentsOf: ">".utf8)
253 default: out.append(b[i])
254 }
255 i += 1
256 }
257 }
258
259 mutating func open(_ cls: String) {
260 out.append(contentsOf: "<span class=\"".utf8)
261 out.append(contentsOf: cls.utf8)
262 out.append(contentsOf: "\">".utf8)
263 }
264
265 mutating func close() {
266 out.append(contentsOf: "</span>".utf8)
267 }
268
269 mutating func span(_ cls: String, _ from: Int, _ to: Int) {
270 open(cls)
271 text(from, to)
272 close()
273 }
274 }
275
276 // MARK: - Bytes
277
278 private static func indentEnd(_ b: [UInt8]) -> Int {
279 var i = 0
280 while i < b.count && isSpace(b[i]) { i += 1 }
281 return i
282 }
283
284 private static func hasPrefix(_ b: [UInt8], at i: Int, _ p: String) -> Bool {
285 var j = i
286 for c in p.utf8 {
287 guard j < b.count, b[j] == c else { return false }
288 j += 1
289 }
290 return true
291 }
292
293 private static func lowerHasPrefix(_ b: [UInt8], at i: Int, _ p: String) -> Bool {
294 var j = i
295 for c in p.utf8 {
296 guard j < b.count, lower(b[j]) == c else { return false }
297 j += 1
298 }
299 return true
300 }
301
302 private static func find(_ b: [UInt8], _ s: String, _ from: Int, _ to: Int) -> Int? {
303 let n = Array(s.utf8)
304 var i = from
305 while i + n.count <= to {
306 if b[i] == n[0] && Array(b[i..<(i + n.count)]) == n { return i }
307 i += 1
308 }
309 return nil
310 }
311
312 /// `YYYY-MM-DD` at `i`.
313 private static func isDate(_ b: [UInt8], _ i: Int, _ to: Int) -> Bool {
314 guard i + 10 <= to else { return false }
315 for k in 0..<10 {
316 let ok = (k == 4 || k == 7) ? b[i + k] == UInt8(ascii: "-") : isDigit(b[i + k])
317 if !ok { return false }
318 }
319 return true
320 }
321
322 private static func contains(_ set: String, _ c: UInt8) -> Bool { set.utf8.contains(c) }
323 private static func lower(_ c: UInt8) -> UInt8 { c >= 65 && c <= 90 ? c + 32 : c }
324 private static func isSpace(_ c: UInt8) -> Bool { c == 32 || c == 9 }
325 private static func isDigit(_ c: UInt8) -> Bool { c >= 48 && c <= 57 }
326 private static func isAlpha(_ c: UInt8) -> Bool { (c >= 65 && c <= 90) || (c >= 97 && c <= 122) }
327 private static func isWordChar(_ c: UInt8) -> Bool { isAlpha(c) || isDigit(c) || c >= 0x80 }
328 private static func isKeyChar(_ c: UInt8) -> Bool { isAlpha(c) || isDigit(c) || c == 95 || c == 45 }
329 private static func isTagChar(_ c: UInt8) -> Bool { isWordChar(c) || c == 95 || c == 64 || c == 35 || c == 37 }
330}