Sources/OrgCore/Agenda/AgendaSource.swift

416 lines · 22225 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            var tags: [(String, Bool)] = itags.map { ($0, true) } + info.localTags.map { ($0, false) }
217            // `delete-dups` over the reversed list: the most local copy of a tag stays.
218            var seen: Set<String> = []
219            tags = tags.reversed().filter { seen.insert($0.0).inserted }.reversed()
220
221            var category = fileCategory
222            for layer in ([index] + model.ancestors(of: index).reversed()) {
223                if let value = model.headings[layer].properties.last(where: { $0.key.uppercased() == "CATEGORY" && !$0.additive })?.value {
224                    category = value
225                    break
226                }
227            }
228
229            var scheduled: (String, Int)?
230            var deadline: (String, Int)?
231            var planningValues: [String: String] = [:]
232            let afterHeading = info.headingRange.upperBound
233            if let planning = planningLines.first(where: { $0.lowerBound == afterHeading }) {
234                let planningText = ns.substring(with: NSRange(location: planning.lowerBound, length: planning.count))
235                let regex = Self.planningRegex
236                let pns = planningText as NSString
237                for m in regex.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
238                    let value = (pns.substring(with: m.range(at: 2)), planning.lowerBound + m.range(at: 2).location - 1)
239                    if pns.substring(with: m.range(at: 1)) == "SCHEDULED" { scheduled = scheduled ?? value } else { deadline = deadline ?? value }
240                }
241                let any = Self.planningAnyRegex
242                for m in any.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
243                    let key = pns.substring(with: m.range(at: 1))
244                    if planningValues[key] == nil { planningValues[key] = pns.substring(with: m.range(at: 2)) }
245                }
246            }
247            var properties: [String: String] = [:]
248            for property in info.properties {
249                let key = property.key.uppercased()
250                if property.additive, let value = properties[key] {
251                    properties[key] = value + " " + property.value
252                } else {
253                    properties[key] = property.value
254                }
255            }
256            let ownStamps = sectionStamps(index)
257            // Matches and `org-is-habit-p` read properties with `org-use-property-inheritance`:
258            // inherited values first, the entry's own over them.
259            var matchProperties = properties
260            if model.settings.propertyInheritance != .none {
261                let keys = Set((model.fileProperties + model.ancestors(of: index).flatMap { model.headings[$0].properties }).map { $0.key.uppercased() })
262                for key in keys where matchProperties[key] == nil && model.inherits(key) {
263                    if let value = model.property(key, of: index)?.value { matchProperties[key] = value }
264                }
265            }
266            let isHabit = matchProperties["STYLE"]?.trimmingCharacters(in: .whitespaces) == "habit"
267            var habit: Habit?
268            if isHabit, let scheduled {
269                let end = index + 1 < model.headings.count ? model.headings[index + 1].headingRange.lowerBound : ns.length
270                let entry = ns.substring(with: NSRange(location: info.headingRange.lowerBound, length: end - info.headingRange.lowerBound))
271                habit = Habit.parse(entry: entry, scheduled: scheduled.0, doneKeywords: settings.todoSequences.flatMap { $0.done.map(\.name) })
272            }
273            var blockedByCheckboxes = false
274            var blockedByHierarchy = false
275            if checksBlocking, info.todo != nil, !info.isDone, buffer.localProperty("NOBLOCKING", heading: info.headingRange.lowerBound).map({ $0 == "nil" }) ?? true {
276                buffer.point = info.headingRange.lowerBound
277                blockedByCheckboxes = buffer.hasOpenCheckbox()
278                blockedByHierarchy = buffer.hierarchyBlocker() != nil
279            }
280            headings.append(Heading(
281                start: info.headingRange.lowerBound, level: info.level, skipped: skipped[index],
282                title: info.title.trimmingCharacters(in: .whitespaces), priority: info.priority, localTags: info.localTags,
283                properties: properties, matchProperties: matchProperties, planning: planningValues,
284                firstActive: ownStamps.first { $0.hasPrefix("<") }, firstInactive: ownStamps.first { $0.hasPrefix("[") },
285                line: line.trimmingCharacters(in: .newlines), head: head, todo: info.todo, isDone: info.isDone,
286                tags: tags, category: category, scheduled: scheduled, deadline: deadline, isHabit: isHabit, habit: habit,
287                blockedByCheckboxes: blockedByCheckboxes, blockedByHierarchy: blockedByHierarchy
288            ))
289        }
290        self.headings = headings
291
292        let starts = model.headings.map(\.headingRange.lowerBound)
293        func heading(at offset: Int) -> Int? {
294            var low = 0
295            var high = starts.count
296            while low < high {
297                let mid = (low + high) / 2
298                if starts[mid] <= offset { low = mid + 1 } else { high = mid }
299            }
300            return low == 0 ? nil : low - 1
301        }
302        func restOfLine(_ offset: Int) -> String {
303            let line = ns.lineRange(for: NSRange(location: offset, length: 0))
304            return ns.substring(with: NSRange(location: offset, length: NSMaxRange(line) - offset)).trimmingCharacters(in: .newlines)
305        }
306
307        // Timestamps: those the parser sees as timestamp objects, and dates in property lines.
308        var stampOffsets = timestampNodes
309        let datePattern = try! NSRegularExpression(pattern: "<[0-9]{4}-[0-9]{2}-[0-9]{2}")
310        for line in propertyLines {
311            for m in datePattern.matches(in: text, range: NSRange(location: line.lowerBound, length: line.count)) {
312                stampOffsets.append(m.range.location)
313            }
314        }
315        var stamps: [Stamp] = []
316        for offset in stampOffsets.sorted() {
317            guard let owner = heading(at: offset), !skipped[owner] else { continue }
318            let rest = restOfLine(offset)
319            guard rest.range(of: "^<([0-9]{4}-[0-9]{2}-[0-9]{2}|%%\\()", options: .regularExpression) != nil else { continue }
320            if Self.inDateRange(offset, ns) { continue }
321            stamps.append(Stamp(offset: offset, heading: owner, rest: rest))
322        }
323        self.stamps = stamps
324
325        // Sexp lines: org searches the raw text for `%%(` at the start of a line. Before the
326        // first heading org's agenda signals an error; they're left out.
327        var sexps: [SexpLine] = []
328        let sexpLine = try! NSRegularExpression(pattern: "^&?%%\\(", options: .anchorsMatchLines)
329        for m in sexpLine.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
330            guard let owner = heading(at: m.range.location), !skipped[owner] else { continue }
331            let open = NSMaxRange(m.range) - 1
332            let tail = ns.substring(with: NSRange(location: open, length: min(ns.length - open, 4096)))
333            guard let (sexp, length) = try? LispReader.readFirst(tail) else { continue }
334            let afterSexp = String(tail.dropFirst(length))
335            let lineRest = afterSexp.prefix { $0 != "\n" && $0 != "\r" }
336            let entry = lineRest.trimmingCharacters(in: CharacterSet(charactersIn: " \t"))
337            sexps.append(SexpLine(offset: m.range.location, heading: owner, sexp: sexp, entry: entry))
338        }
339        self.sexps = sexps
340
341        // Ranges: org scans the raw text, skipping comment lines, skipped trees and src blocks.
342        var blocks: [Block] = []
343        let range = Self.activeRangeRegex
344        for m in range.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
345            let point = NSMaxRange(m.range)
346            let line = ns.substring(with: ns.lineRange(for: NSRange(location: point, length: 0)))
347            if line.range(of: "^\\s*#( |$|\\n)", options: .regularExpression) != nil { continue }
348            guard let owner = heading(at: max(0, point - 1)), !skipped[owner] else { continue }
349            if srcBodies.contains(where: { $0.contains(point) }) { continue }
350            blocks.append(Block(start: ns.substring(with: m.range(at: 1)), end: ns.substring(with: m.range(at: 2)), marker: point, heading: owner))
351        }
352        self.blocks = blocks
353
354        // Log lines: org searches the raw text, then the heading above each match.
355        let keywordPattern = keywords.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|")
356        let logLine = try! NSRegularExpression(pattern: "(\\bCLOSED:|\\bCLOCK:|- +State \"(\(keywordPattern.isEmpty ? "(?!)" : keywordPattern))\".*?) *\\[([0-9]{4}-[0-9]{2}-[0-9]{2})")
357        let inactive = Self.inactiveRegex
358        let clockEnd = try! NSRegularExpression(pattern: "([0-9]{1,2}:[0-9]{2})\\].*?([0-9]{1,2}:[0-9]{2})")
359        let stateNote = try! NSRegularExpression(pattern: ".*\\\\\\n[ \\t]*([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines)
360        let clockNote = try! NSRegularExpression(pattern: ".*\\n[ \\t]*-[ \\t]+([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines)
361        var progress: [Progress] = []
362        for m in logLine.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
363            guard let owner = heading(at: m.range.location), !skipped[owner] else { continue }
364            let keyword = ns.substring(with: m.range(at: 1))
365            let kind: Progress.Kind = keyword == "CLOSED:" ? .closed : keyword == "CLOCK:" ? .clock : .state
366            var timestamp = restOfLine(m.range.location)
367            var clocked = "-"
368            let tns = timestamp as NSString
369            if let ts = inactive.firstMatch(in: timestamp, range: NSRange(location: 0, length: tns.length)) {
370                let rest = tns.substring(from: NSMaxRange(ts.range))
371                timestamp = tns.substring(to: NSMaxRange(ts.range))
372                let rns = rest as NSString
373                if kind == .clock, let end = clockEnd.firstMatch(in: rest, range: NSRange(location: 0, length: rns.length)) {
374                    timestamp = String(timestamp.dropLast()) + "-" + rns.substring(with: end.range(at: 1)) + "]"
375                    clocked = rns.substring(with: end.range(at: 2))
376                }
377            }
378            // The note: after a state line ending in `\\`, or a list item under a clock line.
379            var note: String?
380            let after = NSMaxRange(m.range)
381            let notePattern: NSRegularExpression? = switch kind {
382            case .state: stateNote
383            case .clock: clockNote
384            case .closed: nil
385            }
386            if let notePattern, let n = notePattern.firstMatch(in: text, options: .anchored, range: NSRange(location: after, length: ns.length - after)) {
387                note = ns.substring(with: n.range(at: 1))
388            }
389            progress.append(Progress(
390                kind: kind, offset: m.range.location, heading: owner, date: ns.substring(with: m.range(at: 3)), timestamp: timestamp,
391                clocked: clocked, state: m.range(at: 2).location == NSNotFound ? nil : ns.substring(with: m.range(at: 2)), note: note
392            ))
393        }
394        self.progress = progress
395    }
396
397    /// `org-ts--internal-regexp`.
398    static let tsInternal = "[0-9]{4}-[0-9]{2}-[0-9]{2}(?: .*?)?"
399
400    /// `org-element` reads a title starting with `COMMENT` as a commented heading.
401    static func isCommented(_ title: String) -> Bool {
402        title == "COMMENT" || title.hasPrefix("COMMENT ")
403    }
404
405    /// `org-at-date-range-p` with point just after the date that starts at `offset`.
406    static func inDateRange(_ offset: Int, _ ns: NSString) -> Bool {
407        let point = offset + 11
408        let line = ns.lineRange(for: NSRange(location: offset, length: 0))
409        let regex = Self.dateRangeRegex
410        for m in regex.matches(in: ns as String, range: line) {
411            if m.range.location > point { break }
412            if NSMaxRange(m.range) >= point { return true }
413        }
414        return false
415    }
416}