Sources/OrgCore/Agenda/AgendaSource.swift

d85099bc95bf1766aee990d94671dacda0c0686e
orgstar/Sources/OrgCore/Agenda/AgendaSource.swift history · blame · raw

417 lines · 22280 bytes

  1import Foundation
  2
  3/// What the agenda needs from one file, read once from its text: headings with their planning,
  4/// and the active timestamps and date ranges org's agenda would consider. Positions are UTF-16.
  5public struct AgendaSource: Sendable {
  6    static let planningRegex = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE): *<([^>]+)>")
  7    static let planningAnyRegex = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE|CLOSED): *([\\[<]\(Self.tsInternal)[\\]>])")
  8    static let activeRangeRegex = try! NSRegularExpression(pattern: "<(\(Self.tsInternal))>--?-?<(\(Self.tsInternal))>")
  9    static let inactiveRegex = try! NSRegularExpression(pattern: "\\[([0-9]{4}-[0-9]{2}-[0-9]{2}( +[^\\]+0-9>\\r\\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)\\]")
 10    static let dateRangeRegex = try! NSRegularExpression(pattern: "[\\[<](\(tsInternal))[\\]>]--?-?[\\[<](\(tsInternal))[\\]>]")
 11
 12    public let path: String
 13    /// The file names `#+SETUPFILE`s.
 14    public let readsSetupFiles: Bool
 15
 16    struct Heading: Sendable {
 17        /// Start of the heading line.
 18        let start: Int
 19        let level: Int
 20        /// In an archived or commented tree, which the agenda skips.
 21        let skipped: Bool
 22        /// The title without keyword, priority and tags (`ITEM`).
 23        let title: String
 24        /// The priority cookie's value.
 25        let priority: String?
 26        let localTags: [String]
 27        /// Upper-cased keys of the entry's own drawer.
 28        let properties: [String: String]
 29        /// `properties` with inherited ones (`org-use-property-inheritance`), for matches.
 30        let matchProperties: [String: String]
 31        /// Planning timestamps with brackets, for property matches.
 32        let planning: [String: String]
 33        /// The first active and inactive timestamps in the entry (`TIMESTAMP`, `TIMESTAMP_IA`).
 34        let firstActive: String?
 35        let firstInactive: String?
 36        /// The heading line without its newline.
 37        let line: String
 38        /// The line after the stars.
 39        let head: String
 40        let todo: String?
 41        let isDone: Bool
 42        /// Inherited tags first; the flag marks inherited ones.
 43        let tags: [(name: String, inherited: Bool)]
 44        let category: String
 45        /// The planning timestamp without brackets, and the position of its `<`.
 46        let scheduled: (raw: String, offset: Int)?
 47        let deadline: (raw: String, offset: Int)?
 48        /// `STYLE: habit`.
 49        let isHabit: Bool
 50        /// `org-habit-parse-todo`, nil where it signals an error.
 51        let habit: Habit?
 52        /// `org-entry-blocked-p` with only `org-enforce-todo-checkbox-dependencies`, and with
 53        /// only `org-enforce-todo-dependencies`.
 54        let blockedByCheckboxes: Bool
 55        let blockedByHierarchy: Bool
 56    }
 57
 58    struct Stamp: Sendable {
 59        let offset: Int
 60        let heading: Int
 61        /// From the `<` to the end of the line.
 62        let rest: String
 63    }
 64
 65    struct Block: Sendable {
 66        let start: String
 67        let end: String
 68        /// End of the range; org's marker sits there.
 69        let marker: Int
 70        let heading: Int
 71    }
 72
 73    /// A `CLOSED:`, `CLOCK:` or `- State "…"` line, for log mode (`org-agenda-get-progress`).
 74    struct Progress: Sendable {
 75        enum Kind: Sendable { case closed, clock, state }
 76        let kind: Kind
 77        let offset: Int
 78        let heading: Int
 79        /// `YYYY-MM-DD` of the first timestamp.
 80        let date: String
 81        /// The timestamp, from the keyword; a clock's ends with its end time (`[… 10:00-11:30]`).
 82        let timestamp: String
 83        /// A clock's duration, or `-`.
 84        let clocked: String
 85        /// The state a note records.
 86        let state: String?
 87        /// The first line of the note under it.
 88        let note: String?
 89    }
 90
 91    /// A `%%(…)` line (`org-agenda-get-sexps`).
 92    struct SexpLine: Sendable {
 93        /// Start of the line.
 94        let offset: Int
 95        /// The heading the line is under.
 96        let heading: Int
 97        let sexp: Sexp
 98        /// The rest of the line after the sexp.
 99        let entry: String
100    }
101
102    let headings: [Heading]
103
104    /// The file's habits not done and not in skipped trees: their titles, heading offsets and
105    /// what their consistency graphs are drawn from.
106    public var habits: [(title: String, offset: Int, habit: Habit)] {
107        headings.compactMap { heading in
108            guard heading.isHabit, !heading.skipped, !heading.isDone, let habit = heading.habit else { return nil }
109            return (heading.title, heading.start, habit)
110        }
111    }
112    let stamps: [Stamp]
113    let sexps: [SexpLine]
114    let blocks: [Block]
115    let progress: [Progress]
116    /// The file's TODO keywords, active and done.
117    let keywords: [String]
118    /// The active ones (`org-not-done-keywords`).
119    let notDoneKeywords: [String]
120    /// Each keyword's first done keyword in the first sequence that has it.
121    let firstDone: [String: String]
122    /// The file's text, for the search view.
123    public let text: String
124    let priorities: Priorities
125
126    /// `checksBlocking` false leaves every heading unblocked, for when neither enforce
127    /// setting is on.
128    public init(path: String, text: String, defaults: OrgSettings = .default, checksBlocking: Bool = true) {
129        self.path = path
130        readsSetupFiles = text.containsIgnoringASCIICase("#+setupfile:")
131        let tree = OrgParser.parse(text, defaults: defaults)
132        let model = DocumentModel(tree: tree)
133        let ns = text as NSString
134        let settings = tree.settings
135        keywords = settings.todoSequences.flatMap { $0.active.map(\.name) + $0.done.map(\.name) }
136        notDoneKeywords = settings.todoSequences.flatMap { $0.active.map(\.name) }
137        var firstDone: [String: String] = [:]
138        for sequence in settings.todoSequences {
139            guard let done = sequence.done.first?.name else { continue }
140            for keyword in sequence.active + sequence.done where firstDone[keyword.name] == nil { firstDone[keyword.name] = done }
141        }
142        self.firstDone = firstDone
143        self.text = text
144        priorities = settings.priorities
145
146        var stampsByHeading: [Int: [String]] = [:]
147        var headingIndex = -1
148        func collect(_ node: SyntaxNode) {
149            for child in node.children {
150                if child.kind == .heading { headingIndex += 1 }
151                if child.kind == .timestamp, headingIndex >= 0 {
152                    stampsByHeading[headingIndex, default: []].append(child.text)
153                } else if child.kind != .block, child.kind != .planning {
154                    collect(child)
155                }
156            }
157        }
158        collect(tree.root)
159        func sectionStamps(_ index: Int) -> [String] { stampsByHeading[index] ?? [] }
160
161        var keywordCategory = SetupFile.keywords(tree.settings.setupKeywords).last { $0.key == "CATEGORY" }?.value.trimmingCharacters(in: .whitespaces)
162        var srcBodies: [Range<Int>] = []
163        var planningLines: [Range<Int>] = []
164        var timestampNodes: [Int] = []
165        var propertyLines: [Range<Int>] = []
166        func walk(_ node: SyntaxNode) {
167            for child in node.children {
168                switch child.kind {
169                case .keyword:
170                    let line = child.text.trimmingCharacters(in: .whitespacesAndNewlines)
171                    if line.uppercased().hasPrefix("#+CATEGORY:") {
172                        keywordCategory = line.dropFirst("#+CATEGORY:".count).trimmingCharacters(in: .whitespaces)
173                    }
174                case .block:
175                    if DocumentModel.isSrcBlock(child) {
176                        let lines = child.range
177                        let firstEnd = ns.range(of: "\n", range: NSRange(location: lines.lowerBound, length: lines.count)).location
178                        let lastStart = ns.lineRange(for: NSRange(location: max(lines.lowerBound, lines.upperBound - 1), length: 0)).location
179                        if firstEnd != NSNotFound, firstEnd + 1 <= lastStart { srcBodies.append((firstEnd + 1)..<lastStart) }
180                    }
181                case .planning:
182                    planningLines.append(child.range)
183                case .clock:
184                    break
185                case .nodeProperty:
186                    propertyLines.append(child.range)
187                case .timestamp:
188                    if child.text.hasPrefix("<") { timestampNodes.append(child.offset) }
189                default:
190                    walk(child)
191                }
192            }
193        }
194        walk(tree.root)
195
196        let fileName = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
197        let fileCategory = keywordCategory ?? model.property("CATEGORY", of: nil)?.value ?? fileName
198        let fileTags = model.fileTags
199        let fileArchived = fileTags.contains("ARCHIVE")
200
201        // Archived and commented trees are skipped whole, as `org-agenda-skip` does.
202        var skipped: [Bool] = []
203        var headings: [Heading] = []
204        var options = EditingOptions.org
205        options.listAllowAlphabetical = settings.listAllowAlphabetical
206        let buffer = EmacsBuffer(text, point: 0, settings: settings, options: options)
207        for (index, info) in model.headings.enumerated() {
208            let own = info.localTags.contains("ARCHIVE") || Self.isCommented(info.title)
209            skipped.append(fileArchived || own || (info.parent.map { skipped[$0] } ?? false))
210            let line = ns.substring(with: NSRange(location: info.headingRange.lowerBound, length: info.headingRange.count))
211            let head = line.replacingOccurrences(of: "^\\*+[ \\t]+", with: "", options: .regularExpression)
212                .trimmingCharacters(in: .newlines)
213
214            var itags: [String] = fileTags
215            for ancestor in model.ancestors(of: index) { itags += model.headings[ancestor].localTags }
216            itags = itags.filter(settings.inheritsTag)
217            var tags: [(String, Bool)] = itags.map { ($0, true) } + info.localTags.map { ($0, false) }
218            // `delete-dups` over the reversed list: the most local copy of a tag stays.
219            var seen: Set<String> = []
220            tags = tags.reversed().filter { seen.insert($0.0).inserted }.reversed()
221
222            var category = fileCategory
223            for layer in ([index] + model.ancestors(of: index).reversed()) {
224                if let value = model.headings[layer].properties.last(where: { $0.key.uppercased() == "CATEGORY" && !$0.additive })?.value {
225                    category = value
226                    break
227                }
228            }
229
230            var scheduled: (String, Int)?
231            var deadline: (String, Int)?
232            var planningValues: [String: String] = [:]
233            let afterHeading = info.headingRange.upperBound
234            if let planning = planningLines.first(where: { $0.lowerBound == afterHeading }) {
235                let planningText = ns.substring(with: NSRange(location: planning.lowerBound, length: planning.count))
236                let regex = Self.planningRegex
237                let pns = planningText as NSString
238                for m in regex.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
239                    let value = (pns.substring(with: m.range(at: 2)), planning.lowerBound + m.range(at: 2).location - 1)
240                    if pns.substring(with: m.range(at: 1)) == "SCHEDULED" { scheduled = scheduled ?? value } else { deadline = deadline ?? value }
241                }
242                let any = Self.planningAnyRegex
243                for m in any.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
244                    let key = pns.substring(with: m.range(at: 1))
245                    if planningValues[key] == nil { planningValues[key] = pns.substring(with: m.range(at: 2)) }
246                }
247            }
248            var properties: [String: String] = [:]
249            for property in info.properties {
250                let key = property.key.uppercased()
251                if property.additive, let value = properties[key] {
252                    properties[key] = value + " " + property.value
253                } else {
254                    properties[key] = property.value
255                }
256            }
257            let ownStamps = sectionStamps(index)
258            // Matches and `org-is-habit-p` read properties with `org-use-property-inheritance`:
259            // inherited values first, the entry's own over them.
260            var matchProperties = properties
261            if model.settings.propertyInheritance != .none {
262                let keys = Set((model.fileProperties + model.ancestors(of: index).flatMap { model.headings[$0].properties }).map { $0.key.uppercased() })
263                for key in keys where matchProperties[key] == nil && model.inherits(key) {
264                    if let value = model.property(key, of: index)?.value { matchProperties[key] = value }
265                }
266            }
267            let isHabit = matchProperties["STYLE"]?.trimmingCharacters(in: .whitespaces) == "habit"
268            var habit: Habit?
269            if isHabit, let scheduled {
270                let end = index + 1 < model.headings.count ? model.headings[index + 1].headingRange.lowerBound : ns.length
271                let entry = ns.substring(with: NSRange(location: info.headingRange.lowerBound, length: end - info.headingRange.lowerBound))
272                habit = Habit.parse(entry: entry, scheduled: scheduled.0, doneKeywords: settings.todoSequences.flatMap { $0.done.map(\.name) })
273            }
274            var blockedByCheckboxes = false
275            var blockedByHierarchy = false
276            if checksBlocking, info.todo != nil, !info.isDone, buffer.localProperty("NOBLOCKING", heading: info.headingRange.lowerBound).map({ $0 == "nil" }) ?? true {
277                buffer.point = info.headingRange.lowerBound
278                blockedByCheckboxes = buffer.hasOpenCheckbox()
279                blockedByHierarchy = buffer.hierarchyBlocker() != nil
280            }
281            headings.append(Heading(
282                start: info.headingRange.lowerBound, level: info.level, skipped: skipped[index],
283                title: info.title.trimmingCharacters(in: .whitespaces), priority: info.priority, localTags: info.localTags,
284                properties: properties, matchProperties: matchProperties, planning: planningValues,
285                firstActive: ownStamps.first { $0.hasPrefix("<") }, firstInactive: ownStamps.first { $0.hasPrefix("[") },
286                line: line.trimmingCharacters(in: .newlines), head: head, todo: info.todo, isDone: info.isDone,
287                tags: tags, category: category, scheduled: scheduled, deadline: deadline, isHabit: isHabit, habit: habit,
288                blockedByCheckboxes: blockedByCheckboxes, blockedByHierarchy: blockedByHierarchy
289            ))
290        }
291        self.headings = headings
292
293        let starts = model.headings.map(\.headingRange.lowerBound)
294        func heading(at offset: Int) -> Int? {
295            var low = 0
296            var high = starts.count
297            while low < high {
298                let mid = (low + high) / 2
299                if starts[mid] <= offset { low = mid + 1 } else { high = mid }
300            }
301            return low == 0 ? nil : low - 1
302        }
303        func restOfLine(_ offset: Int) -> String {
304            let line = ns.lineRange(for: NSRange(location: offset, length: 0))
305            return ns.substring(with: NSRange(location: offset, length: NSMaxRange(line) - offset)).trimmingCharacters(in: .newlines)
306        }
307
308        // Timestamps: those the parser sees as timestamp objects, and dates in property lines.
309        var stampOffsets = timestampNodes
310        let datePattern = try! NSRegularExpression(pattern: "<[0-9]{4}-[0-9]{2}-[0-9]{2}")
311        for line in propertyLines {
312            for m in datePattern.matches(in: text, range: NSRange(location: line.lowerBound, length: line.count)) {
313                stampOffsets.append(m.range.location)
314            }
315        }
316        var stamps: [Stamp] = []
317        for offset in stampOffsets.sorted() {
318            guard let owner = heading(at: offset), !skipped[owner] else { continue }
319            let rest = restOfLine(offset)
320            guard rest.range(of: "^<([0-9]{4}-[0-9]{2}-[0-9]{2}|%%\\()", options: .regularExpression) != nil else { continue }
321            if Self.inDateRange(offset, ns) { continue }
322            stamps.append(Stamp(offset: offset, heading: owner, rest: rest))
323        }
324        self.stamps = stamps
325
326        // Sexp lines: org searches the raw text for `%%(` at the start of a line. Before the
327        // first heading org's agenda signals an error; they're left out.
328        var sexps: [SexpLine] = []
329        let sexpLine = try! NSRegularExpression(pattern: "^&?%%\\(", options: .anchorsMatchLines)
330        for m in sexpLine.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
331            guard let owner = heading(at: m.range.location), !skipped[owner] else { continue }
332            let open = NSMaxRange(m.range) - 1
333            let tail = ns.substring(with: NSRange(location: open, length: min(ns.length - open, 4096)))
334            guard let (sexp, length) = try? LispReader.readFirst(tail) else { continue }
335            let afterSexp = String(tail.dropFirst(length))
336            let lineRest = afterSexp.prefix { $0 != "\n" && $0 != "\r" }
337            let entry = lineRest.trimmingCharacters(in: CharacterSet(charactersIn: " \t"))
338            sexps.append(SexpLine(offset: m.range.location, heading: owner, sexp: sexp, entry: entry))
339        }
340        self.sexps = sexps
341
342        // Ranges: org scans the raw text, skipping comment lines, skipped trees and src blocks.
343        var blocks: [Block] = []
344        let range = Self.activeRangeRegex
345        for m in range.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
346            let point = NSMaxRange(m.range)
347            let line = ns.substring(with: ns.lineRange(for: NSRange(location: point, length: 0)))
348            if line.range(of: "^\\s*#( |$|\\n)", options: .regularExpression) != nil { continue }
349            guard let owner = heading(at: max(0, point - 1)), !skipped[owner] else { continue }
350            if srcBodies.contains(where: { $0.contains(point) }) { continue }
351            blocks.append(Block(start: ns.substring(with: m.range(at: 1)), end: ns.substring(with: m.range(at: 2)), marker: point, heading: owner))
352        }
353        self.blocks = blocks
354
355        // Log lines: org searches the raw text, then the heading above each match.
356        let keywordPattern = keywords.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|")
357        let logLine = try! NSRegularExpression(pattern: "(\\bCLOSED:|\\bCLOCK:|- +State \"(\(keywordPattern.isEmpty ? "(?!)" : keywordPattern))\".*?) *\\[([0-9]{4}-[0-9]{2}-[0-9]{2})")
358        let inactive = Self.inactiveRegex
359        let clockEnd = try! NSRegularExpression(pattern: "([0-9]{1,2}:[0-9]{2})\\].*?([0-9]{1,2}:[0-9]{2})")
360        let stateNote = try! NSRegularExpression(pattern: ".*\\\\\\n[ \\t]*([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines)
361        let clockNote = try! NSRegularExpression(pattern: ".*\\n[ \\t]*-[ \\t]+([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines)
362        var progress: [Progress] = []
363        for m in logLine.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
364            guard let owner = heading(at: m.range.location), !skipped[owner] else { continue }
365            let keyword = ns.substring(with: m.range(at: 1))
366            let kind: Progress.Kind = keyword == "CLOSED:" ? .closed : keyword == "CLOCK:" ? .clock : .state
367            var timestamp = restOfLine(m.range.location)
368            var clocked = "-"
369            let tns = timestamp as NSString
370            if let ts = inactive.firstMatch(in: timestamp, range: NSRange(location: 0, length: tns.length)) {
371                let rest = tns.substring(from: NSMaxRange(ts.range))
372                timestamp = tns.substring(to: NSMaxRange(ts.range))
373                let rns = rest as NSString
374                if kind == .clock, let end = clockEnd.firstMatch(in: rest, range: NSRange(location: 0, length: rns.length)) {
375                    timestamp = String(timestamp.dropLast()) + "-" + rns.substring(with: end.range(at: 1)) + "]"
376                    clocked = rns.substring(with: end.range(at: 2))
377                }
378            }
379            // The note: after a state line ending in `\\`, or a list item under a clock line.
380            var note: String?
381            let after = NSMaxRange(m.range)
382            let notePattern: NSRegularExpression? = switch kind {
383            case .state: stateNote
384            case .clock: clockNote
385            case .closed: nil
386            }
387            if let notePattern, let n = notePattern.firstMatch(in: text, options: .anchored, range: NSRange(location: after, length: ns.length - after)) {
388                note = ns.substring(with: n.range(at: 1))
389            }
390            progress.append(Progress(
391                kind: kind, offset: m.range.location, heading: owner, date: ns.substring(with: m.range(at: 3)), timestamp: timestamp,
392                clocked: clocked, state: m.range(at: 2).location == NSNotFound ? nil : ns.substring(with: m.range(at: 2)), note: note
393            ))
394        }
395        self.progress = progress
396    }
397
398    /// `org-ts--internal-regexp`.
399    static let tsInternal = "[0-9]{4}-[0-9]{2}-[0-9]{2}(?: .*?)?"
400
401    /// `org-element` reads a title starting with `COMMENT` as a commented heading.
402    static func isCommented(_ title: String) -> Bool {
403        title == "COMMENT" || title.hasPrefix("COMMENT ")
404    }
405
406    /// `org-at-date-range-p` with point just after the date that starts at `offset`.
407    static func inDateRange(_ offset: Int, _ ns: NSString) -> Bool {
408        let point = offset + 11
409        let line = ns.lineRange(for: NSRange(location: offset, length: 0))
410        let regex = Self.dateRangeRegex
411        for m in regex.matches(in: ns as String, range: line) {
412            if m.range.location > point { break }
413            if NSMaxRange(m.range) >= point { return true }
414        }
415        return false
416    }
417}