Sources/OrgApp/CaptureModel.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgApp/CaptureModel.swift

266 lines · 13771 bytes

19 symbols in this file
  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) && RoamTemplate.Set(rawValue: table.name) == nil {
 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 || values["denote"]?.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            templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options(values)))
 90        }
 91        return (templates.isEmpty ? defaults : templates, templates.isEmpty ? [] : groups, problems)
 92    }
 93
 94    /// A table's template properties beyond the target.
 95    nonisolated static func options(_ values: [String: TOML.Value]) -> CaptureTemplate.Options {
 96        func flag(_ name: String) -> Bool { values[name]?.bool ?? false }
 97        func lines(_ name: String) -> Int? { values[name]?.integer }
 98        return CaptureTemplate.Options(
 99            prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"),
100            emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"),
101            jumpToCaptured: flag("jump-to-captured"), clockIn: flag("clock-in"), clockKeep: flag("clock-keep"), clockResume: flag("clock-resume"),
102            tableLinePos: values["table-line-pos"]?.string, timePrompt: flag("time-prompt"), denote: flag("denote")
103        )
104    }
105
106    /// What `org-capture` lists after the keys typed so far: the groups and templates one key
107    /// longer, in the templates' order. A template with no group for its prefix is listed
108    /// too, so that it can be reached.
109    public static func menu(_ templates: [CaptureTemplate], groups: [CaptureGroup], typed: String) -> [CaptureMenuItem] {
110        let depth = typed.count + 1
111        var items: [CaptureMenuItem] = []
112        var shown: Set<String> = []
113        for template in templates where template.key.hasPrefix(typed) {
114            if template.key.count > depth, let group = groups.first(where: { $0.key == String(template.key.prefix(depth)) }) {
115                if shown.insert(group.key).inserted { items.append(.group(group)) }
116            } else {
117                items.append(.template(template))
118            }
119        }
120        for group in groups where group.key.hasPrefix(typed) && group.key.count == depth && !shown.contains(group.key) { items.append(.group(group)) }
121        return items
122    }
123
124    /// The template's name after the names of the groups above it: `Work › Meeting`.
125    public static func label(_ template: CaptureTemplate, groups: [CaptureGroup]) -> String {
126        let names = (1..<max(1, template.key.count)).compactMap { n in groups.first { $0.key == String(template.key.prefix(n)) }?.name }
127        return (names + [template.name]).joined(separator: " › ")
128    }
129}
130
131/// A key and a description with no template: `("w" "Work")` in `org-capture-templates`.
132public struct CaptureGroup: Sendable, Equatable, Identifiable {
133    public let key: String
134    public let name: String
135    public var id: String { key }
136    public init(key: String, name: String) {
137        self.key = key
138        self.name = name
139    }
140}
141
142public enum CaptureMenuItem: Identifiable {
143    case group(CaptureGroup)
144    case template(CaptureTemplate)
145    public var key: String {
146        switch self {
147        case .group(let g): g.key
148        case .template(let t): t.key
149        }
150    }
151    public var id: String { key }
152}
153
154extension DocumentSession {
155    /// Places captured `text` with `template`: through the buffer when the target is open,
156    /// otherwise in the file, created if missing, through the save path. `id` and `clock`
157    /// targets must be resolved first (`file` names the ID's file). Returns the file and where
158    /// the entry starts.
159    public func capture(_ text: String, template: CaptureTemplate, root: String?, file: String? = nil, now: Date = Date()) -> Result<(path: String, offset: Int), CaptureError> {
160        let path = file ?? Self.resolve(template.target.file, root: root)
161        if !isOpen(path), !FileManager.default.fileExists(atPath: path) {
162            do {
163                try FileManager.default.createDirectory(at: URL(fileURLWithPath: path).deletingLastPathComponent(), withIntermediateDirectories: true)
164                try Data().write(to: URL(fileURLWithPath: path))
165            } catch {
166                return .failure(CaptureError(message: "Can't create \(path): \(error.localizedDescription)"))
167            }
168        }
169        switch perform(CapturePlacement(text: text, template: template), path: path, at: 0, expect: nil, now: now) {
170        case .commit(let result): return .success((path, result.selection?.first?.lowerBound ?? 0))
171        case .failed(let message): return .failure(CaptureError(message: message))
172        default: return .failure(CaptureError(message: "Can't capture there."))
173        }
174    }
175
176    /// A template's file: absolute, `~/…`, or relative to `root`.
177    public static func resolve(_ file: String, root: String?) -> String {
178        if file.hasPrefix("/") { return file }
179        if file.hasPrefix("~") { return OrgPaths.expandingTilde(file) }
180        return ((root ?? OrgPaths.home) as NSString).appendingPathComponent(file)
181    }
182
183    /// `%a`: a link to the heading at the caret, as `org-store-link` makes one.
184    public func captureAnnotation() -> String {
185        guard let path, self.document != nil else { return "" }
186        let abbreviated = path.hasPrefix(OrgPaths.home) ? "~" + path.dropFirst(OrgPaths.home.count) : Substring(path)
187        guard let entry = outline.last(where: { $0.start <= caret }) else { return "[[file:\(abbreviated)]]" }
188        return "[[file:\(abbreviated)::*\(entry.title)][\(entry.title)]]"
189    }
190}
191
192extension CaptureContext {
193    /// `%[file]` reads the file, a relative path from the configuration folder.
194    public mutating func readsTemplateFiles(from directory: URL = UserConfig.directory) {
195        self.directory = directory.path
196        readFile = { try? String(contentsOfFile: $0, encoding: .utf8) }
197    }
198}
199
200public struct CaptureError: Error, Equatable {
201    public let message: String
202    public init(message: String) { self.message = message }
203}
204
205/// The edit `Capture.place` makes, as a command so the save path applies it. The selection
206/// it leaves is the captured entry's start.
207struct CapturePlacement: OrgCommand {
208    let text: String
209    let template: CaptureTemplate
210    var id: String { "internal.capture" }
211    var title: String { "Capture" }
212    func applies(in context: EditContext) -> Bool { true }
213    func run(in context: EditContext) -> CommandStep {
214        switch Capture.placement(text, template: template, in: context.text, settings: context.tree.settings, now: context.now, calendar: context.calendar) {
215        case .failure(.message(let message)):
216            return .failed(message)
217        case .success(let placed):
218            return .commit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, placed.text), selection: [placed.start..<placed.start]))
219        }
220    }
221}
222
223extension DocumentSession {
224    /// Shortcuts' "Capture to Orgstar": `text` as `%i` in the template keyed `key` (the first
225    /// when nil or empty), its prompts taking their defaults, filed without the capture window.
226    /// The template used.
227    public func capture(
228        _ text: String, templateKey key: String?, templates: [CaptureTemplate], workspace: WorkspaceModel, clock: ClockModel,
229        clipboard: String, userName: String
230    ) -> Result<CaptureTemplate, CaptureError> {
231        let key = key.flatMap { $0.isEmpty ? nil : $0 }
232        guard let chosen = key.map({ key in templates.first { $0.key == key } }) ?? templates.first else {
233            return .failure(CaptureError(message: "No capture template \"\(key ?? "")\""))
234        }
235        var context = CaptureContext(initial: text, clipboard: clipboard, userName: userName, allTags: (try? workspace.index.tags()) ?? [])
236        context.readsTemplateFiles()
237        let answers = Capture.questions(chosen.template, context: context).map { _ in "" }
238        guard case .success(let filled) = Capture.fill(chosen.template, context: context, answers: answers) else {
239            return .failure(CaptureError(message: "Can't fill template \"\(chosen.key)\""))
240        }
241        return chosen.resolved(workspace: workspace, session: self, clock: clock).flatMap { resolved in
242            capture(filled.text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file)
243        }.map { _ in chosen }
244    }
245}
246
247extension CaptureTemplate {
248    /// `id` and `clock` targets as a file and a heading.
249    @MainActor
250    public func resolved(
251        workspace: WorkspaceModel, session: DocumentSession, clock: ClockModel
252    ) -> Result<(template: CaptureTemplate, file: String?), CaptureError> {
253        switch target {
254        case .id(let id):
255            guard let location = try? workspace.index.headings(withID: id).first else {
256                return .failure(CaptureError(message: "Cannot find target ID \"\(id)\""))
257            }
258            return .success((self, location.path))
259        case .clock:
260            guard let entry = clock.entry(session) else { return .failure(CaptureError(message: "No running clock")) }
261            return .success((retargeted(.heading(file: entry.path, offset: entry.offset)), entry.path))
262        default:
263            return .success((self, nil))
264        }
265    }
266}
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