Sources/OrgApp/CaptureModel.swift

b6a348930a231ab1ffd793a69f2d512f8b60bad8
orgstar/Sources/OrgApp/CaptureModel.swift

137 lines · 7878 bytes

  1import Foundation
  2import Observation
  3import OrgConfig
  4import OrgCore
  5import OrgDocument
  6
  7extension DocumentSession {
  8    /// Places captured `text` with `template`: through the buffer when the target is open,
  9    /// otherwise in the file, created if missing, through the save path. `id` and `clock`
 10    /// targets must be resolved first (`file` names the ID's file). Returns the file and where
 11    /// the entry starts.
 12    public func capture(_ text: String, template: CaptureTemplate, root: String?, file: String? = nil, now: Date = Date()) -> Result<(path: String, offset: Int), CaptureError> {
 13        let path = file ?? Self.resolve(template.target.file, root: root)
 14        if !isOpen(path), !FileManager.default.fileExists(atPath: path) {
 15            do {
 16                try FileManager.default.createDirectory(at: URL(fileURLWithPath: path).deletingLastPathComponent(), withIntermediateDirectories: true)
 17                try Data().write(to: URL(fileURLWithPath: path))
 18            } catch {
 19                return .failure(CaptureError(message: "Can't create \(path): \(error.localizedDescription)"))
 20            }
 21        }
 22        switch perform(CapturePlacement(text: text, template: template), path: path, at: 0, expect: nil, now: now) {
 23        case .commit(let result): return .success((path, result.selection?.first?.lowerBound ?? 0))
 24        case .failed(let message): return .failure(CaptureError(message: message))
 25        default: return .failure(CaptureError(message: "Can't capture there."))
 26        }
 27    }
 28
 29    /// A template's file: absolute, `~/…`, or relative to `root`.
 30    public static func resolve(_ file: String, root: String?) -> String {
 31        CaptureTemplates.path(file, root: root)
 32    }
 33
 34    /// `%a`: a link to the heading at the caret, as `org-store-link` makes one.
 35    public func captureAnnotation() -> String {
 36        guard let path, self.document != nil else { return "" }
 37        let abbreviated = path.hasPrefix(OrgPaths.home) ? "~" + path.dropFirst(OrgPaths.home.count) : Substring(path)
 38        guard let entry = outline.last(where: { $0.start <= caret }) else { return "[[file:\(abbreviated)]]" }
 39        return "[[file:\(abbreviated)::*\(entry.title)][\(entry.title)]]"
 40    }
 41}
 42
 43public struct CaptureError: Error, Equatable {
 44    public let message: String
 45    public init(message: String) { self.message = message }
 46}
 47
 48extension DocumentSession {
 49    /// Shortcuts' "Capture to Orgstar": `text` as `%i` in the template keyed `key` (the first
 50    /// when nil or empty), its prompts taking their defaults, filed without the capture window.
 51    /// The template used.
 52    public func capture(
 53        _ text: String, templateKey key: String?, templates: [CaptureTemplate], workspace: WorkspaceModel, clock: ClockModel,
 54        clipboard: String, userName: String
 55    ) -> Result<CaptureTemplate, CaptureError> {
 56        capture(text, templateKey: key, templates: templates, workspace: workspace, clock: clock, clipboard: clipboard, userName: userName).map(\.template)
 57    }
 58
 59    /// `capture(_:templateKey:…)` with prompts answered by their prompt text (`%^{What}` by
 60    /// `answers["What"]`, empty when missing) and org-protocol's link properties for `%a`,
 61    /// `%:link` and the like. The template used, and the file and offset of the entry.
 62    public func capture(
 63        _ text: String, templateKey key: String?, templates: [CaptureTemplate], workspace: WorkspaceModel, clock: ClockModel,
 64        clipboard: String, userName: String, answers: [String: String] = [:], properties: [String: String] = [:]
 65    ) -> Result<(template: CaptureTemplate, path: String, offset: Int), CaptureError> {
 66        filled(text, templateKey: key, templates: templates, workspace: workspace, clipboard: clipboard, userName: userName,
 67               answers: answers, properties: properties).flatMap { chosen, filled in
 68            file(filled, with: chosen, workspace: workspace, clock: clock)
 69        }
 70    }
 71
 72    /// `capture(_:templateKey:…)` with the `capture-before-finalize` hooks run on the filled
 73    /// template first. A hook from a file not trusted here is skipped, since nothing asks.
 74    public func captureRunningHooks(
 75        _ text: String, templateKey key: String?, templates: [CaptureTemplate], workspace: WorkspaceModel, clock: ClockModel,
 76        clipboard: String, userName: String, answers: [String: String] = [:], properties: [String: String] = [:]
 77    ) async -> Result<(template: CaptureTemplate, path: String, offset: Int), CaptureError> {
 78        let chosen: CaptureTemplate, filledText: String
 79        switch filled(text, templateKey: key, templates: templates, workspace: workspace, clipboard: clipboard, userName: userName,
 80                      answers: answers, properties: properties) {
 81        case .failure(let error): return .failure(error)
 82        case .success(let prepared): (chosen, filledText) = prepared
 83        }
 84        switch await runCaptureHooks(filledText, template: chosen.key, interactive: false) {
 85        case .failure(let error): return .failure(error)
 86        case .success(let text): return file(text, with: chosen, workspace: workspace, clock: clock)
 87        }
 88    }
 89
 90    private func file(_ text: String, with chosen: CaptureTemplate, workspace: WorkspaceModel, clock: ClockModel)
 91        -> Result<(template: CaptureTemplate, path: String, offset: Int), CaptureError> {
 92        chosen.resolved(workspace: workspace, session: self, clock: clock).flatMap { resolved in
 93            capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file)
 94        }.map { (chosen, $0.path, $0.offset) }
 95    }
 96
 97    /// The template keyed `key` and its text filled as `capture(_:templateKey:…)` fills it.
 98    private func filled(
 99        _ text: String, templateKey key: String?, templates: [CaptureTemplate], workspace: WorkspaceModel,
100        clipboard: String, userName: String, answers: [String: String], properties: [String: String]
101    ) -> Result<(CaptureTemplate, String), CaptureError> {
102        let key = key.flatMap { $0.isEmpty ? nil : $0 }
103        guard let chosen = key.map({ key in templates.first { $0.key == key } }) ?? templates.first else {
104            return .failure(CaptureError(message: "No capture template \"\(key ?? "")\""))
105        }
106        var context = CaptureContext(initial: text, clipboard: clipboard, userName: userName, allTags: (try? workspace.index.tags()) ?? [])
107        if let annotation = properties["annotation"] { context.annotation = annotation }
108        context.linkProperties = properties
109        context.readsTemplateFiles()
110        let answers = Capture.questions(chosen.template, context: context).map { answers[$0.prompt] ?? "" }
111        guard case .success(let filled) = Capture.fill(chosen.template, context: context, answers: answers) else {
112            return .failure(CaptureError(message: "Can't fill template \"\(chosen.key)\""))
113        }
114        return .success((chosen, filled.text))
115    }
116}
117
118extension CaptureTemplate {
119    /// `id` and `clock` targets as a file and a heading.
120    @MainActor
121    public func resolved(
122        workspace: WorkspaceModel, session: DocumentSession, clock: ClockModel
123    ) -> Result<(template: CaptureTemplate, file: String?), CaptureError> {
124        switch target {
125        case .id(let id):
126            guard let location = try? workspace.index.headings(withID: id).first else {
127                return .failure(CaptureError(message: "Cannot find target ID \"\(id)\""))
128            }
129            return .success((self, location.path))
130        case .clock:
131            guard let entry = clock.entry(session) else { return .failure(CaptureError(message: "No running clock")) }
132            return .success((retargeted(.heading(file: entry.path, offset: entry.offset)), entry.path))
133        default:
134            return .success((self, nil))
135        }
136    }
137}
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