Sources/OrgApp/RoamActions.swift

411 lines · 22577 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    /// 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 () -> [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                    createDenote(title, known: nodes(), silo: silo, opened)
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 all = silo.map { silo in nodes().filter { $0.location.path.hasPrefix(silo.hasSuffix("/") ? silo : silo + "/") } } ?? nodes()
190        let counts = Dictionary(all.map { ($0.title, 1) }, uniquingKeysWith: +)
191        let labels = all.map { node in
192            counts[node.title, default: 0] > 1 ? "\(node.title) (\((node.location.path as NSString).lastPathComponent))" : node.title
193        }
194        ask(Prompt(key: "node", message: message, choices: labels, requireMatch: false)) { answer in
195            guard let answer else { return }
196            if let index = labels.firstIndex(of: answer) { return then(.existing(all[index])) }
197            let title = answer.trimmingCharacters(in: .whitespaces)
198            guard !title.isEmpty else { return }
199            if denote || silo != nil { return createDenote(title, known: all, silo: silo, then) }
200            guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") }
201            guard reachFolders([folder]) else { return }
202            do {
203                let node = try RoamNode.create(title: title, in: folder)
204                refresh()
205                show("Created \((node.path as NSString).lastPathComponent)")
206                then(.created(path: node.path, id: node.id, title: title))
207            } catch {
208                show("Can't make the node: \(error)")
209            }
210        }
211    }
212
213    /// What a new Denote note's questions give.
214    struct DenoteAnswers {
215        var keywords: [String] = []
216        var folder: String?
217        var date: Date?
218        var template = ""
219        var signature = ""
220    }
221
222    /// `denote`: after the title, the questions `denote-prompts` lists, in its order, then the
223    /// note in `denote-directory` or the folder chosen under it.
224    /// In a silo, its folder takes the place of `denote-directory`.
225    /// With `signature`, as `denote-use-signature` sets it: that signature, not asked for.
226    func createDenote(_ title: String, known: [IndexStore.Node], silo: String? = nil, signature: String? = nil, _ then: @escaping (NodeChoice) -> Void) {
227        let folders = silo.map { [$0] } ?? DenoteNote.directories(roots: roots())
228        guard !folders.isEmpty else { return show("No folder for new notes") }
229        var answers = DenoteAnswers()
230        if let signature { answers.signature = signature }
231        createDenote(title, roots: folders, prompts: OrgPreferences.denotePrompts().filter { signature == nil || $0 != "signature" },
232                     templates: UserConfig.denoteTemplates(.standard), keywords: Denote.keywords(known.flatMap { Denote.name(ofFile: $0.location.path).keywords }),
233                     answers: answers, then)
234    }
235
236    /// The note goes in the first of `roots`, or the folder the `subdirectory` question picks
237    /// among them and their folders.
238    func createDenote(
239        _ title: String, roots: [String], prompts: [String], templates: [(key: String, text: String)], keywords: [String],
240        answers: DenoteAnswers = DenoteAnswers(), _ then: @escaping (NodeChoice) -> Void
241    ) {
242        let root = roots[0]
243        func next(_ answers: DenoteAnswers) {
244            createDenote(title, roots: roots, prompts: Array(prompts.dropFirst()), templates: templates, keywords: keywords, answers: answers, then)
245        }
246        var answers = answers
247        switch prompts.first {
248        case nil:
249            guard reachFolders([answers.folder ?? root]) else { return }
250            do {
251                let note = try DenoteNote.create(title: title, keywords: answers.keywords, in: answers.folder ?? root, roots: roots,
252                                                 now: answers.date ?? Date(), signature: answers.signature, template: answers.template)
253                refresh()
254                show("Created \((note.path as NSString).lastPathComponent)")
255                then(.created(path: note.path, id: note.id, title: title))
256            } catch {
257                show("Can't make the note: \(error)")
258            }
259        case "keywords":
260            // Separated by commas or spaces; the keywords already in file names are offered.
261            ask(Prompt(key: "keywords", message: "New file KEYWORDS: ", choices: keywords, requireMatch: false)) { answer in
262                guard let answer else { return }
263                answers.keywords = answer.split(whereSeparator: { $0 == "," || $0.isWhitespace }).map(String.init)
264                next(answers)
265            }
266        case "subdirectory":
267            let folders = DenoteNote.folderChoices(roots)
268            guard folders.count > 1 else { return next(answers) }
269            ask(Prompt(key: "subdirectory", message: "Select SUBDIRECTORY: ", choices: folders.map(\.label))) { answer in
270                guard let answer else { return }
271                answers.folder = folders.first { $0.label == answer }?.path ?? root
272                next(answers)
273            }
274        case "date":
275            ask(Prompt(key: "date", message: "DATE and TIME for note: ", date: Prompt.DateRead(defaultDate: nil))) { answer in
276                guard let answer else { return }
277                answers.date = Self.date(answer)
278                next(answers)
279            }
280        case "template":
281            guard !templates.isEmpty else { return next(answers) }
282            ask(Prompt(key: "template", message: "Select TEMPLATE key: ", choices: templates.map(\.key))) { answer in
283                guard let answer else { return }
284                answers.template = templates.first { $0.key == answer }?.text ?? ""
285                next(answers)
286            }
287        case "signature":
288            ask(Prompt(key: "signature", message: "New file SIGNATURE: ", requireMatch: false)) { answer in
289                guard let answer else { return }
290                answers.signature = answer
291                next(answers)
292            }
293        default:
294            // The title is asked first anyway; Org is the only file type; the rest have no equal.
295            next(answers)
296        }
297    }
298
299    /// `denote-rename-file-using-front-matter`: the open file renamed from its title,
300    /// keywords and signature, keeping its identifier.
301    func renameFromFrontMatter() {
302        guard let path = session.path else { return show("No file is open") }
303        guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
304        guard let target = Denote.renamed(path, text: text) else { return show("Not a Denote note: no front matter or identifier") }
305        guard target != path else { return show("Nothing to rename") }
306        rename(path, to: target)
307    }
308
309    /// Saves `path`, moves it to `target` and opens it there.
310    func rename(_ path: String, to target: String) {
311        guard !FileManager.default.fileExists(atPath: target) else { return show("\((target as NSString).lastPathComponent) is already there") }
312        do {
313            try move(path, to: target)
314            refresh()
315            open(target, 0)
316            show("Renamed to \((target as NSString).lastPathComponent)")
317        } catch {
318            show("Can't rename: \(error)")
319        }
320    }
321
322    /// Moves a file, saving it first and closing it when it's open.
323    func move(_ path: String, to target: String) throws {
324        if session.openPaths.contains(path) {
325            guard session.save(path) else { throw Dailies.Failure("Can't save \((path as NSString).lastPathComponent)") }
326        }
327        try FileManager.default.moveItem(atPath: path, toPath: target)
328        if session.openPaths.contains(path) { session.kill(path) }
329    }
330
331    /// `denote-rename-file`: the open file's title, keywords, signature and date, as
332    /// `denote-prompts` asks for them, each starting with the current value, then the file
333    /// renamed in its folder and its front matter rewritten. A file without an identifier
334    /// gets one from its modification time; one without front matter gets it at the top.
335    func renameNote() {
336        guard let path = session.path else { return show("No file is open") }
337        guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
338        let name = Denote.name(ofFile: path), front = Denote.frontMatter(of: text)
339        var title = front.title ?? name.title?.replacingOccurrences(of: "-", with: " ") ?? ""
340        var keywords = front.keywords ?? name.keywords
341        var signature = name.signature ?? front.signature ?? ""
342        var date: Date?
343        let file = (path as NSString).lastPathComponent
344        func ask(_ prompts: ArraySlice<String>) {
345            switch prompts.first {
346            case nil: finish()
347            case "title":
348                self.ask(Prompt(key: "title", message: "Rename \(file) with TITLE (empty to remove): ", initial: title, requireMatch: false)) { answer in
349                    guard let answer else { return }
350                    title = answer
351                    ask(prompts.dropFirst())
352                }
353            case "keywords":
354                self.ask(Prompt(key: "keywords", message: "Rename \(file) with KEYWORDS (empty to remove): ", initial: keywords.joined(separator: ","), requireMatch: false)) { answer in
355                    guard let answer else { return }
356                    keywords = answer.split(whereSeparator: { $0 == "," || $0.isWhitespace }).map(String.init)
357                    ask(prompts.dropFirst())
358                }
359            case "signature":
360                self.ask(Prompt(key: "signature", message: "Rename \(file) with SIGNATURE (empty to remove): ", initial: signature, requireMatch: false)) { answer in
361                    guard let answer else { return }
362                    signature = answer
363                    ask(prompts.dropFirst())
364                }
365            case "date":
366                self.ask(Prompt(key: "date", message: "Rename \(file) with DATE: ", date: Prompt.DateRead(defaultDate: Denote.date(of: text)))) { answer in
367                    guard let answer else { return }
368                    date = answer.isEmpty ? nil : Self.date(answer)
369                    ask(prompts.dropFirst())
370                }
371            default: ask(prompts.dropFirst())
372            }
373        }
374        func finish() {
375            let (target, rewritten) = DenoteNote.renaming(path, text: text, title: title, keywords: keywords, signature: signature, date: date,
376                                                          roots: DenoteNote.directories(roots: roots()))
377            guard target != path || rewritten != text else { return show("Nothing to rename") }
378            if rewritten != text, case .failed(let message) = session.perform(ReplaceText(old: text, new: rewritten), path: path, at: 0, expect: nil) { return show(message) }
379            guard target != path else { return show("Front matter rewritten") }
380            rename(path, to: target)
381        }
382        ask(ArraySlice(OrgPreferences.denotePrompts()))
383    }
384
385    /// `denote-dired-rename-marked-files-using-front-matter`, with every Denote note in a
386    /// folder of `denote-directory` marked: each renamed from its front matter.
387    func renameFolderFromFrontMatter() {
388        let folders = DenoteNote.folderChoices(DenoteNote.directories(roots: roots()))
389        guard !folders.isEmpty else { return show("No folder for notes") }
390        ask(Prompt(key: "folder", message: "Rename notes in: ", choices: folders.map(\.label))) { answer in
391            guard let answer, let folder = folders.first(where: { $0.label == answer })?.path else { return }
392            let shown = session.path
393            var renamed = 0, problems: [String] = []
394            for name in ((try? FileManager.default.contentsOfDirectory(atPath: folder)) ?? []).sorted() where Denote.identifier(ofFile: name) != nil {
395                let path = (folder as NSString).appendingPathComponent(name)
396                guard let text = session.text(of: path) ?? (try? String(contentsOfFile: path, encoding: .utf8)),
397                      let target = Denote.renamed(path, text: text), target != path else { continue }
398                guard !FileManager.default.fileExists(atPath: target) else { problems.append("\((target as NSString).lastPathComponent) is already there"); continue }
399                do {
400                    try move(path, to: target)
401                    renamed += 1
402                    if shown == path { open(target, 0) }
403                } catch {
404                    problems.append("\(error)")
405                }
406            }
407            refresh()
408            show(([renamed == 1 ? "Renamed 1 note" : "Renamed \(renamed) notes"] + problems).joined(separator: "; "))
409        }
410    }
411}