Sources/OrgConfig/CaptureTemplates.swift
194 lines · 9588 bytes
14 symbols in this file
1import Foundation
2import OrgCore
3
4/// Capture templates from `capture.toml`, and capturing into their targets:
5///
6/// ```toml
7/// [[template]]
8/// key = "t"
9/// name = "Personal todo"
10/// type = "entry" # entry, item, checkitem, plain or table-line
11/// file = "todo.org" # relative to the first folder, or ~/… or /…
12/// headline = "Inbox" # or olp = "Projects/Work"; neither for the end of the file
13/// template = "* TODO %?\n%i\n%a"
14/// prepend = false
15/// ```
16///
17/// Other targets: `datetree = true` (under `olp` if given; `tree-type` "day", "week",
18/// "month", or groups such as "year quarter month"), `regexp = "…"` with `file`,
19/// `id = "…"` without `file`, `clock = true` without `file`. Other properties, as in
20/// `org-capture-templates`: `immediate-finish`, `empty-lines`, `empty-lines-before`,
21/// `empty-lines-after`, `jump-to-captured`, `clock-in`, `clock-keep`, `clock-resume`,
22/// `table-line-pos`, `time-prompt`.
23///
24/// A `[[template]]` with only `key` and `name` is a group: the templates whose keys start
25/// with its key are listed under it.
26@MainActor
27public enum CaptureTemplates {
28 public static var userFile: URL { UserConfig.file("capture.toml") }
29
30 /// The tables `RoamTemplate` reads.
31 static let roamTables: Set<String> = ["roam-template", "roam-dailies-template", "roam-ref-template"]
32
33 /// The templates in your Doom configuration.
34 public static let defaults = [
35 CaptureTemplate(key: "t", name: "Personal todo", target: .headline(file: "todo.org", headline: "Inbox"), template: "* TODO %?\n%i\n%a"),
36 CaptureTemplate(key: "n", name: "Personal notes", target: .headline(file: "notes.org", headline: "Inbox"), template: "* %u %?\n%i\n%a"),
37 ]
38
39 public static func load(userFile: URL = userFile) -> (templates: [CaptureTemplate], groups: [CaptureGroup], problems: [String]) {
40 guard let text = try? String(contentsOf: userFile, encoding: .utf8) else { return (defaults, [], []) }
41 let tables: [TOML.Table]
42 do {
43 tables = try TOML.parse(text)
44 } catch {
45 return (defaults, [], ["capture.toml: \(error)"])
46 }
47 var templates: [CaptureTemplate] = []
48 var groups: [CaptureGroup] = []
49 var problems: [String] = []
50 for table in tables where !(table.name.isEmpty && table.values.isEmpty) && !roamTables.contains(table.name) {
51 guard table.name == "template", table.isArrayElement else {
52 problems.append("capture.toml line \(table.line): expected [[template]]")
53 continue
54 }
55 let values = table.values
56 if let key = values["key"]?.string, let name = values["name"]?.string, values.count == 2 {
57 groups.append(CaptureGroup(key: key, name: name))
58 continue
59 }
60 let fileless = values["id"]?.string != nil || values["clock"]?.bool == true || values["denote"]?.bool == true
61 guard let key = values["key"]?.string, let body = values["template"]?.string, let file = values["file"]?.string ?? (fileless ? "" : nil) else {
62 problems.append("capture.toml line \(table.line): a template needs key, file and template")
63 continue
64 }
65 guard let kind = CaptureTemplate.Kind(rawValue: table.values["type"]?.string ?? "entry") else {
66 problems.append("capture.toml line \(table.line): unknown type")
67 continue
68 }
69 let olp = values["olp"]?.string.map { $0.split(separator: "/").map(String.init) }
70 let target: CaptureTemplate.Target
71 if let id = values["id"]?.string {
72 target = .id(id)
73 } else if values["clock"]?.bool == true {
74 target = .clock
75 } else if values["datetree"]?.bool == true {
76 guard let tree = CaptureTemplate.TreeType(rawValue: values["tree-type"]?.string ?? "day") else {
77 problems.append("capture.toml line \(table.line): tree-type is day, week, month, or some of year, quarter, month, week and day")
78 continue
79 }
80 target = .datetree(file: file, path: olp ?? [], tree: tree)
81 } else if let regexp = values["regexp"]?.string {
82 target = .regexp(file: file, regexp: regexp)
83 } else if let headline = values["headline"]?.string {
84 target = .headline(file: file, headline: headline)
85 } else if let olp {
86 target = .outline(file: file, path: olp)
87 } else {
88 target = .file(file)
89 }
90 templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options(values)))
91 }
92 return (templates.isEmpty ? defaults : templates, templates.isEmpty ? [] : groups, problems)
93 }
94
95 /// A table's template properties beyond the target.
96 public nonisolated static func options(_ values: [String: TOML.Value]) -> CaptureTemplate.Options {
97 func flag(_ name: String) -> Bool { values[name]?.bool ?? false }
98 func lines(_ name: String) -> Int? { values[name]?.integer }
99 return CaptureTemplate.Options(
100 prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"),
101 emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"),
102 jumpToCaptured: flag("jump-to-captured"), clockIn: flag("clock-in"), clockKeep: flag("clock-keep"), clockResume: flag("clock-resume"),
103 tableLinePos: values["table-line-pos"]?.string, timePrompt: flag("time-prompt"), denote: flag("denote")
104 )
105 }
106
107 /// What `org-capture` lists after the keys typed so far: the groups and templates one key
108 /// longer, in the templates' order. A template with no group for its prefix is listed
109 /// too, so that it can be reached.
110 public static func menu(_ templates: [CaptureTemplate], groups: [CaptureGroup], typed: String) -> [CaptureMenuItem] {
111 let depth = typed.count + 1
112 var items: [CaptureMenuItem] = []
113 var shown: Set<String> = []
114 for template in templates where template.key.hasPrefix(typed) {
115 if template.key.count > depth, let group = groups.first(where: { $0.key == String(template.key.prefix(depth)) }) {
116 if shown.insert(group.key).inserted { items.append(.group(group)) }
117 } else {
118 items.append(.template(template))
119 }
120 }
121 for group in groups where group.key.hasPrefix(typed) && group.key.count == depth && !shown.contains(group.key) { items.append(.group(group)) }
122 return items
123 }
124
125 /// The template's name after the names of the groups above it: `Work › Meeting`.
126 public static func label(_ template: CaptureTemplate, groups: [CaptureGroup]) -> String {
127 let names = (1..<max(1, template.key.count)).compactMap { n in groups.first { $0.key == String(template.key.prefix(n)) }?.name }
128 return (names + [template.name]).joined(separator: " › ")
129 }
130}
131
132/// A key and a description with no template: `("w" "Work")` in `org-capture-templates`.
133public struct CaptureGroup: Sendable, Equatable, Identifiable {
134 public let key: String
135 public let name: String
136 public var id: String { key }
137 public init(key: String, name: String) {
138 self.key = key
139 self.name = name
140 }
141}
142
143public enum CaptureMenuItem: Identifiable {
144 case group(CaptureGroup)
145 case template(CaptureTemplate)
146 public var key: String {
147 switch self {
148 case .group(let g): g.key
149 case .template(let t): t.key
150 }
151 }
152 public var id: String { key }
153}
154
155extension CaptureContext {
156 /// `%[file]` reads the file, a relative path from the configuration folder.
157 public mutating func readsTemplateFiles(from directory: URL = UserConfig.directory) {
158 self.directory = directory.path
159 readFile = { try? String(contentsOfFile: $0, encoding: .utf8) }
160 }
161}
162
163extension CaptureTemplates {
164 /// A template's file: absolute, `~/…`, or relative to `root`.
165 public nonisolated static func path(_ file: String, root: String?) -> String {
166 if file.hasPrefix("/") { return file }
167 if file.hasPrefix("~") { return OrgPaths.expandingTilde(file) }
168 return ((root ?? OrgPaths.home) as NSString).appendingPathComponent(file)
169 }
170}
171
172/// The edit `Capture.place` makes, as a command so the save path applies it. The selection
173/// it leaves is the captured entry's start.
174public struct CapturePlacement: OrgCommand {
175 let text: String
176 let template: CaptureTemplate
177
178 public init(text: String, template: CaptureTemplate) {
179 self.text = text
180 self.template = template
181 }
182
183 public var id: String { "internal.capture" }
184 public var title: String { "Capture" }
185 public func applies(in context: EditContext) -> Bool { true }
186 public func run(in context: EditContext) -> CommandStep {
187 switch Capture.placement(text, template: template, in: context.text, settings: context.tree.settings, now: context.now, calendar: context.calendar) {
188 case .failure(.message(let message)):
189 return .failed(message)
190 case .success(let placed):
191 return .commit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, placed.text), selection: [placed.start..<placed.start]))
192 }
193 }
194}