Sources/OrgApp/RoamCapture.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgApp/RoamCapture.swift

189 lines · 10403 bytes

9 symbols in this file
  1import Foundation
  2import OrgCore
  3
  4/// An org-roam capture template, from `capture.toml`:
  5///
  6/// ```toml
  7/// [[roam-template]]            # org-roam-capture-templates
  8/// key = "d"
  9/// name = "default"
 10/// type = "plain"               # as for [[template]]; plain unless set
 11/// template = "%?"
 12/// file = "%<%Y%m%d%H%M%S>-${slug}.org"
 13/// head = "#+title: ${title}\n"
 14/// olp = "Projects/Active"      # file+head+olp; the headings are made when missing
 15/// ```
 16///
 17/// `[[roam-dailies-template]]` (`org-roam-dailies-capture-templates`) is the same, an `entry`
 18/// unless set, with `file` in the daily-notes folder; `[[roam-ref-template]]`
 19/// (`org-roam-capture-ref-templates`) is for org-protocol's `roam-ref`. `${title}`, `${slug}`
 20/// and `${id}` fill in the node's title, slug and ID, and for a ref, `${ref}` and `${body}`.
 21/// The other properties of `[[template]]` apply.
 22public struct RoamTemplate: Sendable, Equatable {
 23    public enum Set: String, Sendable {
 24        case node = "roam-template", dailies = "roam-dailies-template", ref = "roam-ref-template"
 25    }
 26
 27    public var key: String
 28    public var name: String
 29    public var kind: CaptureTemplate.Kind
 30    public var template: String
 31    public var file: String
 32    public var head: String
 33    public var olp: [String]
 34    public var options: CaptureTemplate.Options
 35
 36    public init(key: String, name: String, kind: CaptureTemplate.Kind, template: String, file: String, head: String, olp: [String] = [],
 37                options: CaptureTemplate.Options = CaptureTemplate.Options()) {
 38        self.key = key
 39        self.name = name
 40        self.kind = kind
 41        self.template = template
 42        self.file = file
 43        self.head = head
 44        self.olp = olp
 45        self.options = options
 46    }
 47
 48    /// org-roam's defaults; for daily notes, the `org-roam-dailies-…` settings.
 49    public static func defaults(_ set: Set, defaults: UserDefaults = .standard) -> [RoamTemplate] {
 50        switch set {
 51        case .node: [RoamTemplate(key: "d", name: "default", kind: .plain, template: "%?", file: "%<%Y%m%d%H%M%S>-${slug}.org", head: "#+title: ${title}\n")]
 52        case .dailies: [RoamTemplate(key: "d", name: "default", kind: .entry, template: OrgPreferences.dailiesEntry(defaults),
 53                                     file: OrgPreferences.dailiesFile(defaults), head: OrgPreferences.dailiesHead(defaults))]
 54        case .ref: [RoamTemplate(key: "r", name: "ref", kind: .plain, template: "%?", file: "${slug}.org", head: "#+title: ${title}")]
 55        }
 56    }
 57
 58    /// The set's templates in `capture.toml`, or the defaults when it has none, and what was
 59    /// wrong with the tables left out.
 60    public static func load(_ set: Set, userFile: URL = UserConfig.file("capture.toml"), defaults: UserDefaults = .standard) -> (templates: [RoamTemplate], problems: [String]) {
 61        guard let text = try? String(contentsOf: userFile, encoding: .utf8), let tables = try? TOML.parse(text) else { return (Self.defaults(set, defaults: defaults), []) }
 62        var templates: [RoamTemplate] = [], problems: [String] = []
 63        let fallback = Self.defaults(set, defaults: defaults)[0]
 64        for table in tables where table.name == set.rawValue {
 65            let values = table.values
 66            guard let key = values["key"]?.string, !key.isEmpty, let body = values["template"]?.string else {
 67                problems.append("capture.toml line \(table.line): a [[\(set.rawValue)]] needs key and template")
 68                continue
 69            }
 70            guard let kind = CaptureTemplate.Kind(rawValue: values["type"]?.string ?? fallback.kind.rawValue) else {
 71                problems.append("capture.toml line \(table.line): unknown type")
 72                continue
 73            }
 74            templates.append(RoamTemplate(
 75                key: key, name: values["name"]?.string ?? key, kind: kind, template: body, file: values["file"]?.string ?? fallback.file,
 76                head: values["head"]?.string ?? (values["file"] == nil ? fallback.head : ""),
 77                olp: values["olp"]?.string.map { $0.split(separator: "/").map(String.init) } ?? [], options: CaptureTemplates.options(values)))
 78        }
 79        return (templates.isEmpty ? Self.defaults(set, defaults: defaults) : templates, problems)
 80    }
 81
 82    /// `org-roam-format-template`: `${name}` for each field there is a value for.
 83    static func fill(_ text: String, _ fields: [String: String]) -> String {
 84        text.replacing(/\$\{([^}:]+)(?::[^}]*)?\}/) { match in fields[String(match.1)] ?? String(match.0) }
 85    }
 86}
 87
 88/// An org-roam capture (`org-roam-capture-`) waiting for the capture window: the templates to
 89/// choose from, each aimed at its file. Filing makes the file when it's new, with the head and
 90/// an `ID`, or gives an existing one an `ID` when it has none, then places the entry as
 91/// `org-capture` does and calls back with the node's ID.
 92@MainActor
 93public final class RoamCapture: Identifiable {
 94    public let templates: [CaptureTemplate]
 95    /// The date the templates' escapes use: a daily note's day, else when capture began.
 96    public let now: Date
 97    /// Each template's head, filled in, by key.
 98    let heads: [String: String]
 99    /// Put in a new file's property drawer after the ID: a ref capture's `ROAM_REFS`.
100    let properties: [(key: String, value: String)]
101    let session: DocumentSession
102    let refresh: () -> Void
103    let filed: (_ path: String, _ offset: Int, _ id: String) -> Void
104    /// A new file's ID.
105    let newID: String
106    /// Whether the file gets an `ID`; not for a Denote journal entry.
107    let ids: Bool
108
109    /// `templates` filled in for a node titled `title`, their files under `directory`.
110    public init(
111        _ templates: [RoamTemplate], title: String, directory: String, now: Date = Date(), fields: [String: String] = [:],
112        properties: [(key: String, value: String)] = [], ids: Bool = true, session: DocumentSession, refresh: @escaping () -> Void,
113        newID: String = UUID().uuidString.lowercased(), filed: @escaping (_ path: String, _ offset: Int, _ id: String) -> Void
114    ) {
115        let fields = ["title": title, "slug": RoamNode.slug(title), "id": newID].merging(fields) { $1 }
116        var context = CaptureContext(now: now, userName: NSFullUserName())
117        context.readsTemplateFiles()
118        var heads: [String: String] = [:]
119        self.templates = templates.map { template in
120            let name = Dailies.expandTime(RoamTemplate.fill(template.file, fields), now).trimmingCharacters(in: .whitespaces)
121            let path = OrgAttach.expand(name, in: directory)
122            let head = RoamTemplate.fill(template.head, fields)
123            if case .success(let filled) = Capture.fill(head, context: context) { heads[template.key] = filled.text } else { heads[template.key] = Dailies.expandTime(head, now) }
124            return CaptureTemplate(key: template.key, name: template.name, kind: template.kind,
125                                   target: template.olp.isEmpty ? .file(path) : .outline(file: path, path: template.olp),
126                                   template: RoamTemplate.fill(template.template, fields), options: template.options)
127        }
128        self.now = now
129        self.heads = heads
130        self.properties = properties
131        self.session = session
132        self.refresh = refresh
133        self.newID = newID
134        self.ids = ids
135        self.filed = filed
136    }
137
138    /// The template's file: `head` filled in at the top of a new file.
139    public func isNew(_ template: CaptureTemplate) -> Bool {
140        !session.isOpen(template.target.file) && !FileManager.default.fileExists(atPath: template.target.file)
141    }
142
143    /// Files `text`, the capture window's text, with `template`.
144    public func file(_ text: String, with template: CaptureTemplate) -> Result<(path: String, offset: Int), CaptureError> {
145        let path = template.target.file
146        var olp: [String] = []
147        if case .outline(_, let path) = template.target { olp = path }
148        let created = isNew(template)
149        let id: String
150        if created {
151            var head = heads[template.key] ?? ""
152            if !head.isEmpty, !head.hasSuffix("\n") { head += "\n" }
153            let prepared = ids ? RoamTarget.prepare(head, properties: properties, olp: olp) { newID } : (text: head, id: "")
154            do {
155                try FileManager.default.createDirectory(atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
156                try Data(prepared.text.utf8).write(to: URL(fileURLWithPath: path), options: .withoutOverwriting)
157            } catch {
158                return .failure(CaptureError(message: "Can't make \((path as NSString).lastPathComponent): \(error.localizedDescription)"))
159            }
160            id = prepared.id
161        } else {
162            guard let text = session.text(of: path) else { return .failure(CaptureError(message: "Can't read \((path as NSString).lastPathComponent)")) }
163            let prepared = ids ? RoamTarget.prepare(text, olp: olp) { newID } : (text: text, id: "")
164            if prepared.text != text, case .failed(let message) = session.perform(ReplaceText(old: text, new: prepared.text), path: path, at: 0, expect: nil) {
165                return .failure(CaptureError(message: message))
166            }
167            id = prepared.id
168        }
169        let placed = session.capture(text, template: template, root: nil, file: path, now: now)
170        if case .success(let entry) = placed {
171            if created { refresh() }
172            filed(entry.path, entry.offset, id)
173        }
174        return placed
175    }
176
177    /// Files the first template's text with its questions unanswered, without the capture
178    /// window.
179    public func fileFirst() -> Result<(path: String, offset: Int), CaptureError> {
180        guard let template = templates.first else { return .failure(CaptureError(message: "No template")) }
181        var context = CaptureContext(now: now, userName: NSFullUserName())
182        context.readsTemplateFiles()
183        let answers = Capture.questions(template.template, context: context).map { _ in "" }
184        switch Capture.fill(template.template, context: context, answers: answers) {
185        case .success(let filled): return file(filled.text, with: template)
186        case .failure(.message(let message)): return .failure(CaptureError(message: message))
187        }
188    }
189}
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