Commit 2c44c9d610
Verified · cmc
Layout: unified · split
Sources/OrgApp/CaptureModel.swift +68 −10
| @@ -16,11 +16,15 @@ import OrgDocument | ||
| 16 | 16 | /// prepend = false |
| 17 | 17 | /// ``` |
| 18 | 18 | /// |
| 19 | /// Other targets: `datetree = true` (under `olp` if given; `tree-type` "day", "week" or | |
| 20 | /// "month"), `id = "…"` without `file`, `clock = true` without `file`. Other properties, as | |
| 21 | /// in `org-capture-templates`: `immediate-finish`, `empty-lines`, `empty-lines-before`, | |
| 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`, | |
| 22 | 23 | /// `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. | |
| 24 | 28 | @MainActor |
| 25 | 29 | public enum CaptureTemplates { |
| 26 | 30 | public static var userFile: URL { UserConfig.file("capture.toml") } |
| @@ -31,15 +35,16 @@ public enum CaptureTemplates { | ||
| 31 | 35 | CaptureTemplate(key: "n", name: "Personal notes", target: .headline(file: "notes.org", headline: "Inbox"), template: "* %u %?\n%i\n%a"), |
| 32 | 36 | ] |
| 33 | 37 | |
| 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, [], []) } | |
| 36 | 40 | let tables: [TOML.Table] |
| 37 | 41 | do { |
| 38 | 42 | tables = try TOML.parse(text) |
| 39 | 43 | } catch { |
| 40 | return (defaults, ["capture.toml: \(error)"]) | |
| 44 | return (defaults, [], ["capture.toml: \(error)"]) | |
| 41 | 45 | } |
| 42 | 46 | var templates: [CaptureTemplate] = [] |
| 47 | var groups: [CaptureGroup] = [] | |
| 43 | 48 | var problems: [String] = [] |
| 44 | 49 | for table in tables where !(table.name.isEmpty && table.values.isEmpty) { |
| 45 | 50 | guard table.name == "template", table.isArrayElement else { |
| @@ -47,6 +52,10 @@ public enum CaptureTemplates { | ||
| 47 | 52 | continue |
| 48 | 53 | } |
| 49 | 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 | } | |
| 50 | 59 | let fileless = values["id"]?.string != nil || values["clock"]?.bool == true |
| 51 | 60 | guard let key = values["key"]?.string, let body = values["template"]?.string, let file = values["file"]?.string ?? (fileless ? "" : nil) else { |
| 52 | 61 | problems.append("capture.toml line \(table.line): a template needs key, file and template") |
| @@ -64,10 +73,12 @@ public enum CaptureTemplates { | ||
| 64 | 73 | target = .clock |
| 65 | 74 | } else if values["datetree"]?.bool == true { |
| 66 | 75 | 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") | |
| 68 | 77 | continue |
| 69 | 78 | } |
| 70 | 79 | target = .datetree(file: file, path: olp ?? [], tree: tree) |
| 80 | } else if let regexp = values["regexp"]?.string { | |
| 81 | target = .regexp(file: file, regexp: regexp) | |
| 71 | 82 | } else if let headline = values["headline"]?.string { |
| 72 | 83 | target = .headline(file: file, headline: headline) |
| 73 | 84 | } else if let olp { |
| @@ -81,12 +92,59 @@ public enum CaptureTemplates { | ||
| 81 | 92 | prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"), |
| 82 | 93 | emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"), |
| 83 | 94 | 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") | |
| 85 | 96 | ) |
| 86 | 97 | templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options)) |
| 87 | 98 | } |
| 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`. | |
| 128 | public 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 | ||
| 138 | public 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 | } | |
| 89 | 146 | } |
| 147 | public var id: String { key } | |
| 90 | 148 | } |
| 91 | 149 | |
| 92 | 150 | extension DocumentSession { |
Sources/OrgApp/EmacsImport.swift +19 −7
| @@ -806,9 +806,14 @@ public struct EmacsImport: Sendable { | ||
| 806 | 806 | mutating func captureTemplate(_ entry: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) { |
| 807 | 807 | guard let parts = entry.elements, parts.count >= 2, let key = parts[0].string else { return } |
| 808 | 808 | let name = parts[1].string ?? key |
| 809 | func quoted(_ s: String) -> String { UserConfig.format(.string(s)) } | |
| 809 | 810 | guard parts.count >= 5, let type = parts[2].symbol, let target = parts[3].elements, let kind = target.first?.symbol, |
| 810 | 811 | let template = parts[4].string else { |
| 811 | 812 | // 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 | } | |
| 812 | 817 | if parts.count == 2 { return } |
| 813 | 818 | unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "a template that isn't a string", source: source)) |
| 814 | 819 | return |
| @@ -817,7 +822,6 @@ public struct EmacsImport: Sendable { | ||
| 817 | 822 | unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "\(type) templates aren't supported", source: source)) |
| 818 | 823 | return |
| 819 | 824 | } |
| 820 | func quoted(_ s: String) -> String { UserConfig.format(.string(s)) } | |
| 821 | 825 | var toml = "[[template]]\nkey = \(quoted(key))\nname = \(quoted(name))\ntype = \(quoted(type))\n" |
| 822 | 826 | // `org-capture-expand-file`: a variable's value, or a form evaluated. |
| 823 | 827 | let strings = target.dropFirst().compactMap { $0.string ?? Self.evaluate($0, env)?.string } |
| @@ -826,12 +830,20 @@ public struct EmacsImport: Sendable { | ||
| 826 | 830 | let rest = Array(parts.dropFirst(5)) |
| 827 | 831 | for i in stride(from: 0, to: rest.count - 1, by: 2) { if let name = rest[i].symbol { properties[name] = rest[i + 1] } } |
| 828 | 832 | 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 | } | |
| 830 | 840 | let place: String? = switch kind { |
| 831 | 841 | case "file" where strings.count == 1 && target.count == 2: |
| 832 | 842 | "file = \(quoted(strings[0]))\n" |
| 833 | 843 | case "file+headline" where strings.count == 2 && target.count == 3: |
| 834 | 844 | "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" | |
| 835 | 847 | case "file+olp" where strings.count >= 2 && allStrings: |
| 836 | 848 | "file = \(quoted(strings[0]))\nolp = \(quoted(strings.dropFirst().joined(separator: "/")))\n" |
| 837 | 849 | case "file+olp+datetree" where strings.count >= 1 && allStrings: |
| @@ -852,20 +864,20 @@ public struct EmacsImport: Sendable { | ||
| 852 | 864 | if kind == "file+weektree" { treeType = "week" } |
| 853 | 865 | toml += place |
| 854 | 866 | if let treeType { |
| 855 | guard ["day", "week", "month"].contains(treeType) else { | |
| 867 | guard let tree = CaptureTemplate.TreeType(rawValue: treeType) else { | |
| 856 | 868 | unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: ":tree-type \(treeType) isn't supported", source: source)) |
| 857 | 869 | return |
| 858 | 870 | } |
| 859 | if treeType != "day" { toml += "tree-type = \(quoted(treeType))\n" } | |
| 871 | if tree != .day { toml += "tree-type = \(quoted(tree.rawValue))\n" } | |
| 860 | 872 | } |
| 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"] { | |
| 862 | 874 | if let value = properties[":" + flag], value.symbol != "nil" { toml += "\(flag) = true\n" } |
| 863 | 875 | } |
| 864 | 876 | for count in ["empty-lines", "empty-lines-before", "empty-lines-after"] { |
| 865 | 877 | if let n = properties[":" + count]?.integer { toml += "\(count) = \(n)\n" } |
| 866 | 878 | } |
| 867 | 879 | 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) } | |
| 869 | 881 | if !ignored.isEmpty { |
| 870 | 882 | unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "\(ignored.sorted().joined(separator: ", ")) left out", source: source)) |
| 871 | 883 | } |
| @@ -946,7 +958,7 @@ extension EmacsImport { | ||
| 946 | 958 | for item in items { |
| 947 | 959 | guard case .capture(let key, let toml) = item.change, !existingKeys.contains(key) else { continue } |
| 948 | 960 | addedCapture += "\n" + toml |
| 949 | templates += 1 | |
| 961 | if toml.contains("\ntemplate = ") { templates += 1 } | |
| 950 | 962 | } |
| 951 | 963 | if !addedCapture.isEmpty { |
| 952 | 964 | 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 | ||
| 6 | 6 | public struct CaptureTemplate: Sendable, Equatable, Identifiable { |
| 7 | 7 | public enum Kind: String, Sendable, Equatable { case entry, item, checkitem, plain, tableLine = "table-line" } |
| 8 | 8 | |
| 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 | } | |
| 11 | 46 | |
| 12 | 47 | public enum Target: Sendable, Equatable { |
| 13 | 48 | case file(String) |
| @@ -15,6 +50,8 @@ public struct CaptureTemplate: Sendable, Equatable, Identifiable { | ||
| 15 | 50 | case outline(file: String, path: [String]) |
| 16 | 51 | /// `file+olp+datetree`: today's entry in a date tree, under `path` or at the top. |
| 17 | 52 | 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) | |
| 18 | 55 | /// `(id "…")`: the heading with that ID; the app finds its file. |
| 19 | 56 | case id(String) |
| 20 | 57 | /// `(clock)`: the clocked-in entry; the app turns it into `heading`. |
| @@ -25,7 +62,7 @@ public struct CaptureTemplate: Sendable, Equatable, Identifiable { | ||
| 25 | 62 | /// The target file, or "" for `id` and `clock` until the app resolves them. |
| 26 | 63 | public var file: String { |
| 27 | 64 | 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 | |
| 29 | 66 | case .id, .clock: "" |
| 30 | 67 | } |
| 31 | 68 | } |
| @@ -48,13 +85,16 @@ public struct CaptureTemplate: Sendable, Equatable, Identifiable { | ||
| 48 | 85 | public var clockResume = false |
| 49 | 86 | /// `:table-line-pos`: `II-3` is the third line above the second rule. |
| 50 | 87 | public var tableLinePos: String? |
| 88 | /// `:time-prompt`: a date tree asks which day the entry is for. | |
| 89 | public var timePrompt = false | |
| 51 | 90 | |
| 52 | 91 | public init( |
| 53 | 92 | prepend: Bool = false, immediateFinish: Bool = false, emptyLines: Int? = nil, emptyLinesBefore: Int? = nil, |
| 54 | 93 | 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 | |
| 56 | 95 | ) { |
| 57 | 96 | self.tableLinePos = tableLinePos |
| 97 | self.timePrompt = timePrompt | |
| 58 | 98 | self.prepend = prepend |
| 59 | 99 | self.immediateFinish = immediateFinish |
| 60 | 100 | self.emptyLines = emptyLines |
| @@ -90,6 +130,12 @@ public struct CaptureTemplate: Sendable, Equatable, Identifiable { | ||
| 90 | 130 | self.options = options |
| 91 | 131 | } |
| 92 | 132 | |
| 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 | ||
| 93 | 139 | /// The same template aimed at `target`. |
| 94 | 140 | public func retargeted(_ target: Target) -> CaptureTemplate { |
| 95 | 141 | CaptureTemplate(key: key, name: name, kind: kind, target: target, template: template, options: options) |
| @@ -530,6 +576,19 @@ public enum Capture { | ||
| 530 | 576 | return out |
| 531 | 577 | } |
| 532 | 578 | |
| 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 | ||
| 533 | 592 | // MARK: - Placing |
| 534 | 593 | |
| 535 | 594 | /// The target file's text after capturing `text`, as `org-capture-finalize` leaves it. |
| @@ -549,13 +608,20 @@ public enum Capture { | ||
| 549 | 608 | let buffer = EmacsBuffer(fileText, point: 0, settings: settings) |
| 550 | 609 | let start: Int |
| 551 | 610 | do { |
| 552 | let entryHeading = try locate(template.target, buffer, date: calendar.dateComponents([.year, .month, .day], from: now)) | |
| 553 | 611 | 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 | } | |
| 554 | 620 | switch template.kind { |
| 555 | 621 | 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) | |
| 559 | 625 | } |
| 560 | 626 | } catch let error as Failure { |
| 561 | 627 | return .failure(error) |
| @@ -570,6 +636,19 @@ public enum Capture { | ||
| 570 | 636 | return .success((result, start)) |
| 571 | 637 | } |
| 572 | 638 | |
| 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 | ||
| 573 | 652 | /// `org-capture-set-target-location`: point at the target heading, or nil for a file. |
| 574 | 653 | static func locate(_ target: CaptureTemplate.Target, _ buffer: EmacsBuffer, date: DateComponents) throws -> Int? { |
| 575 | 654 | switch target { |
| @@ -590,6 +669,8 @@ public enum Capture { | ||
| 590 | 669 | buffer.point = buffer.lineStart(offset) |
| 591 | 670 | guard atHeading(buffer) else { throw Failure.message("The clocked entry moved; try again") } |
| 592 | 671 | return buffer.point |
| 672 | case .regexp(_, let regexp): | |
| 673 | return try locateRegexp(regexp, prepend: false, buffer).heading | |
| 593 | 674 | case .datetree(_, let path, let tree): |
| 594 | 675 | let parent = path.isEmpty ? nil : try locate(.outline(file: "", path: path), buffer, date: date) |
| 595 | 676 | return Datetree.findCreate(buffer, under: parent, tree: tree, date: date) |
| @@ -679,7 +760,7 @@ public enum Capture { | ||
| 679 | 760 | /// `org--blank-before-heading-p` with `org-blank-before-new-entry` `(heading . auto)`. |
| 680 | 761 | static func blankBeforeHeading(_ buffer: EmacsBuffer) -> Bool { |
| 681 | 762 | buffer.saveExcursion { |
| 682 | let before = buffer.searchBackward("^\\*+ ", caseInsensitive: false) == nil && !atHeading(buffer) | |
| 763 | let before = buffer.saveExcursion { buffer.searchBackward("^\\*+ ", caseInsensitive: false) == nil } && !atHeading(buffer) | |
| 683 | 764 | if before { |
| 684 | 765 | nextHeading(buffer) |
| 685 | 766 | if buffer.point >= buffer.length, !atHeading(buffer) { return false } |
| @@ -788,7 +869,7 @@ public enum Capture { | ||
| 788 | 869 | } |
| 789 | 870 | |
| 790 | 871 | /// `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 { | |
| 792 | 873 | let prepend = options.prepend |
| 793 | 874 | if let heading { |
| 794 | 875 | buffer.point = heading |
| @@ -800,6 +881,8 @@ public enum Capture { | ||
| 800 | 881 | buffer.point = buffer.lineEnd(heading) |
| 801 | 882 | nextHeading(buffer) |
| 802 | 883 | } |
| 884 | } else if let exact { | |
| 885 | buffer.point = exact | |
| 803 | 886 | } else { |
| 804 | 887 | buffer.point = prepend ? 0 : buffer.length |
| 805 | 888 | } |
| @@ -815,13 +898,15 @@ public enum Capture { | ||
| 815 | 898 | /// `org-capture-place-table-line`, then what `org-capture-finalize` does to the table: the |
| 816 | 899 | /// first table in the entry, or the file, gets the line, at its end, after its first rule |
| 817 | 900 | /// 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 { | |
| 819 | 902 | let template = filled.trimmingCharacters(in: .whitespacesAndNewlines) |
| 820 | 903 | // `org-table-border-regexp`: a template that isn't a table line becomes one. |
| 821 | 904 | let text = template.range(of: "^[ \\t]*[^| \\t]", options: .regularExpression) != nil ? "| " + template : template + "\n" |
| 822 | 905 | var begin = 0 |
| 823 | 906 | var end = buffer.length |
| 824 | if let heading { | |
| 907 | if let exact { | |
| 908 | (begin, end) = entryRegion(from: exact, buffer) | |
| 909 | } else if let heading { | |
| 825 | 910 | begin = min(buffer.length, buffer.lineEnd(heading) + 1) |
| 826 | 911 | buffer.point = buffer.lineEnd(heading) |
| 827 | 912 | nextHeading(buffer) |
| @@ -892,6 +977,14 @@ public enum Capture { | ||
| 892 | 977 | return buffer.point |
| 893 | 978 | } |
| 894 | 979 | |
| 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 | ||
| 895 | 988 | /// `org-end-of-meta-data t`: past planning, drawers and the property drawer. |
| 896 | 989 | static func skipMetaData(_ buffer: EmacsBuffer) { |
| 897 | 990 | while buffer.point < buffer.length { |
| @@ -914,7 +1007,7 @@ public enum Capture { | ||
| 914 | 1007 | |
| 915 | 1008 | /// `org-capture-place-item`: after the last item of the first list in the entry (the file |
| 916 | 1009 | /// 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 { | |
| 918 | 1011 | let prepend = options.prepend |
| 919 | 1012 | var item = text.trimmingCharacters(in: .newlines) |
| 920 | 1013 | if item.range(of: "^[ \\t]*([-+*]|[0-9]+[.)])[ \\t]", options: .regularExpression) == nil { |
| @@ -925,7 +1018,9 @@ public enum Capture { | ||
| 925 | 1018 | } |
| 926 | 1019 | let start: Int |
| 927 | 1020 | let end: Int |
| 928 | if let heading { | |
| 1021 | if let exact { | |
| 1022 | (start, end) = entryRegion(from: exact, buffer) | |
| 1023 | } else if let heading { | |
| 929 | 1024 | start = min(buffer.length, buffer.lineEnd(heading) + 1) |
| 930 | 1025 | buffer.point = buffer.lineEnd(heading) |
| 931 | 1026 | nextHeading(buffer) |
| @@ -953,6 +1048,22 @@ public enum Capture { | ||
| 953 | 1048 | if buffer.forwardLine(1) != 0 { break } |
| 954 | 1049 | if !items.isEmpty { items[items.count - 1].end = buffer.point } |
| 955 | 1050 | } |
| 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 | } | |
| 956 | 1067 | if let first = items.first { |
| 957 | 1068 | let indent = first.indent |
| 958 | 1069 | 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 { | ||
| 7 | 7 | static let weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] |
| 8 | 8 | static let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] |
| 9 | 9 | |
| 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. | |
| 11 | 13 | static func levels(_ tree: CaptureTemplate.TreeType, date: DateComponents) -> [(title: String, pattern: String)] { |
| 12 | 14 | var gregorian = Calendar(identifier: .gregorian) |
| 13 | 15 | gregorian.timeZone = TimeZone(identifier: "UTC")! |
| 14 | 16 | 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 | |
| 16 | 18 | var iso = Calendar(identifier: .iso8601) |
| 17 | 19 | iso.timeZone = gregorian.timeZone |
| 18 | 20 | let isoYear = iso.component(.yearForWeekOfYear, from: day) |
| 19 | 21 | 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+")) | |
| 30 | 33 | } |
| 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 | |
| 31 | 40 | } |
| 32 | 41 | |
| 33 | 42 | /// 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 | ||
| 2 | 2 | import Carbon.HIToolbox |
| 3 | 3 | import OrgApp |
| 4 | 4 | import OrgCore |
| 5 | import OrgDocument | |
| 5 | 6 | import SwiftUI |
| 6 | 7 | |
| 7 | 8 | /// 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`). | |
| 9 | 11 | struct CaptureView: View { |
| 10 | 12 | let workspace: WorkspaceModel |
| 11 | 13 | let session: DocumentSession |
| 12 | 14 | let commands: AppCommands |
| 13 | 15 | let clock: ClockModel |
| 14 | 16 | @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? | |
| 15 | 20 | @State private var problem: String? |
| 16 | 21 | @State private var template: CaptureTemplate? |
| 17 | 22 | @State private var questions: [Capture.Question] = [] |
| @@ -26,6 +31,7 @@ struct CaptureView: View { | ||
| 26 | 31 | @State private var day: Int? |
| 27 | 32 | @FocusState private var focused: Bool |
| 28 | 33 | @Environment(\.dismissWindow) private var dismissWindow |
| 34 | @Environment(\.openWindow) private var openWindow | |
| 29 | 35 | |
| 30 | 36 | var body: some View { |
| 31 | 37 | VStack(alignment: .leading, spacing: 12) { |
| @@ -39,6 +45,9 @@ struct CaptureView: View { | ||
| 39 | 45 | Spacer() |
| 40 | 46 | Button("Cancel", role: .cancel) { close() } |
| 41 | 47 | .keyboardShortcut(.cancelAction) |
| 48 | if template.kind == .entry { | |
| 49 | Button("Refile…") { finish(refile: true) } | |
| 50 | } | |
| 42 | 51 | Button("File It") { finish() } |
| 43 | 52 | .keyboardShortcut(.return, modifiers: .command) |
| 44 | 53 | } |
| @@ -63,15 +72,23 @@ struct CaptureView: View { | ||
| 63 | 72 | } else { |
| 64 | 73 | Text((keys.isEmpty ? "Capture" : "Capture: \(keys)") + (day == nil ? "" : ", scheduled " + captureDate(Date()).formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated)))) |
| 65 | 74 | .font(.headline) |
| 66 | ForEach(templates.filter { $0.key.hasPrefix(keys) }) { template in | |
| 75 | ForEach(CaptureTemplates.menu(templates, groups: groups, typed: keys)) { item in | |
| 67 | 76 | Button { |
| 68 | choose(template) | |
| 77 | switch item { | |
| 78 | case .group(let group): keys = group.key | |
| 79 | case .template(let template): choose(template) | |
| 80 | } | |
| 69 | 81 | } label: { |
| 70 | 82 | 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 | } | |
| 75 | 92 | } |
| 76 | 93 | } |
| 77 | 94 | .buttonStyle(.plain) |
| @@ -125,6 +142,7 @@ struct CaptureView: View { | ||
| 125 | 142 | case .headline(_, let headline): return "\(file) / \(headline)" |
| 126 | 143 | case .outline(_, let path): return ([file] + path).joined(separator: " / ") |
| 127 | 144 | case .datetree(_, let path, _): return ([file] + path + ["date tree"]).joined(separator: " / ") |
| 145 | case .regexp(_, let regexp): return "\(file) / \(regexp)" | |
| 128 | 146 | case .id(let id): return "ID \(id)" |
| 129 | 147 | case .clock: return "clocked entry" |
| 130 | 148 | } |
| @@ -133,8 +151,10 @@ struct CaptureView: View { | ||
| 133 | 151 | private func reset() { |
| 134 | 152 | let loaded = CaptureTemplates.load() |
| 135 | 153 | templates = loaded.templates |
| 154 | groups = loaded.groups | |
| 136 | 155 | problem = loaded.problems.first |
| 137 | 156 | template = nil |
| 157 | treeDate = nil | |
| 138 | 158 | editing = false |
| 139 | 159 | keys = "" |
| 140 | 160 | day = nil |
| @@ -178,13 +198,22 @@ struct CaptureView: View { | ||
| 178 | 198 | for heading in DocumentModel(tree: OrgParser.parse(text)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } } |
| 179 | 199 | context.fileTags = tags |
| 180 | 200 | } |
| 181 | questions = Capture.questions(chosen.template, context: context) | |
| 201 | questions = (asksTreeDate(chosen) ? [Self.treeQuestion] : []) + Capture.questions(chosen.template, context: context) | |
| 182 | 202 | answers = questions.map { _ in "" } |
| 183 | 203 | if questions.isEmpty { expand() } |
| 184 | 204 | } |
| 185 | 205 | |
| 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 | ||
| 186 | 211 | private func expand() { |
| 187 | 212 | guard let template else { return } |
| 213 | var answers = answers | |
| 214 | if asksTreeDate(template) { | |
| 215 | treeDate = Capture.treeDate(answers.removeFirst(), now: Date()) | |
| 216 | } | |
| 188 | 217 | context.now = captureDate(Date()) |
| 189 | 218 | switch Capture.fill(template.template, context: context, answers: answers) { |
| 190 | 219 | case .failure(.message(let message)): |
| @@ -207,13 +236,14 @@ struct CaptureView: View { | ||
| 207 | 236 | /// `now` on the agenda day captured for, as `org-overriding-default-time` sets `%t`, `%U` |
| 208 | 237 | /// and the date tree's day. |
| 209 | 238 | private func captureDate(_ now: Date) -> Date { |
| 239 | if let treeDate { return treeDate } | |
| 210 | 240 | guard let day else { return now } |
| 211 | 241 | let d = Days.date(day) |
| 212 | 242 | let time = Calendar.current.dateComponents([.hour, .minute, .second], from: now) |
| 213 | 243 | 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 |
| 214 | 244 | } |
| 215 | 245 | |
| 216 | private func finish() { | |
| 246 | private func finish(refile: Bool = false) { | |
| 217 | 247 | guard let template else { return } |
| 218 | 248 | let opened = context.now |
| 219 | 249 | let now = Date() |
| @@ -229,19 +259,33 @@ struct CaptureView: View { | ||
| 229 | 259 | commands.show("Captured to \(Self.target(template))") |
| 230 | 260 | let options = template.options |
| 231 | 261 | let paths = workspace.files.filter { $0.kind == .org }.map(\.path) |
| 232 | Task { [commands, clock, session] in | |
| 262 | Task { [commands, clock, session, workspace] in | |
| 233 | 263 | let outcome = await clock.captured(entry, options: options, session: session, paths: paths, ask: commands.askClock, opened: opened, now: now) |
| 234 | 264 | 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 { | |
| 236 | 268 | commands.jump(path: jump.path, offset: jump.offset) |
| 237 | 269 | } else if options.jumpToCaptured { |
| 238 | 270 | commands.jump(path: entry.path, offset: entry.offset) |
| 239 | 271 | } |
| 240 | 272 | } |
| 241 | 273 | } |
| 274 | if refile { openWindow(id: "main") } | |
| 242 | 275 | close() |
| 243 | 276 | } |
| 244 | 277 | |
| 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 | ||
| 245 | 289 | private func close() { |
| 246 | 290 | reset() |
| 247 | 291 | dismissWindow(id: "capture") |
Sources/OrgstarMobile/CaptureScreen.swift +48 −7
| @@ -5,7 +5,8 @@ import OrgDocument | ||
| 5 | 5 | import SwiftUI |
| 6 | 6 | |
| 7 | 7 | /// 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`). | |
| 9 | 10 | struct CaptureScreen: View { |
| 10 | 11 | let workspace: WorkspaceModel |
| 11 | 12 | let session: DocumentSession |
| @@ -14,6 +15,11 @@ struct CaptureScreen: View { | ||
| 14 | 15 | @Environment(ClockModel.self) private var clock |
| 15 | 16 | @Environment(MobileModel.self) private var model |
| 16 | 17 | @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? | |
| 17 | 23 | @State private var key: String? |
| 18 | 24 | @State private var context = CaptureContext() |
| 19 | 25 | @State private var questions: [Capture.Question] = [] |
| @@ -33,7 +39,7 @@ struct CaptureScreen: View { | ||
| 33 | 39 | NavigationStack { |
| 34 | 40 | Form { |
| 35 | 41 | 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)) } | |
| 37 | 43 | } |
| 38 | 44 | if editing { |
| 39 | 45 | Section { |
| @@ -67,13 +73,26 @@ struct CaptureScreen: View { | ||
| 67 | 73 | if let tags { change(SetTags(), ["tags": tags.joined(separator: ":")]) } |
| 68 | 74 | } |
| 69 | 75 | } |
| 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 | } | |
| 70 | 86 | .navigationTitle("Capture") |
| 71 | 87 | .navigationBarTitleDisplayMode(.inline) |
| 72 | 88 | .toolbar { |
| 73 | 89 | ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } |
| 90 | if editing, template?.kind == .entry { | |
| 91 | ToolbarItem(placement: .bottomBar) { Button("Refile…") { file(refile: true) } } | |
| 92 | } | |
| 74 | 93 | ToolbarItem(placement: .confirmationAction) { |
| 75 | 94 | if editing { |
| 76 | Button("File", action: file).disabled(template == nil) | |
| 95 | Button("File") { file() }.disabled(template == nil) | |
| 77 | 96 | } else { |
| 78 | 97 | Button("Continue", action: fill) |
| 79 | 98 | } |
| @@ -83,6 +102,7 @@ struct CaptureScreen: View { | ||
| 83 | 102 | .onAppear { |
| 84 | 103 | let loaded = CaptureTemplates.load() |
| 85 | 104 | templates = loaded.templates |
| 105 | groups = loaded.groups | |
| 86 | 106 | problem = loaded.problems.first |
| 87 | 107 | key = request.template.flatMap { wanted in templates.first { $0.key == wanted }?.key } ?? templates.first?.key |
| 88 | 108 | if let wanted = request.template, !templates.contains(where: { $0.key == wanted }) { problem = "No capture template \"\(wanted)\"" } |
| @@ -107,16 +127,27 @@ struct CaptureScreen: View { | ||
| 107 | 127 | for heading in DocumentModel(tree: OrgParser.parse(source)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } } |
| 108 | 128 | context.fileTags = tags |
| 109 | 129 | } |
| 110 | questions = Capture.questions(template.template, context: context) | |
| 130 | questions = (asksTreeDate(template) ? [Self.treeQuestion] : []) + Capture.questions(template.template, context: context) | |
| 111 | 131 | answers = questions.map { _ in "" } |
| 132 | treeDate = nil | |
| 112 | 133 | editing = false |
| 113 | 134 | if questions.isEmpty { fill() } |
| 114 | 135 | } |
| 115 | 136 | |
| 116 | 137 | /// 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 | ||
| 117 | 146 | private func fill() { |
| 118 | 147 | 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 | |
| 120 | 151 | switch Capture.fill(template.template, context: context, answers: answers) { |
| 121 | 152 | case .success(let filled): |
| 122 | 153 | 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 { | ||
| 152 | 183 | return calendar.date(from: parts) ?? Date() |
| 153 | 184 | } |
| 154 | 185 | |
| 155 | private func file() { | |
| 186 | private func file(refile: Bool = false) { | |
| 156 | 187 | guard let template else { return } |
| 157 | 188 | let now = Date() |
| 158 | 189 | 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) | |
| 160 | 191 | } |
| 161 | 192 | switch placed { |
| 162 | 193 | case .failure(let error): |
| @@ -168,12 +199,22 @@ struct CaptureScreen: View { | ||
| 168 | 199 | Task { [clock, session, opened = context.now] in |
| 169 | 200 | _ = await clock.captured(entry, options: template.options, session: session, paths: paths, ask: model.clockPrompts.ask, opened: opened, now: now) |
| 170 | 201 | } |
| 202 | if refile { | |
| 203 | refiling = RefileEntry(path: entry.path, offset: entry.offset) | |
| 204 | return | |
| 205 | } | |
| 171 | 206 | if template.options.jumpToCaptured { model.openRequest = .offset(entry.path, entry.offset) } |
| 172 | 207 | dismiss() |
| 173 | 208 | } |
| 174 | 209 | } |
| 175 | 210 | } |
| 176 | 211 | |
| 212 | private struct RefileEntry: Identifiable { | |
| 213 | let path: String | |
| 214 | let offset: Int | |
| 215 | var id: String { "\(path)\u{0}\(offset)" } | |
| 216 | } | |
| 217 | ||
| 177 | 218 | /// One of a template's questions: text with its choices, tags, or a date. |
| 178 | 219 | struct QuestionField: View { |
| 179 | 220 | let question: Capture.Question |
Tests/OrgAppTests/AppTests.swift +58
| @@ -1093,6 +1093,64 @@ struct CaptureAppTests { | ||
| 1093 | 1093 | #expect(CaptureTemplates.load(userFile: folder.url.appendingPathComponent("none.toml")).templates == CaptureTemplates.defaults) |
| 1094 | 1094 | } |
| 1095 | 1095 | |
| 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 | ||
| 1096 | 1154 | @Test func capturesIntoClosedMissingAndOpenFiles() throws { |
| 1097 | 1155 | let notes = try Folder() |
| 1098 | 1156 | 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 { | ||
| 144 | 144 | #expect(folders == ["~/notes/", "~/work"]) |
| 145 | 145 | #expect(result.unreadable.map(\.name) == ["fill-column"]) |
| 146 | 146 | #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\""]) | |
| 148 | 148 | #expect(result.skipped == 1) |
| 149 | 149 | #expect(result.doomDefaultsLeftOut == 1) |
| 150 | 150 | } |
| @@ -152,12 +152,12 @@ struct EmacsImportTests { | ||
| 152 | 152 | @Test func readsCaptureTemplatesAndBindings() throws { |
| 153 | 153 | let result = try scan() |
| 154 | 154 | 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") | |
| 157 | 157 | #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") | |
| 159 | 159 | #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\"")) | |
| 161 | 161 | |
| 162 | 162 | let bindings = result.items.compactMap { if case .binding(let keys, let command, let mode) = $0.change { "\(keys) \(command) \(mode ?? "-")" } else { nil } } |
| 163 | 163 | #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 { | ||
| 178 | 178 | `(("n" "Note" entry (file+headline org-default-notes-file "Notes") "* %?") |
| 179 | 179 | ("i" "Inbox" entry (file my-inbox) "* TODO %?") |
| 180 | 180 | ("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") "%?"))) | |
| 182 | 184 | """#.write(to: folder.appendingPathComponent("init.el"), atomically: true, encoding: .utf8) |
| 183 | 185 | let result = EmacsImport.scan(EmacsImport.files(in: folder)) |
| 184 | 186 | let files = result.items.compactMap { item -> String? in |
| 185 | 187 | guard case .capture(let key, let toml) = item.change else { return nil } |
| 186 | 188 | return key + " " + (toml.firstMatch(of: /file = "([^"]*)"/).map { String($0.1) } ?? "-") |
| 187 | 189 | } |
| 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)") | |
| 189 | 195 | } |
| 190 | 196 | |
| 191 | 197 | /// The user's own Doom configuration, when there is one. |
| @@ -219,7 +225,7 @@ struct EmacsImportTests { | ||
| 219 | 225 | #expect(defaults.integer(forKey: "agendaStartOffset") == -3) |
| 220 | 226 | #expect(defaults.string(forKey: "todoKeywords") == "TODO(t) WAIT(w) | DONE(d)\nBUG | FIXED") |
| 221 | 227 | 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) | |
| 223 | 229 | #expect(CaptureTemplates.load(userFile: folder.appendingPathComponent("capture.toml")).problems.isEmpty) |
| 224 | 230 | let keymap = folder.appendingPathComponent("keymap.toml") |
| 225 | 231 | #expect(KeymapLoader.load(.doom, userFile: keymap).problems.isEmpty) |
Tests/OrgCoreTests/CaptureTests.swift +60 −1
| @@ -35,11 +35,13 @@ struct CaptureTests { | ||
| 35 | 35 | case .outline(_, let p): target = "(file+olp \(lisp(path)) \(p.map(lisp).joined(separator: " ")))" |
| 36 | 36 | case .datetree(_, let p, let tree): |
| 37 | 37 | 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)))" | |
| 39 | 40 | case .id(let id): target = "(id \(lisp(id)))" |
| 40 | 41 | case .clock, .heading: target = "(clock)" |
| 41 | 42 | } |
| 42 | 43 | forms.append(""" |
| 44 | (condition-case nil | |
| 43 | 45 | (let ((org-capture-templates '(("x" "case" \(c.template.kind.rawValue) \(target) \(lisp(c.template.template))\(properties)))) |
| 44 | 46 | (path \(lisp(path)))) |
| 45 | 47 | (cl-letf (((symbol-function 'org-id-find) |
| @@ -55,6 +57,7 @@ struct CaptureTests { | ||
| 55 | 57 | (org-capture-finalize) |
| 56 | 58 | (with-current-buffer (find-buffer-visiting \(lisp(path))) |
| 57 | 59 | (push (buffer-substring-no-properties (point-min) (point-max)) results))) |
| 60 | (error (push "failed" results))) | |
| 58 | 61 | """) |
| 59 | 62 | } |
| 60 | 63 | let output = folder.appendingPathComponent("out.json") |
| @@ -215,6 +218,62 @@ struct CaptureTests { | ||
| 215 | 218 | } |
| 216 | 219 | } |
| 217 | 220 | |
| 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 | ||
| 218 | 277 | static let optionTemplates: [CaptureTemplate] = [ |
| 219 | 278 | CaptureTemplate(key: "x", name: "", target: .id("journal-id"), template: "* %?"), |
| 220 | 279 | 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 | ||
| 27 | 27 | |
| 28 | 28 | A capture goes through up to three steps. |
| 29 | 29 | |
| 30 | 1. *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. | |
| 31 | 2. *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. | |
| 32 | 3. *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. | |
| 30 | 1. *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. | |
| 31 | 2. *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. | |
| 32 | 3. *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. | |
| 33 | 33 | |
| 34 | 34 | Press Esc (Cancel) at any step to close the window without filing anything, as =org-capture-kill= does. |
| 35 | 35 | |
| @@ -40,7 +40,6 @@ If filing fails, for example because a heading on an =olp= path is missing, the | ||
| 40 | 40 | Limits compared with Emacs: |
| 41 | 41 | |
| 42 | 42 | - 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. | |
| 44 | 43 | - The target is not shown while you edit (the capture buffer in Emacs is narrowed to the new entry in the target file). |
| 45 | 44 | |
| 46 | 45 | * 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 | ||
| 49 | 48 | |
| 50 | 49 | - =%t=, =%T=, =%u= and =%U= give that day. The escapes with a time use the current time of day. |
| 51 | 50 | - 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. | |
| 53 | 52 | |
| 54 | 53 | When 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: |
| 55 | 54 | |
| @@ -84,7 +83,26 @@ The file is read each time the capture window opens. If it doesn't exist, or non | ||
| 84 | 83 | |
| 85 | 84 | A 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. |
| 86 | 85 | |
| 87 | Templates 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. | |
| 86 | Keys of several characters are typed one character at a time, as in Emacs. | |
| 87 | ||
| 88 | ** Template groups | |
| 89 | ||
| 90 | A =[[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]] | |
| 94 | key = "w" | |
| 95 | name = "Work" | |
| 96 | ||
| 97 | [[template]] | |
| 98 | key = "wm" | |
| 99 | name = "Meeting" | |
| 100 | file = "work.org" | |
| 101 | olp = "Meetings" | |
| 102 | template = "* %?" | |
| 103 | #+END_SRC | |
| 104 | ||
| 105 | The 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=. | |
| 88 | 106 | |
| 89 | 107 | ** Keys |
| 90 | 108 | |
| @@ -98,7 +116,9 @@ Templates are a flat list. Keys of several characters are typed one character at | ||
| 98 | 116 | | =headline= | string | A heading in =file= | =file+headline= | |
| 99 | 117 | | =olp= | string | An outline path in =file=, titles separated by =/= | =file+olp= | |
| 100 | 118 | | =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= | | |
| 102 | 122 | | =id= | string | The heading with this =ID= property, in any file | =id= | |
| 103 | 123 | | =clock= | boolean | The entry the clock is running in | =clock= | |
| 104 | 124 | | =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 | ||
| 125 | 145 | |
| 126 | 146 | ** Targets |
| 127 | 147 | |
| 128 | The target keys are checked in this order: =id=, =clock=, =datetree=, =headline=, =olp=; with none of them the target is =file= itself. | |
| 148 | The target keys are checked in this order: =id=, =clock=, =datetree=, =regexp=, =headline=, =olp=; with none of them the target is =file= itself. | |
| 129 | 149 | |
| 130 | 150 | | Target | Where the text goes | |
| 131 | 151 | |---------------------------+-----------------------------------------------------------------------------------------------------------------| |
| @@ -133,12 +153,13 @@ The target keys are checked in this order: =id=, =clock=, =datetree=, =headline= | ||
| 133 | 153 | | =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 | |
| 134 | 154 | | =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= | |
| 135 | 155 | | =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= | | |
| 136 | 157 | | =id = "…"= | Under the heading with that =ID=, found through the workspace index. Fails with =Cannot find target ID= if no heading has it | |
| 137 | 158 | | =clock = true= | Under the heading the running clock is in. Fails with =No running clock= when no clock runs | |
| 138 | 159 | |
| 139 | 160 | =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. |
| 140 | 161 | |
| 141 | Emacs's =file+regexp=, =file+function= and =function= targets, and templates read from a file (=(file "…")=), are not supported. | |
| 162 | Emacs's =file+function= and =function= targets, and templates read from a file (=(file "…")=), are not supported. | |
| 142 | 163 | |
| 143 | 164 | ** Template types |
| 144 | 165 | |
| @@ -232,6 +253,8 @@ With =datetree = true=, the entry goes under today's date in a tree of headings, | ||
| 232 | 253 | | =week= | =* 2026=, =** 2026-W41=, =*** 2026-10-07 Wednesday= (ISO week and its year) | |
| 233 | 254 | | =month= | =* 2026=, =** 2026-10 October= | |
| 234 | 255 | |
| 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 | ||
| 235 | 258 | #+BEGIN_SRC toml |
| 236 | 259 | [[template]] |
| 237 | 260 | key = "j" |
| @@ -241,7 +264,7 @@ datetree = true | ||
| 241 | 264 | template = "* %<%H:%M> %?\n%i" |
| 242 | 265 | #+END_SRC |
| 243 | 266 | |
| 244 | With =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. | |
| 267 | With =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. | |
| 245 | 268 | |
| 246 | 269 | * org-protocol |
| 247 | 270 | |
| @@ -317,6 +340,7 @@ The sheet works as on the Mac, in a form: | ||
| 317 | 340 | - The Template picker chooses the template; it starts on the first one. |
| 318 | 341 | - Prompts appear as fields. Date prompts have a date picker; choices and tags appear as buttons, and tapping a tag adds it. |
| 319 | 342 | - 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. | |
| 320 | 344 | |
| 321 | 345 | Differences 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. |
| 322 | 346 | |
| @@ -345,11 +369,15 @@ Import from Emacs (see [[file:13-configuration.org][Configuration]] and [[file:1 | ||
| 345 | 369 | | =(file+olp+datetree "f" …)= | =file=, =datetree=, =olp= if a path is given | |
| 346 | 370 | | =(file+datetree "f")= | =file=, =datetree= | |
| 347 | 371 | | =(file+weektree "f")= | =file=, =datetree=, =tree-type = "week"= | |
| 372 | | =(file+regexp "f" "re")= | =file=, =regexp= | | |
| 348 | 373 | | =(id "…")= | =id= | |
| 349 | 374 | | =(clock)= | =clock= | |
| 350 | 375 | | =: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= | | |
| 352 | 380 | |
| 353 | A 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. | |
| 381 | A 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=. | |
| 354 | 382 | |
| 355 | 383 | Emacs 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. |