Sources/OrgApp/RoamActions.swift

c396b3453f7cf76ac49e5e2707e01bf5c5753508
orgstar/Sources/OrgApp/RoamActions.swift

217 lines · 11308 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    private func day(_ offset: Int, from now: Date = Date()) -> Date {
 45        Calendar.current.date(byAdding: .day, value: offset, to: now) ?? now
 46    }
 47
 48    public func run(_ id: String) {
 49        switch id {
 50        case "app.dailies.today": goto(day(0))
 51        case "app.dailies.yesterday": goto(day(-1))
 52        case "app.dailies.tomorrow": goto(day(1))
 53        case "app.dailies.capture-today": capture(day(0))
 54        case "app.dailies.capture-yesterday": capture(day(-1))
 55        case "app.dailies.capture-tomorrow": capture(day(1))
 56        case "app.dailies.date", "app.dailies.capture-date":
 57            let goto = id == "app.dailies.date"
 58            ask(Prompt(key: "date", message: goto ? "Find daily-note: " : "Capture to daily-note: ", date: Prompt.DateRead(defaultDate: nil))) { answer in
 59                guard let answer else { return }
 60                let now = Date()
 61                let read = ReadDate.read(answer, default: nil, now: now, calendar: .current)
 62                guard let chosen = Calendar.current.date(from: read.components(.current)) else { return }
 63                // The time of day stays now's, as `org-read-date` with `to-time` keeps it.
 64                let time = Calendar.current.dateComponents([.hour, .minute, .second], from: now)
 65                let date = Calendar.current.date(bySettingHour: read.timeGiven ? read.hour : time.hour!, minute: read.timeGiven ? read.minute : time.minute!,
 66                                                 second: read.timeGiven ? 0 : time.second!, of: chosen) ?? chosen
 67                if goto { self.goto(date) } else { capture(date) }
 68            }
 69        case "app.dailies.next", "app.dailies.previous":
 70            guard let dailies else { return show("No folder for daily notes") }
 71            guard let path = session.path else { return show("Not in a daily-note") }
 72            do {
 73                let note = try dailies.neighbor(of: path, by: id == "app.dailies.next" ? 1 : -1)
 74                open(note, 0)
 75            } catch {
 76                show("\(error)")
 77            }
 78        case "app.node.rename-from-front-matter":
 79            renameFromFrontMatter()
 80        case "app.node.find":
 81            chooseNode("Node: ") { choice in
 82                switch choice {
 83                case .existing(let node): open(node.location.path, node.location.start)
 84                case .created(let path, _, _): open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
 85                }
 86            }
 87        case "app.node.insert":
 88            chooseNode("Node: ") { choice in
 89                switch choice {
 90                case .existing(let node): insertLink(linkType + node.id, node.title)
 91                case .created(_, let id, let title): insertLink(linkType + id, title)
 92                }
 93            }
 94        default:
 95            show("Unknown command \(id)")
 96        }
 97    }
 98
 99    /// `org-roam-dailies-goto-*`: the day's file, made if missing.
