Sources/OrgApp/RoamActions.swift
413 lines · 22763 bytes
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
28 public init(
29 session: DocumentSession, roots: @escaping () -> [String], nodes: @escaping () throws -> [IndexStore.Node], show: @escaping (String) -> Void,
30 ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, open: @escaping (String, Int) -> Void,
31 insertLink: @escaping (String, String) -> Void, refresh: @escaping () -> Void
32 ) {
33 self.session = session
34 self.roots = roots
35 self.nodes = nodes
36 self.show = show
37 self.ask = ask
38 self.open = open
39 self.insertLink = insertLink
40 self.refresh = refresh
41 }
42
43 private var dailies: Dailies? { Dailies.configured(roots: roots()) }
44 private var denote: Bool { OrgPreferences.usesDenote() }
45 private var linkType: String { denote ? "denote:" : "id:" }
46
47 /// A date prompt's answer, read by `org-read-date`. Without a time, the time of day stays
48 /// now's, as `org-read-date` with `to-time` keeps it.
49 nonisolated static func date(_ answer: String, now: Date = Date()) -> Date? {
50 let read = ReadDate.read(answer, default: nil, now: now, calendar: .current)
51 guard let chosen = Calendar.current.date(from: read.components(.current)) else { return nil }
52 let time = Calendar.current.dateComponents([.hour, .minute, .second], from: now)
53 return Calendar.current.date(bySettingHour: read.timeGiven ? read.hour : time.hour!, minute: read.timeGiven ? read.minute : time.minute!,
54 second: read.timeGiven ? 0 : time.second!, of: chosen) ?? chosen
55 }
56
57 private func day(_ offset: Int, from now: Date = Date()) -> Date {
58 Calendar.current.date(byAdding: .day, value: offset, to: now) ?? now
59 }
60
61 public func run(_ id: String) {
62 switch id {
63 case "app.dailies.today": goto(day(0))
64 case "app.dailies.yesterday": goto(day(-1))
65 case "app.dailies.tomorrow": goto(day(1))
66 case "app.dailies.capture-today": capture(day(0))
67 case "app.dailies.capture-yesterday": capture(day(-1))
68 case "app.dailies.capture-tomorrow": capture(day(1))
69 case "app.dailies.date", "app.dailies.capture-date":
70 let goto = id == "app.dailies.date"
71 ask(Prompt(key: "date", message: goto ? "Find daily-note: " : "Capture to daily-note: ", date: Prompt.DateRead(defaultDate: nil))) { answer in
72 guard let answer, let date = Self.date(answer) else { return }
73 if goto { self.goto(date) } else { capture(date) }
74 }
75 case "app.dailies.next", "app.dailies.previous":
76 guard let dailies else { return show("No folder for daily notes") }
77 guard let path = session.path else { return show("Not in a daily-note") }
78 do {
79 let note = try dailies.neighbor(of: path, by: id == "app.dailies.next" ? 1 : -1)
80 open(note, 0)
81 } catch {
82 show("\(error)")
83 }
84 case "app.node.rename-from-front-matter":
85 renameFromFrontMatter()
86 case "app.node.rename":
87 renameNote()
88 case _ where id.hasPrefix("app.node.sequence-"):
89 runSequence(String(id.dropFirst("app.node.sequence-".count)))
90 case "app.node.rename-folder-from-front-matter":
91 renameFolderFromFrontMatter()
92 case "app.node.find":
93 chooseNode("Node: ") { choice in
94 switch choice {
95 case .existing(let node): open(node.location.path, node.location.start)
96 case .created(let path, _, _): open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
97 }
98 }
99 case "app.node.silo-find", "app.node.silo-create":
100 // denote-silo: a folder of `denote-silo-directories` in place of `denote-directory`.
101 let silos = DenoteNote.silos(roots: roots())
102 guard !silos.isEmpty else { return show("No folder for new notes") }
103 ask(Prompt(key: "silo", message: "Select a silo: ", choices: silos.map(DenoteNote.abbreviated))) { answer in
104 guard let answer, let silo = silos.first(where: { DenoteNote.abbreviated($0) == answer }) else { return }
105 let opened: (NodeChoice) -> Void = { choice in
106 switch choice {
107 case .existing(let node): open(node.location.path, node.location.start)
108 case .created(let path, _, _): open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
109 }
110 }
111 guard id == "app.node.silo-create" else { return chooseNode("Node: ", silo: silo, opened) }
112 ask(Prompt(key: "title", message: "New file TITLE: ", requireMatch: false)) { title in
113 guard let title = title?.trimmingCharacters(in: .whitespaces) else { return }
114 do { createDenote(title, known: try nodes(), silo: silo, opened) } catch { show(error.localizedDescription) }
115 }
116 }
117 case "app.node.insert":
118 chooseNode("Node: ") { choice in
119 switch choice {
120 case .existing(let node): insertLink(linkType + node.id, node.title)
121 case .created(_, let id, let title): insertLink(linkType + id, title)
122 }
123 }
124 default:
125 show("Unknown command \(id)")
126 }
127 }
128
129 /// `org-roam-dailies-goto-*`: the day's file, made if missing.
130 func goto(_ day: Date) {
131 guard let dailies else { return show("No folder for daily notes") }
132 guard reachFolders([dailies.directory]) else { return }
133 do {
134 let (path, created) = try dailies.ensure(day)
135 if created { refresh() }
136 open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
137 } catch {
138 show("Can't make the daily note: \(error.localizedDescription)")
139 }
140 }
141
142 /// `org-roam-dailies-capture-*`: the entry template filed at the end of the day's file,
143 /// which opens with the caret at `%?`.
144 func capture(_ day: Date) {
145 guard let dailies else { return show("No folder for daily notes") }
146 guard reachFolders([dailies.directory]) else { return }
147 let context = CaptureContext(now: day, file: session.path ?? "", userName: NSFullUserName())
148 let questions = Capture.questions(dailies.entry, context: context)
149 func ask(_ answers: [String]) {
150 guard answers.count < questions.count else { return file(answers) }
151 let question = questions[answers.count]
152 self.ask(Prompt(key: "q\(answers.count)", message: question.prompt + ": ", initial: question.defaultValue, requireMatch: false)) { answer in
153 if let answer { ask(answers + [answer]) }
154 }
155 }
156 func file(_ answers: [String]) {
157 do {
158 let (path, created) = try dailies.ensure(day)
159 if created { refresh() }
160 guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
161 let filled: (text: String, cursor: Int)
162 switch Capture.fill(dailies.entry, context: context, answers: answers) {
163 case .success(let result): filled = result
164 case .failure(.message(let message)): return show(message)
165 }
166 let template = CaptureTemplate(key: "d", name: "daily", target: .file(path), template: dailies.entry)
167 switch Capture.placement(filled.text, template: template, in: text, now: day) {
168 case .failure(.message(let message)): show(message)
169 case .success(let placed):
170 if case .failed(let message) = session.perform(ReplaceText(old: text, new: placed.text), path: path, at: 0, expect: nil) { return show(message) }
171 open(path, placed.start + filled.cursor)
172 }
173 } catch {
174 show("Can't make the daily note: \(error.localizedDescription)")
175 }
176 }
177 ask([])
178 }
179
180 enum NodeChoice {
181 case existing(IndexStore.Node)
182 case created(path: String, id: String, title: String)
183 }
184
185 /// `org-roam-node-read`: a node by its title, with its file's name when titles repeat. A
186 /// title no node has makes a node with it, as org-roam's default capture template does;
187 /// with Denote, `denote` asks for its keywords and makes the note.
188 private func chooseNode(_ message: String, silo: String? = nil, _ then: @escaping (NodeChoice) -> Void) {
189 let known: [IndexStore.Node]
190 do { known = try nodes() } catch { return show(error.localizedDescription) }
191 let all = silo.map { silo in known.filter { $0.location.path.hasPrefix(silo.hasSuffix("/") ? silo : silo + "/") } } ?? known
192 let counts = Dictionary(all.map { ($0.title, 1) }, uniquingKeysWith: +)
193 let labels = all.map { node in
194 counts[node.title, default: 0] > 1 ? "\(node.title) (\((node.location.path as NSString).lastPathComponent))" : node.title
195 }
196 ask(Prompt(key: "node", message: message, choices: labels, requireMatch: false)) { answer in
197 guard let answer else { return }
198 if let index = labels.firstIndex(of: answer) { return then(.existing(all[index])) }
199 let title = answer.trimmingCharacters(in: .whitespaces)
200 guard !title.isEmpty else { return }
201 if denote || silo != nil { return createDenote(title, known: all, silo: silo, then) }
202 guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") }
203 guard reachFolders([folder]) else { return }
204 do {
205 let node = try RoamNode.create(title: title, in: folder)
206 refresh()
207 show("Created \((node.path as NSString).lastPathComponent)")
208 then(.created(path: node.path, id: node.id, title: title))
209 } catch {
210 show("Can't make the node: \(error)")
211 }
212 }
213 }
214
215 /// What a new Denote note's questions give.
216 struct DenoteAnswers {
217 var keywords: [String] = []
218 var folder: String?
219 var date: Date?
220 var template = ""
221 var signature = ""
222 }
223
224 /// `denote`: after the title, the questions `denote-prompts` lists, in its order, then the
225 /// note in `denote-directory` or the folder chosen under it.
226 /// In a silo, its folder takes the place of `denote-directory`.
227 /// With `signature`, as `denote-use-signature` sets it: that signature, not asked for.
228 func createDenote(_ title: String, known: [IndexStore.Node], silo: String? = nil, signature: String? = nil, _ then: @escaping (NodeChoice) -> Void) {
229 let folders = silo.map { [$0] } ?? DenoteNote.directories(roots: roots())
230 guard !folders.isEmpty else { return show("No folder for new notes") }
231 var answers = DenoteAnswers()
232 if let signature { answers.signature = signature }
233 createDenote(title, roots: folders, prompts: OrgPreferences.denotePrompts().filter { signature == nil || $0 != "signature" },
234 templates: UserConfig.denoteTemplates(.standard), keywords: Denote.keywords(known.flatMap { Denote.name(ofFile: $0.location.path).keywords }),
235 answers: answers, then)
236 }
237
238 /// The note goes in the first of `roots`, or the folder the `subdirectory` question picks
239 /// among them and their folders.
240 func createDenote(
241 _ title: String, roots: [String], prompts: [String], templates: [(key: String, text: String)], keywords: [String],
242 answers: DenoteAnswers = DenoteAnswers(), _ then: @escaping (NodeChoice) -> Void
243 ) {
244 let root = roots[0]
245 func next(_ answers: DenoteAnswers) {
246 createDenote(title, roots: roots, prompts: Array(prompts.dropFirst()), templates: templates, keywords: keywords, answers: answers, then)
247 }
248 var answers = answers
249 switch prompts.first {
250 case nil:
251 guard reachFolders([answers.folder ?? root]) else { return }
252 do {
253 let note = try DenoteNote.create(title: title, keywords: answers.keywords, in: answers.folder ?? root, roots: roots,
254 now: answers.date ?? Date(), signature: answers.signature, template: answers.template)
255 refresh()
256 show("Created \((note.path as NSString).lastPathComponent)")
257 then(.created(path: note.path, id: note.id, title: title))
258 } catch {
259 show("Can't make the note: \(error)")
260 }
261 case "keywords":
262 // Separated by commas or spaces; the keywords already in file names are offered.
263 ask(Prompt(key: "keywords", message: "New file KEYWORDS: ", choices: keywords, requireMatch: false)) { answer in
264 guard let answer else { return }
265 answers.keywords = answer.split(whereSeparator: { $0 == "," || $0.isWhitespace }).map(String.init)
266 next(answers)
267 }
268 case "subdirectory":
269 let folders = DenoteNote.folderChoices(roots)
270 guard folders.count > 1 else { return next(answers) }
271 ask(Prompt(key: "subdirectory", message: "Select SUBDIRECTORY: ", choices: folders.map(\.label))) { answer in
272 guard let answer else { return }
273 answers.folder = folders.first { $0.label == answer }?.path ?? root
274 next(answers)
275 }
276 case "date":
277 ask(Prompt(key: "date", message: "DATE and TIME for note: ", date: Prompt.DateRead(defaultDate: nil))) { answer in
278 guard let answer else { return }
279 answers.date = Self.date(answer)
280 next(answers)
281 }
282 case "template":
283 guard !templates.isEmpty else { return next(answers) }
284 ask(Prompt(key: "template", message: "Select TEMPLATE key: ", choices: templates.map(\.key))) { answer in
285 guard let answer else { return }
286 answers.template = templates.first { $0.key == answer }?.text ?? ""
287 next(answers)
288 }
289 case "signature":
290 ask(Prompt(key: "signature", message: "New file SIGNATURE: ", requireMatch: false)) { answer in
291 guard let answer else { return }
292 answers.signature = answer
293 next(answers)
294 }
295 default:
296 // The title is asked first anyway; Org is the only file type; the rest have no equal.
297 next(answers)
298 }
299 }
300
301 /// `denote-rename-file-using-front-matter`: the open file renamed from its title,
302 /// keywords and signature, keeping its identifier.
303 func renameFromFrontMatter() {
304 guard let path = session.path else { return show("No file is open") }
305 guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
306 guard let target = Denote.renamed(path, text: text) else { return show("Not a Denote note: no front matter or identifier") }
307 guard target != path else { return show("Nothing to rename") }
308 rename(path, to: target)
309 }
310
311 /// Saves `path`, moves it to `target` and opens it there.
312 func rename(_ path: String, to target: String) {
313 guard !FileManager.default.fileExists(atPath: target) else { return show("\((target as NSString).lastPathComponent) is already there") }
314 do {
315 try move(path, to: target)
316 refresh()
317 open(target, 0)
318 show("Renamed to \((target as NSString).lastPathComponent)")
319 } catch {
320 show("Can't rename: \(error)")
321 }
322 }
323
324 /// Moves a file, saving it first and closing it when it's open.
325 func move(_ path: String, to target: String) throws {
326 if session.openPaths.contains(path) {
327 guard session.save(path) else { throw Dailies.Failure("Can't save \((path as NSString).lastPathComponent)") }
328 }
329 try FileManager.default.moveItem(atPath: path, toPath: target)
330 if session.openPaths.contains(path) { session.kill(path) }
331 }
332
333 /// `denote-rename-file`: the open file's title, keywords, signature and date, as
334 /// `denote-prompts` asks for them, each starting with the current value, then the file
335 /// renamed in its folder and its front matter rewritten. A file without an identifier
336 /// gets one from its modification time; one without front matter gets it at the top.
337 func renameNote() {
338 guard let path = session.path else { return show("No file is open") }
339 guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
340 let name = Denote.name(ofFile: path), front = Denote.frontMatter(of: text)
341 var title = front.title ?? name.title?.replacingOccurrences(of: "-", with: " ") ?? ""
342 var keywords = front.keywords ?? name.keywords
343 var signature = name.signature ?? front.signature ?? ""
344 var date: Date?
345 let file = (path as NSString).lastPathComponent
346 func ask(_ prompts: ArraySlice<String>) {
347 switch prompts.first {
348 case nil: finish()
349 case "title":
350 self.ask(Prompt(key: "title", message: "Rename \(file) with TITLE (empty to remove): ", initial: title, requireMatch: false)) { answer in
351 guard let answer else { return }
352 title = answer
353 ask(prompts.dropFirst())
354 }
355 case "keywords":
356 self.ask(Prompt(key: "keywords", message: "Rename \(file) with KEYWORDS (empty to remove): ", initial: keywords.joined(separator: ","), requireMatch: false)) { answer in
357 guard let answer else { return }
358 keywords = answer.split(whereSeparator: { $0 == "," || $0.isWhitespace }).map(String.init)
359 ask(prompts.dropFirst())
360 }
361 case "signature":
362 self.ask(Prompt(key: "signature", message: "Rename \(file) with SIGNATURE (empty to remove): ", initial: signature, requireMatch: false)) { answer in
363 guard let answer else { return }
364 signature = answer
365 ask(prompts.dropFirst())
366 }
367 case "date":
368 self.ask(Prompt(key: "date", message: "Rename \(file) with DATE: ", date: Prompt.DateRead(defaultDate: Denote.date(of: text)))) { answer in
369 guard let answer else { return }
370 date = answer.isEmpty ? nil : Self.date(answer)
371 ask(prompts.dropFirst())
372 }
373 default: ask(prompts.dropFirst())
374 }
375 }
376 func finish() {
377 let (target, rewritten) = DenoteNote.renaming(path, text: text, title: title, keywords: keywords, signature: signature, date: date,
378 roots: DenoteNote.directories(roots: roots()))
379 guard target != path || rewritten != text else { return show("Nothing to rename") }
380 if rewritten != text, case .failed(let message) = session.perform(ReplaceText(old: text, new: rewritten), path: path, at: 0, expect: nil) { return show(message) }
381 guard target != path else { return show("Front matter rewritten") }
382 rename(path, to: target)
383 }
384 ask(ArraySlice(OrgPreferences.denotePrompts()))
385 }
386
387 /// `denote-dired-rename-marked-files-using-front-matter`, with every Denote note in a
388 /// folder of `denote-directory` marked: each renamed from its front matter.
389 func renameFolderFromFrontMatter() {
390 let folders = DenoteNote.folderChoices(DenoteNote.directories(roots: roots()))
391 guard !folders.isEmpty else { return show("No folder for notes") }
392 ask(Prompt(key: "folder", message: "Rename notes in: ", choices: folders.map(\.label))) { answer in
393 guard let answer, let folder = folders.first(where: { $0.label == answer })?.path else { return }
394 let shown = session.path
395 var renamed = 0, problems: [String] = []
396 for name in ((try? FileManager.default.contentsOfDirectory(atPath: folder)) ?? []).sorted() where Denote.identifier(ofFile: name) != nil {
397 let path = (folder as NSString).appendingPathComponent(name)
398 guard let text = session.text(of: path) ?? (try? String(contentsOfFile: path, encoding: .utf8)),
399 let target = Denote.renamed(path, text: text), target != path else { continue }
400 guard !FileManager.default.fileExists(atPath: target) else { problems.append("\((target as NSString).lastPathComponent) is already there"); continue }
401 do {
402 try move(path, to: target)
403 renamed += 1
404 if shown == path { open(target, 0) }
405 } catch {
406 problems.append("\(error)")
407 }
408 }
409 refresh()
410 show(([renamed == 1 ? "Renamed 1 note" : "Renamed \(renamed) notes"] + problems).joined(separator: "; "))
411 }
412 }
413}