Capture: file+regexp, template groups, time-prompt, tree-type groupings, refile !276

merged merged by cmc on 2026-10-11 12:14 UTC · krz/orgstar:issue-31 into main

10 files changed, +508 −82

Layout: unified · split

Sources/OrgApp/CaptureModel.swift +68 −10
@@ -16,11 +16,15 @@ import OrgDocument
1616/// prepend = false
1717/// ```
1818///
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`,
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`,
2223/// `empty-lines-after`, `jump-to-captured`, `clock-in`, `clock-keep`, `clock-resume`,
23/// `table-line-pos`.
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.
2428@MainActor
2529public enum CaptureTemplates {
2630 public static var userFile: URL { UserConfig.file("capture.toml") }
@@ -31,15 +35,16 @@ public enum CaptureTemplates {
3135 CaptureTemplate(key: "n", name: "Personal notes", target: .headline(file: "notes.org", headline: "Inbox"), template: "* %u %?\n%i\n%a"),
3236 ]
3337
34 public static func load(userFile: URL = userFile) -> (templates: [CaptureTemplate], problems: [String]) {
35 guard let text = try? String(contentsOf: userFile, encoding: .utf8) else { return (defaults, []) }
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, [], []) }
3640 let tables: [TOML.Table]
3741 do {
3842 tables = try TOML.parse(text)
3943 } catch {
40 return (defaults, ["capture.toml: \(error)"])
44 return (defaults, [], ["capture.toml: \(error)"])
4145 }
4246 var templates: [CaptureTemplate] = []
47 var groups: [CaptureGroup] = []
4348 var problems: [String] = []
4449 for table in tables where !(table.name.isEmpty && table.values.isEmpty) {
4550 guard table.name == "template", table.isArrayElement else {
@@ -47,6 +52,10 @@ public enum CaptureTemplates {
4752 continue
4853 }
4954 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 }
5059 let fileless = values["id"]?.string != nil || values["clock"]?.bool == true
5160 guard let key = values["key"]?.string, let body = values["template"]?.string, let file = values["file"]?.string ?? (fileless ? "" : nil) else {
5261 problems.append("capture.toml line \(table.line): a template needs key, file and template")
@@ -64,10 +73,12 @@ public enum CaptureTemplates {
6473 target = .clock
6574 } else if values["datetree"]?.bool == true {
6675 guard let tree = CaptureTemplate.TreeType(rawValue: values["tree-type"]?.string ?? "day") else {
67 problems.append("capture.toml line \(table.line): tree-type is day, week or month")
76 problems.append("capture.toml line \(table.line): tree-type is day, week, month, or some of year, quarter, month, week and day")
6877 continue
6978 }
7079 target = .datetree(file: file, path: olp ?? [], tree: tree)
80 } else if let regexp = values["regexp"]?.string {
81 target = .regexp(file: file, regexp: regexp)
7182 } else if let headline = values["headline"]?.string {
7283 target = .headline(file: file, headline: headline)
7384 } else if let olp {
@@ -81,12 +92,59 @@ public enum CaptureTemplates {
8192 prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"),
8293 emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"),
8394 jumpToCaptured: flag("jump-to-captured"), clockIn: flag("clock-in"), clockKeep: flag("clock-keep"), clockResume: flag("clock-resume"),
84 tableLinePos: values["table-line-pos"]?.string
95 tableLinePos: values["table-line-pos"]?.string, timePrompt: flag("time-prompt")
8596 )
8697 templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options))
8798 }
88 return (templates.isEmpty ? defaults : templates, problems)
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 }
89146 }
147 public var id: String { key }
90148}
91149
92150extension DocumentSession {
Sources/OrgApp/EmacsImport.swift +19 −7
@@ -806,9 +806,14 @@ public struct EmacsImport: Sendable {
806806 mutating func captureTemplate(_ entry: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) {
807807 guard let parts = entry.elements, parts.count >= 2, let key = parts[0].string else { return }
808808 let name = parts[1].string ?? key
809 func quoted(_ s: String) -> String { UserConfig.format(.string(s)) }
809810 guard parts.count >= 5, let type = parts[2].symbol, let target = parts[3].elements, let kind = target.first?.symbol,
810811 let template = parts[4].string else {
811812 // A key and a name only: a group of templates.
813 if parts.count == 2 {
814 let toml = "[[template]]\nkey = \(quoted(key))\nname = \(quoted(name))\n"
815 items.append(Item(id: id(), name: "capture \"\(key)\" \(name)", summary: "capture group \"\(key)\"", source: source, change: .capture(key: key, toml: toml)))
816 }
812817 if parts.count == 2 { return }
813818 unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "a template that isn't a string", source: source))
814819 return
@@ -817,7 +822,6 @@ public struct EmacsImport: Sendable {
817822 unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "\(type) templates aren't supported", source: source))
818823 return
819824 }
820 func quoted(_ s: String) -> String { UserConfig.format(.string(s)) }
821825 var toml = "[[template]]\nkey = \(quoted(key))\nname = \(quoted(name))\ntype = \(quoted(type))\n"
822826 // `org-capture-expand-file`: a variable's value, or a form evaluated.
823827 let strings = target.dropFirst().compactMap { $0.string ?? Self.evaluate($0, env)?.string }
@@ -826,12 +830,20 @@ public struct EmacsImport: Sendable {
826830 let rest = Array(parts.dropFirst(5))
827831 for i in stride(from: 0, to: rest.count - 1, by: 2) { if let name = rest[i].symbol { properties[name] = rest[i + 1] } }
828832 let allStrings = strings.count == target.count - 1
829 var treeType = properties[":tree-type"]?.symbol
833 // A symbol, or a list of groups such as `(year quarter)`.
834 var treeType = properties[":tree-type"].flatMap { value in
835 value.symbol ?? value.elements.flatMap { list in
836 let words = list.compactMap(\.symbol)
837 return words.count == list.count ? words.joined(separator: " ") : nil
838 }
839 }
830840 let place: String? = switch kind {
831841 case "file" where strings.count == 1 && target.count == 2:
832842 "file = \(quoted(strings[0]))\n"
833843 case "file+headline" where strings.count == 2 && target.count == 3:
834844 "file = \(quoted(strings[0]))\nheadline = \(quoted(strings[1]))\n"
845 case "file+regexp" where strings.count == 2 && target.count == 3:
846 "file = \(quoted(strings[0]))\nregexp = \(quoted(strings[1]))\n"
835847 case "file+olp" where strings.count >= 2 && allStrings:
836848 "file = \(quoted(strings[0]))\nolp = \(quoted(strings.dropFirst().joined(separator: "/")))\n"
837849 case "file+olp+datetree" where strings.count >= 1 && allStrings:
@@ -852,20 +864,20 @@ public struct EmacsImport: Sendable {
852864 if kind == "file+weektree" { treeType = "week" }
853865 toml += place
854866 if let treeType {
855 guard ["day", "week", "month"].contains(treeType) else {
867 guard let tree = CaptureTemplate.TreeType(rawValue: treeType) else {
856868 unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: ":tree-type \(treeType) isn't supported", source: source))
857869 return
858870 }
859 if treeType != "day" { toml += "tree-type = \(quoted(treeType))\n" }
871 if tree != .day { toml += "tree-type = \(quoted(tree.rawValue))\n" }
860872 }
861 for flag in ["prepend", "immediate-finish", "jump-to-captured", "clock-in", "clock-keep", "clock-resume"] {
873 for flag in ["prepend", "immediate-finish", "jump-to-captured", "clock-in", "clock-keep", "clock-resume", "time-prompt"] {
862874 if let value = properties[":" + flag], value.symbol != "nil" { toml += "\(flag) = true\n" }
863875 }
864876 for count in ["empty-lines", "empty-lines-before", "empty-lines-after"] {
865877 if let n = properties[":" + count]?.integer { toml += "\(count) = \(n)\n" }
866878 }
867879 if let pos = properties[":table-line-pos"]?.string { toml += "table-line-pos = \(quoted(pos))\n" }
868 let ignored = properties.keys.filter { ![":prepend", ":immediate-finish", ":jump-to-captured", ":clock-in", ":clock-keep", ":clock-resume", ":empty-lines", ":empty-lines-before", ":empty-lines-after", ":tree-type", ":table-line-pos"].contains($0) }
880 let ignored = properties.keys.filter { ![":prepend", ":immediate-finish", ":jump-to-captured", ":clock-in", ":clock-keep", ":clock-resume", ":empty-lines", ":empty-lines-before", ":empty-lines-after", ":tree-type", ":table-line-pos", ":time-prompt"].contains($0) }
869881 if !ignored.isEmpty {
870882 unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "\(ignored.sorted().joined(separator: ", ")) left out", source: source))
871883 }
@@ -946,7 +958,7 @@ extension EmacsImport {
946958 for item in items {
947959 guard case .capture(let key, let toml) = item.change, !existingKeys.contains(key) else { continue }
948960 addedCapture += "\n" + toml
949 templates += 1
961 if toml.contains("\ntemplate = ") { templates += 1 }
950962 }
951963 if !addedCapture.isEmpty {
952964 capture += (capture.isEmpty ? "# Capture templates. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedCapture
Sources/OrgCore/Capture/Capture.swift +125 −14
@@ -6,8 +6,43 @@ import Foundation
66public struct CaptureTemplate: Sendable, Equatable, Identifiable {
77 public enum Kind: String, Sendable, Equatable { case entry, item, checkitem, plain, tableLine = "table-line" }
88
9 /// `:tree-type`: what a date tree groups entries by.
10 public enum TreeType: String, Sendable, Equatable { case day, week, month }
9 /// `:tree-type`: what a date tree groups entries by, a subset of year, quarter, month,
10 /// week and day. `day`, `week` and `month` name the usual ones.
11 public struct TreeType: Sendable, Equatable {
12 public enum Group: String, Sendable, CaseIterable { case year, quarter, month, week, day }
13 public let groups: Set<Group>
14 public static let day = TreeType(groups: [.year, .month, .day])
15 public static let week = TreeType(groups: [.year, .week, .day])
16 public static let month = TreeType(groups: [.year, .month])
17
18 public init(groups: Set<Group>) { self.groups = groups }
19
20 /// `day`, `week`, `month`, or groups separated by spaces, as in `year quarter month`.
21 public init?(rawValue: String) {
22 switch rawValue {
23 case "day": self = .day
24 case "week": self = .week
25 case "month": self = .month
26 default:
27 let words = rawValue.split(whereSeparator: \.isWhitespace)
28 let groups = words.compactMap { Group(rawValue: String($0)) }
29 guard !groups.isEmpty, groups.count == words.count else { return nil }
30 self.groups = Set(groups)
31 }
32 }
33
34 public var rawValue: String {
35 switch self {
36 case .day: "day"
37 case .week: "week"
38 case .month: "month"
39 default: Group.allCases.filter(groups.contains).map(\.rawValue).joined(separator: " ")
40 }
41 }
42
43 /// The `:tree-type` value in Lisp.
44 public var lisp: String { [.day, .week, .month].contains(self) ? rawValue : "(" + rawValue + ")" }
45 }
1146
1247 public enum Target: Sendable, Equatable {
1348 case file(String)
@@ -15,6 +50,8 @@ public struct CaptureTemplate: Sendable, Equatable, Identifiable {
1550 case outline(file: String, path: [String])
1651 /// `file+olp+datetree`: today's entry in a date tree, under `path` or at the top.
1752 case datetree(file: String, path: [String], tree: TreeType)
53 /// `file+regexp`: after the first match of an Emacs regexp, or before it with `prepend`.
54 case regexp(file: String, regexp: String)
1855 /// `(id "…")`: the heading with that ID; the app finds its file.
1956 case id(String)
2057 /// `(clock)`: the clocked-in entry; the app turns it into `heading`.
@@ -25,7 +62,7 @@ public struct CaptureTemplate: Sendable, Equatable, Identifiable {
2562 /// The target file, or "" for `id` and `clock` until the app resolves them.
2663 public var file: String {
2764 switch self {
28 case .file(let f), .headline(let f, _), .outline(let f, _), .datetree(let f, _, _), .heading(let f, _): f
65 case .file(let f), .headline(let f, _), .outline(let f, _), .datetree(let f, _, _), .regexp(let f, _), .heading(let f, _): f
2966 case .id, .clock: ""
3067 }
3168 }
@@ -48,13 +85,16 @@ public struct CaptureTemplate: Sendable, Equatable, Identifiable {
4885 public var clockResume = false
4986 /// `:table-line-pos`: `II-3` is the third line above the second rule.
5087 public var tableLinePos: String?
88 /// `:time-prompt`: a date tree asks which day the entry is for.
89 public var timePrompt = false
5190
5291 public init(
5392 prepend: Bool = false, immediateFinish: Bool = false, emptyLines: Int? = nil, emptyLinesBefore: Int? = nil,
5493 emptyLinesAfter: Int? = nil, jumpToCaptured: Bool = false, clockIn: Bool = false, clockKeep: Bool = false, clockResume: Bool = false,
55 tableLinePos: String? = nil
94 tableLinePos: String? = nil, timePrompt: Bool = false
5695 ) {
5796 self.tableLinePos = tableLinePos
97 self.timePrompt = timePrompt
5898 self.prepend = prepend
5999 self.immediateFinish = immediateFinish
60100 self.emptyLines = emptyLines
@@ -90,6 +130,12 @@ public struct CaptureTemplate: Sendable, Equatable, Identifiable {
90130 self.options = options
91131 }
92132
133 /// Whether capture asks "Date for tree entry" first: `:time-prompt` with a date tree.
134 public var asksTreeDate: Bool {
135 guard options.timePrompt, case .datetree = target else { return false }
136 return true
137 }
138
93139 /// The same template aimed at `target`.
94140 public func retargeted(_ target: Target) -> CaptureTemplate {
95141 CaptureTemplate(key: key, name: name, kind: kind, target: target, template: template, options: options)
@@ -530,6 +576,19 @@ public enum Capture {
530576 return out
531577 }
532578
579 /// `:time-prompt`'s answer to "Date for tree entry": the day for the date tree, and the
580 /// template's time, `org-read-date` style. Without a time, another day than today is at
581 /// midnight.
582 public static func treeDate(_ answer: String, now: Date, calendar: Calendar = .current) -> Date {
583 let read = ReadDate.read(answer, default: now, now: now, calendar: calendar)
584 var parts = read.components(calendar)
585 if !read.timeGiven {
586 let today = calendar.dateComponents([.year, .month, .day], from: now)
587 if (parts.year, parts.month, parts.day) != (today.year, today.month, today.day) { (parts.hour, parts.minute) = (0, 0) }
588 }
589 return calendar.date(from: parts) ?? now
590 }
591
533592 // MARK: - Placing
534593
535594 /// The target file's text after capturing `text`, as `org-capture-finalize` leaves it.
@@ -549,13 +608,20 @@ public enum Capture {
549608 let buffer = EmacsBuffer(fileText, point: 0, settings: settings)
550609 let start: Int
551610 do {
552 let entryHeading = try locate(template.target, buffer, date: calendar.dateComponents([.year, .month, .day], from: now))
553611 let options = template.options
612 let date = calendar.dateComponents([.year, .month, .day], from: now)
613 var exact: Int?
614 let entryHeading: Int?
615 if case .regexp(_, let regexp) = template.target {
616 (entryHeading, exact) = try locateRegexp(regexp, prepend: options.prepend, buffer)
617 } else {
618 entryHeading = try locate(template.target, buffer, date: date)
619 }
554620 switch template.kind {
555621 case .entry: start = try placeEntry(text, options: options, heading: entryHeading, buffer)
556 case .plain: start = placePlain(text, options: options, heading: entryHeading, buffer)
557 case .item, .checkitem: start = try placeItem(text, checkbox: template.kind == .checkitem, options: options, heading: entryHeading, buffer)
558 case .tableLine: start = try placeTableLine(text, options: options, heading: entryHeading, buffer)
622 case .plain: start = placePlain(text, options: options, heading: entryHeading, exact: exact, buffer)
623 case .item, .checkitem: start = try placeItem(text, checkbox: template.kind == .checkitem, options: options, heading: entryHeading, exact: exact, buffer)
624 case .tableLine: start = try placeTableLine(text, options: options, heading: entryHeading, exact: exact, buffer)
559625 }
560626 } catch let error as Failure {
561627 return .failure(error)
@@ -570,6 +636,19 @@ public enum Capture {
570636 return .success((result, start))
571637 }
572638
639 /// `file+regexp`: the match's end (its start with `prepend`), and its heading when the
640 /// match ends on a heading line. Emacs searches with `case-fold-search` on.
641 static func locateRegexp(_ regexp: String, prepend: Bool, _ buffer: EmacsBuffer) throws -> (heading: Int?, exact: Int) {
642 buffer.point = 0
643 guard let match = buffer.searchForward(EmacsRegex.translate(regexp), caseInsensitive: true) else {
644 throw Failure.message("No match for target regexp in file")
645 }
646 let exact = prepend ? match[0]!.lowerBound : match[0]!.upperBound
647 let line = buffer.lineStart(exact)
648 buffer.point = line
649 return (atHeading(buffer) ? line : nil, exact)
650 }
651
573652 /// `org-capture-set-target-location`: point at the target heading, or nil for a file.
574653 static func locate(_ target: CaptureTemplate.Target, _ buffer: EmacsBuffer, date: DateComponents) throws -> Int? {
575654 switch target {
@@ -590,6 +669,8 @@ public enum Capture {
590669 buffer.point = buffer.lineStart(offset)
591670 guard atHeading(buffer) else { throw Failure.message("The clocked entry moved; try again") }
592671 return buffer.point
672 case .regexp(_, let regexp):
673 return try locateRegexp(regexp, prepend: false, buffer).heading
593674 case .datetree(_, let path, let tree):
594675 let parent = path.isEmpty ? nil : try locate(.outline(file: "", path: path), buffer, date: date)
595676 return Datetree.findCreate(buffer, under: parent, tree: tree, date: date)
@@ -679,7 +760,7 @@ public enum Capture {
679760 /// `org--blank-before-heading-p` with `org-blank-before-new-entry` `(heading . auto)`.
680761 static func blankBeforeHeading(_ buffer: EmacsBuffer) -> Bool {
681762 buffer.saveExcursion {
682 let before = buffer.searchBackward("^\\*+ ", caseInsensitive: false) == nil && !atHeading(buffer)
763 let before = buffer.saveExcursion { buffer.searchBackward("^\\*+ ", caseInsensitive: false) == nil } && !atHeading(buffer)
683764 if before {
684765 nextHeading(buffer)
685766 if buffer.point >= buffer.length, !atHeading(buffer) { return false }
@@ -788,7 +869,7 @@ public enum Capture {
788869 }
789870
790871 /// `org-capture-place-plain-text`.
791 static func placePlain(_ text: String, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) -> Int {
872 static func placePlain(_ text: String, options: CaptureTemplate.Options, heading: Int?, exact: Int? = nil, _ buffer: EmacsBuffer) -> Int {
792873 let prepend = options.prepend
793874 if let heading {
794875 buffer.point = heading
@@ -800,6 +881,8 @@ public enum Capture {
800881 buffer.point = buffer.lineEnd(heading)
801882 nextHeading(buffer)
802883 }
884 } else if let exact {
885 buffer.point = exact
803886 } else {
804887 buffer.point = prepend ? 0 : buffer.length
805888 }
@@ -815,13 +898,15 @@ public enum Capture {
815898 /// `org-capture-place-table-line`, then what `org-capture-finalize` does to the table: the
816899 /// first table in the entry, or the file, gets the line, at its end, after its first rule
817900 /// with `prepend`, or where `table-line-pos` says; a table is made when there's none.
818 static func placeTableLine(_ filled: String, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) throws -> Int {
901 static func placeTableLine(_ filled: String, options: CaptureTemplate.Options, heading: Int?, exact: Int? = nil, _ buffer: EmacsBuffer) throws -> Int {
819902 let template = filled.trimmingCharacters(in: .whitespacesAndNewlines)
820903 // `org-table-border-regexp`: a template that isn't a table line becomes one.
821904 let text = template.range(of: "^[ \\t]*[^| \\t]", options: .regularExpression) != nil ? "| " + template : template + "\n"
822905 var begin = 0
823906 var end = buffer.length
824 if let heading {
907 if let exact {
908 (begin, end) = entryRegion(from: exact, buffer)
909 } else if let heading {
825910 begin = min(buffer.length, buffer.lineEnd(heading) + 1)
826911 buffer.point = buffer.lineEnd(heading)
827912 nextHeading(buffer)
@@ -892,6 +977,14 @@ public enum Capture {
892977 return buffer.point
893978 }
894979
980 /// An exact position's region: from its line's start to the next heading
981 /// (`org-entry-end-position`).
982 static func entryRegion(from exact: Int, _ buffer: EmacsBuffer) -> (Int, Int) {
983 buffer.point = exact
984 nextHeading(buffer)
985 return (buffer.lineStart(exact), buffer.point)
986 }
987
895988 /// `org-end-of-meta-data t`: past planning, drawers and the property drawer.
896989 static func skipMetaData(_ buffer: EmacsBuffer) {
897990 while buffer.point < buffer.length {
@@ -914,7 +1007,7 @@ public enum Capture {
9141007
9151008 /// `org-capture-place-item`: after the last item of the first list in the entry (the file
9161009 /// for a file target), or at the end of the entry's text.
917 static func placeItem(_ text: String, checkbox: Bool, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) throws -> Int {
1010 static func placeItem(_ text: String, checkbox: Bool, options: CaptureTemplate.Options, heading: Int?, exact: Int? = nil, _ buffer: EmacsBuffer) throws -> Int {
9181011 let prepend = options.prepend
9191012 var item = text.trimmingCharacters(in: .newlines)
9201013 if item.range(of: "^[ \\t]*([-+*]|[0-9]+[.)])[ \\t]", options: .regularExpression) == nil {
@@ -925,7 +1018,9 @@ public enum Capture {
9251018 }
9261019 let start: Int
9271020 let end: Int
928 if let heading {
1021 if let exact {
1022 (start, end) = entryRegion(from: exact, buffer)
1023 } else if let heading {
9291024 start = min(buffer.length, buffer.lineEnd(heading) + 1)
9301025 buffer.point = buffer.lineEnd(heading)
9311026 nextHeading(buffer)
@@ -953,6 +1048,22 @@ public enum Capture {
9531048 if buffer.forwardLine(1) != 0 { break }
9541049 if !items.isEmpty { items[items.count - 1].end = buffer.point }
9551050 }
1051 // A position inside a list: its first item, as `org-element-lineage` finds the list.
1052 if exact != nil, var first = items.first, first.start == start {
1053 var line = first.start
1054 while line > 0 {
1055 let previous = buffer.lineStart(line - 1)
1056 let text = buffer.substring(previous, line - 1)
1057 let indent = text.prefix { $0 == " " || $0 == "\t" }
1058 if let m = text.firstMatch(of: /^([ \t]*)([-+*]|[0-9]+[.)])[ \t]/), String(m.1) == first.indent, m.2 != "*" || !m.1.isEmpty {
1059 first.start = previous
1060 } else if text.trimmingCharacters(in: .whitespaces).isEmpty || indent.count <= first.indent.count {
1061 break
1062 }
1063 line = previous
1064 }
1065 items[0] = first
1066 }
9561067 if let first = items.first {
9571068 let indent = first.indent
9581069 let indented = item.components(separatedBy: "\n").enumerated().map { $0.offset == 0 ? indent + $0.element : indent + $0.element }.joined(separator: "\n")
Sources/OrgCore/Capture/Datetree.swift +21 −12
@@ -7,27 +7,36 @@ enum Datetree {
77 static let weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
88 static let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
99
10 /// Each level's heading title, and the pattern whose first group orders siblings.
10 /// Each level's heading title, and the pattern whose first group orders siblings. With
11 /// weeks, the year and month are those of the ISO week's Thursday; with weeks but no
12 /// months, quarters are 13 weeks.
1113 static func levels(_ tree: CaptureTemplate.TreeType, date: DateComponents) -> [(title: String, pattern: String)] {
1214 var gregorian = Calendar(identifier: .gregorian)
1315 gregorian.timeZone = TimeZone(identifier: "UTC")!
1416 let day = gregorian.date(from: DateComponents(year: date.year, month: date.month, day: date.day))!
15 let weekday = weekdays[gregorian.component(.weekday, from: day) - 1]
17 let weekdayIndex = gregorian.component(.weekday, from: day) - 1
1618 var iso = Calendar(identifier: .iso8601)
1719 iso.timeZone = gregorian.timeZone
1820 let isoYear = iso.component(.yearForWeekOfYear, from: day)
1921 let week = iso.component(.weekOfYear, from: day)
20 let year = (title: String(date.year!), pattern: "([12][0-9]{3})")
21 let dayLevel = (title: String(format: "%04d-%02d-%02d ", date.year!, date.month!, date.day!) + weekday,
22 pattern: "([12][0-9]{3}-[01][0-9]-[0123][0-9]) \\w+")
23 switch tree {
24 case .day, .month:
25 let month = (title: String(format: "%04d-%02d ", date.year!, date.month!) + months[date.month! - 1],
26 pattern: "([12][0-9]{3}-[01][0-9]) \\w+")
27 return tree == .day ? [year, month, dayLevel] : [year, month]
28 case .week:
29 return [(String(isoYear), year.pattern), (String(format: "%04d-W%02d", isoYear, week), "([12][0-9]{3}-W[0-5][0-9])"), dayLevel]
22 let groups = tree.groups
23 let weeks = groups.contains(.week)
24 let year = weeks ? isoYear : date.year!
25 let thursday = gregorian.date(byAdding: .day, value: 4 - (weekdayIndex == 0 ? 7 : weekdayIndex), to: day)!
26 let month = weeks ? gregorian.component(.month, from: thursday) : date.month!
27 let quarter = weeks && !groups.contains(.month) ? min(4, 1 + (week - 1) / 13) : 1 + (month - 1) / 3
28 var levels: [(title: String, pattern: String)] = []
29 if groups.contains(.year) { levels.append((String(year), "([12][0-9]{3})")) }
30 if groups.contains(.quarter) { levels.append(("\(year)-Q\(quarter)", "([12][0-9]{3}-Q[1-4])")) }
31 if groups.contains(.month) {
32 levels.append((String(format: "%04d-%02d ", year, month) + months[month - 1], "([12][0-9]{3}-[01][0-9]) \\w+"))
3033 }
34 if weeks { levels.append((String(format: "%04d-W%02d", isoYear, week), "([12][0-9]{3}-W[0-5][0-9])")) }
35 if groups.contains(.day) {
36 levels.append((String(format: "%04d-%02d-%02d ", date.year!, date.month!, date.day!) + weekdays[weekdayIndex],
37 "([12][0-9]{3}-[01][0-9]-[0123][0-9]) \\w+"))
38 }
39 return levels
3140 }
3241
3342 /// Point at the date's entry, created where missing, under the heading at `parent` or at
Sources/Orgstar/CaptureView.swift +55 −11
@@ -2,16 +2,21 @@ import AppKit
22import Carbon.HIToolbox
33import OrgApp
44import OrgCore
5import OrgDocument
56import SwiftUI
67
78/// The capture window: pick a template by its key, answer its prompts, edit the entry, and
8/// ⌘Return files it where the template says, as `org-capture` does.
9/// ⌘Return files it where the template says, as `org-capture` does. Refile… files it and then
10/// asks where to move it (`org-capture-refile`).
911struct CaptureView: View {
1012 let workspace: WorkspaceModel
1113 let session: DocumentSession
1214 let commands: AppCommands
1315 let clock: ClockModel
1416 @State private var templates = CaptureTemplates.defaults
17 @State private var groups: [CaptureGroup] = []
18 /// The day `:time-prompt` asked for.
19 @State private var treeDate: Date?
1520 @State private var problem: String?
1621 @State private var template: CaptureTemplate?
1722 @State private var questions: [Capture.Question] = []
@@ -26,6 +31,7 @@ struct CaptureView: View {
2631 @State private var day: Int?
2732 @FocusState private var focused: Bool
2833 @Environment(\.dismissWindow) private var dismissWindow
34 @Environment(\.openWindow) private var openWindow
2935
3036 var body: some View {
3137 VStack(alignment: .leading, spacing: 12) {
@@ -39,6 +45,9 @@ struct CaptureView: View {
3945 Spacer()
4046 Button("Cancel", role: .cancel) { close() }
4147 .keyboardShortcut(.cancelAction)
48 if template.kind == .entry {
49 Button("Refile…") { finish(refile: true) }
50 }
4251 Button("File It") { finish() }
4352 .keyboardShortcut(.return, modifiers: .command)
4453 }
@@ -63,15 +72,23 @@ struct CaptureView: View {
6372 } else {
6473 Text((keys.isEmpty ? "Capture" : "Capture: \(keys)") + (day == nil ? "" : ", scheduled " + captureDate(Date()).formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))))
6574 .font(.headline)
66 ForEach(templates.filter { $0.key.hasPrefix(keys) }) { template in
75 ForEach(CaptureTemplates.menu(templates, groups: groups, typed: keys)) { item in
6776 Button {
68 choose(template)
77 switch item {
78 case .group(let group): keys = group.key
79 case .template(let template): choose(template)
80 }
6981 } label: {
7082 HStack {
71 Text("[\(template.key)]").monospaced().foregroundStyle(.secondary)
72 Text(template.name)
73 Spacer()
74 Text(Self.target(template)).foregroundStyle(.secondary).font(.caption)
83 Text("[\(item.key)]").monospaced().foregroundStyle(.secondary)
84 switch item {
85 case .group(let group):
86 Text(group.name + "…")
87 case .template(let template):
88 Text(template.name)
89 Spacer()
90 Text(Self.target(template)).foregroundStyle(.secondary).font(.caption)
91 }
7592 }
7693 }
7794 .buttonStyle(.plain)
@@ -125,6 +142,7 @@ struct CaptureView: View {
125142 case .headline(_, let headline): return "\(file) / \(headline)"
126143 case .outline(_, let path): return ([file] + path).joined(separator: " / ")
127144 case .datetree(_, let path, _): return ([file] + path + ["date tree"]).joined(separator: " / ")
145 case .regexp(_, let regexp): return "\(file) / \(regexp)"
128146 case .id(let id): return "ID \(id)"
129147 case .clock: return "clocked entry"
130148 }
@@ -133,8 +151,10 @@ struct CaptureView: View {
133151 private func reset() {
134152 let loaded = CaptureTemplates.load()
135153 templates = loaded.templates
154 groups = loaded.groups
136155 problem = loaded.problems.first
137156 template = nil
157 treeDate = nil
138158 editing = false
139159 keys = ""
140160 day = nil
@@ -178,13 +198,22 @@ struct CaptureView: View {
178198 for heading in DocumentModel(tree: OrgParser.parse(text)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } }
179199 context.fileTags = tags
180200 }
181 questions = Capture.questions(chosen.template, context: context)
201 questions = (asksTreeDate(chosen) ? [Self.treeQuestion] : []) + Capture.questions(chosen.template, context: context)
182202 answers = questions.map { _ in "" }
183203 if questions.isEmpty { expand() }
184204 }
185205
206 /// `:time-prompt` asks first, unless the agenda day is the date.
207 private func asksTreeDate(_ template: CaptureTemplate) -> Bool { template.asksTreeDate && day == nil }
208
209 static let treeQuestion = Capture.Question(prompt: "Date for tree entry", defaultValue: "", choices: [], kind: .date(withTime: false, inactive: false))
210
186211 private func expand() {
187212 guard let template else { return }
213 var answers = answers
214 if asksTreeDate(template) {
215 treeDate = Capture.treeDate(answers.removeFirst(), now: Date())
216 }
188217 context.now = captureDate(Date())
189218 switch Capture.fill(template.template, context: context, answers: answers) {
190219 case .failure(.message(let message)):
@@ -207,13 +236,14 @@ struct CaptureView: View {
207236 /// `now` on the agenda day captured for, as `org-overriding-default-time` sets `%t`, `%U`
208237 /// and the date tree's day.
209238 private func captureDate(_ now: Date) -> Date {
239 if let treeDate { return treeDate }
210240 guard let day else { return now }
211241 let d = Days.date(day)
212242 let time = Calendar.current.dateComponents([.hour, .minute, .second], from: now)
213243 return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day, hour: time.hour, minute: time.minute, second: time.second)) ?? now
214244 }
215245
216 private func finish() {
246 private func finish(refile: Bool = false) {
217247 guard let template else { return }
218248 let opened = context.now
219249 let now = Date()
@@ -229,19 +259,33 @@ struct CaptureView: View {
229259 commands.show("Captured to \(Self.target(template))")
230260 let options = template.options
231261 let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
232 Task { [commands, clock, session] in
262 Task { [commands, clock, session, workspace] in
233263 let outcome = await clock.captured(entry, options: options, session: session, paths: paths, ask: commands.askClock, opened: opened, now: now)
234264 for message in outcome.messages { commands.show(message) }
235 if let jump = outcome.jump {
265 if refile {
266 Self.refile(entry, session: session, workspace: workspace, commands: commands)
267 } else if let jump = outcome.jump {
236268 commands.jump(path: jump.path, offset: jump.offset)
237269 } else if options.jumpToCaptured {
238270 commands.jump(path: entry.path, offset: entry.offset)
239271 }
240272 }
241273 }
274 if refile { openWindow(id: "main") }
242275 close()
243276 }
244277
278 /// `org-capture-refile`: the filed entry, moved where the answer says.
279 private static func refile(_ entry: (path: String, offset: Int), session: DocumentSession, workspace: WorkspaceModel, commands: AppCommands) {
280 let document = session.openDocuments.first { $0.path == entry.path }?.document
281 ?? FileManager.default.contents(atPath: entry.path).map { DocumentState(bytes: [UInt8]($0)) }
282 let targets = workspace.refileTargets(openPath: entry.path, document: document)
283 commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
284 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
285 if let message = session.refile(to: target, from: entry) { commands.show(message) }
286 }
287 }
288
245289 private func close() {
246290 reset()
247291 dismissWindow(id: "capture")
Sources/OrgstarMobile/CaptureScreen.swift +48 −7
@@ -5,7 +5,8 @@ import OrgDocument
55import SwiftUI
66
77/// Capture with a template: its questions (`%^{…}`, `%^g`, `%^t`…), then its text to edit,
8/// filed where the template says, as `org-capture` does.
8/// filed where the template says, as `org-capture` does. Refile files it and then moves it
9/// (`org-capture-refile`).
910struct CaptureScreen: View {
1011 let workspace: WorkspaceModel
1112 let session: DocumentSession
@@ -14,6 +15,11 @@ struct CaptureScreen: View {
1415 @Environment(ClockModel.self) private var clock
1516 @Environment(MobileModel.self) private var model
1617 @State private var templates: [CaptureTemplate] = []
18 @State private var groups: [CaptureGroup] = []
19 /// The day `:time-prompt` asked for.
20 @State private var treeDate: Date?
21 /// The filed entry, while its refile target is picked.
22 @State private var refiling: RefileEntry?
1723 @State private var key: String?
1824 @State private var context = CaptureContext()
1925 @State private var questions: [Capture.Question] = []
@@ -33,7 +39,7 @@ struct CaptureScreen: View {
3339 NavigationStack {
3440 Form {
3541 Picker("Template", selection: $key) {
36 ForEach(templates) { Text($0.name).tag(Optional($0.key)) }
42 ForEach(templates) { Text(CaptureTemplates.label($0, groups: groups)).tag(Optional($0.key)) }
3743 }
3844 if editing {
3945 Section {
@@ -67,13 +73,26 @@ struct CaptureScreen: View {
6773 if let tags { change(SetTags(), ["tags": tags.joined(separator: ":")]) }
6874 }
6975 }
76 .sheet(item: $refiling, onDismiss: { dismiss() }) { entry in
77 let document = session.openDocuments.first { $0.path == entry.path }?.document
78 ?? FileManager.default.contents(atPath: entry.path).map { DocumentState(bytes: [UInt8]($0)) }
79 RefileSheet(targets: workspace.refileTargets(openPath: entry.path, document: document)) { target in
80 // Filed either way; where refiling fails, the entry opens where it was filed.
81 let message = target.flatMap { session.refile(to: $0, from: (entry.path, entry.offset)) }
82 if target == nil || !(message?.hasPrefix("Refiled") ?? false) { model.openRequest = .offset(entry.path, entry.offset) }
83 refiling = nil
84 }
85 }
7086 .navigationTitle("Capture")
7187 .navigationBarTitleDisplayMode(.inline)
7288 .toolbar {
7389 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
90 if editing, template?.kind == .entry {
91 ToolbarItem(placement: .bottomBar) { Button("Refile…") { file(refile: true) } }
92 }
7493 ToolbarItem(placement: .confirmationAction) {
7594 if editing {
76 Button("File", action: file).disabled(template == nil)
95 Button("File") { file() }.disabled(template == nil)
7796 } else {
7897 Button("Continue", action: fill)
7998 }
@@ -83,6 +102,7 @@ struct CaptureScreen: View {
83102 .onAppear {
84103 let loaded = CaptureTemplates.load()
85104 templates = loaded.templates
105 groups = loaded.groups
86106 problem = loaded.problems.first
87107 key = request.template.flatMap { wanted in templates.first { $0.key == wanted }?.key } ?? templates.first?.key
88108 if let wanted = request.template, !templates.contains(where: { $0.key == wanted }) { problem = "No capture template \"\(wanted)\"" }
@@ -107,16 +127,27 @@ struct CaptureScreen: View {
107127 for heading in DocumentModel(tree: OrgParser.parse(source)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } }
108128 context.fileTags = tags
109129 }
110 questions = Capture.questions(template.template, context: context)
130 questions = (asksTreeDate(template) ? [Self.treeQuestion] : []) + Capture.questions(template.template, context: context)
111131 answers = questions.map { _ in "" }
132 treeDate = nil
112133 editing = false
113134 if questions.isEmpty { fill() }
114135 }
115136
116137 /// The template expanded with the answers; the caret where `%?` was.
138 /// `:time-prompt` asks first, unless the agenda day is the date.
139 private func asksTreeDate(_ template: CaptureTemplate) -> Bool { template.asksTreeDate && request.day == nil }
140
141 static let treeQuestion = Capture.Question(prompt: "Date for tree entry", defaultValue: "", choices: [], kind: .date(withTime: false, inactive: false))
142
143 /// The template's date: the tree's day, the agenda day, or now.
144 private var captureDate: Date { treeDate ?? request.day.map(Self.date) ?? Date() }
145
117146 private func fill() {
118147 guard let template else { return }
119 context.now = request.day.map(Self.date) ?? Date()
148 var answers = answers
149 if asksTreeDate(template) { treeDate = Capture.treeDate(answers.removeFirst(), now: Date()) }
150 context.now = captureDate
120151 switch Capture.fill(template.template, context: context, answers: answers) {
121152 case .success(let filled):
122153 let (filledText, cursor) = request.day.map { Capture.scheduling(filled.text, cursor: filled.cursor, on: $0) } ?? (filled.text, filled.cursor)
@@ -152,11 +183,11 @@ struct CaptureScreen: View {
152183 return calendar.date(from: parts) ?? Date()
153184 }
154185
155 private func file() {
186 private func file(refile: Bool = false) {
156187 guard let template else { return }
157188 let now = Date()
158189 let placed = template.resolved(workspace: workspace, session: session, clock: clock).flatMap { resolved in
159 session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: request.day.map(Self.date) ?? now)
190 session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: treeDate ?? request.day.map(Self.date) ?? now)
160191 }
161192 switch placed {
162193 case .failure(let error):
@@ -168,12 +199,22 @@ struct CaptureScreen: View {
168199 Task { [clock, session, opened = context.now] in
169200 _ = await clock.captured(entry, options: template.options, session: session, paths: paths, ask: model.clockPrompts.ask, opened: opened, now: now)
170201 }
202 if refile {
203 refiling = RefileEntry(path: entry.path, offset: entry.offset)
204 return
205 }
171206 if template.options.jumpToCaptured { model.openRequest = .offset(entry.path, entry.offset) }
172207 dismiss()
173208 }
174209 }
175210}
176211
212private struct RefileEntry: Identifiable {
213 let path: String
214 let offset: Int
215 var id: String { "\(path)\u{0}\(offset)" }
216}
217
177218/// One of a template's questions: text with its choices, tags, or a date.
178219struct QuestionField: View {
179220 let question: Capture.Question
Tests/OrgAppTests/AppTests.swift +58
@@ -1093,6 +1093,64 @@ struct CaptureAppTests {
10931093 #expect(CaptureTemplates.load(userFile: folder.url.appendingPathComponent("none.toml")).templates == CaptureTemplates.defaults)
10941094 }
10951095
1096 @Test func loadsGroupsRegexpsAndTreeTypes() throws {
1097 let folder = try Folder()
1098 let file = try folder.write("capture.toml", """
1099 [[template]]
1100 key = "t"
1101 name = "Todo"
1102 file = "todo.org"
1103 template = "* TODO %?"
1104 [[template]]
1105 key = "w"
1106 name = "Work"
1107 [[template]]
1108 key = "wm"
1109 name = "Meeting"
1110 file = "work.org"
1111 regexp = "^\\\\* Meetings"
1112 template = "* %?"
1113 [[template]]
1114 key = "wq"
1115 name = "Quarter"
1116 file = "work.org"
1117 datetree = true
1118 tree-type = "year quarter"
1119 time-prompt = true
1120 template = "* %?"
1121 [[template]]
1122 key = "xy"
1123 name = "Ungrouped"
1124 file = "x.org"
1125 template = "* %?"
1126 """)
1127 let loaded = CaptureTemplates.load(userFile: file)
1128 #expect(loaded.problems.isEmpty, "\(loaded.problems)")
1129 #expect(loaded.groups == [CaptureGroup(key: "w", name: "Work")])
1130 #expect(loaded.templates.map(\.key) == ["t", "wm", "wq", "xy"])
1131 #expect(loaded.templates[1].target == .regexp(file: "work.org", regexp: "^\\* Meetings"))
1132 #expect(loaded.templates[2].target == .datetree(file: "work.org", path: [], tree: CaptureTemplate.TreeType(groups: [.year, .quarter])))
1133 #expect(loaded.templates[2].asksTreeDate && !loaded.templates[0].asksTreeDate)
1134 #expect(CaptureTemplates.menu(loaded.templates, groups: loaded.groups, typed: "").map(\.key) == ["t", "w", "xy"])
1135 #expect(CaptureTemplates.menu(loaded.templates, groups: loaded.groups, typed: "w").map(\.key) == ["wm", "wq"])
1136 #expect(CaptureTemplates.label(loaded.templates[1], groups: loaded.groups) == "Work › Meeting")
1137 try "[[template]]\nkey = \"d\"\nfile = \"j.org\"\ndatetree = true\ntree-type = \"year fortnight\"\ntemplate = \"* %?\"\n".write(to: file, atomically: true, encoding: .utf8)
1138 #expect(CaptureTemplates.load(userFile: file).problems.count == 1)
1139 }
1140
1141 @Test func treeDateFollowsOrgCapture() {
1142 var calendar = Calendar(identifier: .gregorian)
1143 calendar.timeZone = TimeZone(identifier: "UTC")!
1144 let now = calendar.date(from: DateComponents(year: 2026, month: 10, day: 11, hour: 7, minute: 6, second: 27))!
1145 func text(_ date: Date) -> String {
1146 let c = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date)
1147 return String(format: "%04d-%02d-%02d %02d:%02d", c.year!, c.month!, c.day!, c.hour!, c.minute!)
1148 }
1149 #expect(text(Capture.treeDate("", now: now, calendar: calendar)) == "2026-10-11 07:06")
1150 #expect(text(Capture.treeDate("fri", now: now, calendar: calendar)) == "2026-10-16 00:00")
1151 #expect(text(Capture.treeDate("fri 14:00", now: now, calendar: calendar)) == "2026-10-16 14:00")
1152 }
1153
10961154 @Test func capturesIntoClosedMissingAndOpenFiles() throws {
10971155 let notes = try Folder()
10981156 let todo = try notes.write("todo.org", "* Inbox\n** TODO Old\n* Later\n")
Tests/OrgAppTests/EmacsImportTests.swift +14 −8
@@ -144,7 +144,7 @@ struct EmacsImportTests {
144144 #expect(folders == ["~/notes/", "~/work"])
145145 #expect(result.unreadable.map(\.name) == ["fill-column"])
146146 #expect(Set(result.unsupported.map(\.name)) == ["org-support-shift-select", "doom-theme", "org-roam-directory",
147 "capture \"j\"", "capture \"x\"", "SPC z t → tr/report", "C-c l", "agenda command \"f\""])
147 "capture \"x\"", "SPC z t → tr/report", "C-c l", "agenda command \"f\""])
148148 #expect(result.skipped == 1)
149149 #expect(result.doomDefaultsLeftOut == 1)
150150 }
@@ -152,12 +152,12 @@ struct EmacsImportTests {
152152 @Test func readsCaptureTemplatesAndBindings() throws {
153153 let result = try scan()
154154 let captures = result.items.compactMap { if case .capture(let key, let toml) = $0.change { (key, toml) } else { nil } }
155 #expect(captures.map(\.0) == ["t", "j", "c", "wn"])
156 #expect(captures[1].1 == "[[template]]\nkey = \"j\"\nname = \"Journal\"\ntype = \"entry\"\nfile = \"~/notes/journal.org\"\ndatetree = true\ntree-type = \"week\"\nempty-lines = 1\ntemplate = \"* %?\"\n")
155 #expect(captures.map(\.0) == ["t", "j", "c", "w", "wn"])
156 #expect(captures[1].1 == "[[template]]\nkey = \"j\"\nname = \"Journal\"\ntype = \"entry\"\nfile = \"~/notes/journal.org\"\ndatetree = true\ntree-type = \"week\"\ntime-prompt = true\nempty-lines = 1\ntemplate = \"* %?\"\n")
157157 #expect(captures[2].1.contains("clock = true\n") && captures[2].1.contains("immediate-finish = true\n"))
158 #expect(result.unsupported.contains { $0.name == "capture \"j\"" && $0.reason == ":time-prompt left out" })
158 #expect(captures[3].1 == "[[template]]\nkey = \"w\"\nname = \"Work\"\n")
159159 #expect(captures[0].1 == "[[template]]\nkey = \"t\"\nname = \"Todo\"\ntype = \"entry\"\nfile = \"~/notes/todo.org\"\nheadline = \"Inbox\"\ntemplate = \"* TODO %?\\n%a\"\n")
160 #expect(captures[3].1.contains("prepend = true\n") && captures[3].1.contains("type = \"plain\""))
160 #expect(captures[4].1.contains("prepend = true\n") && captures[4].1.contains("type = \"plain\""))
161161
162162 let bindings = result.items.compactMap { if case .binding(let keys, let command, let mode) = $0.change { "\(keys) \(command) \(mode ?? "-")" } else { nil } }
163163 #expect(bindings == ["SPC m x org.checkbox.toggle normal", "g s app.save normal", "C-c a app.agenda normal"])
@@ -178,14 +178,20 @@ struct EmacsImportTests {
178178 `(("n" "Note" entry (file+headline org-default-notes-file "Notes") "* %?")
179179 ("i" "Inbox" entry (file my-inbox) "* TODO %?")
180180 ("w" "Work" entry (file ,(concat org-directory "/work.org")) "* %?")
181 ("j" "Journal" entry (file+olp+datetree (concat org-directory "/journal.org")) "* %?")))
181 ("j" "Journal" entry (file+olp+datetree (concat org-directory "/journal.org")) "* %?")
182 ("q" "Quarter" entry (file+olp+datetree "~/q.org") "* %?" :tree-type (year quarter))
183 ("r" "Reading" plain (file+regexp "~/r.org" "^\\* Reading") "%?")))
182184 """#.write(to: folder.appendingPathComponent("init.el"), atomically: true, encoding: .utf8)
183185 let result = EmacsImport.scan(EmacsImport.files(in: folder))
184186 let files = result.items.compactMap { item -> String? in
185187 guard case .capture(let key, let toml) = item.change else { return nil }
186188 return key + " " + (toml.firstMatch(of: /file = "([^"]*)"/).map { String($0.1) } ?? "-")
187189 }
188 #expect(files == ["n ~/org/notes.org", "i ~/org/inbox.org", "w ~/org/work.org", "j ~/org/journal.org"])
190 #expect(files == ["n ~/org/notes.org", "i ~/org/inbox.org", "w ~/org/work.org", "j ~/org/journal.org", "q ~/q.org", "r ~/r.org"])
191 let tomls = result.items.compactMap { if case .capture(_, let toml) = $0.change { toml } else { nil } }
192 #expect(tomls[4].contains("tree-type = \"year quarter\"\n"))
193 #expect(tomls[5].contains("regexp = \"^\\\\* Reading\"\n"))
194 #expect(!result.unsupported.contains { $0.name.hasPrefix("capture") }, "\(result.unsupported)")
189195 }
190196
191197 /// The user's own Doom configuration, when there is one.
@@ -219,7 +225,7 @@ struct EmacsImportTests {
219225 #expect(defaults.integer(forKey: "agendaStartOffset") == -3)
220226 #expect(defaults.string(forKey: "todoKeywords") == "TODO(t) WAIT(w) | DONE(d)\nBUG | FIXED")
221227 let capture = try String(contentsOf: folder.appendingPathComponent("capture.toml"), encoding: .utf8)
222 #expect(capture.components(separatedBy: "[[template]]").count == 5)
228 #expect(capture.components(separatedBy: "[[template]]").count == 6)
223229 #expect(CaptureTemplates.load(userFile: folder.appendingPathComponent("capture.toml")).problems.isEmpty)
224230 let keymap = folder.appendingPathComponent("keymap.toml")
225231 #expect(KeymapLoader.load(.doom, userFile: keymap).problems.isEmpty)
Tests/OrgCoreTests/CaptureTests.swift +60 −1
@@ -35,11 +35,13 @@ struct CaptureTests {
3535 case .outline(_, let p): target = "(file+olp \(lisp(path)) \(p.map(lisp).joined(separator: " ")))"
3636 case .datetree(_, let p, let tree):
3737 target = "(file+olp+datetree \(lisp(path)) \(p.map(lisp).joined(separator: " ")))"
38 properties += " :tree-type \(tree.rawValue)"
38 properties += " :tree-type \(tree.lisp)"
39 case .regexp(_, let r): target = "(file+regexp \(lisp(path)) \(lisp(r)))"
3940 case .id(let id): target = "(id \(lisp(id)))"
4041 case .clock, .heading: target = "(clock)"
4142 }
4243 forms.append("""
44 (condition-case nil
4345 (let ((org-capture-templates '(("x" "case" \(c.template.kind.rawValue) \(target) \(lisp(c.template.template))\(properties))))
4446 (path \(lisp(path))))
4547 (cl-letf (((symbol-function 'org-id-find)
@@ -55,6 +57,7 @@ struct CaptureTests {
5557 (org-capture-finalize)
5658 (with-current-buffer (find-buffer-visiting \(lisp(path)))
5759 (push (buffer-substring-no-properties (point-min) (point-max)) results)))
60 (error (push "failed" results)))
5861 """)
5962 }
6063 let output = folder.appendingPathComponent("out.json")
@@ -215,6 +218,62 @@ struct CaptureTests {
215218 }
216219 }
217220
221 static let groupings = ["year", "year quarter", "year quarter month", "year quarter week", "year quarter month week day", "year month week",
222 "year week", "month day", "quarter", "week day", "day"]
223
224 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil),
225 arguments: [1_789_000_000, 1_798_804_800, 1_767_139_200, 1_609_459_200, 1_664_582_400])
226 func treeGroupingsMatchEmacs(seconds: Int) throws {
227 let files = ["", "* 2026\n** 2026-Q1\n* 2027\n", "* Journal\n** 2025\n*** 2025-W40\n"]
228 var cases: [Case] = []
229 for grouping in Self.groupings {
230 for file in files {
231 let tree = CaptureTemplate.TreeType(rawValue: grouping)!
232 cases.append(Case(file: file, template: CaptureTemplate(key: "x", name: "", target: .datetree(file: "", path: [], tree: tree), template: "* %?"), typed: "Entry"))
233 }
234 }
235 let emacs = try Self.emacs(cases, seconds: seconds)
236 let now = Date(timeIntervalSince1970: Double(seconds))
237 for (c, expected) in zip(cases, emacs) {
238 let mine = Self.ours(c, now: now)
239 #expect(mine == expected, "\(c.template.target) into \(c.file.debugDescription)\nours:\n\(mine.debugDescription)\nemacs:\n\(expected.debugDescription)")
240 }
241 }
242
243 static let regexpTemplates: [CaptureTemplate] = [
244 CaptureTemplate(key: "x", name: "", target: .regexp(file: "", regexp: "^\\* Inbox"), template: "* %?"),
245 CaptureTemplate(key: "x", name: "", target: .regexp(file: "", regexp: "^\\* inbox"), template: "* %?", options: .init(prepend: true)),
246 CaptureTemplate(key: "x", name: "", target: .regexp(file: "", regexp: "notes\\."), template: "* %?"),
247 CaptureTemplate(key: "x", name: "", target: .regexp(file: "", regexp: "notes\\."), template: "* %?", options: .init(prepend: true)),
248 CaptureTemplate(key: "x", name: "", kind: .plain, target: .regexp(file: "", regexp: "notes\\."), template: "Plain %?"),
249 CaptureTemplate(key: "x", name: "", kind: .plain, target: .regexp(file: "", regexp: "^Some"), template: "Plain %?", options: .init(prepend: true)),
250 CaptureTemplate(key: "x", name: "", kind: .plain, target: .regexp(file: "", regexp: "Inbox$"), template: "Plain %?"),
251 CaptureTemplate(key: "x", name: "", kind: .plain, target: .regexp(file: "", regexp: "Inbox$"), template: "Plain %?", options: .init(prepend: true)),
252 CaptureTemplate(key: "x", name: "", kind: .item, target: .regexp(file: "", regexp: "notes\\."), template: "%?"),
253 CaptureTemplate(key: "x", name: "", kind: .item, target: .regexp(file: "", regexp: "Inbox"), template: "%?"),
254 CaptureTemplate(key: "x", name: "", kind: .item, target: .regexp(file: "", regexp: "^- two"), template: "%?", options: .init(prepend: true)),
255 CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .regexp(file: "", regexp: "Table"), template: "| %? |"),
256 CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .regexp(file: "", regexp: "notes"), template: "| %? |"),
257 CaptureTemplate(key: "x", name: "", target: .regexp(file: "", regexp: "\\(Child\\|Later\\)"), template: "** %?"),
258 CaptureTemplate(key: "x", name: "", target: .regexp(file: "", regexp: "Missing"), template: "* %?"),
259 ]
260
261 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
262 func regexpTargetsMatchEmacs() throws {
263 let files = ["* Inbox\nSome notes.\n- one\n- two\n\n** Child\n* Later\n", "Preamble notes.\n* Inbox\n", "* Table\n| a |\n|---|\n| 1 |\n* Inbox\n"]
264 var cases: [Case] = []
265 for template in Self.regexpTemplates {
266 for file in files { cases.append(Case(file: file, template: template, typed: "Entry")) }
267 }
268 let seconds = 1_789_000_000
269 let emacs = try Self.emacs(cases, seconds: seconds)
270 for (c, expected) in zip(cases, emacs) {
271 var mine = Self.ours(c, now: Date(timeIntervalSince1970: Double(seconds)))
272 if mine.hasPrefix("failed:") { mine = "failed" }
273 #expect(mine == expected, "\(c.template.target) \(c.template.kind) \(c.template.options) into \(c.file.debugDescription)\nours:\n\(mine.debugDescription)\nemacs:\n\(expected.debugDescription)")
274 }
275 }
276
218277 static let optionTemplates: [CaptureTemplate] = [
219278 CaptureTemplate(key: "x", name: "", target: .id("journal-id"), template: "* %?"),
220279 CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* %?", options: .init(emptyLines: 1)),
docs/manual/guide/08-capture.org +40 −12
@@ -27,9 +27,9 @@ Captures can also arrive from a browser through org-protocol, from Shortcuts, an
2727
2828A capture goes through up to three steps.
2929
301. *Choose a template.* The window lists your templates with their keys and targets. Type a template's key, or click it. For a key of several characters, such as =wb=, each character you type narrows the list to the templates whose keys start with what you typed, and the header shows the keys so far (=Capture: w=). =Delete= removes the last key typed. The template is chosen as soon as the keys match one.
312. *Answer its questions.* If the template has prompts (=%^{…}=, =%^g=, =%^t= and the others below), they appear as a form. Leave a field empty for its default. Press Return (Continue) to go on.
323. *Edit and file.* The filled template appears in an editor, headed with the template's name and target, with the cursor where =%?= was. Press =⌘Return= (File It) to file it.
301. *Choose a template.* The window lists your templates and groups with their keys and targets. Type a template's key, or click it. For a key of several characters, such as =wb=, each character you type narrows the list, and the header shows the keys so far (=Capture: w=). With a group for =w= (see [[*Template groups][Template groups]]), typing =w= or clicking the group lists what is in it. =Delete= removes the last key typed. The template is chosen as soon as the keys match one.
312. *Answer its questions.* If the template has prompts (=%^{…}=, =%^g=, =%^t= and the others below), they appear as a form, after =Date for tree entry= for a template with =time-prompt=. Leave a field empty for its default. Press Return (Continue) to go on.
323. *Edit and file.* The filled template appears in an editor, headed with the template's name and target, with the cursor where =%?= was. Press =⌘Return= (File It) to file it, or click Refile… to file it and then move it, as =C-c C-w= (=org-capture-refile=) does. Refile… asks for the target in the main window's echo area, offering the same targets as Refile in the editor (see [[file:04-outlines.org::*Refiling][Refiling]]); it appears for =entry= templates only, as in Org.
3333
3434Press Esc (Cancel) at any step to close the window without filing anything, as =org-capture-kill= does.
3535
@@ -40,7 +40,6 @@ If filing fails, for example because a heading on an =olp= path is missing, the
4040Limits compared with Emacs:
4141
4242- The editor is a plain text editor. Org editing commands and keys such as =C-c C-c= and =C-c C-k= don't work in it; use =⌘Return= and Esc.
43- There is no refile from the capture window (=C-c C-w= in an Emacs capture buffer). Capture to an inbox heading and refile from the agenda or the editor.
4443- The target is not shown while you edit (the capture buffer in Emacs is narrowed to the new entry in the target file).
4544
4645* Capturing onto an agenda day
@@ -49,7 +48,7 @@ The + at the right of a day's header in the agenda, or =k= in the Mac agenda (=o
4948
5049- =%t=, =%T=, =%u= and =%U= give that day. The escapes with a time use the current time of day.
5150- An empty answer to a date prompt (=%^t= and the others) is that day.
52- With =datetree = true=, the entry goes under that day in the date tree.
51- With =datetree = true=, the entry goes under that day in the date tree, and =time-prompt= doesn't ask.
5352
5453When the filled template is a heading without an active timestamp, orgstar adds =SCHEDULED:= with that day on the line after the heading, or at the end of the planning line when the template has one:
5554
@@ -84,7 +83,26 @@ The file is read each time the capture window opens. If it doesn't exist, or non
8483
8584A problem in the file, such as a table without a key, shows in red at the bottom of the window; the other templates still load.
8685
87Templates are a flat list. Keys of several characters are typed one character at a time, as in Emacs, but Emacs's template groups (an entry with only a key and a description) have no equivalent: the list shows every template whose key starts with what you typed.
86Keys of several characters are typed one character at a time, as in Emacs.
87
88** Template groups
89
90A =[[template]]= with only =key= and =name= is a group, as an entry with only a key and a description is in =org-capture-templates=:
91
92#+BEGIN_SRC toml
93[[template]]
94key = "w"
95name = "Work"
96
97[[template]]
98key = "wm"
99name = "Meeting"
100file = "work.org"
101olp = "Meetings"
102template = "* %?"
103#+END_SRC
104
105The first list then shows =[w] Work…= in place of the templates under it; choosing it lists the templates whose keys are one character longer and start with =w=, and the groups below it. A template longer than the next key with no group for its prefix is listed anyway, so that it can still be chosen. On iOS, the Template picker names each template after its groups, as =Work › Meeting=.
88106
89107** Keys
90108
@@ -98,7 +116,9 @@ Templates are a flat list. Keys of several characters are typed one character at
98116| =headline= | string | A heading in =file= | =file+headline= |
99117| =olp= | string | An outline path in =file=, titles separated by =/= | =file+olp= |
100118| =datetree= | boolean | Today's entry in a date tree in =file=, under =olp= if given | =file+olp+datetree= |
101| =tree-type= | string | =day= (the default), =week= or =month=, for =datetree= | =:tree-type= |
119| =tree-type= | string | =day= (the default), =week=, =month=, or groups such as ="year quarter"=, for =datetree= | =:tree-type= |
120| =time-prompt= | boolean | With =datetree=, ask which day the entry is for | =:time-prompt= |
121| =regexp= | string | After the first match of an Emacs regexp in =file= | =file+regexp= |
102122| =id= | string | The heading with this =ID= property, in any file | =id= |
103123| =clock= | boolean | The entry the clock is running in | =clock= |
104124| =prepend= | boolean | Put the text first rather than last | =:prepend= |
@@ -125,7 +145,7 @@ template = "* %^{Topic} :meeting:\n%U\n- Attendees: %^{Attendees}\n- Topic again
125145
126146** Targets
127147
128The target keys are checked in this order: =id=, =clock=, =datetree=, =headline=, =olp=; with none of them the target is =file= itself.
148The target keys are checked in this order: =id=, =clock=, =datetree=, =regexp=, =headline=, =olp=; with none of them the target is =file= itself.
129149
130150| Target | Where the text goes |
131151|---------------------------+-----------------------------------------------------------------------------------------------------------------|
@@ -133,12 +153,13 @@ The target keys are checked in this order: =id=, =clock=, =datetree=, =headline=
133153| =headline = "Inbox"= | Under the first heading with that exact title, at any level. If there is none, =* Inbox= is added at the end of the file |
134154| =olp = "Projects/Work"= | Under =Work=, a child of =Projects=. Every heading on the path must exist; otherwise filing fails with =Heading not found on outline path= |
135155| =datetree = true= | Under today's heading in a date tree; see [[*Date trees][Date trees]] |
156| =regexp = "…"= | At the end of the first match (its start, with =prepend=), searched ignoring case. When the match is on a heading line, as under =headline=; otherwise an =entry= goes to the file's top level, =plain= text goes at the match, and an =item= or =table-line= uses the first list or table from the match's line to the next heading. Fails with =No match for target regexp in file= |
136157| =id = "…"= | Under the heading with that =ID=, found through the workspace index. Fails with =Cannot find target ID= if no heading has it |
137158| =clock = true= | Under the heading the running clock is in. Fails with =No running clock= when no clock runs |
138159
139160=file= may be absolute (=/Users/me/org/todo.org=), start with =~/=, or be relative. A relative path is relative to the first folder in the sidebar (your home folder if you have none). Heading titles match the title text without its TODO keyword, priority or tags. Because =olp= uses =/= as its separator, a heading whose title contains =/= can't be on an outline path; use =headline= or =id= for it.
140161
141Emacs's =file+regexp=, =file+function= and =function= targets, and templates read from a file (=(file "…")=), are not supported.
162Emacs's =file+function= and =function= targets, and templates read from a file (=(file "…")=), are not supported.
142163
143164** Template types
144165
@@ -232,6 +253,8 @@ With =datetree = true=, the entry goes under today's date in a tree of headings,
232253| =week= | =* 2026=, =** 2026-W41=, =*** 2026-10-07 Wednesday= (ISO week and its year) |
233254| =month= | =* 2026=, =** 2026-10 October= |
234255
256=tree-type= may instead list the levels, any of =year=, =quarter=, =month=, =week= and =day= separated by spaces, as a list does in Org: ="year quarter month"= gives =* 2026=, =** 2026-Q4=, =*** 2026-10 October=. The levels always come in that order. With =week=, the year is the ISO week's year and the month is the month of the week's Thursday; with =week= and =quarter= but no =month=, quarters are 13-week periods. The day heading always uses the calendar date.
257
235258#+BEGIN_SRC toml
236259[[template]]
237260key = "j"
@@ -241,7 +264,7 @@ datetree = true
241264template = "* %<%H:%M> %?\n%i"
242265#+END_SRC
243266
244With =olp=, the tree goes under that outline path, one level down, instead of at the top of the file. The date is the day you file the capture. There is no =:time-prompt= to choose another day.
267With =olp=, the tree goes under that outline path, one level down, instead of at the top of the file. The date is the day you file the capture, or, with =time-prompt = true=, the day you give for =Date for tree entry=, read as =org-read-date= reads it (=+2d=, =fri=). That date is also the template's date: without a time, a day other than today is midnight, so =%U= gives =00:00=; with a time, such as =fri 14:00=, it is that time. Org only asks for date trees, and so does orgstar.
245268
246269* org-protocol
247270
@@ -317,6 +340,7 @@ The sheet works as on the Mac, in a form:
317340- The Template picker chooses the template; it starts on the first one.
318341- Prompts appear as fields. Date prompts have a date picker; choices and tags appear as buttons, and tapping a tag adds it.
319342- Continue fills the template and shows the text to edit; File files it; Cancel discards it.
343- Refile… in the bottom bar, for =entry= templates, files the text and then shows the refile targets. If you cancel or refiling fails, the entry opens where it was filed.
320344
321345Differences from the Mac: there is no selection, clipboard, current file, user name or clock link to insert, so =%i= and =%a= are empty unless the capture came from a link or the share sheet, and =%c=, =%x=, =%f=, =%F=, =%n=, =%k= and =%K= are empty. An org-protocol link naming a template key that doesn't exist opens the sheet on the first template and shows =No capture template "x"= with the key.
322346
@@ -345,11 +369,15 @@ Import from Emacs (see [[file:13-configuration.org][Configuration]] and [[file:1
345369| =(file+olp+datetree "f" …)= | =file=, =datetree=, =olp= if a path is given |
346370| =(file+datetree "f")= | =file=, =datetree= |
347371| =(file+weektree "f")= | =file=, =datetree=, =tree-type = "week"= |
372| =(file+regexp "f" "re")= | =file=, =regexp= |
348373| =(id "…")= | =id= |
349374| =(clock)= | =clock= |
350375| =:prepend=, =:immediate-finish=, =:jump-to-captured=, =:clock-in=, =:clock-keep=, =:clock-resume= | the boolean of the same name |
351| =:empty-lines=, =:empty-lines-before=, =:empty-lines-after=, =:table-line-pos=, =:tree-type= | the key of the same name |
376| =:empty-lines=, =:empty-lines-before=, =:empty-lines-after=, =:table-line-pos= | the key of the same name |
377| =:tree-type=, a symbol or a list such as =(year quarter)= | =tree-type= |
378| =:time-prompt= | =time-prompt = true= |
379| =("w" "Work")=, a key and a description | a group: =key= and =name= |
352380
353A file name given as a variable or a simple form is evaluated where the importer can. The import report lists what it left out: other targets, templates that aren't strings, unknown =:tree-type= values, and other properties such as =:time-prompt=, =:kill-buffer= or =:unnarrowed=. Template groups are skipped.
381A file name given as a variable or a simple form is evaluated where the importer can. The import report lists what it left out: other targets, templates that aren't strings, unknown =:tree-type= values, and other properties such as =:kill-buffer= or =:unnarrowed=.
354382
355383Emacs resolves relative target files against =org-directory=; orgstar resolves them against the first folder in the sidebar. If =org-directory= isn't your first folder, edit the imported =file= values or make them absolute.