Sources/OrgApp/UserConfig.swift

b5449dec59a00fac6867954166c6c612ffd6aee4
orgstar/Sources/OrgApp/UserConfig.swift history · blame · raw

281 lines · 16546 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    /// Settings Emacs has a variable for sit at the top of the file under that variable's
 35    /// name; the rest go in `[orgstar]`.
 36    public struct Setting: Sendable {
 37        public enum Kind: Sendable {
 38            case bool, integer, string
 39            /// A string in the file for each stored value.
 40            case choice([(name: String, stored: String)])
 41            case integerChoice([(name: String, stored: Int)])
 42            /// `org-agenda-start-day`: `"-3d"` in the file, -3 stored.
 43            case dayOffset
 44        }
 45
 46        public let section: String
 47        public let key: String
 48        public let defaultsKey: String
 49        public let kind: Kind
 50        public let fallback: TOML.Value
 51        public let comment: String
 52        /// Where earlier versions of the file kept it, `section.key`.
 53        public let legacy: String
 54
 55        public var path: String { section.isEmpty ? key : section + "." + key }
 56    }
 57
 58    public static let settings: [Setting] = [
 59        Setting(section: "", key: "fill-column", defaultsKey: "fillColumn", kind: .integer, fallback: .integer(80),
 60                comment: "M-q fills to this column", legacy: "editor.fill-column"),
 61        Setting(section: "", key: "org-tags-column", defaultsKey: "tagsColumn", kind: .integer, fallback: .integer(-77),
 62                comment: "negative: tags end at that column; 0: one space before them", legacy: "editor.tags-column"),
 63        Setting(section: "", key: "org-insert-heading-respect-content", defaultsKey: "headingAfterSubtree", kind: .bool, fallback: .bool(true),
 64                comment: "M-RET adds the new heading after the subtree", legacy: "editor.insert-heading-respect-content"),
 65        Setting(section: "", key: "org-M-RET-may-split-line", defaultsKey: "splitLine", kind: .bool, fallback: .bool(false),
 66                comment: "M-RET splits the line at the caret", legacy: "editor.meta-return-may-split-line"),
 67        Setting(section: "", key: "org-list-allow-alphabetical", defaultsKey: "alphabeticalLists", kind: .bool, fallback: .bool(true),
 68                comment: "lists can use a. b. c.", legacy: "editor.list-allow-alphabetical"),
 69        Setting(section: "", key: "org-hide-emphasis-markers", defaultsKey: "hiddenMarkers", kind: .bool, fallback: .bool(true),
 70                comment: "hide *bold* and =code= markers when markup is hidden", legacy: "editor.hide-emphasis-markers"),
 71        Setting(section: "", key: "org-pretty-entities", defaultsKey: "prettyEntities", kind: .bool, fallback: .bool(true),
 72                comment: "\\alpha shows as α and x_{1} is lowered when markup is hidden", legacy: "editor.pretty-entities"),
 73        Setting(section: "", key: "org-todo-keywords", defaultsKey: "todoKeywords", kind: .string, fallback: .string("TODO PROJ LOOP STRT WAIT HOLD IDEA | DONE KILL"),
 74                comment: "one sequence, in #+TODO syntax, for files without #+TODO; read at launch", legacy: "editor.todo-keywords"),
 75        Setting(section: "", key: "display-line-numbers-type", defaultsKey: "showLineNumbers", kind: .bool, fallback: .bool(true),
 76                comment: "line numbers (View ▸ Show Line Numbers)", legacy: "editor.line-numbers"),
 77        Setting(section: "", key: "org-agenda-span", defaultsKey: "agendaSpan", kind: .integer, fallback: .integer(10),
 78                comment: "days the agenda shows", legacy: "agenda.span"),
 79        Setting(section: "", key: "org-agenda-start-day", defaultsKey: "agendaStartOffset", kind: .dayOffset, fallback: .string("-3d"),
 80                comment: "the agenda's first day: \"-3d\", \"+0d\"", legacy: "agenda.start-offset"),
 81        Setting(section: "", key: "appt-message-warning-time", defaultsKey: "reminderLead", kind: .integer, fallback: .integer(12),
 82                comment: "minutes of warning before timed entries; APPT_WARNTIME overrides", legacy: "agenda.reminder-lead"),
 83        Setting(section: "orgstar", key: "save", defaultsKey: "saveMode", kind: .choice([("automatic", "automatic"), ("explicit", "explicit")]),
 84                fallback: .string("automatic"), comment: "automatic (1 s after typing stops) or explicit (only with ⌘S)", legacy: "general.save"),
 85        Setting(section: "orgstar", key: "keymap", defaultsKey: "keymap", kind: .choice([("emacs", "emacs"), ("mac", "mac"), ("doom", "doom")]),
 86                fallback: .string("emacs"), comment: "emacs, mac or doom; your own bindings go in keymap.toml", legacy: "general.keymap"),
 87        Setting(section: "orgstar", key: "option-as-meta", defaultsKey: "optionAsMeta",
 88                kind: .integerChoice([("left", 1), ("right", 2), ("both", 3), ("none", 0)]), fallback: .string("left"),
 89                comment: "left, right, both or none", legacy: "general.option-as-meta"),
 90        Setting(section: "orgstar", key: "show-markup", defaultsKey: "showMarkup", kind: .bool, fallback: .bool(false),
 91                comment: "show link brackets and emphasis markers (View ▸ Show Markup)", legacy: "editor.show-markup"),
 92        Setting(section: "orgstar", key: "agenda-include-subfolders", defaultsKey: "agendaSubfolders", kind: .bool, fallback: .bool(false),
 93                comment: "the agenda reads org files in subfolders too", legacy: "agenda.include-subfolders"),
 94        Setting(section: "orgstar", key: "reminders", defaultsKey: "reminders", kind: .bool, fallback: .bool(true),
 95                comment: "notify before timed entries", legacy: "agenda.reminders"),
 96        Setting(section: "orgstar", key: "global-capture-hotkey", defaultsKey: "globalCapture", kind: .bool, fallback: .bool(true),
 97                comment: "⌃⌥Space opens Capture from any app; templates go in capture.toml", legacy: "capture.global-hotkey"),
 98    ]
 99
