Sources/OrgDocument/CaptureEntry.swift

9a7439fd01e4ce5041bc5fab90542f083143ae10
orgstar/Sources/OrgDocument/CaptureEntry.swift history · blame · raw

49 lines · 2457 bytes

 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        let range = tree.settings.priorities
28        if let high = Int(range.highest), let low = Int(range.lowest), high <= low {
29            priorities = (high...low).map(String.init)
30        } else if let high = range.highest.unicodeScalars.first?.value, let low = range.lowest.unicodeScalars.first?.value, high <= low {
31            priorities = (high...low).compactMap(Unicode.Scalar.init).map { String(Character($0)) }
32        } else {
33            priorities = []
34        }
35    }
36
37    /// `text` after `command` runs on its first heading with `answers`, or nil when the command
38    /// asks something else, fails, or changes nothing.
39    public static func applying(
40        _ command: any OrgCommand, answers: [String: String], to text: String, defaults: OrgSettings = .default,
41        options: EditingOptions = .org, now: Date = Date()
42    ) -> String? {
43        var state = DocumentState(bytes: Array(text.utf8), defaults: defaults)
44        guard let start = DocumentModel(tree: state.tree).headings.first?.headingRange.lowerBound,
45              case .commit = try? state.run(command, selection: [start..<start], now: now, answers: answers, options: options),
46              state.text != text else { return nil }
47        return state.text
48    }
49}