Sources/OrgCore/Replace/TextReplace.swift
157 lines · 7026 bytes
10 symbols in this file
1import Foundation
2
3/// A replace across files: plain text or a regexp in the dialect of the editor's find bar and
4/// `:s` (ICU, as `NSRegularExpression` reads it, `^` and `$` at line ends), with Emacs's case
5/// rules. `case-fold-search` folds case unless the pattern has an upper-case letter
6/// (`search-upper-case`); while it folds, `case-replace` makes the replacement follow the
7/// case of each match as `replace-match` does.
8public struct TextReplace: Sendable, Equatable {
9 public var pattern: String
10 /// Literal for plain text. For a regexp, `\N` or `$N` is group N, `\&` or `$0` the whole
11 /// match, `\\` a backslash and `\$` a dollar sign.
12 public var replacement: String
13 public var isRegexp: Bool
14 /// `case-fold-search`.
15 public var caseFold: Bool
16 /// `case-replace`.
17 public var caseReplace: Bool
18
19 public init(pattern: String, replacement: String, isRegexp: Bool = false, caseFold: Bool = true, caseReplace: Bool = true) {
20 self.pattern = pattern
21 self.replacement = replacement
22 self.isRegexp = isRegexp
23 self.caseFold = caseFold
24 self.caseReplace = caseReplace
25 }
26
27 public enum InvalidPattern: Error, Equatable {
28 case empty
29 /// ICU can't compile it.
30 case invalid
31 }
32
33 /// Whether matching ignores case: `case-fold-search` on and no upper-case letter in the
34 /// pattern.
35 public var foldsCase: Bool { caseFold && !Self.hasUpperCase(pattern, regexp: isRegexp) }
36
37 /// The pattern compiled, or why it can't be.
38 public func regex() throws -> NSRegularExpression {
39 guard !pattern.isEmpty else { throw InvalidPattern.empty }
40 var options: NSRegularExpression.Options = [.anchorsMatchLines]
41 if foldsCase { options.insert(.caseInsensitive) }
42 do {
43 return try NSRegularExpression(pattern: isRegexp ? pattern : NSRegularExpression.escapedPattern(for: pattern), options: options)
44 } catch {
45 throw InvalidPattern.invalid
46 }
47 }
48
49 /// Every match in `text` outside `skipping`, as changes. `regex` is `regex()`, compiled
50 /// once for many files.
51 public func changes(in text: String, skipping: [Range<Int>] = [], regex: NSRegularExpression? = nil) throws -> [ProposedChange] {
52 let regex = try regex ?? self.regex()
53 let ns = text as NSString
54 let lines = LineStarts(ns)
55 let casifies = caseReplace && foldsCase
56 var changes: [ProposedChange] = []
57 for match in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
58 let range = match.range.location..<NSMaxRange(match.range)
59 guard !EncryptedText.overlaps(range, skipping) else { continue }
60 var new = isRegexp ? Self.expand(replacement, match: match, in: ns) : replacement
61 if casifies { new = Self.casified(new, like: ns.substring(with: match.range)) }
62 changes.append(lines.change(id: changes.count, TextEdit(range: range, replacement: new)))
63 }
64 return changes
65 }
66
67 /// `isearch-no-upper-case-p` negated: whether `pattern` has an upper-case letter, not
68 /// counting, in a regexp, a letter after a backslash or in `[:class:]` and `\p{…}`.
69 static func hasUpperCase(_ pattern: String, regexp: Bool) -> Bool {
70 guard regexp else { return pattern.contains { $0.isUppercase } }
71 var stripped = pattern.replacingOccurrences(of: "\\[:[a-z]+:\\]", with: "", options: .regularExpression)
72 stripped = stripped.replacingOccurrences(of: "\\\\[pP]\\{[^}]*\\}", with: "", options: .regularExpression)
73 var escaped = false
74 for character in stripped {
75 if escaped {
76 escaped = false
77 continue
78 }
79 if character == "\\" {
80 escaped = true
81 continue
82 }
83 if character.isUppercase { return true }
84 }
85 return false
86 }
87
88 /// `template` with the match's groups in place of `\N`, `$N`, `\&`.
89 static func expand(_ template: String, match: NSTextCheckingResult, in ns: NSString) -> String {
90 func group(_ n: Int) -> String {
91 guard n < match.numberOfRanges else { return "" }
92 let range = match.range(at: n)
93 return range.location == NSNotFound ? "" : ns.substring(with: range)
94 }
95 var result = ""
96 var characters = template[...]
97 while let c = characters.popFirst() {
98 if c == "\\" || c == "$", let next = characters.first {
99 if let digit = next.wholeNumberValue, next.isASCII {
100 characters.removeFirst()
101 result += group(digit)
102 continue
103 }
104 if c == "\\", next == "&" {
105 characters.removeFirst()
106 result += group(0)
107 continue
108 }
109 if c == "\\", next == "\\" || next == "$" {
110 characters.removeFirst()
111 result.append(next)
112 continue
113 }
114 }
115 result.append(c)
116 }
117 return result
118 }
119
120 /// `replace-match`'s case conversion: `new` in capitals when `matched` is in capitals
121 /// with a word of two or more letters (or is one capital letter), with each word's
122 /// initial capitalized when every word of `matched` starts with a capital, else as it is.
123 static func casified(_ new: String, like matched: String) -> String {
124 var someMultiletterWord = false, someLowercase = false, someUppercase = false, someNonuppercaseInitial = false
125 var previous: Character = "\n"
126 for c in matched {
127 if c.isLowercase {
128 someLowercase = true
129 if isWord(previous) { someMultiletterWord = true } else { someNonuppercaseInitial = true }
130 } else if c.isUppercase {
131 someUppercase = true
132 if isWord(previous) { someMultiletterWord = true }
133 } else if !isWord(previous), isWord(c) {
134 someNonuppercaseInitial = true
135 }
136 previous = c
137 }
138 if !someLowercase, someMultiletterWord { return new.uppercased() }
139 if !someNonuppercaseInitial, someMultiletterWord { return upcaseInitials(new) }
140 if !someNonuppercaseInitial, someUppercase { return new.uppercased() }
141 return new
142 }
143
144 /// Word constituents in Org mode's syntax table: letters and digits.
145 private static func isWord(_ c: Character) -> Bool { c.isLetter || c.isNumber }
146
147 /// `upcase-initials`: the first letter of each word in capitals, the rest as it is.
148 private static func upcaseInitials(_ text: String) -> String {
149 var result = ""
150 var previous: Character = "\n"
151 for c in text {
152 result += !isWord(previous) && c.isLetter ? c.uppercased() : String(c)
153 previous = c
154 }
155 return result
156 }
157}