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