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