Sources/OrgCore/Agenda/AgendaSource.swift

8d1ab6bd94908b1294919072454046c1878373e9
orgstar/Sources/OrgCore/Agenda/AgendaSource.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form