import Foundation /// `char-syntax` of each ASCII character in a syntax table. struct ElispSyntax: Equatable { let classes: [Character] /// `org-mode-syntax-table`, where table formulas run. static let org = ElispSyntax(classes: Array("......... . .................. .\".ww_w()__._._wwwwwwwwww..(_)..wwwwwwwwwwwwwwwwwwwwwwwwww(_)._.wwwwwwwwwwwwwwwwwwwwwwwwww(_)_.")) /// `lisp-interaction-mode`'s table, which `emacs -Q --batch -l` evaluates Emacs Lisp /// blocks with, in `*scratch*`. static let emacsLisp = ElispSyntax(classes: Array("_________ >_ ___________________ _\"'___'()__'___wwwwwwwwww_<_____wwwwwwwwwwwwwwwwwwwwwwwwww(\\)__'wwwwwwwwwwwwwwwwwwwwwwwwww_____")) func codes(_ syntaxClass: Character) -> [UInt32] { classes.indices.filter { classes[$0] == syntaxClass }.map(UInt32.init) } var word: [UInt32] { codes("w") } var symbol: [UInt32] { word + codes("_") } func isWord(_ c: Unicode.Scalar) -> Bool { c.isASCII && classes[Int(c.value)] == "w" } } /// An Emacs regexp as an `NSRegularExpression`, with the syntax table of the buffer it runs /// in. A construct it can't translate exactly throws `Elisp.Unsupported`, and so do subjects /// where ICU's tables could differ from Emacs's: syntax classes against text past ASCII, and /// case folding with letters past ASCII. struct ElispRegex { let pattern: String let groups: Int /// Has letters, ranges over letters or case classes: case folding changes what matches. let foldable: Bool /// Has classes whose members past ASCII come from Emacs's syntax or Unicode tables. let asciiClasses: Bool /// Has letters with case past ASCII. let nonASCIILetters: Bool let plain: NSRegularExpression let folded: NSRegularExpression static func hex(_ c: UInt32) -> String { "\\x{" + String(c, radix: 16) + "}" } static func set(_ codes: [UInt32], negated: Bool = false) -> String { "[" + (negated ? "^" : "") + codes.map(hex).joined() + "]" } /// A letter with case, which case folding changes. static func isLetter(_ c: UInt32) -> Bool { (65...90).contains(c) || (97...122).contains(c) || c > 127 && Unicode.Scalar(c).map { $0.properties.changesWhenCaseMapped || $0.properties.changesWhenCaseFolded } ?? false } init(_ pattern: String, syntax: ElispSyntax = .org) throws { self.pattern = pattern let p = Array(pattern.unicodeScalars) var out = "" var groups = 0 var open: [Int] = [] var closed: Set = [] var foldable = false var asciiClasses = false // Where `^` is an anchor, and where `*`, `+` and `?` are ordinary characters: at the // start, after `\(` or `\|`, and for the second also after that `^`. var anchor = true var ordinary = true var quantifiable = false // After a repetition, and whether a `?` may make it non-greedy. var quantified = false var lazy = false var i = 0 func unsupported(_ what: String) -> Elisp.Unsupported { Elisp.Unsupported(what: "regexp \(what) in \(Elisp.printed(.string(pattern), escape: true))") } func literal(_ c: Unicode.Scalar) { if c.isASCII, c.properties.isAlphabetic || ("0"..."9").contains(c) { out.unicodeScalars.append(c) } else { out += Self.hex(c.value) } if Self.isLetter(c.value) { foldable = true } (anchor, ordinary, quantifiable, quantified) = (false, false, true, false) } func atom(_ text: String) { out += text (anchor, ordinary, quantifiable, quantified) = (false, false, true, false) } func assertion(_ text: String) { out += text (anchor, ordinary, quantifiable, quantified) = (false, false, false, false) } while i < p.count { let c = p[i] i += 1 switch c { case "^": if anchor { out += "(?:(?= 65, c.value <= 122 || end.value > 127 { foldable = true } j += 3 continue } text += Self.hex(c.value) if Self.isLetter(c.value) { foldable = true } j += 1 } i = j atom(text + "]") case "\\": guard i < p.count else { throw unsupported("\\ at the end") } let e = p[i] i += 1 switch e { case "(": if i < p.count, p[i] == "?" { guard i + 1 < p.count, p[i + 1] == ":" else { throw unsupported("\\(?") } i += 2 out += "(?:" open.append(0) } else { groups += 1 out += "(" open.append(groups) } (anchor, ordinary, quantifiable, quantified) = (true, true, false, false) case ")": guard let n = open.popLast() else { throw unsupported("\\)") } closed.insert(n) atom(")") case "|": out += "|" (anchor, ordinary, quantifiable, quantified) = (true, true, false, false) case "{": guard quantifiable else { throw unsupported("\\{") } var low = "" var high: String? while i < p.count, ("0"..."9").contains(p[i]) { low.unicodeScalars.append(p[i]) i += 1 } if i < p.count, p[i] == "," { i += 1 var digits = "" while i < p.count, ("0"..."9").contains(p[i]) { digits.unicodeScalars.append(p[i]) i += 1 } high = digits } guard i + 1 < p.count, p[i] == "\\", p[i + 1] == "}", !low.isEmpty || high != nil else { throw unsupported("\\{") } i += 2 out += "{" + (low.isEmpty ? "0" : low) + (high.map { "," + $0 } ?? "") + "}" (quantifiable, quantified, lazy) = (false, true, false) case "1"..."9": let n = Int(e.value) - 48 guard closed.contains(n) else { throw unsupported("\\\(n)") } atom("(?:\\\(n))") case "w", "W": asciiClasses = true atom(Self.set(syntax.word, negated: e == "W")) case "s", "S": guard i < p.count else { throw unsupported("\\s") } let code: Character = switch p[i] { case "-", " ": " " case "w", "_", ".", "(", ")", "\"": Character(p[i]) default: throw unsupported("\\s\(p[i])") } i += 1 asciiClasses = true let codes = syntax.codes(code) atom(codes.isEmpty ? (e == "S" ? "[\\s\\S]" : "[^\\s\\S]") : Self.set(codes, negated: e == "S")) case "b", "B", "<", ">": asciiClasses = true let w = Self.set(syntax.word) let text = switch e { case "b": "(?:(?<=\(w))(?!\(w))|(?" else { throw unsupported("\\_") } asciiClasses = true let s = Self.set(syntax.symbol) assertion(p[i] == "<" ? "(? [Range?]? { let subjectNonASCII = s.unicodeScalars.contains { !$0.isASCII } if asciiClasses, subjectNonASCII { throw Elisp.Unsupported(what: "regexp classes on text past ASCII") } // Folding agrees for ASCII letters, unless the text has a character whose case maps // to ASCII, like the Kelvin sign or ß. if caseFold, foldable, nonASCIILetters || subjectNonASCII && s.unicodeScalars.contains(where: { c in !c.isASCII && (String(c).lowercased() + String(c).uppercased()).unicodeScalars.contains(where: \.isASCII) }) { throw Elisp.Unsupported(what: "case folding past ASCII") } // UTF-16 offset of each character, and the end. var offsets = [0] if subjectNonASCII { for scalar in s.unicodeScalars { offsets.append(offsets.last! + scalar.utf16.count) } } func utf16(_ i: Int) -> Int { subjectNonASCII ? offsets[i] : i } func character(_ u: Int) -> Int { guard subjectNonASCII else { return u } var low = 0 var high = offsets.count - 1 while low < high { let mid = (low + high) / 2 if offsets[mid] < u { low = mid + 1 } else { high = mid } } return low } let length = (s as NSString).length let from = utf16(start) guard let m = (caseFold ? folded : plain).firstMatch(in: s, options: [.withTransparentBounds, .withoutAnchoringBounds], range: NSRange(location: from, length: length - from)) else { return nil } return (0...groups).map { g in let r = m.range(at: g) return r.location == NSNotFound ? nil : character(r.location).. ElispRegex { if let cached = regexes[pattern] { return cached } let compiled = try ElispRegex(pattern, syntax: syntax) regexes[pattern] = compiled return compiled } /// `string-match`: the match data, or nil. func stringMatch(_ pattern: String, _ s: String, start: Sexp = .nil) throws -> [Range?]? { let count = s.unicodeScalars.count var from = Self.isNil(start) ? 0 : try Self.int(start) if from < 0 { from += count } guard (0...count).contains(from) else { throw Signal(message: "Args out of range: \(Self.printed(.string(s), escape: true)), \(Self.printed(start))") } return try regex(pattern).firstMatch(in: s, from: from, caseFold: caseFold) } static func substring(_ s: String, _ range: Range) throws -> String { let scalars = Array(s.unicodeScalars) guard range.upperBound <= scalars.count else { throw Signal(message: "Args out of range") } return String(String.UnicodeScalarView(scalars[range])) } /// `replace-match` on a string, with the match data in characters of `s`. func replaceMatch(_ newText: String, fixedCase: Bool, literal: Bool, in s: String, subexp: Int) throws -> String { guard subexp < matchData.count, let target = matchData[subexp] else { throw Signal(message: "replace-match subexpression does not exist") } var text = "" if literal { text = newText } else { var chars = newText.unicodeScalars.makeIterator() while let c = chars.next() { guard c == "\\" else { text.unicodeScalars.append(c) continue } switch chars.next() { case "&": text += try Self.substring(s, matchData[0]!) case "\\": text += "\\" // Kept as is, for `query-replace-regexp`. case "?": text += "\\?" case let d? where ("1"..."9").contains(d): let n = Int(d.value) - 48 if n < matchData.count, let r = matchData[n] { text += try Self.substring(s, r) } default: throw Signal(message: "Invalid use of ‘\\’ in replacement text") } } } let old = try Self.substring(s, target) if !fixedCase, !old.unicodeScalars.allSatisfy(\.isASCII) { // Past ASCII, only the cases that keep the replacement's case: no letter with a // case, or a lowercase letter first. let first = old.unicodeScalars.first.map { $0.properties.isLowercase && $0.properties.changesWhenUppercased } ?? false guard first || !old.unicodeScalars.contains(where: \.properties.changesWhenCaseMapped) else { throw Unsupported(what: "replace-match case past ASCII") } } else if !fixedCase { // How `replace-match` decides to change the replacement's case from the replaced text. let isWord = syntax.isWord var (multiletter, lower, nonUpperInitial, upper) = (false, false, false, false) var previous: Unicode.Scalar = "\n" for c in old.unicodeScalars { if ("a"..."z").contains(c) { lower = true if isWord(previous) { multiletter = true } else { nonUpperInitial = true } } else if ("A"..."Z").contains(c) { upper = true if isWord(previous) { multiletter = true } } else if !isWord(previous), isWord(c) { nonUpperInitial = true } previous = c } let allCaps = (!lower && multiletter) || (!nonUpperInitial && !multiletter && upper) let initials = !allCaps && !nonUpperInitial && multiletter if allCaps || initials { guard text.unicodeScalars.allSatisfy(\.isASCII) else { throw Unsupported(what: "replace-match case past ASCII") } if allCaps { text = text.uppercased() } else { var result = "" var previous: Unicode.Scalar = "\n" for c in text.unicodeScalars { result += !isWord(previous) ? String(c).uppercased() : String(c) previous = c } text = result } } } let scalars = Array(s.unicodeScalars) return String(String.UnicodeScalarView(scalars[.. 2 ? args[2] : .nil) else { return .nil } if name == "string-match" { lisp.matchData = data } return .integer(data[0]!.lowerBound) } } for name in ["match-beginning", "match-end"] { lisp.define(name) { lisp, args in try arity(args, 1...1, name) let n = try int(args[0]) guard n >= 0 else { throw Signal(message: "Args out of range: \(n)") } guard n < lisp.matchData.count, let r = lisp.matchData[n] else { return .nil } return .integer(name == "match-beginning" ? r.lowerBound : r.upperBound) } } for name in ["match-string", "match-string-no-properties"] { lisp.define(name) { lisp, args in try arity(args, 1...2, name) guard args.count == 2, !isNil(args[1]) else { throw Unsupported(what: "\(name) in a buffer") } let n = try int(args[0]) guard n >= 0, n < lisp.matchData.count, let r = lisp.matchData[n] else { return .nil } return .string(try substring(try string(args[1]), r)) } } lisp.define("replace-match") { lisp, args in try arity(args, 1...5, "replace-match") guard args.count > 3, !isNil(args[3]) else { throw Unsupported(what: "replace-match in a buffer") } return .string(try lisp.replaceMatch(try string(args[0]), fixedCase: args.count > 1 && !isNil(args[1]), literal: args.count > 2 && !isNil(args[2]), in: try string(args[3]), subexp: args.count > 4 && !isNil(args[4]) ? try int(args[4]) : 0)) } lisp.define("replace-regexp-in-string") { lisp, args in try arity(args, 3...7, "replace-regexp-in-string") func optional(_ i: Int) -> Sexp { i < args.count ? args[i] : .nil } let regexp = try string(args[0]) let s = try string(args[2]) let scalars = Array(s.unicodeScalars) func piece(_ r: Range) -> String { String(String.UnicodeScalarView(scalars[r])) } let l = scalars.count var start = isNil(optional(6)) ? 0 : try int(optional(6)) guard start >= 0 else { throw Unsupported(what: "replace-regexp-in-string from the end") } var matches = "" let saved = lisp.matchData defer { lisp.matchData = saved } while start < l, let data = try lisp.stringMatch(regexp, s, start: .integer(start)) { lisp.matchData = data let mb = data[0]!.lowerBound var me = data[0]!.upperBound if me == mb { me = min(l, mb + 1) } lisp.matchData = data.map { $0.map { ($0.lowerBound - mb)..<($0.upperBound - mb) } } let str = piece(mb.. Sexp { i < args.count ? args[i] : .nil } let s = try string(args[0]) let length = s.unicodeScalars.count let keepEmpty = !isNil(optional(1)) && isNil(optional(2)) let separators = isNil(optional(1)) ? "[ \u{0C}\t\n\r\u{0B}]+" : try string(optional(1)) let trim = isNil(optional(3)) ? nil : try string(optional(3)) var list: [Sexp] = [] // The loop of Emacs 31's `split-string`, empty separator matches included. func push(_ item: String, last: Bool) throws { guard let trim else { if !last || keepEmpty || !item.isEmpty { list.append(.string(item)) } return } let count = item.unicodeScalars.count var begin = 0 if let data = try lisp.stringMatch("\\`\\(?:" + trim + "\\)", item) { lisp.matchData = data begin = data[0]!.upperBound } let end = try lisp.stringMatch("\\(?:" + trim + "\\)\\'", item, start: .integer(begin))?[0]!.lowerBound ?? count let trimmed = begin > 0 || end < count ? try substring(item, begin..