Sources/OrgApp/CaptureModel.swift

262 lines · 13556 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, plain or table-line
 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",
 20/// "month", or groups such as "year quarter month"), `regexp = "…"` with `file`,
 21/// `id = "…"` without `file`, `clock = true` without `file`. Other properties, as in
 22/// `org-capture-templates`: `immediate-finish`, `empty-lines`, `empty-lines-before`,
 23/// `empty-lines-after`, `jump-to-captured`, `clock-in`, `clock-keep`, `clock-resume`,
 24/// `table-line-pos`, `time-prompt`.
 25///
 26/// A `[[template]]` with only `key` and `name` is a group: the templates whose keys start
 27/// with its key are listed under it.
 28@MainActor
 29public enum CaptureTemplates {
 30    public static var userFile: URL { UserConfig.file("capture.toml") }
 31
 32    /// The templates in your Doom configuration.
 33    public static let defaults = [
 34        CaptureTemplate(key: "t", name: "Personal todo", target: .headline(file: "todo.org", headline: "Inbox"), template: "* TODO %?\n%i\n%a"),
 35        CaptureTemplate(key: "n", name: "Personal notes", target: .headline(file: "notes.org", headline: "Inbox"), template: "* %u %?\n%i\n%a"),
 36    ]
 37
 38    public static func load(userFile: URL = userFile) -> (templates: [CaptureTemplate], groups: [CaptureGroup], problems: [String]) {
 39        guard let text = try? String(contentsOf: userFile, encoding: .utf8) else { return (defaults, [], []) }
 40        let tables: [TOML.Table]
 41        do {
 42            tables = try TOML.parse(text)
 43        } catch {
 44            return (defaults, [], ["capture.toml: \(error)"])
 45        }
 46        var templates: [CaptureTemplate] = []
 47        var groups: [CaptureGroup] = []
 48        var problems: [String] = []
 49        for table in tables where !(table.name.isEmpty && table.values.isEmpty) {
 50            guard table.name == "template", table.isArrayElement else {
 51                problems.append("capture.toml line \(table.line): expected [[template]]")
 52                continue
 53            }
 54            let values = table.values
 55            if let key = values["key"]?.string, let name = values["name"]?.string, values.count == 2 {
 56                groups.append(CaptureGroup(key: key, name: name))
 57                continue
 58            }
 59            let fileless = values["id"]?.string != nil || values["clock"]?.bool == true
 60            guard let key = values["key"]?.string, let body = values["template"]?.string, let file = values["file"]?.string ?? (fileless ? "" : nil) else {
 61                problems.append("capture.toml line \(table.line): a template needs key, file and template")
 62                continue
 63            }
 64            guard let kind = CaptureTemplate.Kind(rawValue: table.values["type"]?.string ?? "entry") else {
 65                problems.append("capture.toml line \(table.line): unknown type")
 66                continue
 67            }
 68            let olp = values["olp"]?.string.map { $0.split(separator: "/").map(String.init) }
 69            let target: CaptureTemplate.Target
 70            if let id = values["id"]?.string {
 71                target = .id(id)
 72            } else if values["clock"]?.bool == true {
 73                target = .clock
 74            } else if values["datetree"]?.bool == true {
 75                guard let tree = CaptureTemplate.TreeType(rawValue: values["tree-type"]?.string ?? "day") else {
 76                    problems.append("capture.toml line \(table.line): tree-type is day, week, month, or some of year, quarter, month, week and day")
 77                    continue
 78                }
 79                target = .datetree(file: file, path: olp ?? [], tree: tree)
 80            } else if let regexp = values["regexp"]?.string {
 81                target = .regexp(file: file, regexp: regexp)
 82            } else if let headline = values["headline"]?.string {
 83                target = .headline(file: file, headline: headline)
 84            } else if let olp {
 85                target = .outline(file: file, path: olp)
 86            } else {
 87                target = .file(file)
 88            }
 89            func flag(_ name: String) -> Bool { values[name]?.bool ?? false }
 90            func lines(_ name: String) -> Int? { values[name]?.integer }
 91            let options = CaptureTemplate.Options(
 92                prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"),
 93                emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"),
 94                jumpToCaptured: flag("jump-to-captured"), clockIn: flag("clock-in"), clockKeep: flag("clock-keep"), clockResume: flag("clock-resume"),
 95                tableLinePos: values["table-line-pos"]?.string, timePrompt: flag("time-prompt")
 96            )
 97            templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options))
 98        }
 99        return (templates.isEmpty ? defaults : templates, templates.isEmpty ? [] : groups, problems)
