Sources/OrgApp/RoamActions.swift
cmc org-roam: aliases, refs, excludes, chooser tags, template choice, capture buffer
ed22b081d6 2 hours ago481 lines · 27008 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 chooseNode("Node: ") { choice in
126 switch choice {
127 case .existing(let node, let title): insertLink(linkType + node.id, title)
128 case .created(_, _, let id, let title): insertLink(linkType + id, title)
129 }
130 }
131 default:
132 show("Unknown command \(id)")
133 }
134 }
135
136 /// The daily-note templates: `[[roam-dailies-template]]`, or one from the
137 /// `org-roam-dailies-…` settings; for a Denote journal, one for the day's entry.
138 private func dailyTemplates(_ dailies: Dailies, _ day: Date) -> [RoamTemplate] {
139 if dailies.journal != nil {
140 return [RoamTemplate(key: "d", name: "default", kind: .entry, template: dailies.entry, file: dailies.path(for: day), head: dailies.newText(day, id: ""))]
141 }
142 let (templates, problems) = self.templates(.dailies)
143 if let problem = problems.first { show(problem) }
144 return templates
145 }
146
147 /// `org-roam-dailies-goto-*`: the day's file, made if missing. With templates aimed at
148 /// different files, asks which.
149 func goto(_ day: Date) {
150 guard let dailies else { return show("No folder for daily notes") }
151 guard reachFolders([dailies.directory]) else { return }
152 let templates = dailyTemplates(dailies, day)
153 func go(_ template: RoamTemplate) {
154 var dailies = dailies
155 if dailies.journal == nil {
156 dailies.file = template.file
157 dailies.head = template.head
158 }
159 do {
160 let (path, created) = try dailies.ensure(day)
161 if created { refresh() }
162 open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
163 } catch {
164 show("Can't make the daily note: \(error.localizedDescription)")
165 }
166 }
167 guard Set(templates.map(\.file)).count > 1 else { return go(templates[0]) }
168 chooseTemplate(templates) { go($0) }
169 }
170
171 /// `org-capture`'s template menu, for a command that files nothing.
172 private func chooseTemplate(_ templates: [RoamTemplate], _ then: @escaping (RoamTemplate) -> Void) {
173 let labels = templates.map { "[\($0.key)] \($0.name)" }
174 ask(Prompt(key: "template", message: "Template: ", choices: labels)) { answer in
175 guard let answer, let index = labels.firstIndex(of: answer) else { return }
176 then(templates[index])
177 }
178 }
179
180 /// `org-roam-dailies-capture-*`: the capture window with the daily-note templates; the
181 /// entry goes at the end of the day's file, made with its head when it's new.
182 func capture(_ day: Date) {
183 guard let dailies else { return show("No folder for daily notes") }
184 guard reachFolders([dailies.directory]) else { return }
185 start(RoamCapture(dailyTemplates(dailies, day), title: "", directory: dailies.directory, now: day, ids: dailies.journal == nil,
186 session: session, refresh: refresh) { _, _, _ in })
187 }
188
189 /// Shows the capture window, or without one, files the first template at once and opens
190 /// what it filed.
191 func start(_ roam: RoamCapture) {
192 if let capture { return capture(roam) }
193 switch roam.fileFirst() {
194 case .success(let entry): open(entry.path, entry.offset)
195 case .failure(let error): show(error.message)
196 }
197 }
198
199 enum NodeChoice {
200 /// A node, by the title or alias chosen.
201 case existing(IndexStore.Node, title: String)
202 /// A new node, with where its text went.
203 case created(path: String, offset: Int, id: String, title: String)
204 }
205
206 /// `org-roam-node-read--completions`: a candidate for each node's title and each of its
207 /// aliases, with its file's name when names repeat, and its tags after it as Doom's
208 /// `org-roam-node-display-template` shows them.
209 nonisolated static func candidates(_ nodes: [IndexStore.Node]) -> [(label: String, node: IndexStore.Node, title: String)] {
210 let names = nodes.flatMap { node in ([node.title] + node.aliases).map { (node: node, name: $0) } }
211 let counts = Dictionary(names.map { ($0.name, 1) }, uniquingKeysWith: +)
212 return names.map { node, name in
213 var label = counts[name, default: 0] > 1 ? "\(name) (\((node.location.path as NSString).lastPathComponent))" : name
214 if !node.tags.isEmpty { label += " " + node.tags.map { "#" + $0 }.joined(separator: " ") }
215 return (label, node, name)
216 }
217 }
218
219 /// `org-roam-node-read`: a node by its title or an alias. A title no node has goes to the
220 /// capture window with `[[roam-template]]`'s templates, as `org-roam-capture-` does, and
221 /// once filed makes the node; with Denote, `denote` asks for its keywords and makes the note.
222 private func chooseNode(_ message: String, silo: String? = nil, _ then: @escaping (NodeChoice) -> Void) {
223 let known: [IndexStore.Node]
224 do { known = try nodes() } catch { return show(error.localizedDescription) }
225 let all = silo.map { silo in known.filter { $0.location.path.hasPrefix(silo.hasSuffix("/") ? silo : silo + "/") } } ?? known
226 let candidates = Self.candidates(all)
227 ask(Prompt(key: "node", message: message, choices: candidates.map(\.label), requireMatch: false)) { answer in
228 guard let answer else { return }
229 if let chosen = candidates.first(where: { $0.label == answer }) ?? candidates.first(where: { $0.title == answer }) {
230 return then(.existing(chosen.node, title: chosen.title))
231 }
232 let title = answer.trimmingCharacters(in: .whitespaces)
233 guard !title.isEmpty else { return }
234 if denote || silo != nil { return createDenote(title, known: all, silo: silo, then) }
235 guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") }
236 guard reachFolders([folder]) else { return }
237 let (templates, problems) = self.templates(.node)
238 if let problem = problems.first { show(problem) }
239 start(RoamCapture(templates, title: title, directory: folder, session: session, refresh: refresh) { path, offset, id in
240 then(.created(path: path, offset: offset, id: id, title: title))
241 })
242 }
243 }
244
245 /// `org-roam-ref-find`: a node by one of its `ROAM_REFS`, shown with its title.
246 private func findRef() {
247 let known: [IndexStore.Node]
248 do { known = try nodes() } catch { return show(error.localizedDescription) }
249 let refs = known.flatMap { node in node.refs.map { (label: "\($0) \(node.title)", node: node) } }
250 guard !refs.isEmpty else { return show("No node has refs") }
251 ask(Prompt(key: "ref", message: "Ref: ", choices: refs.map(\.label))) { answer in
252 guard let answer, let chosen = refs.first(where: { $0.label == answer }) else { return }
253 open(chosen.node.location.path, chosen.node.location.start)
254 }
255 }
256
257 /// org-roam-protocol's `roam-ref`: the node with the ref, else the capture window with
258 /// `[[roam-ref-template]]`'s templates (only the one keyed `template` when given) for a new
259 /// node with the ref in its `ROAM_REFS`; and `roam-node`: the node with the ID.
260 public func follow(_ request: OrgProtocol.Request) {
261 let known: [IndexStore.Node]
262 do { known = try nodes() } catch { return show(error.localizedDescription) }
263 switch request {
264 case .roamNode(let id):
265 guard let node = known.first(where: { $0.id == id }) else { return show("No node has the ID \(id)") }
266 open(node.location.path, node.location.start)
267 case .roamRef(let ref, let title, let body, let key):
268 if let node = known.first(where: { $0.refs.contains(ref) }) { return open(node.location.path, node.location.start) }
269 guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") }
270 guard reachFolders([folder]) else { return }
271 let (all, problems) = self.templates(.ref)
272 if let problem = problems.first { show(problem) }
273 let templates = key.map { key in all.filter { $0.key == key } } ?? all
274 guard !templates.isEmpty else { return show("No roam-ref template \"\(key ?? "")\"") }
275 let quoted = ref.contains(where: \.isWhitespace) ? "\"" + ref.replacingOccurrences(of: "\"", with: "\\\"") + "\"" : ref
276 start(RoamCapture(templates, title: title ?? ref, directory: folder, fields: ["ref": ref, "body": body ?? ""], properties: [("ROAM_REFS", quoted)],
277 session: session, refresh: refresh) { path, offset, _ in open(path, offset) })
278 default:
279 break
280 }
281 }
282
283 /// What a new Denote note's questions give.
284 struct DenoteAnswers {
285 var keywords: [String] = []
286 var folder: String?
287 var date: Date?
288 var template = ""
289 var signature = ""
290 }
291
292 /// `denote`: after the title, the questions `denote-prompts` lists, in its order, then the
293 /// note in `denote-directory` or the folder chosen under it.
294 /// In a silo, its folder takes the place of `denote-directory`.
295 /// With `signature`, as `denote-use-signature` sets it: that signature, not asked for.
296 func createDenote(_ title: String, known: [IndexStore.Node], silo: String? = nil, signature: String? = nil, _ then: @escaping (NodeChoice) -> Void) {
297 let folders = silo.map { [$0] } ?? DenoteNote.directories(roots: roots())
298 guard !folders.isEmpty else { return show("No folder for new notes") }
299 var answers = DenoteAnswers()
300 if let signature { answers.signature = signature }
301 createDenote(title, roots: folders, prompts: OrgPreferences.denotePrompts().filter { signature == nil || $0 != "signature" },
302 templates: UserConfig.denoteTemplates(.standard), keywords: Denote.keywords(known.flatMap { Denote.name(ofFile: $0.location.path).keywords }),
303 answers: answers, then)
304 }
305
306 /// The note goes in the first of `roots`, or the folder the `subdirectory` question picks
307 /// among them and their folders.
308 func createDenote(
309 _ title: String, roots: [String], prompts: [String], templates: [(key: String, text: String)], keywords: [String],
310 answers: DenoteAnswers = DenoteAnswers(), _ then: @escaping (NodeChoice) -> Void
311 ) {
312 let root = roots[0]
313 func next(_ answers: DenoteAnswers) {
314 createDenote(title, roots: roots, prompts: Array(prompts.dropFirst()), templates: templates, keywords: keywords, answers: answers, then)
315 }
316 var answers = answers
317 switch prompts.first {
318 case nil:
319 guard reachFolders([answers.folder ?? root]) else { return }
320 do {
321 let note = try DenoteNote.create(title: title, keywords: answers.keywords, in: answers.folder ?? root, roots: roots,
322 now: answers.date ?? Date(), signature: answers.signature, template: answers.template)
323 refresh()
324 show("Created \((note.path as NSString).lastPathComponent)")
325 then(.created(path: note.path, offset: (session.text(of: note.path).map { ($0 as NSString).length }) ?? 0, id: note.id, title: title))
326 } catch {
327 show("Can't make the note: \(error)")
328 }
329 case "keywords":
330 // Separated by commas or spaces; the keywords already in file names are offered.
331 ask(Prompt(key: "keywords", message: "New file KEYWORDS: ", choices: keywords, requireMatch: false)) { answer in
332 guard let answer else { return }
333 answers.keywords = answer.split(whereSeparator: { $0 == "," || $0.isWhitespace }).map(String.init)
334 next(answers)
335 }
336 case "subdirectory":
337 let folders = DenoteNote.folderChoices(roots)
338 guard folders.count > 1 else { return next(answers) }
339 ask(Prompt(key: "subdirectory", message: "Select SUBDIRECTORY: ", choices: folders.map(\.label))) { answer in
340 guard let answer else { return }
341 answers.folder = folders.first { $0.label == answer }?.path ?? root
342 next(answers)
343 }
344 case "date":
345 ask(Prompt(key: "date", message: "DATE and TIME for note: ", date: Prompt.DateRead(defaultDate: nil))) { answer in
346 guard let answer else { return }
347 answers.date = Self.date(answer)
348 next(answers)
349 }
350 case "template":
351 guard !templates.isEmpty else { return next(answers) }
352 ask(Prompt(key: "template", message: "Select TEMPLATE key: ", choices: templates.map(\.key))) { answer in
353 guard let answer else { return }
354 answers.template = templates.first { $0.key == answer }?.text ?? ""
355 next(answers)
356 }
357 case "signature":
358 ask(Prompt(key: "signature", message: "New file SIGNATURE: ", requireMatch: false)) { answer in
359 guard let answer else { return }
360 answers.signature = answer
361 next(answers)
362 }
363 default:
364 // The title is asked first anyway; Org is the only file type; the rest have no equal.
365 next(answers)
366 }
367 }
368
369 /// `denote-rename-file-using-front-matter`: the open file renamed from its title,
370 /// keywords and signature, keeping its identifier.
371 func renameFromFrontMatter() {
372 guard let path = session.path else { return show("No file is open") }
373 guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
374 guard let target = Denote.renamed(path, text: text) else { return show("Not a Denote note: no front matter or identifier") }
375 guard target != path else { return show("Nothing to rename") }
376 rename(path, to: target)
377 }
378
379 /// Saves `path`, moves it to `target` and opens it there.
380 func rename(_ path: String, to target: String) {
381 guard !FileManager.default.fileExists(atPath: target) else { return show("\((target as NSString).lastPathComponent) is already there") }
382 do {
383 try move(path, to: target)
384 refresh()
385 open(target, 0)
386 show("Renamed to \((target as NSString).lastPathComponent)")
387 } catch {
388 show("Can't rename: \(error)")
389 }
390 }
391
392 /// Moves a file, saving it first and closing it when it's open.
393 func move(_ path: String, to target: String) throws {
394 if session.openPaths.contains(path) {
395 guard session.save(path) else { throw Dailies.Failure("Can't save \((path as NSString).lastPathComponent)") }
396 }
397 try FileManager.default.moveItem(atPath: path, toPath: target)
398 if session.openPaths.contains(path) { session.kill(path) }
399 }
400
401 /// `denote-rename-file`: the open file's title, keywords, signature and date, as
402 /// `denote-prompts` asks for them, each starting with the current value, then the file
403 /// renamed in its folder and its front matter rewritten. A file without an identifier
404 /// gets one from its modification time; one without front matter gets it at the top.
405 func renameNote() {
406 guard let path = session.path else { return show("No file is open") }
407 guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
408 let name = Denote.name(ofFile: path), front = Denote.frontMatter(of: text)
409 var title = front.title ?? name.title?.replacingOccurrences(of: "-", with: " ") ?? ""
410 var keywords = front.keywords ?? name.keywords
411 var signature = name.signature ?? front.signature ?? ""
412 var date: Date?
413 let file = (path as NSString).lastPathComponent
414 func ask(_ prompts: ArraySlice<String>) {
415 switch prompts.first {
416 case nil: finish()
417 case "title":
418 self.ask(Prompt(key: "title", message: "Rename \(file) with TITLE (empty to remove): ", initial: title, requireMatch: false)) { answer in
419 guard let answer else { return }
420 title = answer
421 ask(prompts.dropFirst())
422 }
423 case "keywords":
424 self.ask(Prompt(key: "keywords", message: "Rename \(file) with KEYWORDS (empty to remove): ", initial: keywords.joined(separator: ","), requireMatch: false)) { answer in
425 guard let answer else { return }
426 keywords = answer.split(whereSeparator: { $0 == "," || $0.isWhitespace }).map(String.init)
427 ask(prompts.dropFirst())
428 }
429 case "signature":
430 self.ask(Prompt(key: "signature", message: "Rename \(file) with SIGNATURE (empty to remove): ", initial: signature, requireMatch: false)) { answer in
431 guard let answer else { return }
432 signature = answer
433 ask(prompts.dropFirst())
434 }
435 case "date":
436 self.ask(Prompt(key: "date", message: "Rename \(file) with DATE: ", date: Prompt.DateRead(defaultDate: Denote.date(of: text)))) { answer in
437 guard let answer else { return }
438 date = answer.isEmpty ? nil : Self.date(answer)
439 ask(prompts.dropFirst())
440 }
441 default: ask(prompts.dropFirst())
442 }
443 }
444 func finish() {
445 let (target, rewritten) = DenoteNote.renaming(path, text: text, title: title, keywords: keywords, signature: signature, date: date,
446 roots: DenoteNote.directories(roots: roots()))
447 guard target != path || rewritten != text else { return show("Nothing to rename") }
448 if rewritten != text, case .failed(let message) = session.perform(ReplaceText(old: text, new: rewritten), path: path, at: 0, expect: nil) { return show(message) }
449 guard target != path else { return show("Front matter rewritten") }
450 rename(path, to: target)
451 }
452 ask(ArraySlice(OrgPreferences.denotePrompts()))
453 }
454
455 /// `denote-dired-rename-marked-files-using-front-matter`, with every Denote note in a
456 /// folder of `denote-directory` marked: each renamed from its front matter.
457 func renameFolderFromFrontMatter() {
458 let folders = DenoteNote.folderChoices(DenoteNote.directories(roots: roots()))
459 guard !folders.isEmpty else { return show("No folder for notes") }
460 ask(Prompt(key: "folder", message: "Rename notes in: ", choices: folders.map(\.label))) { answer in
461 guard let answer, let folder = folders.first(where: { $0.label == answer })?.path else { return }
462 let shown = session.path
463 var renamed = 0, problems: [String] = []
464 for name in ((try? FileManager.default.contentsOfDirectory(atPath: folder)) ?? []).sorted() where Denote.identifier(ofFile: name) != nil {
465 let path = (folder as NSString).appendingPathComponent(name)
466 guard let text = session.text(of: path) ?? (try? String(contentsOfFile: path, encoding: .utf8)),
467 let target = Denote.renamed(path, text: text), target != path else { continue }
468 guard !FileManager.default.fileExists(atPath: target) else { problems.append("\((target as NSString).lastPathComponent) is already there"); continue }
469 do {
470 try move(path, to: target)
471 renamed += 1
472 if shown == path { open(target, 0) }
473 } catch {
474 problems.append("\(error)")
475 }
476 }
477 refresh()
478 show(([renamed == 1 ? "Renamed 1 note" : "Renamed \(renamed) notes"] + problems).joined(separator: "; "))
479 }
480 }
481}