Sources/OrgApp/RoamActions.swift
495 lines · 28384 bytes
25 symbols in this file
1import Foundation
2import OrgCore
3import OrgIndex
4
5/// The `app.dailies.` and `app.node.` commands: org-roam's daily notes, and finding and
6/// linking ID nodes, or with Denote set, denote-journal's entries and Denote's notes, with
7/// the platform's questions and file opening.
8@MainActor
9public struct RoamActions {
10 public var session: DocumentSession
11 /// The sidebar folders, the first being `org-roam-directory` unless it's set.
12 public var roots: () -> [String]
13 /// Headings and files with IDs.
14 public var nodes: () throws -> [IndexStore.Node]
15 public var show: (String) -> Void
16 public var ask: (Prompt, @escaping (String?) -> Void) -> Void
17 /// Opens a file with the caret at an offset.
18 public var open: (_ path: String, _ offset: Int) -> Void
19 /// Puts a link at the caret, in place of the selection, which describes it; without one,
20 /// the title does.
21 public var insertLink: (_ link: String, _ title: String) -> Void
22 /// The index reads new files.
23 public var refresh: () -> Void
24 /// In the Mac sandbox, asks for access to folders outside the sidebar's that new notes go
25 /// in. False when one is still out of reach.
26 public var reachFolders: ([String]) -> Bool = { _ in true }
27 /// Shows the capture window for an org-roam capture. Without it, the first template is
28 /// filed at once and its file opened there.
29 public var capture: ((RoamCapture) -> Void)?
30 /// org-roam's capture templates, from capture.toml.
31 public var templates: (RoamTemplate.Set) -> (templates: [RoamTemplate], problems: [String]) = { RoamTemplate.load($0) }
32
33 public init(
34 session: DocumentSession, roots: @escaping () -> [String], nodes: @escaping () throws -> [IndexStore.Node], show: @escaping (String) -> Void,
35 ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, open: @escaping (String, Int) -> Void,
36 insertLink: @escaping (String, String) -> Void, refresh: @escaping () -> Void
37 ) {
38 self.session = session
39 self.roots = roots
40 self.nodes = nodes
41 self.show = show
42 self.ask = ask
43 self.open = open
44 self.insertLink = insertLink
45 self.refresh = refresh
46 }
47
48 private var dailies: Dailies? { Dailies.configured(roots: roots()) }
49 private var denote: Bool { OrgPreferences.usesDenote() }
50 private var linkType: String { denote ? "denote:" : "id:" }
51
52 /// A date prompt's answer, read by `org-read-date`. Without a time, the time of day stays
53 /// now's, as `org-read-date` with `to-time` keeps it.
54 nonisolated static func date(_ answer: String, now: Date = Date()) -> Date? {
55 let read = ReadDate.read(answer, default: nil, now: now, calendar: .current)
56 guard let chosen = Calendar.current.date(from: read.components(.current)) else { return nil }
57 let time = Calendar.current.dateComponents([.hour, .minute, .second], from: now)
58 return Calendar.current.date(bySettingHour: read.timeGiven ? read.hour : time.hour!, minute: read.timeGiven ? read.minute : time.minute!,
59 second: read.timeGiven ? 0 : time.second!, of: chosen) ?? chosen
60 }
61
62 private func day(_ offset: Int, from now: Date = Date()) -> Date {
63 Calendar.current.date(byAdding: .day, value: offset, to: now) ?? now
64 }
65
66 public func run(_ id: String) {
67 switch id {
68 case "app.dailies.today": goto(day(0))
69 case "app.dailies.yesterday": goto(day(-1))
70 case "app.dailies.tomorrow": goto(day(1))
71 case "app.dailies.capture-today": capture(day(0))
72 case "app.dailies.capture-yesterday": capture(day(-1))
73 case "app.dailies.capture-tomorrow": capture(day(1))
74 case "app.dailies.date", "app.dailies.capture-date":
75 let goto = id == "app.dailies.date"
76 ask(Prompt(key: "date", message: goto ? "Find daily-note: " : "Capture to daily-note: ", date: Prompt.DateRead(defaultDate: nil))) { answer in
77 guard let answer, let date = Self.date(answer) else { return }
78 if goto { self.goto(date) } else { capture(date) }
79 }
80 case "app.dailies.next", "app.dailies.previous":
81 guard let dailies else { return show("No folder for daily notes") }
82 guard let path = session.path else { return show("Not in a daily-note") }
83 do {
84 let note = try dailies.neighbor(of: path, by: id == "app.dailies.next" ? 1 : -1)
85 open(note, 0)
86 } catch {
87 show("\(error)")
88 }
89 case "app.node.rename-from-front-matter":
90 renameFromFrontMatter()
91 case "app.node.rename":
92 renameNote()
93 case _ where id.hasPrefix("app.node.sequence-"):
94 runSequence(String(id.dropFirst("app.node.sequence-".count)))
95 case "app.node.rename-folder-from-front-matter":
96 renameFolderFromFrontMatter()
97 case "app.node.find":
98 chooseNode("Node: ") { choice in
99 switch choice {
100 case .existing(let node, _): open(node.location.path, node.location.start)
101 case .created(let path, let offset, _, _): open(path, offset)
102 }
103 }
104 case "app.node.find-ref":
105 findRef()
106 case "app.node.silo-find", "app.node.silo-create":
107 // denote-silo: a folder of `denote-silo-directories` in place of `denote-directory`.
108 let silos = DenoteNote.silos(roots: roots())
109 guard !silos.isEmpty else { return show("No folder for new notes") }
110 ask(Prompt(key: "silo", message: "Select a silo: ", choices: silos.map(DenoteNote.abbreviated))) { answer in
111 guard let answer, let silo = silos.first(where: { DenoteNote.abbreviated($0) == answer }) else { return }
112 let opened: (NodeChoice) -> Void = { choice in
113 switch choice {
114 case .existing(let node, _): open(node.location.path, node.location.start)
115 case .created(let path, _, _, _): open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
116 }
117 }
118 guard id == "app.node.silo-create" else { return chooseNode("Node: ", silo: silo, opened) }
119 ask(Prompt(key: "title", message: "New file TITLE: ", requireMatch: false)) { title in
120 guard let title = title?.trimmingCharacters(in: .whitespaces) else { return }
121 do { createDenote(title, known: try nodes(), silo: silo, opened) } catch { show(error.localizedDescription) }
122 }
123 }
124 case "app.node.insert":
125 // An `id:` link is org syntax; only Denote's links go in its Markdown and text notes.
126 if !denote, let path = session.path, !DocumentSession.isOrgPath(path) { return show("Not an org file") }
127 chooseNode("Node: ") { choice in
128 switch choice {
129 case .existing(let node, let title): insertLink(linkType + node.id, title)
130 case .created(_, _, let id, let title): insertLink(linkType + id, title)
131 }
132 }
133 default:
134 show("Unknown command \(id)")
135 }
136 }
137
138 /// The daily-note templates: `[[roam-dailies-template]]`, or one from the
139 /// `org-roam-dailies-…` settings; for a Denote journal, one for the day's entry.
140 private func dailyTemplates(_ dailies: Dailies, _ day: Date) -> [RoamTemplate] {
141 if dailies.journal != nil {
142 return [RoamTemplate(key: "d", name: "default", kind: .entry, template: dailies.entry, file: dailies.path(for: day), head: dailies.newText(day, id: ""))]
143 }
144 let (templates, problems) = self.templates(.dailies)
145 if let problem = problems.first { show(problem) }
146 return templates
147 }
148
149 /// `org-roam-dailies-goto-*`: the day's file, made if missing. With templates aimed at
150 /// different files, asks which.
151 func goto(_ day: Date) {
152 guard let dailies else { return show("No folder for daily notes") }
153 guard reachFolders([dailies.directory]) else { return }
154 let templates = dailyTemplates(dailies, day)
155 func go(_ template: RoamTemplate) {
156 var dailies = dailies
157 if dailies.journal == nil {
158 dailies.file = template.file
159 dailies.head = template.head
160 }
161 do {
162 let (path, created) = try dailies.ensure(day)
163 if created { refresh() }
164 open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
165 } catch {
166 show("Can't make the daily note: \(error.localizedDescription)")
167 }
168 }
169 guard Set(templates.map(\.file)).count > 1 else { return go(templates[0]) }
170 chooseTemplate(templates) { go($0) }
171 }
172
173 /// `org-capture`'s template menu, for a command that files nothing.
174 private func chooseTemplate(_ templates: [RoamTemplate], _ then: @escaping (RoamTemplate) -> Void) {
175 let labels = templates.map { "[\($0.key)] \($0.name)" }
176 ask(Prompt(key: "template", message: "Template: ", choices: labels)) { answer in
177 guard let answer, let index = labels.firstIndex(of: answer) else { return }
178 then(templates[index])
179 }
180 }
181
182 /// `org-roam-dailies-capture-*`: the capture window with the daily-note templates; the
183 /// entry goes at the end of the day's file, made with its head when it's new.
184 func capture(_ day: Date) {
185 guard let dailies else { return show("No folder for daily notes") }
186 guard reachFolders([dailies.directory]) else { return }
187 start(RoamCapture(dailyTemplates(dailies, day), title: "", directory: dailies.directory, now: day, ids: dailies.journal == nil,
188 session: session, refresh: refresh) { _, _, _ in })
189 }
190
191 /// Shows the capture window, or without one, files the first template at once and opens
192 /// what it filed.
193 func start(_ roam: RoamCapture) {
194 if let capture { return capture(roam) }
195 switch roam.fileFirst() {
196 case .success(let entry): open(entry.path, entry.offset)
197 case .failure(let error): show(error.message)
198 }
199 }
200
201 enum NodeChoice {
202 /// A node, by the title or alias chosen.
203 case existing(IndexStore.Node, title: String)
204 /// A new node, with where its text went.
205 case created(path: String, offset: Int, id: String, title: String)
206 }
207
208 /// `org-roam-node-read--completions`: a candidate for each node's title and each of its
209 /// aliases, with its file's name when names repeat, and its tags after it as Doom's
210 /// `org-roam-node-display-template` shows them.
211 nonisolated static func candidates(_ nodes: [IndexStore.Node]) -> [(label: String, node: IndexStore.Node, title: String)] {
212 let names = nodes.flatMap { node in ([node.title] + node.aliases).map { (node: node, name: $0) } }
213 let counts = Dictionary(names.map { ($0.name, 1) }, uniquingKeysWith: +)
214 return names.map { node, name in
215 var label = counts[name, default: 0] > 1 ? "\(name) (\((node.location.path as NSString).lastPathComponent))" : name
216 if !node.tags.isEmpty { label += " " + node.tags.map { "#" + $0 }.joined(separator: " ") }
217 return (label, node, name)
218 }
219 }
220
221 /// `org-roam-node-read`: a node by its title or an alias. A title no node has goes to the
222 /// capture window with `[[roam-template]]`'s templates, as `org-roam-capture-` does, and
223 /// once filed makes the node; with Denote, `denote` asks for its keywords and makes the note.
224 private func chooseNode(_ message: String, silo: String? = nil, _ then: @escaping (NodeChoice) -> Void) {
225 let known: [IndexStore.Node]
226 do { known = try nodes() } catch { return show(error.localizedDescription) }
227 let all = silo.map { silo in known.filter { $0.location.path.hasPrefix(silo.hasSuffix("/") ? silo : silo + "/") } } ?? known
228 let candidates = Self.candidates(all)
229 ask(Prompt(key: "node", message: message, choices: candidates.map(\.label), requireMatch: false)) { answer in
230 guard let answer else { return }
231 if let chosen = candidates.first(where: { $0.label == answer }) ?? candidates.first(where: { $0.title == answer }) {
232 return then(.existing(chosen.node, title: chosen.title))
233 }
234 let title = answer.trimmingCharacters(in: .whitespaces)
235 guard !title.isEmpty else { return }
236 if denote || silo != nil { return createDenote(title, known: all, silo: silo, then) }
237 guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") }
238 guard reachFolders([folder]) else { return }
239 let (templates, problems) = self.templates(.node)
240 if let problem = problems.first { show(problem) }
241 start(RoamCapture(templates, title: title, directory: folder, session: session, refresh: refresh) { path, offset, id in
242 then(.created(path: path, offset: offset, id: id, title: title))
243 })
244 }
245 }
246
247 /// `org-roam-ref-find`: a node by one of its `ROAM_REFS`, shown with its title.
248 private func findRef() {
249 let known: [IndexStore.Node]
250 do { known = try nodes() } catch { return show(error.localizedDescription) }
251 let refs = known.flatMap { node in node.refs.map { (label: "\($0) \(node.title)", node: node) } }
252 guard !refs.isEmpty else { return show("No node has refs") }
253 ask(Prompt(key: "ref", message: "Ref: ", choices: refs.map(\.label))) { answer in
254 guard let answer, let chosen = refs.first(where: { $0.label == answer }) else { return }
255 open(chosen.node.location.path, chosen.node.location.start)
256 }
257 }
258
259 /// org-roam-protocol's `roam-ref`: the node with the ref, else the capture window with
260 /// `[[roam-ref-template]]`'s templates (only the one keyed `template` when given) for a new
261 /// node with the ref in its `ROAM_REFS`; and `roam-node`: the node with the ID.
262 public func follow(_ request: OrgProtocol.Request) {
263 let known: [IndexStore.Node]
264 do { known = try nodes() } catch { return show(error.localizedDescription) }
265 switch request {
266 case .roamNode(let id):
267 guard let node = known.first(where: { $0.id == id }) else { return show("No node has the ID \(id)") }
268 open(node.location.path, node.location.start)
269 case .roamRef(let ref, let title, let body, let key):
270 if let node = known.first(where: { $0.refs.contains(ref) }) { return open(node.location.path, node.location.start) }
271 guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") }
272 guard reachFolders([folder]) else { return }
273 let (all, problems) = self.templates(.ref)
274 if let problem = problems.first { show(problem) }
275 let templates = key.map { key in all.filter { $0.key == key } } ?? all
276 guard !templates.isEmpty else { return show("No roam-ref template \"\(key ?? "")\"") }
277 let quoted = ref.contains(where: \.isWhitespace) ? "\"" + ref.replacingOccurrences(of: "\"", with: "\\\"") + "\"" : ref
278 start(RoamCapture(templates, title: title ?? ref, directory: folder, fields: ["ref": ref, "body": body ?? ""], properties: [("ROAM_REFS", quoted)],
279 session: session, refresh: refresh) { path, offset, _ in open(path, offset) })
280 default:
281 break
282 }
283 }
284
285 /// What a new Denote note's questions give.
286 struct DenoteAnswers {
287 var keywords: [String] = []
288 var folder: String?
289 var date: Date?
290 var template = ""
291 var signature = ""
292 }
293
294 /// `denote`: after the title, the questions `denote-prompts` lists, in its order, then the
295 /// note in `denote-directory` or the folder chosen under it.
296 /// In a silo, its folder takes the place of `denote-directory`.
297 /// With `signature`, as `denote-use-signature` sets it: that signature, not asked for.
298 func createDenote(_ title: String, known: [IndexStore.Node], silo: String? = nil, signature: String? = nil, _ then: @escaping (NodeChoice) -> Void) {
299 let folders = silo.map { [$0] } ?? DenoteNote.directories(roots: roots())
300 guard !folders.isEmpty else { return show("No folder for new notes") }
301 var answers = DenoteAnswers()
302 if let signature { answers.signature = signature }
303 createDenote(title, roots: folders, prompts: OrgPreferences.denotePrompts().filter { signature == nil || $0 != "signature" },
304 templates: UserConfig.denoteTemplates(.standard), keywords: Denote.keywords(known.flatMap { Denote.name(ofFile: $0.location.path).keywords }),
305 answers: answers, then)
306 }
307
308 /// The note goes in the first of `roots`, or the folder the `subdirectory` question picks
309 /// among them and their folders.
310 func createDenote(
311 _ title: String, roots: [String], prompts: [String], templates: [(key: String, text: String)], keywords: [String],
312 answers: DenoteAnswers = DenoteAnswers(), _ then: @escaping (NodeChoice) -> Void
313 ) {
314 let root = roots[0]
315 func next(_ answers: DenoteAnswers) {
316 createDenote(title, roots: roots, prompts: Array(prompts.dropFirst()), templates: templates, keywords: keywords, answers: answers, then)
317 }
318 var answers = answers
319 switch prompts.first {
320 case nil:
321 guard reachFolders([answers.folder ?? root]) else { return }
322 do {
323 let note = try DenoteNote.create(title: title, keywords: answers.keywords, in: answers.folder ?? root, roots: roots,
324 now: answers.date ?? Date(), signature: answers.signature, template: answers.template,
325 type: OrgPreferences.denoteFileType())
326 refresh()
327 show("Created \((note.path as NSString).lastPathComponent)")
328 then(.created(path: note.path, offset: (session.text(of: note.path).map { ($0 as NSString).length }) ?? 0, id: note.id, title: title))
329 } catch {
330 show("Can't make the note: \(error)")
331 }
332 case "keywords":
333 // Separated by commas or spaces; the keywords already in file names are offered.
334 ask(Prompt(key: "keywords", message: "New file KEYWORDS: ", choices: keywords, requireMatch: false)) { answer in
335 guard let answer else { return }
336 answers.keywords = answer.split(whereSeparator: { $0 == "," || $0.isWhitespace }).map(String.init)
337 next(answers)
338 }
339 case "subdirectory":
340 let folders = DenoteNote.folderChoices(roots)
341 guard folders.count > 1 else { return next(answers) }
342 ask(Prompt(key: "subdirectory", message: "Select SUBDIRECTORY: ", choices: folders.map(\.label))) { answer in
343 guard let answer else { return }
344 answers.folder = folders.first { $0.label == answer }?.path ?? root
345 next(answers)
346 }
347 case "date":
348 ask(Prompt(key: "date", message: "DATE and TIME for note: ", date: Prompt.DateRead(defaultDate: nil))) { answer in
349 guard let answer else { return }
350 answers.date = Self.date(answer)
351 next(answers)
352 }
353 case "template":
354 guard !templates.isEmpty else { return next(answers) }
355 ask(Prompt(key: "template", message: "Select TEMPLATE key: ", choices: templates.map(\.key))) { answer in
356 guard let answer else { return }
357 answers.template = templates.first { $0.key == answer }?.text ?? ""
358 next(answers)
359 }
360 case "signature":
361 ask(Prompt(key: "signature", message: "New file SIGNATURE: ", requireMatch: false)) { answer in
362 guard let answer else { return }
363 answers.signature = answer
364 next(answers)
365 }
366 default:
367 // The title is asked first anyway; Org is the only file type; the rest have no equal.
368 next(answers)
369 }
370 }
371
372 /// `denote-rename-file-using-front-matter`: the open file renamed from its title,
373 /// keywords and signature, keeping its identifier, and its front matter rewritten from them.
374 func renameFromFrontMatter() {
375 guard let path = session.path else { return show("No file is open") }
376 guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
377 guard let (target, rewritten) = Denote.renamed(path, text: text) else { return show("Not a Denote note: no front matter or identifier") }
378 guard target != path || rewritten != text else { return show("Nothing to rename") }
379 if rewritten != text, case .failed(let message) = session.perform(ReplaceText(old: text, new: rewritten), path: path, at: 0, expect: nil) { return show(message) }
380 guard target != path else { return show("Front matter rewritten") }
381 rename(path, to: target)
382 }
383
384 /// Saves `path`, moves it to `target` and opens it there.
385 func rename(_ path: String, to target: String) {
386 guard !FileManager.default.fileExists(atPath: target) else { return show("\((target as NSString).lastPathComponent) is already there") }
387 do {
388 try move(path, to: target)
389 refresh()
390 open(target, 0)
391 show("Renamed to \((target as NSString).lastPathComponent)")
392 } catch {
393 show("Can't rename: \(error)")
394 }
395 }
396
397 /// Moves a file, saving it first and closing it when it's open.
398 func move(_ path: String, to target: String) throws {
399 if session.openPaths.contains(path) {
400 guard session.save(path) else { throw Dailies.Failure("Can't save \((path as NSString).lastPathComponent)") }
401 }
402 try FileManager.default.moveItem(atPath: path, toPath: target)
403 if session.openPaths.contains(path) { session.kill(path) }
404 }
405
406 /// `denote-rename-file`: the open file's title, keywords, signature and date, as
407 /// `denote-prompts` asks for them, each starting with the current value, then the file
408 /// renamed in its folder and its front matter rewritten. A file without an identifier
409 /// gets one from its modification time; one without front matter gets it at the top.
410 func renameNote() {
411 guard let path = session.path else { return show("No file is open") }
412 guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
413 let name = Denote.name(ofFile: path), type = Denote.FileType(path: path, text: text) ?? .org, front = Denote.frontMatter(of: text, type: type)
414 var title = front.title ?? name.title?.replacingOccurrences(of: "-", with: " ") ?? ""
415 var keywords = front.keywords ?? name.keywords
416 var signature = name.signature ?? front.signature ?? ""
417 var date: Date?
418 let file = (path as NSString).lastPathComponent
419 func ask(_ prompts: ArraySlice<String>) {
420 switch prompts.first {
421 case nil: finish()
422 case "title":
423 self.ask(Prompt(key: "title", message: "Rename \(file) with TITLE (empty to remove): ", initial: title, requireMatch: false)) { answer in
424 guard let answer else { return }
425 title = answer
426 ask(prompts.dropFirst())
427 }
428 case "keywords":
429 self.ask(Prompt(key: "keywords", message: "Rename \(file) with KEYWORDS (empty to remove): ", initial: keywords.joined(separator: ","), requireMatch: false)) { answer in
430 guard let answer else { return }
431 keywords = answer.split(whereSeparator: { $0 == "," || $0.isWhitespace }).map(String.init)
432 ask(prompts.dropFirst())
433 }
434 case "signature":
435 self.ask(Prompt(key: "signature", message: "Rename \(file) with SIGNATURE (empty to remove): ", initial: signature, requireMatch: false)) { answer in
436 guard let answer else { return }
437 signature = answer
438 ask(prompts.dropFirst())
439 }
440 case "date":
441 self.ask(Prompt(key: "date", message: "Rename \(file) with DATE: ", date: Prompt.DateRead(defaultDate: Denote.date(of: text, type: type)))) { answer in
442 guard let answer else { return }
443 date = answer.isEmpty ? nil : Self.date(answer)
444 ask(prompts.dropFirst())
445 }
446 default: ask(prompts.dropFirst())
447 }
448 }
449 func finish() {
450 let (target, rewritten) = DenoteNote.renaming(path, text: text, title: title, keywords: keywords, signature: signature, date: date,
451 roots: DenoteNote.directories(roots: roots()), preferred: OrgPreferences.denoteFileType())
452 guard target != path || rewritten != text else { return show("Nothing to rename") }
453 if rewritten != text, case .failed(let message) = session.perform(ReplaceText(old: text, new: rewritten), path: path, at: 0, expect: nil) { return show(message) }
454 guard target != path else { return show("Front matter rewritten") }
455 rename(path, to: target)
456 }
457 ask(ArraySlice(OrgPreferences.denotePrompts()))
458 }
459
460 /// `denote-dired-rename-marked-files-using-front-matter`, with every Denote note in a
461 /// folder of `denote-directory` marked: each renamed from its front matter, which is
462 /// rewritten from the values read.
463 func renameFolderFromFrontMatter() {
464 let folders = DenoteNote.folderChoices(DenoteNote.directories(roots: roots()))
465 guard !folders.isEmpty else { return show("No folder for notes") }
466 ask(Prompt(key: "folder", message: "Rename notes in: ", choices: folders.map(\.label))) { answer in
467 guard let answer, let folder = folders.first(where: { $0.label == answer })?.path else { return }
468 let shown = session.path
469 var renamed = 0, problems: [String] = []
470 for name in ((try? FileManager.default.contentsOfDirectory(atPath: folder)) ?? []).sorted() where Denote.identifier(ofFile: name) != nil {
471 let path = (folder as NSString).appendingPathComponent(name)
472 guard let text = session.text(of: path) ?? (try? String(contentsOfFile: path, encoding: .utf8)),
473 let (target, rewritten) = Denote.renamed(path, text: text), target != path || rewritten != text else { continue }
474 guard target == path || !FileManager.default.fileExists(atPath: target) else { problems.append("\((target as NSString).lastPathComponent) is already there"); continue }
475 do {
476 if rewritten != text {
477 if session.openPaths.contains(path) {
478 if case .failed(let message) = session.perform(ReplaceText(old: text, new: rewritten), path: path, at: 0, expect: nil) { throw Dailies.Failure(message) }
479 } else {
480 try rewritten.write(toFile: path, atomically: true, encoding: .utf8)
481 }
482 }
483 guard target != path else { continue }
484 try move(path, to: target)
485 renamed += 1
486 if shown == path { open(target, 0) }
487 } catch {
488 problems.append("\(error)")
489 }
490 }
491 refresh()
492 show(([renamed == 1 ? "Renamed 1 note" : "Renamed \(renamed) notes"] + problems).joined(separator: "; "))
493 }
494 }
495}