Sources/OrgApp/UserConfig.swift

4b4dc0135e1d59d493a0a49865fcd155aeea59e0
orgstar/Sources/OrgApp/UserConfig.swift history · blame · raw

344 lines · 22524 bytes

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