Sources/OrgApp/CaptureModel.swift

b7b7f8ef81367a5e787840c1b28d8a82bf7da545
orgstar/Sources/OrgApp/CaptureModel.swift history · blame · raw

149 lines · 8005 bytes

  1import Foundation
  2import Observation
  3import OrgCore
  4import OrgDocument
  5
  6/// Capture templates from `capture.toml`, and capturing into their targets:
  7///
  8/// ```toml
  9/// [[template]]
 10/// key = "t"
 11/// name = "Personal todo"
 12/// type = "entry"            # entry, item, checkitem or plain
 13/// file = "todo.org"         # relative to the first folder, or ~/… or /…
 14/// headline = "Inbox"        # or olp = "Projects/Work"; neither for the end of the file
 15/// template = "* TODO %?\n%i\n%a"
 16/// prepend = false
 17/// ```
 18///
 19/// Other targets: `datetree = true` (under `olp` if given; `tree-type` "day", "week" or
 20/// "month"), `id = "…"` without `file`, `clock = true` without `file`. Other properties, as
 21/// in `org-capture-templates`: `immediate-finish`, `empty-lines`, `empty-lines-before`,
 22/// `empty-lines-after`, `jump-to-captured`, `clock-in`, `clock-keep`, `clock-resume`.
 23@MainActor
 24public enum CaptureTemplates {
 25    public static var userFile: URL { UserConfig.file("capture.toml") }
 26
 27    /// The templates in your Doom configuration.
 28    public static let defaults = [
 29        CaptureTemplate(key: "t", name: "Personal todo", target: .headline(file: "todo.org", headline: "Inbox"), template: "* TODO %?\n%i\n%a"),
 30        CaptureTemplate(key: "n", name: "Personal notes", target: .headline(file: "notes.org", headline: "Inbox"), template: "* %u %?\n%i\n%a"),
 31    ]
 32
 33    public static func load(userFile: URL = userFile) -> (templates: [CaptureTemplate], problems: [String]) {
 34        guard let text = try? String(contentsOf: userFile, encoding: .utf8) else { return (defaults, []) }
 35        let tables: [TOML.Table]
 36        do {
 37            tables = try TOML.parse(text)
 38        } catch {
 39            return (defaults, ["capture.toml: \(error)"])
 40        }
 41        var templates: [CaptureTemplate] = []
 42        var problems: [String] = []
 43        for table in tables where !(table.name.isEmpty && table.values.isEmpty) {
 44            guard table.name == "template", table.isArrayElement else {
 45                problems.append("capture.toml line \(table.line): expected [[template]]")
 46                continue
 47            }
 48            let values = table.values
 49            let fileless = values["id"]?.string != nil || values["clock"]?.bool == true
 50            guard let key = values["key"]?.string, let body = values["template"]?.string, let file = values["file"]?.string ?? (fileless ? "" : nil) else {
 51                problems.append("capture.toml line \(table.line): a template needs key, file and template")
 52                continue
 53            }
 54            guard let kind = CaptureTemplate.Kind(rawValue: table.values["type"]?.string ?? "entry") else {
 55                problems.append("capture.toml line \(table.line): unknown type")
 56                continue
 57            }
 58            let olp = values["olp"]?.string.map { $0.split(separator: "/").map(String.init) }
 59            let target: CaptureTemplate.Target
 60            if let id = values["id"]?.string {
 61                target = .id(id)
 62            } else if values["clock"]?.bool == true {
 63                target = .clock
 64            } else if values["datetree"]?.bool == true {
 65                guard let tree = CaptureTemplate.TreeType(rawValue: values["tree-type"]?.string ?? "day") else {
 66                    problems.append("capture.toml line \(table.line): tree-type is day, week or month")
 67                    continue
 68                }
 69                target = .datetree(file: file, path: olp ?? [], tree: tree)
 70            } else if let headline = values["headline"]?.string {
 71                target = .headline(file: file, headline: headline)
 72            } else if let olp {
 73                target = .outline(file: file, path: olp)
 74            } else {
 75                target = .file(file)
 76            }
 77            func flag(_ name: String) -> Bool { values[name]?.bool ?? false }
 78            func lines(_ name: String) -> Int? { values[name]?.integer }
 79            let options = CaptureTemplate.Options(
 80                prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"),
 81                emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"),
 82                jumpToCaptured: flag("jump-to-captured"), clockIn: flag("clock-in"), clockKeep: flag("clock-keep"), clockResume: flag("clock-resume")
 83            )
 84            templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options))
 85        }
 86        return (templates.isEmpty ? defaults : templates, problems)
 87    }
 88}
 89
 90extension DocumentSession {
 91    /// Places captured `text` with `template`: through the buffer when the target is open,
 92    /// otherwise in the file, created if missing, through the save path. `id` and `clock`
 93    /// targets must be resolved first (`file` names the ID's file). Returns the file and where
 94    /// the entry starts.
 95    public func capture(_ text: String, template: CaptureTemplate, root: String?, file: String? = nil, now: Date = Date()) -> Result<(path: String, offset: Int), CaptureError> {
 96        let path = file ?? Self.resolve(template.target.file, root: root)
 97        if !isOpen(path), !FileManager.default.fileExists(atPath: path) {
 98            do {
 99                try FileManager.default.createDirectory(at: URL(fileURLWithPath: path).deletingLastPathComponent(), withIntermediateDirectories: true)
100                try Data().write(to: URL(fileURLWithPath: path))
101            } catch {
102                return .failure(CaptureError(message: "Can't create \(path): \(error.localizedDescription)"))
103            }
104        }
105        switch perform(CapturePlacement(text: text, template: template), path: path, at: 0, expect: nil, now: now) {
106        case .commit(let result): return .success((path, result.selection?.first?.lowerBound ?? 0))
107        case .failed(let message): return .failure(CaptureError(message: message))
108        default: return .failure(CaptureError(message: "Can't capture there."))
109        }
110    }
111
112    /// A template's file: absolute, `~/…`, or relative to `root`.
113    public static func resolve(_ file: String, root: String?) -> String {
114        if file.hasPrefix("/") { return file }
115        if file.hasPrefix("~") { return (file as NSString).expandingTildeInPath }
116        return ((root ?? FileManager.default.homeDirectoryForCurrentUser.path) as NSString).appendingPathComponent(file)
117    }
118
119    /// `%a`: a link to the heading at the caret, as `org-store-link` makes one.
120    public func captureAnnotation() -> String {
121        guard let path, self.document != nil else { return "" }
122        let abbreviated = path.hasPrefix(NSHomeDirectory()) ? "~" + path.dropFirst(NSHomeDirectory().count) : Substring(path)
123        guard let entry = outline.last(where: { $0.start <= caret }) else { return "[[file:\(abbreviated)]]" }
124        return "[[file:\(abbreviated)::*\(entry.title)][\(entry.title)]]"
125    }
126}
127
128public struct CaptureError: Error, Equatable {
129    public let message: String
130    public init(message: String) { self.message = message }
131}
132
133/// The edit `Capture.place` makes, as a command so the save path applies it. The selection
134/// it leaves is the captured entry's start.
135struct CapturePlacement: OrgCommand {
136    let text: String
137    let template: CaptureTemplate
138    var id: String { "internal.capture" }
139    var title: String { "Capture" }
140    func applies(in context: EditContext) -> Bool { true }
141    func run(in context: EditContext) -> CommandStep {
142        switch Capture.placement(text, template: template, in: context.text, settings: context.tree.settings, now: context.now, calendar: context.calendar) {
143        case .failure(.message(let message)):
144            return .failed(message)
145        case .success(let placed):
146            return .commit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, placed.text), selection: [placed.start..<placed.start]))
147        }
148    }
149}