Sources/OrgApp/UserConfig.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/OrgApp/UserConfig.swift history · blame · raw

539 lines · 38585 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    /// A folder chosen in the app (on iOS, a synced copy of the Mac's), used over the default.
 12    nonisolated(unsafe) public static var directoryOverride: URL?
 13
 14    public static var directory: URL {
 15        if let directoryOverride { return directoryOverride }
 16        let environment = ProcessInfo.processInfo.environment
 17        if let override = environment["ORGSTAR_CONFIG_DIR"] { return URL(fileURLWithPath: override) }
 18        // Development runs keep everything in their data folder.
 19        if let data = environment["ORGSTAR_DATA_DIR"] { return URL(fileURLWithPath: data) }
 20        if let xdg = environment["XDG_CONFIG_HOME"], !xdg.isEmpty {
 21            return URL(fileURLWithPath: xdg).appendingPathComponent("orgstar")
 22        }
 23        return URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent(".config/orgstar")
 24    }
 25
 26    /// The theme `config.toml` (`text`) sets: its `[theme]` tables' colors over those of
 27    /// `theme-file` (a path relative to `folder`), over the default theme; with problems in
 28    /// both. Nil when `text` isn't TOML.
 29    public static func theme(
 30        config text: String, themeFile name: String?, in folder: URL,
 31        read: (URL) -> String? = { try? String(contentsOf: $0, encoding: .utf8) }
 32    ) -> (theme: ThemeSpec, problems: [String])? {
 33        guard let tables = try? TOML.parse(text) else { return nil }
 34        var spec = ThemeSpec.default
 35        var problems: [String] = []
 36        if let name, !name.isEmpty {
 37            if let themeText = read(folder.appendingPathComponent(name)) {
 38                do {
 39                    (spec, problems) = ThemeSpec.reading(try TOML.parse(themeText), file: name)
 40                } catch {
 41                    problems.append("\(name): \(error)")
 42                }
 43            } else {
 44                problems.append("config.toml: theme-file \(name) can't be read")
 45            }
 46        }
 47        let (merged, more) = ThemeSpec.reading(tables, over: spec)
 48        return (merged, problems + more)
 49    }
 50
 51    /// Where earlier versions kept the configuration files.
 52    public static var legacyDirectory: URL {
 53        FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Orgstar")
 54    }
 55
 56    /// A file of the configuration folder; one that exists only where earlier versions kept
 57    /// it (Application Support) is still read from there.
 58    public static func file(_ name: String) -> URL {
 59        let url = directory.appendingPathComponent(name)
 60        let legacy = legacyDirectory.appendingPathComponent(name)
 61        let manager = FileManager.default
 62        if !manager.fileExists(atPath: url.path), manager.fileExists(atPath: legacy.path) { return legacy }
 63        return url
 64    }
 65
 66    public static var configFile: URL { directory.appendingPathComponent("config.toml") }
 67
 68    /// One setting: where it sits in the file, its user-defaults key, and how values convert.
 69    /// Settings Emacs has a variable for sit at the top of the file under that variable's
 70    /// name; the rest go in `[orgstar]`.
 71    public struct Setting: Sendable {
 72        public enum Kind: Sendable {
 73            case bool, integer, string
 74            /// A string in the file for each stored value.
 75            case choice([(name: String, stored: String)])
 76            case integerChoice([(name: String, stored: Int)])
 77            /// `org-agenda-start-day`: `"-3d"` in the file, -3 stored.
 78            case dayOffset
 79        }
 80
 81        public let section: String
 82        public let key: String
 83        public let defaultsKey: String
 84        public let kind: Kind
 85        public let fallback: TOML.Value
 86        public let comment: String
 87        /// Where earlier versions of the file kept it, `section.key`.
 88        public let legacy: String
 89
 90        public var path: String { section.isEmpty ? key : section + "." + key }
 91    }
 92
 93    public static let settings: [Setting] = [
 94        Setting(section: "", key: "fill-column", defaultsKey: "fillColumn", kind: .integer, fallback: .integer(80),
 95                comment: "M-q fills to this column", legacy: "editor.fill-column"),
 96        Setting(section: "", key: "org-tags-column", defaultsKey: "tagsColumn", kind: .integer, fallback: .integer(-77),
 97                comment: "negative: tags end at that column; 0: one space before them", legacy: "editor.tags-column"),
 98        Setting(section: "", key: "org-insert-heading-respect-content", defaultsKey: "headingAfterSubtree", kind: .bool, fallback: .bool(true),
 99                comment: "M-RET adds the new heading after the subtree", legacy: "editor.insert-heading-respect-content"),
100        Setting(section: "", key: "org-M-RET-may-split-line", defaultsKey: "splitLine", kind: .bool, fallback: .bool(false),
101                comment: "M-RET splits the line at the caret", legacy: "editor.meta-return-may-split-line"),
102        Setting(section: "", key: "org-use-property-inheritance", defaultsKey: "propertyInheritance", kind: .string, fallback: .string("nil"),
103                comment: "nil, t, or property names that inherit, separated by spaces, such as \"STYLE\"", legacy: ""),
104        Setting(section: "", key: "org-list-allow-alphabetical", defaultsKey: "alphabeticalLists", kind: .bool, fallback: .bool(true),
105                comment: "lists can use a. b. c.", legacy: "editor.list-allow-alphabetical"),
106        Setting(section: "", key: "org-hide-emphasis-markers", defaultsKey: "hiddenMarkers", kind: .bool, fallback: .bool(true),
107                comment: "hide *bold* and =code= markers when markup is hidden", legacy: "editor.hide-emphasis-markers"),
108        Setting(section: "", key: "org-pretty-entities", defaultsKey: "prettyEntities", kind: .bool, fallback: .bool(true),
109                comment: "\\alpha shows as α and x_{1} is lowered when markup is hidden", legacy: "editor.pretty-entities"),
110        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)"),
111                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"),
112        Setting(section: "", key: "org-log-done", defaultsKey: "logDone", kind: .choice([("nil", "nil"), ("time", "time"), ("note", "note")]),
113                fallback: .string("nil"), comment: "nil, time (CLOSED when done) or note (CLOSED and a note)", legacy: ""),
114        Setting(section: "", key: "org-log-reschedule", defaultsKey: "logReschedule", kind: .choice([("nil", "nil"), ("time", "time"), ("note", "note")]),
115                fallback: .string("nil"), comment: "nil, time or note: log changing or removing a SCHEDULED date", legacy: ""),
116        Setting(section: "", key: "org-log-redeadline", defaultsKey: "logRedeadline", kind: .choice([("nil", "nil"), ("time", "time"), ("note", "note")]),
117                fallback: .string("nil"), comment: "nil, time or note: log changing or removing a DEADLINE", legacy: ""),
118        Setting(section: "", key: "org-log-into-drawer", defaultsKey: "logIntoDrawer", kind: .string, fallback: .string(""),
119                comment: "the drawer state notes go in (\"LOGBOOK\" is Emacs's t); \"\" for none", legacy: ""),
120        Setting(section: "", key: "org-enforce-todo-dependencies", defaultsKey: "enforceTodoDependencies", kind: .bool, fallback: .bool(false),
121                comment: "an entry can't be done before its TODO children, or under an ORDERED parent before its earlier siblings", legacy: ""),
122        Setting(section: "", key: "org-enforce-todo-checkbox-dependencies", defaultsKey: "enforceTodoCheckboxDependencies", kind: .bool, fallback: .bool(false),
123                comment: "an entry can't be done while it has unchecked boxes", legacy: ""),
124        Setting(section: "", key: "org-archive-location", defaultsKey: "archiveLocation", kind: .string, fallback: .string("%s_archive::"),
125                comment: "where Archive Subtree moves an entry without an ARCHIVE property or #+ARCHIVE: file::heading, %s the file's name", legacy: ""),
126        Setting(section: "", key: "org-use-tag-inheritance", defaultsKey: "tagInheritance", kind: .string, fallback: .string("t"),
127                comment: "t, nil, tags that inherit separated by spaces, or a regexp in braces such as \"{^@}\"", legacy: ""),
128        Setting(section: "", key: "org-tags-exclude-from-inheritance", defaultsKey: "tagsExcludedFromInheritance", kind: .string, fallback: .string(""),
129                comment: "tags that never inherit, separated by spaces", legacy: ""),
130        Setting(section: "", key: "org-tag-alist", defaultsKey: "tagAlist", kind: .string, fallback: .string(""),
131                comment: "tags C-c C-q offers in files without #+TAGS, in #+TAGS syntax: \"work(w) home(h) { @office(o) @home(H) }\"", legacy: ""),
132        Setting(section: "", key: "org-track-ordered-property-with-tag", defaultsKey: "trackOrderedTag", kind: .string, fallback: .string("nil"),
133                comment: "nil, t (the tag ORDERED) or a tag that Toggle ORDERED Property toggles too", legacy: ""),
134        Setting(section: "", key: "org-startup-indented", defaultsKey: "startupIndented", kind: .bool, fallback: .bool(true),
135                comment: "indent bodies under their headings (org-indent-mode); #+STARTUP: (no)indent overrides", legacy: ""),
136        Setting(section: "", key: "org-hide-leading-stars", defaultsKey: "hideLeadingStars", kind: .bool, fallback: .bool(false),
137                comment: "show only a heading's last star without indentation; #+STARTUP: hidestars/showstars overrides", legacy: ""),
138        Setting(section: "", key: "org-startup-align-all-tables", defaultsKey: "startupAlignAllTables", kind: .bool, fallback: .bool(false),
139                comment: "align every table when a file opens; #+STARTUP: (no)align overrides", legacy: ""),
140        Setting(section: "", key: "org-startup-truncated", defaultsKey: "startupTruncated", kind: .bool, fallback: .bool(false),
141                comment: "truncate long lines instead of wrapping them (Emacs's default is t; Doom wraps)", legacy: ""),
142        Setting(section: "", key: "spell-check", defaultsKey: "spellCheck", kind: .bool, fallback: .bool(false),
143                comment: "check spelling while typing, outside code, links, dates, tags and keywords", legacy: ""),
144        Setting(section: "", key: "electric-pair-mode", defaultsKey: "electricPair", kind: .bool, fallback: .bool(true),
145                comment: "type brackets, <> and quotes in pairs as electric-pair-mode does (off in plain Emacs; Doom pairs with smartparens)", legacy: ""),
146        Setting(section: "", key: "org-startup-with-inline-images", defaultsKey: "startupWithInlineImages", kind: .bool, fallback: .bool(false),
147                comment: "show image links as images when a file opens; #+STARTUP: (no)inlineimages overrides", legacy: ""),
148        Setting(section: "", key: "org-use-speed-commands", defaultsKey: "useSpeedCommands", kind: .bool, fallback: .bool(false),
149                comment: "single keys at the start of a heading line run commands (n, p, t, c, …)", legacy: ""),
150        Setting(section: "", key: "org-cycle-hide-drawer-startup", defaultsKey: "hideDrawerStartup", kind: .bool, fallback: .bool(true),
151                comment: "fold drawers when a file opens; #+STARTUP: nohidedrawers overrides", legacy: ""),
152        Setting(section: "", key: "org-cycle-hide-block-startup", defaultsKey: "hideBlockStartup", kind: .bool, fallback: .bool(false),
153                comment: "fold blocks when a file opens; #+STARTUP: hideblocks overrides", legacy: ""),
154        Setting(section: "", key: "display-line-numbers-type", defaultsKey: "showLineNumbers", kind: .bool, fallback: .bool(true),
155                comment: "line numbers (View ▸ Show Line Numbers)", legacy: "editor.line-numbers"),
156        Setting(section: "", key: "org-agenda-span", defaultsKey: "agendaSpan", kind: .integer, fallback: .integer(10),
157                comment: "days the agenda shows", legacy: "agenda.span"),
158        Setting(section: "", key: "org-agenda-start-day", defaultsKey: "agendaStartOffset", kind: .dayOffset, fallback: .string("+0d"),
159                comment: "the agenda's first day: \"-3d\", \"+0d\"", legacy: "agenda.start-offset"),
160        Setting(section: "", key: "org-deadline-warning-days", defaultsKey: "deadlineWarningDays", kind: .integer, fallback: .integer(14),
161                comment: "days ahead the agenda warns about a deadline; a -Nd cookie overrides", legacy: ""),
162        Setting(section: "", key: "org-agenda-start-on-weekday", defaultsKey: "agendaStartOnWeekday",
163                kind: .choice([("nil", "nil")] + (0...6).map { ("\($0)", "\($0)") }), fallback: .string("1"),
164                comment: "weeks start on this day, 0 Sunday to 6 Saturday, or nil for the agenda's first day", legacy: ""),
165        Setting(section: "", key: "org-agenda-show-all-dates", defaultsKey: "agendaShowAllDates", kind: .bool, fallback: .bool(false),
166                comment: "show days with no entries (Emacs's default is t; orgstar hides them); today always shows", legacy: ""),
167        Setting(section: "", key: "org-agenda-skip-scheduled-if-done", defaultsKey: "agendaSkipScheduledIfDone", kind: .bool, fallback: .bool(false),
168                comment: "leave done entries out of the agenda even on the day they are scheduled", legacy: ""),
169        Setting(section: "", key: "org-agenda-skip-deadline-if-done", defaultsKey: "agendaSkipDeadlineIfDone", kind: .bool, fallback: .bool(false),
170                comment: "leave done entries out of the agenda even on the day they are due", legacy: ""),
171        Setting(section: "", key: "org-agenda-log-mode-items", defaultsKey: "agendaLogModeItems", kind: .string, fallback: .string("closed clock"),
172                comment: "what log mode shows, separated by spaces: closed, clock, state", legacy: ""),
173        Setting(section: "", key: "org-agenda-todo-ignore-with-date", defaultsKey: "agendaTodoIgnoreWithDate", kind: .bool, fallback: .bool(false),
174                comment: "the TODO list leaves out entries with any active timestamp", legacy: ""),
175        Setting(section: "", key: "org-agenda-todo-ignore-scheduled", defaultsKey: "agendaTodoIgnoreScheduled", kind: .string, fallback: .string("nil"),
176                comment: "the TODO list leaves out scheduled entries: nil, all, future, past, or days ahead (negative: days ago)", legacy: ""),
177        Setting(section: "", key: "org-agenda-todo-ignore-deadlines", defaultsKey: "agendaTodoIgnoreDeadlines", kind: .string, fallback: .string("nil"),
178                comment: "the TODO list leaves out entries with deadlines: nil, near, far, all, future, past, or days", legacy: ""),
179        Setting(section: "", key: "org-agenda-todo-ignore-timestamp", defaultsKey: "agendaTodoIgnoreTimestamp", kind: .string, fallback: .string("nil"),
180                comment: "the TODO list leaves out entries with other active timestamps: nil, all, future, past, or days", legacy: ""),
181        Setting(section: "", key: "org-agenda-tags-todo-honor-ignore-options", defaultsKey: "agendaTagsTodoHonorIgnore", kind: .bool, fallback: .bool(false),
182                comment: "the org-agenda-todo-ignore settings apply to TODO-only matches too", legacy: ""),
183        Setting(section: "", key: "org-agenda-search-view-always-boolean", defaultsKey: "agendaSearchAlwaysBoolean", kind: .bool, fallback: .bool(false),
184                comment: "search strings are always +word -word {regexp} snippets, never a phrase", legacy: ""),
185        Setting(section: "", key: "org-agenda-search-view-force-full-words", defaultsKey: "agendaSearchForceFullWords", kind: .bool, fallback: .bool(false),
186                comment: "search snippets match whole words only", legacy: ""),
187        Setting(section: "", key: "org-agenda-dim-blocked-tasks", defaultsKey: "agendaDimBlockedTasks",
188                kind: .choice([("t", "t"), ("nil", "nil"), ("invisible", "invisible")]), fallback: .string("t"),
189                comment: "t dims entries the enforce settings block, invisible hides them (unless only checkboxes block them), nil shows them as usual", legacy: ""),
190        Setting(section: "", key: "appt-message-warning-time", defaultsKey: "reminderLead", kind: .integer, fallback: .integer(12),
191                comment: "minutes of warning before timed entries; APPT_WARNTIME overrides", legacy: "agenda.reminder-lead"),
192        Setting(section: "", key: "org-clock-idle-time", defaultsKey: "clockIdleTime", kind: .integer, fallback: .integer(0),
193                comment: "minutes idle with a clock running before asking what to do with the time; 0 never (nil)", legacy: ""),
194        Setting(section: "", key: "org-clock-into-drawer", defaultsKey: "clockIntoDrawer", kind: .string, fallback: .string("t"),
195                comment: "t: clock lines go in the log drawer (LOGBOOK); nil: none; a number: once there are that many; or a drawer name", legacy: ""),
196        Setting(section: "", key: "org-clock-rounding-minutes", defaultsKey: "clockRoundingMinutes", kind: .integer, fallback: .integer(0),
197                comment: "clocks start and end on multiples of this many minutes; 0 doesn't round", legacy: ""),
198        Setting(section: "", key: "org-clock-out-remove-zero-time-clocks", defaultsKey: "clockRemoveZeroTime", kind: .bool, fallback: .bool(false),
199                comment: "clocking out removes a clock line of 0:00", legacy: ""),
200        Setting(section: "", key: "org-clock-in-switch-to-state", defaultsKey: "clockInSwitchToState", kind: .string, fallback: .string(""),
201                comment: "the TODO keyword an entry takes when you clock in; \"\" leaves it", legacy: ""),
202        Setting(section: "", key: "org-clock-out-when-done", defaultsKey: "clockOutWhenDone", kind: .string, fallback: .string("t"),
203                comment: "t: marking the clocked entry done clocks out; nil: it doesn't; or keywords that clock out, separated by spaces", legacy: ""),
204        Setting(section: "", key: "org-clock-history-length", defaultsKey: "clockHistoryLength", kind: .integer, fallback: .integer(5),
205                comment: "recently clocked entries to remember", legacy: ""),
206        Setting(section: "org-agenda-prefix-format", key: "agenda", defaultsKey: "agendaPrefixAgenda", kind: .string, fallback: .string(PrefixFormat.defaults["agenda"]!),
207                comment: "%c category, %t time, %s scheduled/deadline, %e effort, %l level, %b outline path; %-12 pads", legacy: ""),
208        Setting(section: "org-agenda-prefix-format", key: "todo", defaultsKey: "agendaPrefixTodo", kind: .string, fallback: .string(PrefixFormat.defaults["todo"]!),
209                comment: "the TODO list", legacy: ""),
210        Setting(section: "org-agenda-prefix-format", key: "tags", defaultsKey: "agendaPrefixTags", kind: .string, fallback: .string(PrefixFormat.defaults["tags"]!),
211                comment: "tag and property matches", legacy: ""),
212        Setting(section: "theme", key: "font", defaultsKey: "themeFont", kind: .string, fallback: .string(""),
213                comment: "a monospaced font family; \"\" for the system's", legacy: ""),
214        Setting(section: "theme", key: "font-size", defaultsKey: "themeFontSize", kind: .integer, fallback: .integer(13),
215                comment: "points", legacy: ""),
216        Setting(section: "theme", key: "line-spacing", defaultsKey: "themeLineSpacing", kind: .integer, fallback: .integer(2),
217                comment: "points between lines", legacy: ""),
218        Setting(section: "theme", key: "heading-size-step", defaultsKey: "themeHeadingStep", kind: .integer, fallback: .integer(1),
219                comment: "points a heading is larger than the level below; level 4 and deeper are body size", legacy: ""),
220        Setting(section: "theme", key: "theme-file", defaultsKey: "themeFile", kind: .string, fallback: .string(""),
221                comment: "a theme in its own file in this folder, under the colors set here; colors: see default-theme.toml", legacy: ""),
222        Setting(section: "orgstar", key: "save", defaultsKey: "saveMode", kind: .choice([("automatic", "automatic"), ("explicit", "explicit")]),
223                fallback: .string("automatic"), comment: "automatic (1 s after typing stops) or explicit (only with ⌘S)", legacy: "general.save"),
224        Setting(section: "orgstar", key: "keymap", defaultsKey: "keymap", kind: .choice([("emacs", "emacs"), ("mac", "mac"), ("doom", "doom")]),
225                fallback: .string("emacs"), comment: "emacs, mac or doom; your own bindings go in keymap.toml", legacy: "general.keymap"),
226        Setting(section: "orgstar", key: "option-as-meta", defaultsKey: "optionAsMeta",
227                kind: .integerChoice([("left", 1), ("right", 2), ("both", 3), ("none", 0)]), fallback: .string("left"),
228                comment: "left, right, both or none", legacy: "general.option-as-meta"),
229        Setting(section: "orgstar", key: "tab-bar", defaultsKey: "showTabBar", kind: .bool, fallback: .bool(false),
230                comment: "a tab for each open buffer above the editor (View ▸ Show Tab Bar)", legacy: ""),
231        Setting(section: "orgstar", key: "show-markup", defaultsKey: "showMarkup", kind: .bool, fallback: .bool(false),
232                comment: "show link brackets and emphasis markers (View ▸ Show Markup)", legacy: "editor.show-markup"),
233        Setting(section: "orgstar", key: "show-hidden-files", defaultsKey: "showHiddenFiles", kind: .bool, fallback: .bool(true),
234                comment: "list dotfiles and dot folders in your folders", legacy: ""),
235        Setting(section: "orgstar", key: "ignored-folders", defaultsKey: "ignoredFolders", kind: .string,
236                fallback: .string(ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ")),
237                comment: "folder names never listed or searched, separated by spaces", legacy: ""),
238        Setting(section: "orgstar", key: "agenda-include-subfolders", defaultsKey: "agendaSubfolders", kind: .bool, fallback: .bool(false),
239                comment: "the agenda reads org files in subfolders too", legacy: "agenda.include-subfolders"),
240        Setting(section: "orgstar", key: "reminders", defaultsKey: "reminders", kind: .bool, fallback: .bool(true),
241                comment: "notify before timed entries", legacy: "agenda.reminders"),
242        Setting(section: "orgstar", key: "calendar-events", defaultsKey: "calendarEvents", kind: .bool, fallback: .bool(false),
243                comment: "show events from Calendar in the agenda, read-only", legacy: ""),
244        Setting(section: "orgstar", key: "calendar-event-calendars", defaultsKey: "calendarEventCalendars", kind: .string, fallback: .string(""),
245                comment: "the calendars whose events show, by title or identifier, separated by commas; \"\" for all", legacy: ""),
246        Setting(section: "orgstar", key: "global-capture-hotkey", defaultsKey: "globalCapture", kind: .bool, fallback: .bool(true),
247                comment: "⌃⌥Space opens Capture from any app; templates go in capture.toml", legacy: "capture.global-hotkey"),
248    ]
249
250    /// `"-3d"` as -3; nil for anything else.
251    static func dayOffset(_ s: String) -> Int? {
252        guard s.hasSuffix("d"), let n = Int(s.dropLast().replacingOccurrences(of: "+", with: "")) else { return nil }
253        return n
254    }
255
256    // MARK: - Values
257
258    /// The file value for what `defaults` holds, or the fallback.
259    public static func value(_ setting: Setting, in defaults: UserDefaults) -> TOML.Value {
260        guard defaults.object(forKey: setting.defaultsKey) != nil else { return setting.fallback }
261        switch setting.kind {
262        case .bool: return .bool(defaults.bool(forKey: setting.defaultsKey))
263        case .integer: return .integer(defaults.integer(forKey: setting.defaultsKey))
264        case .string: return .string(defaults.string(forKey: setting.defaultsKey) ?? "")
265        case .choice(let choices):
266            let stored = defaults.string(forKey: setting.defaultsKey)
267            return choices.first { $0.stored == stored }.map { .string($0.name) } ?? setting.fallback
268        case .integerChoice(let choices):
269            let stored = defaults.integer(forKey: setting.defaultsKey)
270            return choices.first { $0.stored == stored }.map { .string($0.name) } ?? setting.fallback
271        case .dayOffset:
272            let days = defaults.integer(forKey: setting.defaultsKey)
273            return .string((days < 0 ? "" : "+") + "\(days)d")
274        }
275    }
276
277    /// Stores a file value; a value of the wrong kind is a problem.
278    static func store(_ value: TOML.Value, _ setting: Setting, in defaults: UserDefaults) -> String? {
279        let key = setting.defaultsKey
280        switch (setting.kind, value) {
281        case (.bool, .bool(let b)): defaults.set(b, forKey: key)
282        case (.integer, .integer(let i)): defaults.set(i, forKey: key)
283        case (.string, .string(let s)): defaults.set(s, forKey: key)
284        case (.choice(let choices), .string(let s)):
285            guard let choice = choices.first(where: { $0.name == s }) else {
286                return "\(setting.key) must be one of \(choices.map(\.name).joined(separator: ", "))"
287            }
288            defaults.set(choice.stored, forKey: key)
289        case (.integerChoice(let choices), .string(let s)):
290            guard let choice = choices.first(where: { $0.name == s }) else {
291                return "\(setting.key) must be one of \(choices.map(\.name).joined(separator: ", "))"
292            }
293            defaults.set(choice.stored, forKey: key)
294        case (.dayOffset, .string(let s)):
295            guard let days = dayOffset(s) else { return "\(setting.key) must look like \"-3d\" or \"+0d\"" }
296            defaults.set(days, forKey: key)
297        default:
298            return "\(setting.path) has the wrong kind of value"
299        }
300        return nil
301    }
302
303    /// Applies a file to `defaults`; settings it leaves out go back to their defaults.
304    /// Returns problems.
305    @discardableResult
306    public static func apply(_ text: String, to defaults: UserDefaults) -> [String] {
307        let tables: [TOML.Table]
308        do { tables = try TOML.parse(text) } catch { return ["config.toml: \(error)"] }
309        var problems: [String] = []
310        let present = Set(tables.flatMap { table in table.values.keys.map { path(table.name, $0) } })
311        for setting in settings where !present.contains(setting.path) && !present.contains(setting.legacy) {
312            if defaults.object(forKey: setting.defaultsKey) != nil { defaults.removeObject(forKey: setting.defaultsKey) }
313        }
314        let templates = tables.first { $0.name == structureTemplateTable }
315        if templates == nil, defaults.object(forKey: structureTemplatesKey) != nil { defaults.removeObject(forKey: structureTemplatesKey) }
316        for table in tables {
317            if table.name == structureTemplateTable {
318                var rows: [String] = []
319                for key in table.keys {
320                    guard let type = table.values[key]?.string, !type.isEmpty else {
321                        problems.append("config.toml: \(structureTemplateTable).\(key) must be a block type, such as \"src python\"")
322                        continue
323                    }
324                    rows.append(key + "\t" + type)
325                }
326                if defaults.stringArray(forKey: structureTemplatesKey) != rows { defaults.set(rows, forKey: structureTemplatesKey) }
327                continue
328            }
329            // Colors are the theme's to read.
330            if ThemeSpec.isThemeTable(table.name), table.name != "theme" { continue }
331            for (key, value) in table.values.sorted(by: { $0.key < $1.key }) {
332                if table.name == "theme", !ThemeSpec.typeKeys.contains(key) { continue }
333                let name = path(table.name, key)
334                guard let setting = settings.first(where: { $0.path == name || $0.legacy == name }) else {
335                    problems.append("config.toml: unknown setting \(name)")
336                    continue
337                }
338                if let current = currentValue(setting, in: defaults), current == value { continue }
339                if let problem = store(value, setting, in: defaults) { problems.append("config.toml: \(problem)") }
340            }
341        }
342        return problems
343    }
344
345    /// `[org-structure-template-alist]`: block templates by key, over Org's, as
346    /// `key = "type"`. Kept in user defaults under `structureTemplatesKey` as `key<Tab>type`.
347    public static let structureTemplateTable = "org-structure-template-alist"
348    static let structureTemplatesKey = "structureTemplates"
349
350    /// The templates of `[org-structure-template-alist]`.
351    public static func structureTemplates(_ defaults: UserDefaults) -> [StructureTemplate] {
352        (defaults.stringArray(forKey: structureTemplatesKey) ?? []).compactMap { row in
353            guard let tab = row.firstIndex(of: "\t") else { return nil }
354            return StructureTemplate(key: String(row[..<tab]), type: String(row[row.index(after: tab)...]))
355        }
356    }
357
358    public static func setStructureTemplates(_ templates: [StructureTemplate], in defaults: UserDefaults) {
359        defaults.set(templates.map { $0.key + "\t" + $0.type }, forKey: structureTemplatesKey)
360    }
361
362    static func path(_ section: String, _ key: String) -> String { section.isEmpty ? key : section + "." + key }
363
364    /// Whether the file uses names from before settings took Emacs's names.
365    public static func usesLegacyNames(_ text: String) -> Bool {
366        let names = Set(settings.map(\.legacy))
367        return values(in: text).keys.contains { names.contains($0) }
368    }
369
370    /// `text` with settings under their old names moved to their current names and places,
371    /// keeping comments and everything else. A section the move leaves empty is removed.
372    public static func migratingLegacyNames(_ text: String) -> String {
373        let values = values(in: text)
374        var blocks: [[String]] = [[]]
375        for line in text.components(separatedBy: "\n") {
376            if line.trimmingCharacters(in: .whitespaces).hasPrefix("[") { blocks.append([]) }
377            blocks[blocks.count - 1].append(line)
378        }
379        var moves: [(setting: Setting, value: TOML.Value, comment: String)] = []
380        var kept: [String] = []
381        for block in blocks {
382            let header = block.first.map { $0.trimmingCharacters(in: .whitespaces) }.flatMap { $0.hasPrefix("[") ? $0 : nil }
383            let section = header.map { String($0.dropFirst().prefix { $0 != "]" }).trimmingCharacters(in: .whitespaces) } ?? ""
384            var remaining: [String] = []
385            for (index, line) in block.enumerated() {
386                guard header == nil || index > 0, let equals = line.firstIndex(of: "=") else {
387                    remaining.append(line)
388                    continue
389                }
390                let name = path(section, line[..<equals].trimmingCharacters(in: .whitespaces))
391                guard let setting = settings.first(where: { !$0.legacy.isEmpty && $0.legacy == name }), let value = values[name] else {
392                    remaining.append(line)
393                    continue
394                }
395                // A setting also under its new name keeps that one.
396                if values[setting.path] == nil {
397                    moves.append((setting, value, commentStart(line, after: equals).map { String(line[$0...]) } ?? ""))
398                }
399            }
400            let emptied = header != nil && remaining.count < block.count
401                && remaining.dropFirst().allSatisfy { $0.trimmingCharacters(in: .whitespaces).isEmpty }
402            if !emptied { kept += remaining }
403        }
404        var out = kept.joined(separator: "\n")
405        if text.hasSuffix("\n"), !out.isEmpty, !out.hasSuffix("\n") { out += "\n" }
406        for move in moves {
407            out = setting(out, section: move.setting.section, key: move.setting.key, to: move.value)
408            guard !move.comment.isEmpty else { continue }
409            var lines = out.components(separatedBy: "\n")
410            if let index = lines.firstIndex(of: "\(move.setting.key) = \(format(move.value))") {
411                lines[index] += "  " + move.comment
412                out = lines.joined(separator: "\n")
413            }
414        }
415        return out
416    }
417
418    private static func currentValue(_ setting: Setting, in defaults: UserDefaults) -> TOML.Value? {
419        defaults.object(forKey: setting.defaultsKey) == nil ? nil : value(setting, in: defaults)
420    }
421
422    /// The values a file sets, by `section.key`.
423    static func values(in text: String) -> [String: TOML.Value] {
424        guard let tables = try? TOML.parse(text) else { return [:] }
425        var result: [String: TOML.Value] = [:]
426        for table in tables { for (key, value) in table.values { result[path(table.name, key)] = value } }
427        return result
428    }
429
430    // MARK: - Text
431
432    static func format(_ value: TOML.Value) -> String {
433        switch value {
434        case .bool(let b): b ? "true" : "false"
435        case .integer(let i): String(i)
436        case .string(let s):
437            "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")
438                .replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\t", with: "\\t") + "\""
439        }
440    }
441
442    /// A commented file with every setting at its current value.
443    public static func template(from defaults: UserDefaults) -> String {
444        template { value($0, in: defaults) }
445    }
446
447    /// A commented file with every setting at its default.
448    public static var defaultTemplate: String { template(\.fallback) }
449
450    private static func template(_ value: (Setting) -> TOML.Value) -> String {
451        var out = """
452            # orgstar settings. The Settings window writes its changes here, and edits made here
453            # apply while orgstar runs. Keys go in keymap.toml, capture templates in capture.toml
454            # and saved agenda views in views.toml, all in this folder.
455
456            # Emacs variables, by their Emacs names.
457
458            """
459        var section = ""
460        for setting in settings {
461            if setting.section != section {
462                section = setting.section
463                out += "\n[\(section)]\n"
464            }
465            out += "\(setting.key) = \(format(value(setting)))  # \(setting.comment)\n"
466        }
467        return out
468    }
469
470    /// `text` with the sections it lacks entirely added at the end, every setting at its
471    /// value in `defaults`: how a file from an earlier version gets settings added since.
472    /// Single lines left out stay out; they mean the default.
473    public static func addingMissingSections(_ text: String, from defaults: UserDefaults) -> String {
474        let tables = (try? TOML.parse(text)) ?? []
475        let present = Set(tables.filter { !$0.values.isEmpty || $0.name != "" }.map(\.name))
476        var out = text
477        var section: String?
478        for setting in settings where !setting.section.isEmpty && !present.contains(setting.section) {
479            if setting.section != section {
480                section = setting.section
481                if !out.hasSuffix("\n") { out += "\n" }
482                out += "\n[\(setting.section)]\n"
483            }
484            out += "\(setting.key) = \(format(value(setting, in: defaults)))  # \(setting.comment)\n"
485        }
486        return out
487    }
488
489    /// `text` with `section.key` set to `value`: the line's value is replaced (its comment
490    /// stays), or a line is added at the end of the section, or the section at the end.
491    public static func setting(_ text: String, section: String, key: String, to value: TOML.Value) -> String {
492        var lines = text.components(separatedBy: "\n")
493        var current = ""
494        var lastInSection: Int?
495        for (index, line) in lines.enumerated() {
496            let trimmed = line.trimmingCharacters(in: .whitespaces)
497            if trimmed.hasPrefix("[") && !trimmed.hasPrefix("[[") {
498                current = String(trimmed.dropFirst().prefix { $0 != "]" }).trimmingCharacters(in: .whitespaces)
499                if current == section { lastInSection = index }
500                continue
501            }
502            guard current == section else { continue }
503            if !trimmed.isEmpty { lastInSection = index }
504            guard let equals = line.firstIndex(of: "="),
505                  line[..<equals].trimmingCharacters(in: .whitespaces) == key else { continue }
506            let comment = commentStart(line, after: equals).map { "  " + line[$0...] } ?? ""
507            lines[index] = line[..<equals] + "= " + format(value) + comment
508            return lines.joined(separator: "\n")
509        }
510        if let lastInSection {
511            lines.insert("\(key) = \(format(value))", at: lastInSection + 1)
512        } else if section.isEmpty {
513            let firstHeader = lines.firstIndex { $0.trimmingCharacters(in: .whitespaces).hasPrefix("[") } ?? lines.count
514            lines.insert(contentsOf: ["\(key) = \(format(value))", ""], at: firstHeader)
515        } else {
516            if lines.last == "" { lines.removeLast() }
517            lines += ["", "[\(section)]", "\(key) = \(format(value))", ""]
518        }
519        return lines.joined(separator: "\n")
520    }
521
522    /// Where a `#` comment starts after the value, outside quotes.
523    private static func commentStart(_ line: String, after equals: String.Index) -> String.Index? {
524        var quote: Character?
525        var index = line.index(after: equals)
526        while index < line.endIndex {
527            let c = line[index]
528            if let q = quote {
529                if c == "\\" && q == "\"" { index = line.index(after: index) } else if c == q { quote = nil }
530            } else if c == "\"" || c == "'" {
531                quote = c
532            } else if c == "#" {
533                return index
534            }
535            if index < line.endIndex { index = line.index(after: index) }
536        }
537        return nil
538    }
539}