Sources/OrgCore/Parser/Settings.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgCore/Parser/Settings.swift

194 lines · 8885 bytes

14 symbols in this file
  1public struct TodoKeyword: Sendable, Hashable {
  2    public var name: String
  3    public var fastKey: Character?
  4    /// Logging flag when entering the state (`!` or `@`), from `NAME(k!/@)`.
  5    public var logOnEnter: String?
  6    /// Logging flag when leaving the state.
  7    public var logOnLeave: String?
  8
  9    public init(name: String, fastKey: Character? = nil, logOnEnter: String? = nil, logOnLeave: String? = nil) {
 10        self.name = name
 11        self.fastKey = fastKey
 12        self.logOnEnter = logOnEnter
 13        self.logOnLeave = logOnLeave
 14    }
 15}
 16
 17public struct TodoSequence: Sendable, Equatable {
 18    public enum Kind: Sendable, Equatable { case sequence, type }
 19
 20    public var kind: Kind
 21    public var active: [TodoKeyword]
 22    public var done: [TodoKeyword]
 23
 24    public init(kind: Kind, active: [TodoKeyword], done: [TodoKeyword]) {
 25        self.kind = kind
 26        self.active = active
 27        self.done = done
 28    }
 29}
 30
 31public struct Priorities: Sendable, Equatable {
 32    public var highest: String
 33    public var lowest: String
 34    public var `default`: String
 35
 36    public init(highest: String, lowest: String, default: String) {
 37        self.highest = highest
 38        self.lowest = lowest
 39        self.default = `default`
 40    }
 41}
 42
 43public struct OrgSettings: Sendable, Equatable {
 44    public var todoSequences: [TodoSequence]
 45    public var priorities: Priorities
 46    /// `<<<radio target>>>` texts in the file, longest first: their words elsewhere are links.
 47    public var radioTargets: [String] = []
 48    /// `org-list-allow-alphabetical`: `a.` and `A)` are bullets.
 49    public var listAllowAlphabetical = false
 50    /// `org-use-property-inheritance`.
 51    public var propertyInheritance: SemanticSettings.PropertyInheritance = .none
 52    /// `org-deadline-warning-days`.
 53    public var deadlineWarningDays = 14
 54    /// `org-use-tag-inheritance` and `org-tags-exclude-from-inheritance`.
 55    public var tagInheritance: SemanticSettings.TagInheritance = .all
 56    public var tagsExcludedFromInheritance: Set<String> = []
 57    /// `org-attach-id-dir` and `org-attach-use-inheritance` (nil for `selective`), for export.
 58    public var attachIDDir = "data/"
 59    public var attachUseInheritance: Bool?
 60    /// `org-cite-global-bibliography`: files every document's citations are read from.
 61    public var citeGlobalBibliography: [String] = []
 62
 63    /// `org-remove-uninherited-tags` for one tag.
 64    public func inheritsTag(_ tag: String) -> Bool {
 65        SemanticSettings(tagInheritance: tagInheritance, tagsExcludedFromInheritance: tagsExcludedFromInheritance).inheritsTag(tag)
 66    }
 67    /// Keyword lines from the file's `#+SETUPFILE`s, as `#+KEY: value` lines: they count as
 68    /// the file's own, before them.
 69    public var setupKeywords = ""
 70    /// Words of the `#+STARTUP` keyword lines outside blocks, setup files' first.
 71    public var startup: [String] = []
 72
 73    public init(todoSequences: [TodoSequence], priorities: Priorities, radioTargets: [String] = []) {
 74        self.todoSequences = todoSequences
 75        self.priorities = priorities
 76        self.radioTargets = radioTargets
 77    }
 78
 79    public static let `default` = OrgSettings(
 80        todoSequences: [TodoSequence(kind: .sequence, active: [TodoKeyword(name: "TODO")], done: [TodoKeyword(name: "DONE")])],
 81        priorities: Priorities(highest: "A", lowest: "C", default: "B")
 82    )
 83
 84    public var todoKeywordNames: Set<String> {
 85        Set(todoSequences.flatMap { ($0.active + $0.done).map(\.name) })
 86    }
 87
 88    /// These settings with TODO keywords from `#+TODO:` syntax (`TODO NEXT | DONE`), one
 89    /// sequence per line; nil when there are no keywords.
 90    public func withTodoKeywords(_ lines: String) -> OrgSettings? {
 91        let sequences = lines.split(separator: "\n").compactMap { SettingsScanner.todoSequence($0, kind: .sequence) }
 92        guard !sequences.isEmpty else { return nil }
 93        var copy = self
 94        copy.todoSequences = sequences
 95        return copy
 96    }
 97
 98    public func isDone(_ name: String) -> Bool {
 99        todoSequences.contains { $0.done.contains { $0.name == name } }
100    }
101}
102
103enum SettingsScanner {
104    /// Reads `#+TODO`, `#+SEQ_TODO`, `#+TYP_TODO`, `#+PRIORITIES` and `#+STARTUP` outside blocks. Any TODO
105    /// line replaces the default sequences; as in org, `TYP_TODO` sequences come first, then
106    /// `TODO`, then `SEQ_TODO`.
107    static func scan(lines: [RawLine], info: [ClassifiedLine], blockEnds: [Int: Int], defaults: OrgSettings) -> OrgSettings {
108        var types: [TodoSequence] = [], todos: [TodoSequence] = [], seqs: [TodoSequence] = []
109        var priorities = defaults.priorities
110        var startup: [String] = []
111        func apply(_ key: String, _ value: Substring) {
112            switch key {
113            case "TODO":
114                if let s = todoSequence(value, kind: .sequence) { todos.append(s) }
115            case "SEQ_TODO":
116                if let s = todoSequence(value, kind: .sequence) { seqs.append(s) }
117            case "TYP_TODO":
118                if let s = todoSequence(value, kind: .type) { types.append(s) }
119            case "STARTUP":
120                startup += value.split(whereSeparator: \.isWhitespace).map(String.init)
121            case "PRIORITIES":
122                let words = value.split(whereSeparator: \.isWhitespace)
123                if words.count == 3 {
124                    priorities = Priorities(highest: String(words[0]), lowest: String(words[1]), default: String(words[2]))
125                }
126            default:
127                break
128            }
129        }
130        for (key, value) in SetupFile.keywords(defaults.setupKeywords) { apply(key, value) }
131        var k = 0
132        while k < lines.count {
133            switch info[k].cls {
134            case .blockBegin, .dynamicBegin:
135                if let end = blockEnds[k] { k = end }
136            case .keyword(let key):
137                apply(key, keywordValue(lines[k].content))
138            default:
139                break
140            }
141            k += 1
142        }
143        let sequences = types + todos + seqs
144        var radio: [String] = []
145        for line in lines where containsBytes(line.content.utf8, UInt8(ascii: "<"), count: 3) {
146            for m in String(line.content).matches(of: /<<<([^<>\n\r \t](?:[^<>\n\r]*[^<>\n\r \t])?)>>>/) where !radio.contains(String(m.1)) {
147                radio.append(String(m.1))
148            }
149        }
150        var settings = OrgSettings(todoSequences: sequences.isEmpty ? defaults.todoSequences : sequences, priorities: priorities,
151                                   radioTargets: radio.sorted { $0.count > $1.count })
152        settings.listAllowAlphabetical = defaults.listAllowAlphabetical
153        settings.propertyInheritance = defaults.propertyInheritance
154        settings.deadlineWarningDays = defaults.deadlineWarningDays
155        settings.tagInheritance = defaults.tagInheritance
156        settings.tagsExcludedFromInheritance = defaults.tagsExcludedFromInheritance
157        settings.attachIDDir = defaults.attachIDDir
158        settings.attachUseInheritance = defaults.attachUseInheritance
159        settings.citeGlobalBibliography = defaults.citeGlobalBibliography
160        settings.setupKeywords = defaults.setupKeywords
161        settings.startup = startup
162        return settings
163    }
164
165    static func keywordValue(_ line: Substring) -> Substring {
166        guard let colon = line.firstIndex(of: ":") else { return "" }
167        return line[line.index(after: colon)...]
168    }
169
170    static func todoSequence(_ value: Substring, kind: TodoSequence.Kind) -> TodoSequence? {
171        let words = value.split(whereSeparator: \.isWhitespace)
172        guard !words.isEmpty else { return nil }
173        if let bar = words.firstIndex(of: "|") {
174            return TodoSequence(kind: kind, active: words[..<bar].map(todoKeyword), done: words[(bar + 1)...].map(todoKeyword))
175        }
176        return TodoSequence(kind: kind, active: words.dropLast().map(todoKeyword), done: [todoKeyword(words.last!)])
177    }
178
179    /// `NAME`, or `NAME(spec)` where spec is an optional fast key followed by `enter/leave`
180    /// logging flags.
181    static func todoKeyword(_ word: Substring) -> TodoKeyword {
182        guard let open = word.firstIndex(of: "("), word.last == ")" else { return TodoKeyword(name: String(word)) }
183        var spec = word[word.index(after: open)..<word.index(before: word.endIndex)]
184        var fastKey: Character?
185        if let first = spec.first, first != "!", first != "@", first != "/" {
186            fastKey = first
187            spec = spec.dropFirst()
188        }
189        let parts = spec.split(separator: "/", omittingEmptySubsequences: false)
190        let enter = parts.first.flatMap { $0.isEmpty ? nil : String($0) }
191        let leave = parts.count > 1 && !parts[1].isEmpty ? String(parts[1]) : nil
192        return TodoKeyword(name: String(word[..<open]), fastKey: fastKey, logOnEnter: enter, logOnLeave: leave)
193    }
194}
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