100    /// `"-3d"` as -3; nil for anything else.
101    static func dayOffset(_ s: String) -> Int? {
102        guard s.hasSuffix("d"), let n = Int(s.dropLast().replacingOccurrences(of: "+", with: "")) else { return nil }
103        return n
104    }
105
106    // MARK: - Values
107
108    /// The file value for what `defaults` holds, or the fallback.
109    public static func value(_ setting: Setting, in defaults: UserDefaults) -> TOML.Value {
110        guard defaults.object(forKey: setting.defaultsKey) != nil else { return setting.fallback }
111        switch setting.kind {
112        case .bool: return .bool(defaults.bool(forKey: setting.defaultsKey))
113        case .integer: return .integer(defaults.integer(forKey: setting.defaultsKey))
114        case .string: return .string(defaults.string(forKey: setting.defaultsKey) ?? "")
115        case .choice(let choices):
116            let stored = defaults.string(forKey: setting.defaultsKey)
117            return choices.first { $0.stored == stored }.map { .string($0.name) } ?? setting.fallback
118        case .integerChoice(let choices):
119            let stored = defaults.integer(forKey: setting.defaultsKey)
120            return choices.first { $0.stored == stored }.map { .string($0.name) } ?? setting.fallback
121        case .dayOffset:
122            let days = defaults.integer(forKey: setting.defaultsKey)
123            return .string((days < 0 ? "" : "+") + "\(days)d")
124        }
125    }
126
127    /// Stores a file value; a value of the wrong kind is a problem.
128    static func store(_ value: TOML.Value, _ setting: Setting, in defaults: UserDefaults) -> String? {
129        let key = setting.defaultsKey
130        switch (setting.kind, value) {
131        case (.bool, .bool(let b)): defaults.set(b, forKey: key)
132        case (.integer, .integer(let i)): defaults.set(i, forKey: key)
133        case (.string, .string(let s)): defaults.set(s, forKey: key)
134        case (.choice(let choices), .string(let s)):
135            guard let choice = choices.first(where: { $0.name == s }) else {
136                return "\(setting.key) must be one of \(choices.map(\.name).joined(separator: ", "))"
137            }
138            defaults.set(choice.stored, forKey: key)
139        case (.integerChoice(let choices), .string(let s)):
140            guard let choice = choices.first(where: { $0.name == s }) else {
141                return "\(setting.key) must be one of \(choices.map(\.name).joined(separator: ", "))"
142            }
143            defaults.set(choice.stored, forKey: key)
144        case (.dayOffset, .string(let s)):
145            guard let days = dayOffset(s) else { return "\(setting.key) must look like \"-3d\" or \"+0d\"" }
146            defaults.set(days, forKey: key)
147        default:
148            return "\(setting.path) has the wrong kind of value"
149        }
150        return nil
151    }
152
153    /// Applies a file to `defaults`; settings it leaves out go back to their defaults.
154    /// Returns problems.
155    @discardableResult
156    public static func apply(_ text: String, to defaults: UserDefaults) -> [String] {
157        let tables: [TOML.Table]
158        do { tables = try TOML.parse(text) } catch { return ["config.toml: \(error)"] }
159        var problems: [String] = []
160        let present = Set(tables.flatMap { table in table.values.keys.map { path(table.name, $0) } })
161        for setting in settings where !present.contains(setting.path) && !present.contains(setting.legacy) {
162            if defaults.object(forKey: setting.defaultsKey) != nil { defaults.removeObject(forKey: setting.defaultsKey) }
163        }
164        for table in tables {
165            for (key, value) in table.values.sorted(by: { $0.key < $1.key }) {
166                let name = path(table.name, key)
167                guard let setting = settings.first(where: { $0.path == name || $0.legacy == name }) else {
168                    problems.append("config.toml: unknown setting \(name)")
169                    continue
170                }
171                if let current = currentValue(setting, in: defaults), current == value { continue }
172                if let problem = store(value, setting, in: defaults) { problems.append("config.toml: \(problem)") }
173            }
174        }
175        return problems
176    }
177
178    static func path(_ section: String, _ key: String) -> String { section.isEmpty ? key : section + "." + key }
179
180    /// Whether the file uses names from before settings took Emacs's names.
181    public static func usesLegacyNames(_ text: String) -> Bool {
182        let names = Set(settings.map(\.legacy))
183        return values(in: text).keys.contains { names.contains($0) }
184    }
185
186    private static func currentValue(_ setting: Setting, in defaults: UserDefaults) -> TOML.Value? {
187        defaults.object(forKey: setting.defaultsKey) == nil ? nil : value(setting, in: defaults)
188    }
189
190    /// The values a file sets, by `section.key`.
191    static func values(in text: String) -> [String: TOML.Value] {
192        guard let tables = try? TOML.parse(text) else { return [:] }
193        var result: [String: TOML.Value] = [:]
194        for table in tables { for (key, value) in table.values { result[path(table.name, key)] = value } }
195        return result
196    }
197
198    // MARK: - Text
199
200    static func format(_ value: TOML.Value) -> String {
201        switch value {
202        case .bool(let b): b ? "true" : "false"
203        case .integer(let i): String(i)
204        case .string(let s):
205            "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")
206                .replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\t", with: "\\t") + "\""
207        }
208    }
209
210    /// A commented file with every setting at its current value.
211    public static func template(from defaults: UserDefaults) -> String {
212        var out = """
213            # Orgstar settings. The Settings window writes its changes here, and edits made here
214            # apply while Orgstar runs. Keys go in keymap.toml, capture templates in capture.toml
215            # and saved agenda views in views.toml, all in this folder.
216
217            # Emacs variables, by their Emacs names.
218
219            """
220        var section = ""
221        for setting in settings {
222            if setting.section != section {
223                section = setting.section
224                out += "\n[\(section)]\n"
225            }
226            out += "\(setting.key) = \(format(value(setting, in: defaults)))  # \(setting.comment)\n"
227        }
228        return out
229    }
230
231    /// `text` with `section.key` set to `value`: the line's value is replaced (its comment
232    /// stays), or a line is added at the end of the section, or the section at the end.
233    public static func setting(_ text: String, section: String, key: String, to value: TOML.Value) -> String {
234        var lines = text.components(separatedBy: "\n")
235        var current = ""
236        var lastInSection: Int?
237        for (index, line) in lines.enumerated() {
238            let trimmed = line.trimmingCharacters(in: .whitespaces)
239            if trimmed.hasPrefix("[") && !trimmed.hasPrefix("[[") {
240                current = String(trimmed.dropFirst().prefix { $0 != "]" }).trimmingCharacters(in: .whitespaces)
241                if current == section { lastInSection = index }
242                continue
243            }
244            guard current == section else { continue }
245            if !trimmed.isEmpty { lastInSection = index }
246            guard let equals = line.firstIndex(of: "="),
247                  line[..<equals].trimmingCharacters(in: .whitespaces) == key else { continue }
248            let comment = commentStart(line, after: equals).map { "  " + line[$0...] } ?? ""
249            lines[index] = line[..<equals] + "= " + format(value) + comment
250            return lines.joined(separator: "\n")
251        }
252        if let lastInSection {
253            lines.insert("\(key) = \(format(value))", at: lastInSection + 1)
254        } else if section.isEmpty {
255            let firstHeader = lines.firstIndex { $0.trimmingCharacters(in: .whitespaces).hasPrefix("[") } ?? lines.count
256            lines.insert(contentsOf: ["\(key) = \(format(value))", ""], at: firstHeader)
257        } else {
258            if lines.last == "" { lines.removeLast() }
259            lines += ["", "[\(section)]", "\(key) = \(format(value))", ""]
260        }
261        return lines.joined(separator: "\n")
262    }
263
264    /// Where a `#` comment starts after the value, outside quotes.
265    private static func commentStart(_ line: String, after equals: String.Index) -> String.Index? {
266        var quote: Character?
267        var index = line.index(after: equals)
268        while index < line.endIndex {
269            let c = line[index]
270            if let q = quote {
271                if c == "\\" && q == "\"" { index = line.index(after: index) } else if c == q { quote = nil }
272            } else if c == "\"" || c == "'" {
273                quote = c
274            } else if c == "#" {
275                return index
276            }
277            if index < line.endIndex { index = line.index(after: index) }
278        }
279        return nil
280    }
281}