Sources/OrgCore/Config/ElispRegex.swift
523 lines · 25756 bytes
1import Foundation
2
3/// An Emacs regexp as an `NSRegularExpression`, with the syntax table of an Org buffer, where
4/// table formulas and Emacs Lisp blocks run. A construct it can't translate exactly throws
5/// `Elisp.Unsupported`, and so do subjects where ICU's tables could differ from Emacs's:
6/// syntax classes against text past ASCII, and case folding with letters past ASCII.
7struct ElispRegex {
8 let pattern: String
9 let groups: Int
10 /// Has letters, ranges over letters or case classes: case folding changes what matches.
11 let foldable: Bool
12 /// Has classes whose members past ASCII come from Emacs's syntax or Unicode tables.
13 let asciiClasses: Bool
14 /// Has letters with case past ASCII.
15 let nonASCIILetters: Bool
16 let plain: NSRegularExpression
17 let folded: NSRegularExpression
18
19 /// `char-syntax` of each ASCII character in `org-mode-syntax-table`.
20 static let syntax = Array("......... . .................. .\".ww_w()__._._wwwwwwwwww..(_)..wwwwwwwwwwwwwwwwwwwwwwwwww(_)._.wwwwwwwwwwwwwwwwwwwwwwwwww(_)_.")
21
22 static func codes(_ syntaxClass: Character) -> [UInt32] {
23 syntax.indices.filter { syntax[$0] == syntaxClass }.map(UInt32.init)
24 }
25
26 static func hex(_ c: UInt32) -> String { "\\x{" + String(c, radix: 16) + "}" }
27
28 static func set(_ codes: [UInt32], negated: Bool = false) -> String {
29 "[" + (negated ? "^" : "") + codes.map(hex).joined() + "]"
30 }
31
32 static let word = codes("w")
33 static let symbol = word + codes("_")
34
35 /// A letter with case, which case folding changes.
36 static func isLetter(_ c: UInt32) -> Bool {
37 (65...90).contains(c) || (97...122).contains(c) || c > 127 && Unicode.Scalar(c).map { $0.properties.changesWhenCaseMapped || $0.properties.changesWhenCaseFolded } ?? false
38 }
39
40 init(_ pattern: String) throws {
41 self.pattern = pattern
42 let p = Array(pattern.unicodeScalars)
43 var out = ""
44 var groups = 0
45 var open: [Int] = []
46 var closed: Set<Int> = []
47 var foldable = false
48 var asciiClasses = false
49 // Where `^` is an anchor, and where `*`, `+` and `?` are ordinary characters: at the
50 // start, after `\(` or `\|`, and for the second also after that `^`.
51 var anchor = true
52 var ordinary = true
53 var quantifiable = false
54 // After a repetition, and whether a `?` may make it non-greedy.
55 var quantified = false
56 var lazy = false
57 var i = 0
58 func unsupported(_ what: String) -> Elisp.Unsupported { Elisp.Unsupported(what: "regexp \(what) in \(Elisp.printed(.string(pattern), escape: true))") }
59 func literal(_ c: Unicode.Scalar) {
60 if c.isASCII, c.properties.isAlphabetic || ("0"..."9").contains(c) { out.unicodeScalars.append(c) } else { out += Self.hex(c.value) }
61 if Self.isLetter(c.value) { foldable = true }
62 (anchor, ordinary, quantifiable, quantified) = (false, false, true, false)
63 }
64 func atom(_ text: String) {
65 out += text
66 (anchor, ordinary, quantifiable, quantified) = (false, false, true, false)
67 }
68 func assertion(_ text: String) {
69 out += text
70 (anchor, ordinary, quantifiable, quantified) = (false, false, false, false)
71 }
72 while i < p.count {
73 let c = p[i]
74 i += 1
75 switch c {
76 case "^":
77 if anchor {
78 out += "(?:(?<![\\s\\S])|(?<=\\n))"
79 anchor = false
80 } else {
81 literal(c)
82 }
83 case "$":
84 let rest = p[i...]
85 if rest.isEmpty || rest.starts(with: ["\\", ")"]) || rest.starts(with: ["\\", "|"]) {
86 assertion("(?=\\n|(?![\\s\\S]))")
87 } else {
88 literal(c)
89 }
90 case ".":
91 atom("[^\\n]")
92 case "*", "+", "?":
93 if quantified {
94 guard c == "?", lazy else { throw unsupported("\(c) after a repetition") }
95 out += "?"
96 lazy = false
97 } else if quantifiable {
98 out.unicodeScalars.append(c)
99 (quantifiable, quantified, lazy) = (false, true, true)
100 } else if ordinary {
101 literal(c)
102 } else {
103 throw unsupported(String(c))
104 }
105 case "[":
106 var j = i
107 var text = "["
108 if j < p.count, p[j] == "^" {
109 text += "^"
110 j += 1
111 }
112 var first = true
113 while true {
114 guard j < p.count else { throw unsupported("[") }
115 let c = p[j]
116 if c == "]", !first {
117 j += 1
118 break
119 }
120 first = false
121 if c == "[", j + 1 < p.count, p[j + 1] == ":" {
122 var k = j + 2
123 var name = ""
124 while k + 1 < p.count, !(p[k] == ":" && p[k + 1] == "]") {
125 name.unicodeScalars.append(p[k])
126 k += 1
127 }
128 guard k + 1 < p.count else { throw unsupported("[:") }
129 j = k + 2
130 let ascii: (String, Bool, Bool) = switch name {
131 case "alpha": ("A-Za-z", true, false)
132 case "alnum": ("0-9A-Za-z", true, false)
133 case "upper": ("A-Z", true, true)
134 case "lower": ("a-z", true, true)
135 case "digit": ("0-9", false, false)
136 case "xdigit": ("0-9A-Fa-f", false, false)
137 case "cntrl": ("\\x{0}-\\x{1f}", false, false)
138 case "ascii": ("\\x{0}-\\x{7f}", false, false)
139 case "nonascii": ("\\x{80}-\\x{10ffff}", false, false)
140 case "space": (Self.codes(" ").map(Self.hex).joined(), true, false)
141 case "blank": ("\\x{9}\\x{20}", true, false)
142 case "punct": ((33...126).filter { !Self.isLetter($0) && !(48...57).contains($0) }.map(Self.hex).joined(), true, false)
143 case "graph": ("\\x{21}-\\x{7e}", true, false)
144 case "print": ("\\x{20}-\\x{7e}", true, false)
145 case "word": (Self.word.map(Self.hex).joined(), true, false)
146 default: throw unsupported("[:\(name):]")
147 }
148 text += ascii.0
149 if ascii.1 { asciiClasses = true }
150 if ascii.2 { foldable = true }
151 continue
152 }
153 if j + 2 < p.count, p[j + 1] == "-", p[j + 2] != "]" {
154 let end = p[j + 2]
155 guard c.value <= end.value else { throw unsupported("range") }
156 text += Self.hex(c.value) + "-" + Self.hex(end.value)
157 if end.value >= 65, c.value <= 122 || end.value > 127 { foldable = true }
158 j += 3
159 continue
160 }
161 text += Self.hex(c.value)
162 if Self.isLetter(c.value) { foldable = true }
163 j += 1
164 }
165 i = j
166 atom(text + "]")
167 case "\\":
168 guard i < p.count else { throw unsupported("\\ at the end") }
169 let e = p[i]
170 i += 1
171 switch e {
172 case "(":
173 if i < p.count, p[i] == "?" {
174 guard i + 1 < p.count, p[i + 1] == ":" else { throw unsupported("\\(?") }
175 i += 2
176 out += "(?:"
177 open.append(0)
178 } else {
179 groups += 1
180 out += "("
181 open.append(groups)
182 }
183 (anchor, ordinary, quantifiable, quantified) = (true, true, false, false)
184 case ")":
185 guard let n = open.popLast() else { throw unsupported("\\)") }
186 closed.insert(n)
187 atom(")")
188 case "|":
189 out += "|"
190 (anchor, ordinary, quantifiable, quantified) = (true, true, false, false)
191 case "{":
192 guard quantifiable else { throw unsupported("\\{") }
193 var low = ""
194 var high: String?
195 while i < p.count, ("0"..."9").contains(p[i]) {
196 low.unicodeScalars.append(p[i])
197 i += 1
198 }
199 if i < p.count, p[i] == "," {
200 i += 1
201 var digits = ""
202 while i < p.count, ("0"..."9").contains(p[i]) {
203 digits.unicodeScalars.append(p[i])
204 i += 1
205 }
206 high = digits
207 }
208 guard i + 1 < p.count, p[i] == "\\", p[i + 1] == "}", !low.isEmpty || high != nil else { throw unsupported("\\{") }
209 i += 2
210 out += "{" + (low.isEmpty ? "0" : low) + (high.map { "," + $0 } ?? "") + "}"
211 (quantifiable, quantified, lazy) = (false, true, false)
212 case "1"..."9":
213 let n = Int(e.value) - 48
214 guard closed.contains(n) else { throw unsupported("\\\(n)") }
215 atom("(?:\\\(n))")
216 case "w", "W":
217 asciiClasses = true
218 atom(Self.set(Self.word, negated: e == "W"))
219 case "s", "S":
220 guard i < p.count else { throw unsupported("\\s") }
221 let code: Character = switch p[i] {
222 case "-", " ": " "
223 case "w", "_", ".", "(", ")", "\"": Character(p[i])
224 default: throw unsupported("\\s\(p[i])")
225 }
226 i += 1
227 asciiClasses = true
228 atom(Self.set(Self.codes(code), negated: e == "S"))
229 case "b", "B", "<", ">":
230 asciiClasses = true
231 let w = Self.set(Self.word)
232 let text = switch e {
233 case "b": "(?:(?<=\(w))(?!\(w))|(?<!\(w))(?=\(w)))"
234 case "B": "(?:(?<=\(w))(?=\(w))|(?<!\(w))(?!\(w)))"
235 case "<": "(?<!\(w))(?=\(w))"
236 default: "(?<=\(w))(?!\(w))"
237 }
238 assertion(text)
239 case "_":
240 guard i < p.count, p[i] == "<" || p[i] == ">" else { throw unsupported("\\_") }
241 asciiClasses = true
242 let s = Self.set(Self.symbol)
243 assertion(p[i] == "<" ? "(?<!\(s))(?=\(s))" : "(?<=\(s))(?!\(s))")
244 i += 1
245 case "`":
246 assertion("(?<![\\s\\S])")
247 case "'":
248 assertion("(?![\\s\\S])")
249 default:
250 guard !e.isASCII || !(e.properties.isAlphabetic || ("0"..."9").contains(e) || e == "}") else { throw unsupported("\\\(e)") }
251 literal(e)
252 }
253 default:
254 literal(c)
255 }
256 }
257 guard open.isEmpty else { throw unsupported("\\(") }
258 self.groups = groups
259 self.foldable = foldable
260 self.asciiClasses = asciiClasses
261 nonASCIILetters = p.contains { !$0.isASCII && Self.isLetter($0.value) }
262 do {
263 plain = try NSRegularExpression(pattern: out.isEmpty ? "(?:)" : out)
264 folded = try NSRegularExpression(pattern: out.isEmpty ? "(?:)" : out, options: .caseInsensitive)
265 } catch {
266 throw unsupported("syntax")
267 }
268 }
269
270 /// The first match at or after character `start`: each group's range in characters, nil
271 /// for groups that didn't match.
272 func firstMatch(in s: String, from start: Int, caseFold: Bool) throws -> [Range<Int>?]? {
273 let subjectNonASCII = s.unicodeScalars.contains { !$0.isASCII }
274 if asciiClasses, subjectNonASCII { throw Elisp.Unsupported(what: "regexp classes on text past ASCII") }
275 // Folding agrees for ASCII letters, unless the text has a character whose case maps
276 // to ASCII, like the Kelvin sign or ß.
277 if caseFold, foldable, nonASCIILetters || subjectNonASCII && s.unicodeScalars.contains(where: { c in
278 !c.isASCII && (String(c).lowercased() + String(c).uppercased()).unicodeScalars.contains(where: \.isASCII)
279 }) {
280 throw Elisp.Unsupported(what: "case folding past ASCII")
281 }
282 // UTF-16 offset of each character, and the end.
283 var offsets = [0]
284 if subjectNonASCII {
285 for scalar in s.unicodeScalars { offsets.append(offsets.last! + scalar.utf16.count) }
286 }
287 func utf16(_ i: Int) -> Int { subjectNonASCII ? offsets[i] : i }
288 func character(_ u: Int) -> Int {
289 guard subjectNonASCII else { return u }
290 var low = 0
291 var high = offsets.count - 1
292 while low < high {
293 let mid = (low + high) / 2
294 if offsets[mid] < u { low = mid + 1 } else { high = mid }
295 }
296 return low
297 }
298 let length = (s as NSString).length
299 let from = utf16(start)
300 guard let m = (caseFold ? folded : plain).firstMatch(in: s, options: [.withTransparentBounds, .withoutAnchoringBounds],
301 range: NSRange(location: from, length: length - from)) else { return nil }
302 return (0...groups).map { g in
303 let r = m.range(at: g)
304 return r.location == NSNotFound ? nil : character(r.location)..<character(NSMaxRange(r))
305 }
306 }
307}
308
309extension Elisp {
310 /// `case-fold-search`.
311 var caseFold: Bool { (try? value("case-fold-search")).map { !Self.isNil($0) } ?? true }
312
313 func regex(_ pattern: String) throws -> ElispRegex {
314 if let cached = regexes[pattern] { return cached }
315 let compiled = try ElispRegex(pattern)
316 regexes[pattern] = compiled
317 return compiled
318 }
319
320 /// `string-match`: the match data, or nil.
321 func stringMatch(_ pattern: String, _ s: String, start: Sexp = .nil) throws -> [Range<Int>?]? {
322 let count = s.unicodeScalars.count
323 var from = Self.isNil(start) ? 0 : try Self.int(start)
324 if from < 0 { from += count }
325 guard (0...count).contains(from) else { throw Signal(message: "Args out of range: \(Self.printed(.string(s), escape: true)), \(Self.printed(start))") }
326 return try regex(pattern).firstMatch(in: s, from: from, caseFold: caseFold)
327 }
328
329 static func substring(_ s: String, _ range: Range<Int>) throws -> String {
330 let scalars = Array(s.unicodeScalars)
331 guard range.upperBound <= scalars.count else { throw Signal(message: "Args out of range") }
332 return String(String.UnicodeScalarView(scalars[range]))
333 }
334
335 /// `replace-match` on a string, with the match data in characters of `s`.
336 func replaceMatch(_ newText: String, fixedCase: Bool, literal: Bool, in s: String, subexp: Int) throws -> String {
337 guard subexp < matchData.count, let target = matchData[subexp] else {
338 throw Signal(message: "replace-match subexpression does not exist")
339 }
340 var text = ""
341 if literal {
342 text = newText
343 } else {
344 var chars = newText.unicodeScalars.makeIterator()
345 while let c = chars.next() {
346 guard c == "\\" else {
347 text.unicodeScalars.append(c)
348 continue
349 }
350 switch chars.next() {
351 case "&": text += try Self.substring(s, matchData[0]!)
352 case "\\": text += "\\"
353 case let d? where ("1"..."9").contains(d):
354 let n = Int(d.value) - 48
355 if n < matchData.count, let r = matchData[n] { text += try Self.substring(s, r) }
356 default: throw Signal(message: "Invalid use of ‘\\’ in replacement text")
357 }
358 }
359 }
360 let old = try Self.substring(s, target)
361 if !fixedCase, !old.unicodeScalars.allSatisfy(\.isASCII) {
362 // Past ASCII, only the cases that keep the replacement's case: no letter with a
363 // case, or a lowercase letter first.
364 let first = old.unicodeScalars.first.map { $0.properties.isLowercase && $0.properties.changesWhenUppercased } ?? false
365 guard first || !old.unicodeScalars.contains(where: \.properties.changesWhenCaseMapped) else {
366 throw Unsupported(what: "replace-match case past ASCII")
367 }
368 } else if !fixedCase {
369 // How `replace-match` decides to change the replacement's case from the replaced text.
370 func isWord(_ c: Unicode.Scalar) -> Bool { c.isASCII && ElispRegex.syntax[Int(c.value)] == "w" }
371 var (multiletter, lower, nonUpperInitial, upper) = (false, false, false, false)
372 var previous: Unicode.Scalar = "\n"
373 for c in old.unicodeScalars {
374 if ("a"..."z").contains(c) {
375 lower = true
376 if isWord(previous) { multiletter = true } else { nonUpperInitial = true }
377 } else if ("A"..."Z").contains(c) {
378 upper = true
379 if isWord(previous) { multiletter = true }
380 } else if !isWord(previous), isWord(c) {
381 nonUpperInitial = true
382 }
383 previous = c
384 }
385 let allCaps = (!lower && multiletter) || (!nonUpperInitial && !multiletter && upper)
386 let initials = !allCaps && !nonUpperInitial && multiletter
387 if allCaps || initials {
388 guard text.unicodeScalars.allSatisfy(\.isASCII) else { throw Unsupported(what: "replace-match case past ASCII") }
389 if allCaps {
390 text = text.uppercased()
391 } else {
392 var result = ""
393 var previous: Unicode.Scalar = "\n"
394 for c in text.unicodeScalars {
395 result += !isWord(previous) ? String(c).uppercased() : String(c)
396 previous = c
397 }
398 text = result
399 }
400 }
401 }
402 let scalars = Array(s.unicodeScalars)
403 return String(String.UnicodeScalarView(scalars[..<target.lowerBound])) + text + String(String.UnicodeScalarView(scalars[target.upperBound...]))
404 }
405
406 static func regexFunctions(_ lisp: Elisp) {
407 lisp.set("case-fold-search", t)
408 for name in ["string-match", "string-match-p"] {
409 lisp.define(name) { lisp, args in
410 try arity(args, 2...4, name)
411 guard let data = try lisp.stringMatch(try string(args[0]), try string(args[1]), start: args.count > 2 ? args[2] : .nil) else { return .nil }
412 if name == "string-match" { lisp.matchData = data }
413 return .integer(data[0]!.lowerBound)
414 }
415 }
416 for name in ["match-beginning", "match-end"] {
417 lisp.define(name) { lisp, args in
418 try arity(args, 1...1, name)
419 let n = try int(args[0])
420 guard n >= 0 else { throw Signal(message: "Args out of range: \(n)") }
421 guard n < lisp.matchData.count, let r = lisp.matchData[n] else { return .nil }
422 return .integer(name == "match-beginning" ? r.lowerBound : r.upperBound)
423 }
424 }
425 for name in ["match-string", "match-string-no-properties"] {
426 lisp.define(name) { lisp, args in
427 try arity(args, 1...2, name)
428 guard args.count == 2, !isNil(args[1]) else { throw Unsupported(what: "\(name) in a buffer") }
429 let n = try int(args[0])
430 guard n >= 0, n < lisp.matchData.count, let r = lisp.matchData[n] else { return .nil }
431 return .string(try substring(try string(args[1]), r))
432 }
433 }
434 lisp.define("replace-match") { lisp, args in
435 try arity(args, 1...5, "replace-match")
436 guard args.count > 3, !isNil(args[3]) else { throw Unsupported(what: "replace-match in a buffer") }
437 return .string(try lisp.replaceMatch(try string(args[0]), fixedCase: args.count > 1 && !isNil(args[1]), literal: args.count > 2 && !isNil(args[2]),
438 in: try string(args[3]), subexp: args.count > 4 && !isNil(args[4]) ? try int(args[4]) : 0))
439 }
440 lisp.define("replace-regexp-in-string") { lisp, args in
441 try arity(args, 3...7, "replace-regexp-in-string")
442 func optional(_ i: Int) -> Sexp { i < args.count ? args[i] : .nil }
443 let regexp = try string(args[0])
444 let s = try string(args[2])
445 let scalars = Array(s.unicodeScalars)
446 func piece(_ r: Range<Int>) -> String { String(String.UnicodeScalarView(scalars[r])) }
447 let l = scalars.count
448 var start = isNil(optional(6)) ? 0 : try int(optional(6))
449 guard start >= 0 else { throw Unsupported(what: "replace-regexp-in-string from the end") }
450 var matches = ""
451 let saved = lisp.matchData
452 defer { lisp.matchData = saved }
453 while start < l, let data = try lisp.stringMatch(regexp, s, start: .integer(start)) {
454 lisp.matchData = data
455 let mb = data[0]!.lowerBound
456 var me = data[0]!.upperBound
457 if me == mb { me = min(l, mb + 1) }
458 lisp.matchData = data.map { $0.map { ($0.lowerBound - mb)..<($0.upperBound - mb) } }
459 let str = piece(mb..<me)
460 let rep: String
461 if case .string(let text) = args[1] {
462 rep = text
463 } else {
464 rep = try string(try lisp.call(args[1], [.string(try substring(str, lisp.matchData[0]!))]))
465 }
466 matches += piece(start..<mb)
467 matches += try lisp.replaceMatch(rep, fixedCase: !isNil(optional(3)), literal: !isNil(optional(4)), in: str,
468 subexp: isNil(optional(5)) ? 0 : try int(optional(5)))
469 start = me
470 }
471 guard start <= l else { throw Signal(message: "Args out of range") }
472 return .string(matches + piece(start..<l))
473 }
474 lisp.define("regexp-quote") { _, args in
475 try arity(args, 1...1, "regexp-quote")
476 var out = ""
477 for c in try string(args[0]).unicodeScalars {
478 if "[*.\\?+^$".unicodeScalars.contains(c) { out += "\\" }
479 out.unicodeScalars.append(c)
480 }
481 return .string(out)
482 }
483 lisp.define("split-string") { lisp, args in
484 try arity(args, 1...4, "split-string")
485 func optional(_ i: Int) -> Sexp { i < args.count ? args[i] : .nil }
486 let s = try string(args[0])
487 let length = s.unicodeScalars.count
488 let keepNulls = isNil(optional(1)) ? false : isNil(optional(2))
489 let separators = isNil(optional(1)) ? "[ \u{0C}\t\n\r\u{0B}]+" : try string(optional(1))
490 let trim = isNil(optional(3)) ? nil : try string(optional(3))
491 var list: [Sexp] = []
492 func push(_ from: Int, _ to: Int) throws {
493 var from = from
494 if let trim, let data = try lisp.stringMatch(trim, s, start: .integer(from)) {
495 lisp.matchData = data
496 if data[0]!.lowerBound == from { from = data[0]!.upperBound }
497 }
498 guard keepNulls || from < to else { return }
499 guard from <= to else { throw Signal(message: "Args out of range") }
500 var this = try substring(s, from..<to)
501 if let trim, let data = try lisp.stringMatch(trim + "\\'", this) {
502 lisp.matchData = data
503 if data[0]!.lowerBound < this.unicodeScalars.count { this = try substring(this, 0..<data[0]!.lowerBound) }
504 }
505 if keepNulls || !this.isEmpty { list.append(.string(this)) }
506 }
507 var start = 0
508 var notFirst = false
509 while true {
510 let from = notFirst && start == lisp.matchData.first??.lowerBound && start < length ? start + 1 : start
511 guard let data = try lisp.stringMatch(separators, s, start: .integer(from)) else { break }
512 lisp.matchData = data
513 guard start < length else { break }
514 notFirst = true
515 let thisStart = start
516 start = data[0]!.upperBound
517 try push(thisStart, data[0]!.lowerBound)
518 }
519 try push(start, length)
520 return Elisp.list(list)
521 }
522 }
523}