Sources/OrgApp/UserConfig.swift

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

314 lines · 18850 bytes

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