Sources/OrgApp/ReplaceInFiles.swift
341 lines · 16228 bytes
1import Foundation
2import Observation
3import OrgCore
4import OrgDocument
5
6/// Replace in Files, Rename Tag and Rename TODO Keyword: a search of the files of one folder or
7/// all folders, off the main actor and cancellable, whose changes are listed by file and line
8/// to untick, then applied as one change per file through `DocumentSession.applyChanges`.
9/// Open buffers are searched as they are, unsaved edits included. Encrypted files (`.gpg`) and
10/// org-crypt's encrypted entries are left out.
11@MainActor
12@Observable
13public final class ReplaceInFiles {
14 public enum Mode: Sendable, Equatable {
15 case replace(TextReplace)
16 case renameTag(from: String, to: String)
17 case renameKeyword(from: String, to: String)
18 }
19
20 /// `org-todo-keywords` and `org-tag-alist` in config.toml, and how to change one by its
21 /// user-defaults key.
22 public struct Config {
23 public var todoKeywords: String
24 public var tagAlist: String
25 public var set: @MainActor (_ defaultsKey: String, _ value: String) -> Void
26
27 public init(todoKeywords: String, tagAlist: String, set: @escaping @MainActor (String, String) -> Void) {
28 self.todoKeywords = todoKeywords
29 self.tagAlist = tagAlist
30 self.set = set
31 }
32
33 /// From user defaults; on the Mac, a change there is written into config.toml.
34 public static var standard: Config {
35 let defaults = UserDefaults.standard
36 return Config(todoKeywords: defaults.string(forKey: "todoKeywords") ?? OrgPreferences.defaultTodoKeywords,
37 tagAlist: defaults.string(forKey: "tagAlist") ?? "") { key, value in defaults.set(value, forKey: key) }
38 }
39 }
40
41 /// The changes found in one file.
42 public struct FileChanges: Identifiable, Sendable {
43 public let path: String
44 /// The path below its folder.
45 public let relativePath: String
46 public let changes: [ProposedChange]
47 /// The text the changes were found in.
48 let text: String
49 /// Changes left out, by id.
50 public var unticked: Set<Int> = []
51 public var id: String { path }
52 public var name: String { (path as NSString).lastPathComponent }
53 public var isIncluded: Bool { unticked.count < changes.count }
54 }
55
56 /// A setting of config.toml the rename changes too, if the user agrees.
57 public struct ConfigChange: Equatable, Sendable {
58 /// Its name in config.toml.
59 public let key: String
60 let defaultsKey: String
61 public let old: String
62 public let new: String
63 }
64
65 public private(set) var mode: Mode?
66 public private(set) var files: [FileChanges] = []
67 public private(set) var configChange: ConfigChange?
68 /// Apply also changes config.toml.
69 public var changesConfig = true
70 /// Files searched so far, of how many.
71 public private(set) var progress: (done: Int, total: Int) = (0, 0)
72 public private(set) var isSearching = false
73 public private(set) var wasCancelled = false
74 /// Why there is nothing to apply: a pattern that doesn't compile, a refused rename.
75 public private(set) var problem: String?
76
77 private let session: DocumentSession
78 private let workspace: WorkspaceModel
79 @ObservationIgnored private var config: Config
80 @ObservationIgnored private var task: Task<Void, Never>?
81 @ObservationIgnored private var generation = 0
82
83 public init(session: DocumentSession, workspace: WorkspaceModel, config: Config = .standard) {
84 self.session = session
85 self.workspace = workspace
86 self.config = config
87 }
88
89 public var changeCount: Int { files.reduce(0) { $0 + $1.changes.count } }
90 public var tickedCount: Int { files.reduce(0) { $0 + $1.changes.count - $1.unticked.count } }
91
92 /// Extensions searched besides org files, by Replace in Files.
93 static let textExtensions: Set<String> = ["txt", "md", "markdown"]
94
95 /// Searches the files of the folder `scope` (a root's path), or of every folder. A rename
96 /// with `includeConfig` also renames in config.toml. Cancels a search that is running.
97 public func start(_ mode: Mode, scope: String?, includeConfig: Bool = true, cryptTag: String = OrgPreferences.cryptTag()) {
98 task?.cancel()
99 generation += 1
100 self.mode = mode
101 files = []
102 configChange = nil
103 problem = nil
104 wasCancelled = false
105 changesConfig = includeConfig
106 isSearching = false
107 progress = (0, 0)
108
109 var regex: NSRegularExpression?
110 switch mode {
111 case .replace(let query):
112 do {
113 regex = try query.regex()
114 } catch TextReplace.InvalidPattern.empty {
115 return problem = String(localized: "Nothing to search for", comment: "Replace in Files: the search field is empty")
116 } catch {
117 return problem = String(localized: "Not a regular expression: \(query.pattern)", comment: "Replace in Files")
118 }
119 case .renameTag(let old, let new):
120 if let refusal = Self.refusal(old, new, valid: TagRename.isValidName, kind: .tag) { return problem = refusal }
121 if let renamed = TagRename.renamedTagAlist(config.tagAlist, from: old, to: new) {
122 configChange = ConfigChange(key: "org-tag-alist", defaultsKey: "tagAlist", old: config.tagAlist, new: renamed)
123 }
124 case .renameKeyword(let old, let new):
125 if let refusal = Self.refusal(old, new, valid: KeywordRename.isValidName, kind: .keyword) { return problem = refusal }
126 let settings = OrgSettings.default.withTodoKeywords(config.todoKeywords) ?? .default
127 if KeywordRename.crossesStates(settings, from: old, to: new) {
128 return problem = Self.crossing(old, new, settings, in: "config.toml")
129 }
130 if let renamed = KeywordRename.renamedTodoKeywords(config.todoKeywords, from: old, to: new) {
131 configChange = ConfigChange(key: "org-todo-keywords", defaultsKey: "todoKeywords", old: config.todoKeywords, new: renamed)
132 }
133 }
134
135 let entries = workspace.files.filter { entry in
136 guard scope == nil || entry.root == scope, !EncryptedText.isEncryptedFile(entry.path) else { return false }
137 switch entry.kind {
138 case .org, .archive: return true
139 case .other:
140 if case .replace = mode { return Self.textExtensions.contains((entry.path as NSString).pathExtension.lowercased()) }
141 return false
142 case .conflict: return false
143 }
144 }
145 // Open buffers as they are; the rest is read from disk off the main actor.
146 var open: [String: String?] = [:]
147 for entry in entries {
148 if let document = session.document(of: entry.path) { open[entry.path] = document.isEditable ? document.text : nil }
149 }
150 let job = Job(mode: mode, regex: regex, options: session.options, defaults: session.defaults, cryptTag: cryptTag,
151 configRenamed: includeConfig && configChange != nil, scope: Set(entries.map(\.path)))
152 let generation = generation
153 let list = entries.map { ($0.path, $0.relativePath) }
154 progress = (0, list.count)
155 isSearching = true
156 task = Task.detached(priority: .userInitiated) { [weak self] in
157 var found: [FileChanges] = []
158 var refusal: String?
159 for (index, (path, relative)) in list.enumerated() {
160 if Task.isCancelled { break }
161 let text: String?
162 if let buffered = open[path] {
163 text = buffered
164 } else {
165 text = (try? Data(contentsOf: URL(fileURLWithPath: path))).flatMap { data in
166 let source = SourceText(bytes: [UInt8](data))
167 return source.isEditable ? source.text : nil
168 }
169 }
170 if let text {
171 switch job.changes(in: text, path: path) {
172 case .success(let changes):
173 if !changes.isEmpty { found.append(FileChanges(path: path, relativePath: relative, changes: changes, text: text)) }
174 case .failure(let reason):
175 refusal = reason.message
176 }
177 }
178 if refusal != nil { break }
179 if index % 16 == 15 || index == list.count - 1 {
180 let done = index + 1
181 await MainActor.run { self?.reportProgress(done, generation: generation) }
182 }
183 }
184 let cancelled = Task.isCancelled
185 await MainActor.run { [found, refusal] in self?.finish(found, refusal: refusal, cancelled: cancelled, generation: generation) }
186 }
187 }
188
189 /// Waits for the running search, for tests.
190 public func waitForSearch() async {
191 await task?.value
192 }
193
194 /// Stops the search; what it found so far stays listed.
195 public func cancel() {
196 guard isSearching else { return }
197 task?.cancel()
198 wasCancelled = true
199 }
200
201 private func reportProgress(_ done: Int, generation: Int) {
202 guard generation == self.generation else { return }
203 progress.done = done
204 }
205
206 private func finish(_ found: [FileChanges], refusal: String?, cancelled: Bool, generation: Int) {
207 guard generation == self.generation else { return }
208 isSearching = false
209 if cancelled { wasCancelled = true }
210 if let refusal {
211 problem = refusal
212 files = []
213 configChange = nil
214 return
215 }
216 files = found.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending }
217 }
218
219 // MARK: - Choosing
220
221 public func isTicked(_ change: Int, in path: String) -> Bool {
222 files.first { $0.path == path }.map { !$0.unticked.contains(change) } ?? false
223 }
224
225 public func setTicked(_ on: Bool, change: Int, in path: String) {
226 guard let index = files.firstIndex(where: { $0.path == path }) else { return }
227 if on { files[index].unticked.remove(change) } else { files[index].unticked.insert(change) }
228 }
229
230 /// Ticks or unticks every change in a file.
231 public func setTicked(_ on: Bool, file path: String) {
232 guard let index = files.firstIndex(where: { $0.path == path }) else { return }
233 files[index].unticked = on ? [] : Set(files[index].changes.map(\.id))
234 }
235
236 // MARK: - Applying
237
238 /// Applies the ticked changes, one change per file, and config.toml's when `changesConfig`.
239 /// Returns what happened, for the echo area.
240 @discardableResult
241 public func apply(now: Date = Date()) -> String {
242 var changed = 0
243 var problems: [String] = []
244 for file in files where file.isIncluded {
245 let edits = file.changes.filter { !file.unticked.contains($0.id) }.map(\.edit)
246 if let problem = session.applyChanges(edits, to: file.path, expecting: file.text, now: now) {
247 problems.append(problem)
248 } else {
249 changed += 1
250 }
251 }
252 if let configChange, changesConfig {
253 config.set(configChange.defaultsKey, configChange.new)
254 config = Config(todoKeywords: configChange.defaultsKey == "todoKeywords" ? configChange.new : config.todoKeywords,
255 tagAlist: configChange.defaultsKey == "tagAlist" ? configChange.new : config.tagAlist, set: config.set)
256 }
257 let appliedConfig = configChange != nil && changesConfig
258 files = []
259 configChange = nil
260 var summary = String(localized: "Files changed: \(changed)", comment: "Replace in Files: after applying")
261 if appliedConfig { summary += "; " + String(localized: "config.toml changed", comment: "Replace in Files: after applying") }
262 return ([summary] + problems).joined(separator: "; ")
263 }
264
265 // MARK: - Refusals
266
267 enum NameKind { case tag, keyword }
268
269 private static func refusal(_ old: String, _ new: String, valid: (String) -> Bool, kind: NameKind) -> String? {
270 if old.isEmpty || new.isEmpty { return String(localized: "Give the old and the new name.", comment: "Rename Tag or TODO Keyword") }
271 if old == new { return String(localized: "The new name is the old one.", comment: "Rename Tag or TODO Keyword") }
272 guard valid(new) else {
273 return switch kind {
274 case .tag: String(localized: "\(new) can't be a tag: a tag is letters, digits, _, @, # and %.", comment: "Rename Tag")
275 case .keyword: String(localized: "\(new) can't be a TODO keyword: it has a space, a bar or a parenthesis.", comment: "Rename TODO Keyword")
276 }
277 }
278 return nil
279 }
280
281 nonisolated static func crossing(_ old: String, _ new: String, _ settings: OrgSettings, in place: String) -> String {
282 settings.isDone(old)
283 ? String(localized: "Can't rename \(old) to \(new): in \(place), \(old) is a done state and \(new) isn't.", comment: "Rename TODO Keyword: refused")
284 : String(localized: "Can't rename \(old) to \(new): in \(place), \(new) is a done state and \(old) isn't.", comment: "Rename TODO Keyword: refused")
285 }
286
287 // MARK: - The search
288
289 struct Refusal: Error {
290 let message: String
291 }
292
293 /// What a search looks for, with what it needs to look off the main actor.
294 struct Job: Sendable {
295 let mode: Mode
296 let regex: NSRegularExpression?
297 let options: EditingOptions
298 let defaults: OrgSettings
299 let cryptTag: String
300 /// config.toml's `org-todo-keywords` is renamed too.
301 let configRenamed: Bool
302 /// Every file searched.
303 let scope: Set<String>
304
305 func changes(in text: String, path: String) -> Result<[ProposedChange], Refusal> {
306 let skipping = EncryptedText.ranges(in: text, tag: cryptTag)
307 switch mode {
308 case .replace(let query):
309 return .success((try? query.changes(in: text, skipping: skipping, regex: regex)) ?? [])
310 case .renameTag(let old, let new):
311 guard Self.isOrg(path), text.contains(old) else { return .success([]) }
312 let tree = OrgParser.parse(text, defaults: defaults.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
313 return .success(TagRename.changes(in: text, tree: tree, from: old, to: new, options: options, skipping: skipping))
314 case .renameKeyword(let old, let new):
315 guard Self.isOrg(path), text.contains(old) else { return .success([]) }
316 var setupFiles: [String] = []
317 let settings = defaults.resolvingSetupFiles(in: text, path: path) { file in
318 setupFiles.append(file)
319 return OrgSettings.readFile(file)
320 }
321 let tree = OrgParser.parse(text, defaults: settings)
322 if KeywordRename.crossesStates(tree.settings, from: old, to: new) {
323 return .failure(Refusal(message: ReplaceInFiles.crossing(old, new, tree.settings, in: (path as NSString).lastPathComponent)))
324 }
325 // Headings change where the keyword they get will be one: where the file's own
326 // lines name it, or setup files also searched, or config.toml when it changes.
327 let headings = switch KeywordRename.source(of: old, in: tree) {
328 case .file: true
329 case .setupFile: setupFiles.allSatisfy { scope.contains(($0 as NSString).standardizingPath) || scope.contains($0) }
330 case .defaults: configRenamed
331 case .none: false
332 }
333 return .success(KeywordRename.changes(in: text, tree: tree, from: old, to: new, headings: headings, options: options, skipping: skipping))
334 }
335 }
336
337 static func isOrg(_ path: String) -> Bool {
338 path.hasSuffix(".org") || path.hasSuffix(".org_archive")
339 }
340 }
341}