Sources/OrgDocument/CaptureEntry.swift
52 lines · 2602 bytes
3 symbols in this file
1import Foundation
2import OrgCore
3
4/// The first heading of a capture's text, as the capture sheet shows and changes it: its
5/// keyword, priority, tags and planning, set by running the editor's own commands on the text.
6public struct CaptureEntry: Sendable, Equatable {
7 public var todo: String?
8 public var priority: String?
9 public var tags: [String]
10 public var scheduled: Timestamp?
11 public var deadline: Timestamp?
12 /// The keywords of the text's settings, as sequences list them, active before done.
13 public var keywords: [String]
14 /// The priorities from highest to lowest: `A`, `B`, `C`, or numbers.
15 public var priorities: [String]
16
17 /// Nil when the text has no heading.
18 public init?(text: String, defaults: OrgSettings = .default) {
19 let tree = OrgParser.parse(text, defaults: defaults)
20 guard let heading = DocumentModel(tree: tree).headings.first else { return nil }
21 todo = heading.todo
22 priority = heading.priority
23 tags = heading.localTags
24 scheduled = heading.scheduled
25 deadline = heading.deadline
26 keywords = tree.settings.todoSequences.flatMap { $0.active.map(\.name) + $0.done.map(\.name) }
27 priorities = Self.priorities(tree.settings.priorities)
28 }
29
30 /// The priorities from `range.highest` to `range.lowest`: `A`, `B`, `C`, or numbers.
31 public static func priorities(_ range: Priorities) -> [String] {
32 if let high = Int(range.highest), let low = Int(range.lowest), high <= low {
33 return (high...low).map(String.init)
34 } else if let high = range.highest.unicodeScalars.first?.value, let low = range.lowest.unicodeScalars.first?.value, high <= low {
35 return (high...low).compactMap(Unicode.Scalar.init).map { String(Character($0)) }
36 }
37 return []
38 }
39
40 /// `text` after `command` runs on its first heading with `answers`, or nil when the command
41 /// asks something else, fails, or changes nothing.
42 public static func applying(
43 _ command: any OrgCommand, answers: [String: String], to text: String, defaults: OrgSettings = .default,
44 options: EditingOptions = .org, now: Date = Date()
45 ) -> String? {
46 var state = DocumentState(bytes: Array(text.utf8), defaults: defaults)
47 guard let start = DocumentModel(tree: state.tree).headings.first?.headingRange.lowerBound,
48 case .commit = try? state.run(command, selection: [start..<start], now: now, answers: answers, options: options),
49 state.text != text else { return nil }
50 return state.text
51 }
52}