Sources/OrgApp/UserConfig.swift

3dd5b060e7ddb3d4d7f0fc2e06a7b09a3eb5a546
orgstar/Sources/OrgApp/UserConfig.swift history · blame · raw

242 lines · 14051 bytes

  1import Foundation
  2import OrgCore
  3
  4/// The configuration folder (`$XDG_CONFIG_HOME/orgstar`, else `~/.config/orgstar`) and
  5/// `config.toml` in it: every setting of the Settings window as text, to edit, keep in a
  6/// dotfiles repository and share. The file is the source of truth: Settings writes its changes
  7/// into it, keeping comments and order, and edits to it apply while the app runs.
  8public enum UserConfig {
  9    public static var directory: URL {
 10        let environment = ProcessInfo.processInfo.environment
 11        if let override = environment["ORGSTAR_CONFIG_DIR"] { return URL(fileURLWithPath: override) }
 12        // Development runs keep everything in their data folder.
 13        if let data = environment["ORGSTAR_DATA_DIR"] { return URL(fileURLWithPath: data) }
 14        if let xdg = environment["XDG_CONFIG_HOME"], !xdg.isEmpty {
 15            return URL(fileURLWithPath: xdg).appendingPathComponent("orgstar")
 16        }
 17        return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".config/orgstar")
 18    }
 19
 20    /// A file of the configuration folder; one that exists only where earlier versions kept
 21    /// it (Application Support) is still read from there.
 22    public static func file(_ name: String) -> URL {
 23        let url = directory.appendingPathComponent(name)
 24        let legacy = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
 25            .appendingPathComponent("Orgstar").appendingPathComponent(name)
 26        let manager = FileManager.default
 27        if !manager.fileExists(atPath: url.path), manager.fileExists(atPath: legacy.path) { return legacy }
 28        return url
 29    }
 30
 31    public static var configFile: URL { directory.appendingPathComponent("config.toml") }
 32
 33    /// One setting: where it sits in the file, its user-defaults key, and how values convert.
 34    public struct Setting: Sendable {
 35        public enum Kind: Sendable {
 36            case bool, integer, string
 37            /// A string in the file for each stored value.
 38            case choice([(name: String, stored: String)])
 39            case integerChoice([(name: String, stored: Int)])
 40        }
 41
 42        public let section: String
 43        public let key: String
 44        public let defaultsKey: String
 45        public let kind: Kind
 46        public let fallback: TOML.Value
 47        public let comment: String
 48    }
 49
 50    public static let settings: [Setting] = [
 51        Setting(section: "general", key: "save", defaultsKey: "saveMode", kind: .choice([("automatic", "automatic"), ("explicit", "explicit")]),
 52                fallback: .string("automatic"), comment: "automatic (1 s after typing stops) or explicit (only with ⌘S)"),
 53        Setting(section: "general", key: "keymap", defaultsKey: "keymap", kind: .choice([("emacs", "emacs"), ("mac", "mac"), ("doom", "doom")]),
 54                fallback: .string("emacs"), comment: "emacs, mac or doom; your own bindings go in keymap.toml"),
 55        Setting(section: "general", key: "option-as-meta", defaultsKey: "optionAsMeta",
 56                kind: .integerChoice([("left", 1), ("right", 2), ("both", 3), ("none", 0)]), fallback: .string("left"), comment: "left, right, both or none"),
 57        Setting(section: "editor", key: "tags-column", defaultsKey: "tagsColumn", kind: .integer, fallback: .integer(-77),
 58                comment: "org-tags-column: negative aligns tags to end there, 0 puts one space before them"),
 59        Setting(section: "editor", key: "insert-heading-respect-content", defaultsKey: "headingAfterSubtree", kind: .bool, fallback: .bool(true),
 60                comment: "M-RET adds the new heading after the subtree"),
 61        Setting(section: "editor", key: "meta-return-may-split-line", defaultsKey: "splitLine", kind: .bool, fallback: .bool(false),
 62                comment: "M-RET splits the line at the caret"),
 63        Setting(section: "editor", key: "list-allow-alphabetical", defaultsKey: "alphabeticalLists", kind: .bool, fallback: .bool(true),
 64                comment: "lists can use a. b. c."),
 65        Setting(section: "editor", key: "fill-column", defaultsKey: "fillColumn", kind: .integer, fallback: .integer(80), comment: "M-q fills to this column"),
 66        Setting(section: "editor", key: "hide-emphasis-markers", defaultsKey: "hiddenMarkers", kind: .bool, fallback: .bool(true),
 67                comment: "org-hide-emphasis-markers: hide *bold* and =code= markers when markup is hidden"),
 68        Setting(section: "editor", key: "pretty-entities", defaultsKey: "prettyEntities", kind: .bool, fallback: .bool(true),
 69                comment: "org-pretty-entities: \\alpha shows as α and x_{1} is lowered when markup is hidden"),
 70        Setting(section: "editor", key: "todo-keywords", defaultsKey: "todoKeywords", kind: .string, fallback: .string("TODO PROJ LOOP STRT WAIT HOLD IDEA | DONE KILL"),
 71                comment: "for files without #+TODO, in #+TODO syntax; read at launch"),
 72        Setting(section: "editor", key: "show-markup", defaultsKey: "showMarkup", kind: .bool, fallback: .bool(false),
 73                comment: "show link brackets and emphasis markers (View ▸ Show Markup)"),
 74        Setting(section: "editor", key: "line-numbers", defaultsKey: "showLineNumbers", kind: .bool, fallback: .bool(true),
 75                comment: "View ▸ Show Line Numbers"),
 76        Setting(section: "agenda", key: "span", defaultsKey: "agendaSpan", kind: .integer, fallback: .integer(10), comment: "days shown"),
 77        Setting(section: "agenda", key: "start-offset", defaultsKey: "agendaStartOffset", kind: .integer, fallback: .integer(-3),
 78                comment: "first day, relative to today"),
 79        Setting(section: "agenda", key: "include-subfolders", defaultsKey: "agendaSubfolders", kind: .bool, fallback: .bool(false),
 80                comment: "read org files in subfolders too"),
 81        Setting(section: "agenda", key: "reminders", defaultsKey: "reminders", kind: .bool, fallback: .bool(true),
 82                comment: "notify before timed entries"),
 83        Setting(section: "agenda", key: "reminder-lead", defaultsKey: "reminderLead", kind: .integer, fallback: .integer(12),
 84                comment: "minutes before; APPT_WARNTIME overrides"),
 85        Setting(section: "capture", key: "global-hotkey", defaultsKey: "globalCapture", kind: .bool, fallback: .bool(true),
 86                comment: "⌃⌥Space opens Capture from any app; templates go in capture.toml"),
 87    ]
 88
 89    // MARK: - Values
 90
 91    /// The file value for what `defaults` holds, or the fallback.
 92    public static func value(_ setting: Setting, in defaults: UserDefaults) -> TOML.Value {
 93        guard defaults.object(forKey: setting.defaultsKey) != nil else { return setting.fallback }
 94        switch setting.kind {
 95        case .bool: return .bool(defaults.bool(forKey: setting.defaultsKey))
 96        case .integer: return .integer(defaults.integer(forKey: setting.defaultsKey))
 97        case .string: return .string(defaults.string(forKey: setting.defaultsKey) ?? "")
 98        case .choice(let choices):
 99            let stored = defaults.string(forKey: setting.defaultsKey)
100            return choices.first { $0.stored == stored }.map { .string($0.name) } ?? setting.fallback
101        case .integerChoice(let choices):
102            let stored = defaults.integer(forKey: setting.defaultsKey)
103            return choices.first { $0.stored == stored }.map { .string($0.name) } ?? setting.fallback
104        }
105    }
106
107    /// Stores a file value; a value of the wrong kind is a problem.
108    static func store(_ value: TOML.Value, _ setting: Setting, in defaults: UserDefaults) -> String? {
109        let key = setting.defaultsKey
110        switch (setting.kind, value) {
111        case (.bool, .bool(let b)): defaults.set(b, forKey: key)
112        case (.integer, .integer(let i)): defaults.set(i, forKey: key)
113        case (.string, .string(let s)): defaults.set(s, forKey: key)
114        case (.choice(let choices), .string(let s)):
115            guard let choice = choices.first(where: { $0.name == s }) else {
116                return "\(setting.key) must be one of \(choices.map(\.name).joined(separator: ", "))"
117            }
118            defaults.set(choice.stored, forKey: key)
119        case (.integerChoice(let choices), .string(let s)):
120            guard let choice = choices.first(where: { $0.name == s }) else {
121                return "\(setting.key) must be one of \(choices.map(\.name).joined(separator: ", "))"
122            }
123            defaults.set(choice.stored, forKey: key)
124        default:
125            return "\(setting.section).\(setting.key) has the wrong kind of value"
126        }
127        return nil
128    }
129
130    /// Applies a file to `defaults`; settings it leaves out go back to their defaults.
131    /// Returns problems.
132    @discardableResult
133    public static func apply(_ text: String, to defaults: UserDefaults) -> [String] {
134        let tables: [TOML.Table]
135        do { tables = try TOML.parse(text) } catch { return ["config.toml: \(error)"] }
136        var problems: [String] = []
137        let present = Set(tables.flatMap { table in table.values.keys.map { table.name + "." + $0 } })
138        for setting in settings where !present.contains(setting.section + "." + setting.key) {
139            if defaults.object(forKey: setting.defaultsKey) != nil { defaults.removeObject(forKey: setting.defaultsKey) }
140        }
141        for table in tables {
142            for (key, value) in table.values.sorted(by: { $0.key < $1.key }) {
143                guard let setting = settings.first(where: { $0.section == table.name && $0.key == key }) else {
144                    problems.append("config.toml line \(table.line): unknown setting \(table.name.isEmpty ? "" : table.name + ".")\(key)")
145                    continue
146                }
147                if let current = currentValue(setting, in: defaults), current == value { continue }
148                if let problem = store(value, setting, in: defaults) { problems.append("config.toml: \(problem)") }
149            }
150        }
151        return problems
152    }
153
154    private static func currentValue(_ setting: Setting, in defaults: UserDefaults) -> TOML.Value? {
155        defaults.object(forKey: setting.defaultsKey) == nil ? nil : value(setting, in: defaults)
156    }
157
158    /// The values a file sets, by `section.key`.
159    static func values(in text: String) -> [String: TOML.Value] {
160        guard let tables = try? TOML.parse(text) else { return [:] }
161        var result: [String: TOML.Value] = [:]
162        for table in tables { for (key, value) in table.values { result[table.name + "." + key] = value } }
163        return result
164    }
165
166    // MARK: - Text
167
168    static func format(_ value: TOML.Value) -> String {
169        switch value {
170        case .bool(let b): b ? "true" : "false"
171        case .integer(let i): String(i)
172        case .string(let s): "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
173        }
174    }
175
176    /// A commented file with every setting at its current value.
177    public static func template(from defaults: UserDefaults) -> String {
178        var out = """
179            # Orgstar settings. The Settings window writes its changes here, and edits made here
180            # apply while Orgstar runs. Keys go in keymap.toml, capture templates in capture.toml
181            # and saved agenda views in views.toml, all in this folder.
182
183            """
184        var section = ""
185        for setting in settings {
186            if setting.section != section {
187                section = setting.section
188                out += "\n[\(section)]\n"
189            }
190            out += "\(setting.key) = \(format(value(setting, in: defaults)))  # \(setting.comment)\n"
191        }
192        return out
193    }
194
195    /// `text` with `section.key` set to `value`: the line's value is replaced (its comment
196    /// stays), or a line is added at the end of the section, or the section at the end.
197    public static func setting(_ text: String, section: String, key: String, to value: TOML.Value) -> String {
198        var lines = text.components(separatedBy: "\n")
199        var current = ""
200        var lastInSection: Int?
201        for (index, line) in lines.enumerated() {
202            let trimmed = line.trimmingCharacters(in: .whitespaces)
203            if trimmed.hasPrefix("[") && !trimmed.hasPrefix("[[") {
204                current = String(trimmed.dropFirst().prefix { $0 != "]" }).trimmingCharacters(in: .whitespaces)
205                if current == section { lastInSection = index }
206                continue
207            }
208            guard current == section else { continue }
209            if !trimmed.isEmpty { lastInSection = index }
210            guard let equals = line.firstIndex(of: "="),
211                  line[..<equals].trimmingCharacters(in: .whitespaces) == key else { continue }
212            let comment = commentStart(line, after: equals).map { "  " + line[$0...] } ?? ""
213            lines[index] = line[..<equals] + "= " + format(value) + comment
214            return lines.joined(separator: "\n")
215        }
216        if let lastInSection {
217            lines.insert("\(key) = \(format(value))", at: lastInSection + 1)
218        } else {
219            if lines.last == "" { lines.removeLast() }
220            lines += ["", "[\(section)]", "\(key) = \(format(value))", ""]
221        }
222        return lines.joined(separator: "\n")
223    }
224
225    /// Where a `#` comment starts after the value, outside quotes.
226    private static func commentStart(_ line: String, after equals: String.Index) -> String.Index? {
227        var quote: Character?
228        var index = line.index(after: equals)
229        while index < line.endIndex {
230            let c = line[index]
231            if let q = quote {
232                if c == "\\" && q == "\"" { index = line.index(after: index) } else if c == q { quote = nil }
233            } else if c == "\"" || c == "'" {
234                quote = c
235            } else if c == "#" {
236                return index
237            }
238            if index < line.endIndex { index = line.index(after: index) }
239        }
240        return nil
241    }
242}