100    }
101
102    /// What `org-capture` lists after the keys typed so far: the groups and templates one key
103    /// longer, in the templates' order. A template with no group for its prefix is listed
104    /// too, so that it can be reached.
105    public static func menu(_ templates: [CaptureTemplate], groups: [CaptureGroup], typed: String) -> [CaptureMenuItem] {
106        let depth = typed.count + 1
107        var items: [CaptureMenuItem] = []
108        var shown: Set<String> = []
109        for template in templates where template.key.hasPrefix(typed) {
110            if template.key.count > depth, let group = groups.first(where: { $0.key == String(template.key.prefix(depth)) }) {
111                if shown.insert(group.key).inserted { items.append(.group(group)) }
112            } else {
113                items.append(.template(template))
114            }
115        }
116        for group in groups where group.key.hasPrefix(typed) && group.key.count == depth && !shown.contains(group.key) { items.append(.group(group)) }
117        return items
118    }
119
120    /// The template's name after the names of the groups above it: `Work › Meeting`.
121    public static func label(_ template: CaptureTemplate, groups: [CaptureGroup]) -> String {
122        let names = (1..<max(1, template.key.count)).compactMap { n in groups.first { $0.key == String(template.key.prefix(n)) }?.name }
123        return (names + [template.name]).joined(separator: " › ")
124    }
125}
126
127/// A key and a description with no template: `("w" "Work")` in `org-capture-templates`.
128public struct CaptureGroup: Sendable, Equatable, Identifiable {
129    public let key: String
130    public let name: String
131    public var id: String { key }
132    public init(key: String, name: String) {
133        self.key = key
134        self.name = name
135    }
136}
137
138public enum CaptureMenuItem: Identifiable {
139    case group(CaptureGroup)
140    case template(CaptureTemplate)
141    public var key: String {
142        switch self {
143        case .group(let g): g.key
144        case .template(let t): t.key
145        }
146    }
147    public var id: String { key }
148}
149
150extension DocumentSession {
151    /// Places captured `text` with `template`: through the buffer when the target is open,
152    /// otherwise in the file, created if missing, through the save path. `id` and `clock`
153    /// targets must be resolved first (`file` names the ID's file). Returns the file and where
154    /// the entry starts.
155    public func capture(_ text: String, template: CaptureTemplate, root: String?, file: String? = nil, now: Date = Date()) -> Result<(path: String, offset: Int), CaptureError> {
156        let path = file ?? Self.resolve(template.target.file, root: root)
157        if !isOpen(path), !FileManager.default.fileExists(atPath: path) {
158            do {
159                try FileManager.default.createDirectory(at: URL(fileURLWithPath: path).deletingLastPathComponent(), withIntermediateDirectories: true)
160                try Data().write(to: URL(fileURLWithPath: path))
161            } catch {
162                return .failure(CaptureError(message: "Can't create \(path): \(error.localizedDescription)"))
163            }
164        }
165        switch perform(CapturePlacement(text: text, template: template), path: path, at: 0, expect: nil, now: now) {
166        case .commit(let result): return .success((path, result.selection?.first?.lowerBound ?? 0))
167        case .failed(let message): return .failure(CaptureError(message: message))
168        default: return .failure(CaptureError(message: "Can't capture there."))
169        }
170    }
171
172    /// A template's file: absolute, `~/…`, or relative to `root`.
173    public static func resolve(_ file: String, root: String?) -> String {
174        if file.hasPrefix("/") { return file }
175        if file.hasPrefix("~") { return (file as NSString).expandingTildeInPath }
176        return ((root ?? NSHomeDirectory()) as NSString).appendingPathComponent(file)
177    }
178
179    /// `%a`: a link to the heading at the caret, as `org-store-link` makes one.
180    public func captureAnnotation() -> String {
181        guard let path, self.document != nil else { return "" }
182        let abbreviated = path.hasPrefix(NSHomeDirectory()) ? "~" + path.dropFirst(NSHomeDirectory().count) : Substring(path)
183        guard let entry = outline.last(where: { $0.start <= caret }) else { return "[[file:\(abbreviated)]]" }
184        return "[[file:\(abbreviated)::*\(entry.title)][\(entry.title)]]"
185    }
186}
187
188extension CaptureContext {
189    /// `%[file]` reads the file, a relative path from the configuration folder.
190    public mutating func readsTemplateFiles(from directory: URL = UserConfig.directory) {
191        self.directory = directory.path
192        readFile = { try? String(contentsOfFile: $0, encoding: .utf8) }
193    }
194}
195
196public struct CaptureError: Error, Equatable {
197    public let message: String
198    public init(message: String) { self.message = message }
199}
200
201/// The edit `Capture.place` makes, as a command so the save path applies it. The selection
202/// it leaves is the captured entry's start.
203struct CapturePlacement: OrgCommand {
204    let text: String
205    let template: CaptureTemplate
206    var id: String { "internal.capture" }
207    var title: String { "Capture" }
208    func applies(in context: EditContext) -> Bool { true }
209    func run(in context: EditContext) -> CommandStep {
210        switch Capture.placement(text, template: template, in: context.text, settings: context.tree.settings, now: context.now, calendar: context.calendar) {
211        case .failure(.message(let message)):
212            return .failed(message)
213        case .success(let placed):
214            return .commit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, placed.text), selection: [placed.start..<placed.start]))
215        }
216    }
217}
218
219extension DocumentSession {
220    /// Shortcuts' "Capture to Orgstar": `text` as `%i` in the template keyed `key` (the first
221    /// when nil or empty), its prompts taking their defaults, filed without the capture window.
222    /// The template used.
223    public func capture(
224        _ text: String, templateKey key: String?, templates: [CaptureTemplate], workspace: WorkspaceModel, clock: ClockModel,
225        clipboard: String, userName: String
226    ) -> Result<CaptureTemplate, CaptureError> {
227        let key = key.flatMap { $0.isEmpty ? nil : $0 }
228        guard let chosen = key.map({ key in templates.first { $0.key == key } }) ?? templates.first else {
229            return .failure(CaptureError(message: "No capture template \"\(key ?? "")\""))
230        }
231        var context = CaptureContext(initial: text, clipboard: clipboard, userName: userName, allTags: (try? workspace.index.tags()) ?? [])
232        context.readsTemplateFiles()
233        let answers = Capture.questions(chosen.template, context: context).map { _ in "" }
234        guard case .success(let filled) = Capture.fill(chosen.template, context: context, answers: answers) else {
235            return .failure(CaptureError(message: "Can't fill template \"\(chosen.key)\""))
236        }
237        return chosen.resolved(workspace: workspace, session: self, clock: clock).flatMap { resolved in
238            capture(filled.text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file)
239        }.map { _ in chosen }
240    }
241}
242
243extension CaptureTemplate {
244    /// `id` and `clock` targets as a file and a heading.
245    @MainActor
246    public func resolved(
247        workspace: WorkspaceModel, session: DocumentSession, clock: ClockModel
248    ) -> Result<(template: CaptureTemplate, file: String?), CaptureError> {
249        switch target {
250        case .id(let id):
251            guard let location = try? workspace.index.headings(withID: id).first else {
252                return .failure(CaptureError(message: "Cannot find target ID \"\(id)\""))
253            }
254            return .success((self, location.path))
255        case .clock:
256            guard let entry = clock.entry(session) else { return .failure(CaptureError(message: "No running clock")) }
257            return .success((retargeted(.heading(file: entry.path, offset: entry.offset)), entry.path))
258        default:
259            return .success((self, nil))
260        }
261    }
262}