100    func goto(_ day: Date) {
101        guard let dailies else { return show("No folder for daily notes") }
102        do {
103            let (path, created) = try dailies.ensure(day)
104            if created { refresh() }
105            open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
106        } catch {
107            show("Can't make the daily note: \(error.localizedDescription)")
108        }
109    }
110
111    /// `org-roam-dailies-capture-*`: the entry template filed at the end of the day's file,
112    /// which opens with the caret at `%?`.
113    func capture(_ day: Date) {
114        guard let dailies else { return show("No folder for daily notes") }
115        let context = CaptureContext(now: day, file: session.path ?? "", userName: NSFullUserName())
116        let questions = Capture.questions(dailies.entry, context: context)
117        func ask(_ answers: [String]) {
118            guard answers.count < questions.count else { return file(answers) }
119            let question = questions[answers.count]
120            self.ask(Prompt(key: "q\(answers.count)", message: question.prompt + ": ", initial: question.defaultValue, requireMatch: false)) { answer in
121                if let answer { ask(answers + [answer]) }
122            }
123        }
124        func file(_ answers: [String]) {
125            do {
126                let (path, created) = try dailies.ensure(day)
127                if created { refresh() }
128                guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
129                let filled: (text: String, cursor: Int)
130                switch Capture.fill(dailies.entry, context: context, answers: answers) {
131                case .success(let result): filled = result
132                case .failure(.message(let message)): return show(message)
133                }
134                let template = CaptureTemplate(key: "d", name: "daily", target: .file(path), template: dailies.entry)
135                switch Capture.placement(filled.text, template: template, in: text, now: day) {
136                case .failure(.message(let message)): show(message)
137                case .success(let placed):
138                    if case .failed(let message) = session.perform(ReplaceText(old: text, new: placed.text), path: path, at: 0, expect: nil) { return show(message) }
139                    open(path, placed.start + filled.cursor)
140                }
141            } catch {
142                show("Can't make the daily note: \(error.localizedDescription)")
143            }
144        }
145        ask([])
146    }
147
148    enum NodeChoice {
149        case existing(IndexStore.Node)
150        case created(path: String, id: String, title: String)
151    }
152
153    /// `org-roam-node-read`: a node by its title, with its file's name when titles repeat. A
154    /// title no node has makes a node with it, as org-roam's default capture template does;
155    /// with Denote, `denote` asks for its keywords and makes the note.
156    private func chooseNode(_ message: String, _ then: @escaping (NodeChoice) -> Void) {
157        let all = nodes()
158        let counts = Dictionary(all.map { ($0.title, 1) }, uniquingKeysWith: +)
159        let labels = all.map { node in
160            counts[node.title, default: 0] > 1 ? "\(node.title) (\((node.location.path as NSString).lastPathComponent))" : node.title
161        }
162        ask(Prompt(key: "node", message: message, choices: labels, requireMatch: false)) { answer in
163            guard let answer else { return }
164            if let index = labels.firstIndex(of: answer) { return then(.existing(all[index])) }
165            let title = answer.trimmingCharacters(in: .whitespaces)
166            guard !title.isEmpty else { return }
167            if denote { return createDenote(title, known: all, then) }
168            guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") }
169            do {
170                let node = try RoamNode.create(title: title, in: folder)
171                refresh()
172                show("Created \((node.path as NSString).lastPathComponent)")
173                then(.created(path: node.path, id: node.id, title: title))
174            } catch {
175                show("Can't make the node: \(error)")
176            }
177        }
178    }
179
180    /// `denote`: the keywords, separated by commas or spaces, then the note in
181    /// `denote-directory`. The keywords already in file names are offered.
182    private func createDenote(_ title: String, known: [IndexStore.Node], _ then: @escaping (NodeChoice) -> Void) {
183        let keywords = Denote.keywords(known.flatMap { Denote.name(ofFile: $0.location.path).keywords })
184        ask(Prompt(key: "keywords", message: "New file KEYWORDS: ", choices: keywords, requireMatch: false)) { answer in
185            guard let answer else { return }
186            guard let folder = DenoteNote.directory(roots: roots()) else { return show("No folder for new notes") }
187            do {
188                let note = try DenoteNote.create(title: title, keywords: answer.split(whereSeparator: { $0 == "," || $0.isWhitespace }).map(String.init), in: folder)
189                refresh()
190                show("Created \((note.path as NSString).lastPathComponent)")
191                then(.created(path: note.path, id: note.id, title: title))
192            } catch {
193                show("Can't make the note: \(error)")
194            }
195        }
196    }
197
198    /// `denote-rename-file-using-front-matter`: the open file renamed from its title and
199    /// keywords, keeping its identifier and signature.
200    func renameFromFrontMatter() {
201        guard let path = session.path else { return show("No file is open") }
202        guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
203        guard let target = Denote.renamed(path, text: text) else { return show("Not a Denote note: no identifier") }
204        guard target != path else { return show("Nothing to rename") }
205        guard !FileManager.default.fileExists(atPath: target) else { return show("\((target as NSString).lastPathComponent) is already there") }
206        guard session.save(path) else { return show("Can't save \((path as NSString).lastPathComponent)") }
207        do {
208            try FileManager.default.moveItem(atPath: path, toPath: target)
209            session.kill(path)
210            refresh()
211            open(target, 0)
212            show("Renamed to \((target as NSString).lastPathComponent)")
213        } catch {
214            show("Can't rename: \(error.localizedDescription)")
215        }
216    }
217}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form