Sources/OrgApp/UserConfig.swift

42a385196913dc8d1d9ee9a6ea134db4fa4cd546
orgstar/Sources/OrgApp/UserConfig.swift

654 lines · 52590 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 palettes `light-theme` and
 28    /// `dark-theme` name; with problems in all three. Nil when `text` isn't TOML.
 29    public static func theme(
 30        config text: String, themeFile name: String?, lightTheme: String? = nil, darkTheme: String? = nil, 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, problems) = ThemeSpec.base(light: lightTheme, dark: darkTheme)
 35        if let name, !name.isEmpty {
 36            if let themeText = read(folder.appendingPathComponent(name)) {
 37                do {
 38                    let (read, more) = ThemeSpec.reading(try TOML.parse(themeText), over: spec, file: name)
 39                    spec = read
 40                    problems += more
 41                } catch {
 42                    problems.append("\(name): \(error)")
 43                }
 44            } else {
 45                problems.append("config.toml: theme-file \(name) can't be read")
 46            }
 47        }
 48        let (merged, more) = ThemeSpec.reading(tables, over: spec)
 49        return (merged, problems + more)
 50    }
 51
 52    /// Where earlier versions kept the configuration files.
 53    public static var legacyDirectory: URL {
 54        FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Orgstar")
 55    }
 56
 57    /// A file of the configuration folder; one that exists only where earlier versions kept
 58    /// it (Application Support) is still read from there.
 59    public static func file(_ name: String) -> URL {
 60        let url = directory.appendingPathComponent(name)
 61        let legacy = legacyDirectory.appendingPathComponent(name)
 62        let manager = FileManager.default
 63        if !manager.fileExists(atPath: url.path), manager.fileExists(atPath: legacy.path) { return legacy }
 64        return url
 65    }
 66
 67    public static var configFile: URL { directory.appendingPathComponent("config.toml") }
 68
 69    /// One setting: where it sits in the file, its user-defaults key, and how values convert.
 70    /// Settings Emacs has a variable for sit at the top of the file under that variable's
 71    /// name; the rest go in `[orgstar]`.
 72    public struct Setting: Sendable {
 73        public enum Kind: Sendable {
 74            case bool, integer, string
 75            /// A string in the file for each stored value.
 76            case choice([(name: String, stored: String)])
 77            case integerChoice([(name: String, stored: Int)])
 78            /// `org-agenda-start-day`: `"-3d"` in the file, -3 stored.
 79            case dayOffset
 80            /// `display-line-numbers-type`: `true`, `false`, `"relative"` or `"visual"`, stored as
 81            /// a switch and, in `lineNumbersType`, the kind.
 82            case lineNumbers
 83        }
 84
 85        public let section: String
 86        public let key: String
 87        public let defaultsKey: String
 88        public let kind: Kind
 89        public let fallback: TOML.Value
 90        public let comment: String
 91        /// Where earlier versions of the file kept it, `section.key`.
 92        public let legacy: String
 93
 94        public var path: String { section.isEmpty ? key : section + "." + key }
 95    }
 96
 97    public static let settings: [Setting] = [
 98        Setting(section: "", key: "fill-column", defaultsKey: "fillColumn", kind: .integer, fallback: .integer(80),
 99                comment: "M-q fills to this column", legacy: "editor.fill-column"),
100        Setting(section: "", key: "org-tags-column", defaultsKey: "tagsColumn", kind: .integer, fallback: .integer(-77),
101                comment: "negative: tags end at that column; 0: one space before them", legacy: "editor.tags-column"),
102        Setting(section: "", key: "org-insert-heading-respect-content", defaultsKey: "headingAfterSubtree", kind: .bool, fallback: .bool(false),
103                comment: "M-RET adds the new heading after the subtree", legacy: "editor.insert-heading-respect-content"),
104        Setting(section: "", key: "org-M-RET-may-split-line", defaultsKey: "splitLine", kind: .bool, fallback: .bool(false),
105                comment: "M-RET splits the line at the caret", legacy: "editor.meta-return-may-split-line"),
106        Setting(section: "", key: "org-use-property-inheritance", defaultsKey: "propertyInheritance", kind: .string, fallback: .string("nil"),
107                comment: "nil, t, or property names that inherit, separated by spaces, such as \"STYLE\"", legacy: ""),
108        Setting(section: "", key: "org-list-allow-alphabetical", defaultsKey: "alphabeticalLists", kind: .bool, fallback: .bool(true),
109                comment: "lists can use a. b. c.", legacy: "editor.list-allow-alphabetical"),
110        Setting(section: "", key: "org-hide-emphasis-markers", defaultsKey: "hiddenMarkers", kind: .bool, fallback: .bool(true),
111                comment: "hide *bold* and =code= markers when markup is hidden", legacy: "editor.hide-emphasis-markers"),
112        Setting(section: "", key: "org-pretty-entities", defaultsKey: "prettyEntities", kind: .bool, fallback: .bool(true),
113                comment: "\\alpha shows as α and x_{1} is lowered when markup is hidden", legacy: "editor.pretty-entities"),
114        Setting(section: "", key: "org-todo-keywords", defaultsKey: "todoKeywords", kind: .string, fallback: .string("TODO | DONE"),
115                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"),
116        Setting(section: "", key: "org-log-done", defaultsKey: "logDone", kind: .choice([("nil", "nil"), ("time", "time"), ("note", "note")]),
117                fallback: .string("nil"), comment: "nil, time (CLOSED when done) or note (CLOSED and a note)", legacy: ""),
118        Setting(section: "", key: "org-log-reschedule", defaultsKey: "logReschedule", kind: .choice([("nil", "nil"), ("time", "time"), ("note", "note")]),
119                fallback: .string("nil"), comment: "nil, time or note: log changing or removing a SCHEDULED date", legacy: ""),
120        Setting(section: "", key: "org-log-redeadline", defaultsKey: "logRedeadline", kind: .choice([("nil", "nil"), ("time", "time"), ("note", "note")]),
121                fallback: .string("nil"), comment: "nil, time or note: log changing or removing a DEADLINE", legacy: ""),
122        Setting(section: "", key: "org-log-into-drawer", defaultsKey: "logIntoDrawer", kind: .string, fallback: .string(""),
123                comment: "the drawer state notes go in (\"LOGBOOK\" is Emacs's t); \"\" for none", legacy: ""),
124        Setting(section: "", key: "org-enforce-todo-dependencies", defaultsKey: "enforceTodoDependencies", kind: .bool, fallback: .bool(false),
125                comment: "an entry can't be done before its TODO children, or under an ORDERED parent before its earlier siblings", legacy: ""),
126        Setting(section: "", key: "org-enforce-todo-checkbox-dependencies", defaultsKey: "enforceTodoCheckboxDependencies", kind: .bool, fallback: .bool(false),
127                comment: "an entry can't be done while it has unchecked boxes", legacy: ""),
128        Setting(section: "", key: "org-archive-location", defaultsKey: "archiveLocation", kind: .string, fallback: .string("%s_archive::"),
129                comment: "where Archive Subtree moves an entry without an ARCHIVE property or #+ARCHIVE: file::heading, %s the file's name", legacy: ""),
130        Setting(section: "", key: "org-export-default-language", defaultsKey: "exportLanguage", kind: .string, fallback: .string("en"),
131                comment: "the language of exports without #+LANGUAGE and of clock tables without :lang, such as \"de\"", legacy: ""),
132        Setting(section: "", key: "org-use-tag-inheritance", defaultsKey: "tagInheritance", kind: .string, fallback: .string("t"),
133                comment: "t, nil, tags that inherit separated by spaces, or a regexp in braces such as \"{^@}\"", legacy: ""),
134        Setting(section: "", key: "org-tags-exclude-from-inheritance", defaultsKey: "tagsExcludedFromInheritance", kind: .string, fallback: .string(""),
135                comment: "tags that never inherit, separated by spaces", legacy: ""),
136        Setting(section: "", key: "org-tag-alist", defaultsKey: "tagAlist", kind: .string, fallback: .string(""),
137                comment: "tags C-c C-q offers in files without #+TAGS, in #+TAGS syntax: \"work(w) home(h) { @office(o) @home(H) }\"", legacy: ""),
138        Setting(section: "", key: "org-track-ordered-property-with-tag", defaultsKey: "trackOrderedTag", kind: .string, fallback: .string("nil"),
139                comment: "nil, t (the tag ORDERED) or a tag that Toggle ORDERED Property toggles too", legacy: ""),
140        Setting(section: "", key: "org-startup-indented", defaultsKey: "startupIndented", kind: .bool, fallback: .bool(true),
141                comment: "indent bodies under their headings (org-indent-mode); #+STARTUP: (no)indent overrides", legacy: ""),
142        Setting(section: "", key: "org-hide-leading-stars", defaultsKey: "hideLeadingStars", kind: .bool, fallback: .bool(false),
143                comment: "show only a heading's last star without indentation; #+STARTUP: hidestars/showstars overrides", legacy: ""),
144        Setting(section: "", key: "org-startup-align-all-tables", defaultsKey: "startupAlignAllTables", kind: .bool, fallback: .bool(false),
145                comment: "align every table when a file opens; #+STARTUP: (no)align overrides", legacy: ""),
146        Setting(section: "", key: "org-startup-truncated", defaultsKey: "startupTruncated", kind: .bool, fallback: .bool(false),
147                comment: "truncate long lines instead of wrapping them (Emacs's default is t; Doom wraps)", legacy: ""),
148        Setting(section: "", key: "spell-check", defaultsKey: "spellCheck", kind: .bool, fallback: .bool(false),
149                comment: "check spelling while typing, outside code, links, dates, tags and keywords", legacy: ""),
150        Setting(section: "", key: "electric-pair-mode", defaultsKey: "electricPair", kind: .bool, fallback: .bool(true),
151                comment: "type brackets, <> and quotes in pairs as electric-pair-mode does (off in plain Emacs; Doom pairs with smartparens)", legacy: ""),
152        Setting(section: "", key: "org-startup-with-inline-images", defaultsKey: "startupWithInlineImages", kind: .bool, fallback: .bool(false),
153                comment: "show image links as images when a file opens; #+STARTUP: (no)inlineimages overrides", legacy: ""),
154        Setting(section: "", key: "org-startup-with-latex-preview", defaultsKey: "startupWithLatexPreview", kind: .bool, fallback: .bool(false),
155                comment: "show LaTeX fragments as typeset math when a file opens; #+STARTUP: (no)latexpreview overrides", legacy: ""),
156        Setting(section: "", key: "org-roam-directory", defaultsKey: "roamDirectory", kind: .string, fallback: .string(""),
157                comment: "the folder org-roam notes are in; empty for the first folder", legacy: ""),
158        Setting(section: "", key: "org-roam-dailies-directory", defaultsKey: "dailiesDirectory", kind: .string, fallback: .string("daily/"),
159                comment: "the folder daily notes are in, relative to org-roam-directory", legacy: ""),
160        Setting(section: "", key: "org-roam-dailies-file", defaultsKey: "dailiesFile", kind: .string, fallback: .string("%<%Y-%m-%d>.org"),
161                comment: "a daily note's file name; %<...> formats the date as format-time-string does", legacy: ""),
162        Setting(section: "", key: "org-roam-dailies-head", defaultsKey: "dailiesHead", kind: .string, fallback: .string("#+title: %<%Y-%m-%d>\n"),
163                comment: "what a new daily note starts with, under its ID", legacy: ""),
164        Setting(section: "", key: "org-roam-dailies-entry", defaultsKey: "dailiesEntry", kind: .string, fallback: .string("* %?"),
165                comment: "the capture template Capture to Daily Note files", legacy: ""),
166        Setting(section: "", key: "auto-fill-mode", defaultsKey: "autoFill", kind: .bool, fallback: .bool(false),
167                comment: "typing a space past fill-column breaks the line (View ▸ Auto Fill)", legacy: ""),
168        Setting(section: "", key: "org-timer-format", defaultsKey: "timerFormat", kind: .string, fallback: .string("%s "),
169                comment: "how Insert Timer Value writes the timer; %s is h:mm:ss", legacy: ""),
170        Setting(section: "", key: "org-timer-default-timer", defaultsKey: "timerDefault", kind: .string, fallback: .string("0"),
171                comment: "the countdown Set Countdown Timer offers, in minutes or h:mm:ss; 0 offers none", legacy: ""),
172        Setting(section: "", key: "org-attach-id-dir", defaultsKey: "attachIDDir", kind: .string, fallback: .string("data/"),
173                comment: "the folder attachment folders named by ID go in, relative to the org file's folder unless absolute", legacy: ""),
174        Setting(section: "", key: "org-attach-use-inheritance", defaultsKey: "attachUseInheritance",
175                kind: .choice([("selective", "selective"), ("t", "t"), ("nil", "nil")]), fallback: .string("selective"),
176                comment: "whether DIR and ID inherit for attachments: selective (as org-use-property-inheritance), t or nil", legacy: ""),
177        Setting(section: "", key: "org-yank-image-save-method", defaultsKey: "yankImageSaveMethod", kind: .string, fallback: .string("attach"),
178                comment: "where pasted images go: attach (the entry's attachments) or a folder, relative to the org file's folder unless absolute", legacy: ""),
179        Setting(section: "", key: "org-yank-dnd-method", defaultsKey: "yankDndMethod",
180                kind: .choice([("ask", "ask"), ("attach", "attach"), ("open", "open"), ("file-link", "file-link")]), fallback: .string("ask"),
181                comment: "files dropped on the editor: ask, attach, open or file-link", legacy: ""),
182        Setting(section: "", key: "org-crypt-tag-matcher", defaultsKey: "cryptTagMatcher", kind: .string, fallback: .string("crypt"),
183                comment: "the tag of entries Encrypt Tagged Entries encrypts", legacy: ""),
184        Setting(section: "", key: "org-display-remote-inline-images", defaultsKey: "remoteInlineImages",
185                kind: .choice([("skip", "skip"), ("download", "download"), ("cache", "cache")]), fallback: .string("skip"),
186                comment: "images at http(s) links: skip, download (each run) or cache (kept on disk)", legacy: ""),
187        Setting(section: "", key: "org-use-speed-commands", defaultsKey: "useSpeedCommands", kind: .bool, fallback: .bool(false),
188                comment: "single keys at the start of a heading line run commands (n, p, t, c, …)", legacy: ""),
189        Setting(section: "", key: "org-cycle-hide-drawer-startup", defaultsKey: "hideDrawerStartup", kind: .bool, fallback: .bool(true),
190                comment: "fold drawers when a file opens; #+STARTUP: nohidedrawers overrides", legacy: ""),
191        Setting(section: "", key: "org-cycle-hide-block-startup", defaultsKey: "hideBlockStartup", kind: .bool, fallback: .bool(false),
192                comment: "fold blocks when a file opens; #+STARTUP: hideblocks overrides", legacy: ""),
193        Setting(section: "", key: "display-line-numbers-type", defaultsKey: "showLineNumbers", kind: .lineNumbers, fallback: .bool(false),
194                comment: "line numbers: true, false, \"relative\" or \"visual\" (View ▸ Line Numbers)", legacy: "editor.line-numbers"),
195        Setting(section: "", key: "org-agenda-span", defaultsKey: "agendaSpan", kind: .integer, fallback: .integer(10),
196                comment: "days the agenda shows", legacy: "agenda.span"),
197        Setting(section: "", key: "org-agenda-start-day", defaultsKey: "agendaStartOffset", kind: .dayOffset, fallback: .string("+0d"),
198                comment: "the agenda's first day: \"-3d\", \"+0d\"", legacy: "agenda.start-offset"),
199        Setting(section: "", key: "org-deadline-warning-days", defaultsKey: "deadlineWarningDays", kind: .integer, fallback: .integer(14),
200                comment: "days ahead the agenda warns about a deadline; a -Nd cookie overrides", legacy: ""),
201        Setting(section: "", key: "org-agenda-start-on-weekday", defaultsKey: "agendaStartOnWeekday",
202                kind: .choice([("nil", "nil")] + (0...6).map { ("\($0)", "\($0)") }), fallback: .string("1"),
203                comment: "weeks start on this day, 0 Sunday to 6 Saturday, or nil for the agenda's first day", legacy: ""),
204        Setting(section: "", key: "org-agenda-show-all-dates", defaultsKey: "agendaShowAllDates", kind: .bool, fallback: .bool(false),
205                comment: "show days with no entries (Emacs's default is t; orgstar hides them); today always shows", legacy: ""),
206        Setting(section: "", key: "org-agenda-skip-scheduled-if-done", defaultsKey: "agendaSkipScheduledIfDone", kind: .bool, fallback: .bool(false),
207                comment: "leave done entries out of the agenda even on the day they are scheduled", legacy: ""),
208        Setting(section: "", key: "org-agenda-skip-deadline-if-done", defaultsKey: "agendaSkipDeadlineIfDone", kind: .bool, fallback: .bool(false),
209                comment: "leave done entries out of the agenda even on the day they are due", legacy: ""),
210        Setting(section: "", key: "org-habit-show-habits-only-for-today", defaultsKey: "habitsOnlyForToday", kind: .bool, fallback: .bool(true),
211                comment: "habits show only on today's agenda, not on the later days they are scheduled for", legacy: ""),
212        Setting(section: "", key: "org-agenda-log-mode-items", defaultsKey: "agendaLogModeItems", kind: .string, fallback: .string("closed clock"),
213                comment: "what log mode shows, separated by spaces: closed, clock, state", legacy: ""),
214        Setting(section: "", key: "org-agenda-todo-ignore-with-date", defaultsKey: "agendaTodoIgnoreWithDate", kind: .bool, fallback: .bool(false),
215                comment: "the TODO list leaves out entries with any active timestamp", legacy: ""),
216        Setting(section: "", key: "org-agenda-todo-ignore-scheduled", defaultsKey: "agendaTodoIgnoreScheduled", kind: .string, fallback: .string("nil"),
217                comment: "the TODO list leaves out scheduled entries: nil, all, future, past, or days ahead (negative: days ago)", legacy: ""),
218        Setting(section: "", key: "org-agenda-todo-ignore-deadlines", defaultsKey: "agendaTodoIgnoreDeadlines", kind: .string, fallback: .string("nil"),
219                comment: "the TODO list leaves out entries with deadlines: nil, near, far, all, future, past, or days", legacy: ""),
220        Setting(section: "", key: "org-agenda-todo-ignore-timestamp", defaultsKey: "agendaTodoIgnoreTimestamp", kind: .string, fallback: .string("nil"),
221                comment: "the TODO list leaves out entries with other active timestamps: nil, all, future, past, or days", legacy: ""),
222        Setting(section: "", key: "org-agenda-tags-todo-honor-ignore-options", defaultsKey: "agendaTagsTodoHonorIgnore", kind: .bool, fallback: .bool(false),
223                comment: "the org-agenda-todo-ignore settings apply to TODO-only matches too", legacy: ""),
224        Setting(section: "", key: "org-agenda-search-view-always-boolean", defaultsKey: "agendaSearchAlwaysBoolean", kind: .bool, fallback: .bool(false),
225                comment: "search strings are always +word -word {regexp} snippets, never a phrase", legacy: ""),
226        Setting(section: "", key: "org-agenda-search-view-force-full-words", defaultsKey: "agendaSearchForceFullWords", kind: .bool, fallback: .bool(false),
227                comment: "search snippets match whole words only", legacy: ""),
228        Setting(section: "", key: "org-agenda-dim-blocked-tasks", defaultsKey: "agendaDimBlockedTasks",
229                kind: .choice([("t", "t"), ("nil", "nil"), ("invisible", "invisible")]), fallback: .string("t"),
230                comment: "t dims entries the enforce settings block, invisible hides them (unless only checkboxes block them), nil shows them as usual", legacy: ""),
231        Setting(section: "", key: "appt-message-warning-time", defaultsKey: "reminderLead", kind: .integer, fallback: .integer(12),
232                comment: "minutes of warning before timed entries; APPT_WARNTIME overrides", legacy: "agenda.reminder-lead"),
233        Setting(section: "", key: "org-clock-idle-time", defaultsKey: "clockIdleTime", kind: .integer, fallback: .integer(0),
234                comment: "minutes idle with a clock running before asking what to do with the time; 0 never (nil)", legacy: ""),
235        Setting(section: "", key: "org-clock-into-drawer", defaultsKey: "clockIntoDrawer", kind: .string, fallback: .string("t"),
236                comment: "t: clock lines go in the log drawer (LOGBOOK); nil: none; a number: once there are that many; or a drawer name", legacy: ""),
237        Setting(section: "", key: "org-clock-rounding-minutes", defaultsKey: "clockRoundingMinutes", kind: .integer, fallback: .integer(0),
238                comment: "clocks start and end on multiples of this many minutes; 0 doesn't round", legacy: ""),
239        Setting(section: "", key: "org-clock-out-remove-zero-time-clocks", defaultsKey: "clockRemoveZeroTime", kind: .bool, fallback: .bool(false),
240                comment: "clocking out removes a clock line of 0:00", legacy: ""),
241        Setting(section: "", key: "org-clock-in-switch-to-state", defaultsKey: "clockInSwitchToState", kind: .string, fallback: .string(""),
242                comment: "the TODO keyword an entry takes when you clock in; \"\" leaves it", legacy: ""),
243        Setting(section: "", key: "org-clock-out-when-done", defaultsKey: "clockOutWhenDone", kind: .string, fallback: .string("t"),
244                comment: "t: marking the clocked entry done clocks out; nil: it doesn't; or keywords that clock out, separated by spaces", legacy: ""),
245        Setting(section: "", key: "org-clock-history-length", defaultsKey: "clockHistoryLength", kind: .integer, fallback: .integer(5),
246                comment: "recently clocked entries to remember", legacy: ""),
247        Setting(section: "", key: "org-refile-targets", defaultsKey: "refileTargets", kind: .string, fallback: .string(""),
248                comment: "as Lisp: ((nil :maxlevel . 3) (org-agenda-files :tag . \"project\")); \"\" offers headings to level 3 in every file", legacy: ""),
249        Setting(section: "", key: "org-refile-use-outline-path", defaultsKey: "refileUseOutlinePath", kind: .string, fallback: .string("file"),
250                comment: "how targets are named: nil, t, file, full-file-path, buffer-name or title", legacy: ""),
251        Setting(section: "", key: "org-refile-allow-creating-parent-nodes", defaultsKey: "refileAllowCreatingParentNodes", kind: .string, fallback: .string("nil"),
252                comment: "a target typed as parent/new adds the heading: t, confirm (asks first) or nil", legacy: ""),
253        Setting(section: "", key: "org-agenda-files", defaultsKey: "agendaFiles", kind: .string, fallback: .string(""),
254                comment: "files and folders the agenda reads, separated by \\n; a file that isn't .org lists more, one per line; \"\" reads the folders' files", legacy: ""),
255        Setting(section: "", key: "org-icalendar-use-deadline", defaultsKey: "icalendarUseDeadline", kind: .string, fallback: .string("event-if-not-todo todo-due"),
256                comment: "iCalendar export: what a DEADLINE makes, of event-if-not-todo, event-if-todo, event-if-todo-not-done and todo-due", legacy: ""),
257        Setting(section: "", key: "org-icalendar-use-scheduled", defaultsKey: "icalendarUseScheduled", kind: .string, fallback: .string("todo-start"),
258                comment: "iCalendar export: what SCHEDULED makes, of event-if-not-todo, event-if-todo, event-if-todo-not-done and todo-start", legacy: ""),
259        Setting(section: "", key: "org-icalendar-include-todo", defaultsKey: "icalendarIncludeTodo", kind: .string, fallback: .string("nil"),
260                comment: "iCalendar export: tasks as VTODOs: nil, t (not done), all, unblocked, or TODO keywords separated by spaces", legacy: ""),
261        Setting(section: "", key: "org-icalendar-combined-agenda-file", defaultsKey: "icalendarCombinedAgendaFile", kind: .string, fallback: .string("~/org.ics"),
262                comment: "where Combine Agenda Files into iCalendar writes", legacy: ""),
263        Setting(section: "", key: "org-agenda-use-time-grid", defaultsKey: "agendaUseTimeGrid", kind: .bool, fallback: .bool(true),
264                comment: "time grid lines among timed entries, as [org-agenda-time-grid] says", legacy: ""),
265        Setting(section: "", key: "org-agenda-show-current-time-in-grid", defaultsKey: "agendaShowCurrentTime", kind: .bool, fallback: .bool(true),
266                comment: "the now line on today's grid", legacy: ""),
267        Setting(section: "", key: "org-agenda-sort-notime-is-late", defaultsKey: "agendaSortNotimeIsLate", kind: .bool, fallback: .bool(true),
268                comment: "lines without a time sort after timed ones for time-up, and without a date after dated ones", legacy: ""),
269        Setting(section: "", key: "org-agenda-sort-noeffort-is-high", defaultsKey: "agendaSortNoeffortIsHigh", kind: .bool, fallback: .bool(true),
270                comment: "entries without an effort sort as the longest for effort-up", legacy: ""),
271        Setting(section: "org-agenda-prefix-format", key: "agenda", defaultsKey: "agendaPrefixAgenda", kind: .string, fallback: .string(PrefixFormat.defaults["agenda"]!),
272                comment: "%c category, %t time, %s scheduled/deadline, %e effort, %l level, %b outline path; %-12 pads", legacy: ""),
273        Setting(section: "org-agenda-prefix-format", key: "todo", defaultsKey: "agendaPrefixTodo", kind: .string, fallback: .string(PrefixFormat.defaults["todo"]!),
274                comment: "the TODO list", legacy: ""),
275        Setting(section: "org-agenda-prefix-format", key: "tags", defaultsKey: "agendaPrefixTags", kind: .string, fallback: .string(PrefixFormat.defaults["tags"]!),
276                comment: "tag and property matches", legacy: ""),
277        Setting(section: "org-agenda-sorting-strategy", key: "agenda", defaultsKey: "agendaSortAgenda", kind: .string, fallback: .string(AgendaSort.defaults["agenda"]!.joined(separator: " ")),
278                comment: "how lines of a day are ordered: time-up, priority-down, category-keep, alpha-up, effort-up, tag-up, todo-state-up, …", legacy: ""),
279        Setting(section: "org-agenda-sorting-strategy", key: "todo", defaultsKey: "agendaSortTodo", kind: .string, fallback: .string(AgendaSort.defaults["todo"]!.joined(separator: " ")),
280                comment: "the TODO list", legacy: ""),
281        Setting(section: "org-agenda-sorting-strategy", key: "tags", defaultsKey: "agendaSortTags", kind: .string, fallback: .string(AgendaSort.defaults["tags"]!.joined(separator: " ")),
282                comment: "tag and property matches", legacy: ""),
283        Setting(section: "org-agenda-sorting-strategy", key: "search", defaultsKey: "agendaSortSearch", kind: .string, fallback: .string(AgendaSort.defaults["search"]!.joined(separator: " ")),
284                comment: "text search", legacy: ""),
285        Setting(section: "org-stuck-projects", key: "match", defaultsKey: "stuckProjectsMatch", kind: .string, fallback: .string("+LEVEL=2/-DONE"),
286                comment: "the entries that are projects, as a tag and property match", legacy: ""),
287        Setting(section: "org-stuck-projects", key: "todo", defaultsKey: "stuckProjectsTodo", kind: .string, fallback: .string("TODO NEXT NEXTACTION"),
288                comment: "a heading in the project with one of these keywords unsticks it; * for any open keyword", legacy: ""),
289        Setting(section: "org-stuck-projects", key: "tags", defaultsKey: "stuckProjectsTags", kind: .string, fallback: .string(""),
290                comment: "a heading in the project with one of these tags unsticks it; * for any tag", legacy: ""),
291        Setting(section: "org-stuck-projects", key: "regexp", defaultsKey: "stuckProjectsRegexp", kind: .string, fallback: .string(""),
292                comment: "text in the project matching this Emacs regexp unsticks it", legacy: ""),
293        Setting(section: "org-agenda-time-grid", key: "when", defaultsKey: "agendaTimeGridWhen", kind: .string, fallback: .string("daily today require-timed"),
294                comment: "daily (one-day views), today, weekly (every day), require-timed (only with timed entries), remove-match (no line at an entry's time)", legacy: ""),
295        Setting(section: "org-agenda-time-grid", key: "times", defaultsKey: "agendaTimeGridTimes", kind: .string, fallback: .string("800 1000 1200 1400 1600 1800 2000"),
296                comment: "the grid's times as HHMM, separated by spaces", legacy: ""),
297        Setting(section: "theme", key: "font", defaultsKey: "themeFont", kind: .string, fallback: .string(""),
298                comment: "a monospaced font family; \"\" for the system's", legacy: ""),
299        Setting(section: "theme", key: "body-font", defaultsKey: "themeBodyFont", kind: .string, fallback: .string(""),
300                comment: "a font family for prose, or \"system\"; tables, code, dates and tags keep the font above; \"\" for the font above throughout", legacy: ""),
301        Setting(section: "theme", key: "font-size", defaultsKey: "themeFontSize", kind: .integer, fallback: .integer(13),
302                comment: "points", legacy: ""),
303        Setting(section: "theme", key: "line-spacing", defaultsKey: "themeLineSpacing", kind: .integer, fallback: .integer(2),
304                comment: "points between lines", legacy: ""),
305        Setting(section: "theme", key: "text-width", defaultsKey: "themeTextWidth", kind: .integer, fallback: .integer(0),
306                comment: "the widest the text runs, in columns, centred in a wider editor; 0 for the whole width", legacy: ""),
307        Setting(section: "theme", key: "heading-size-step", defaultsKey: "themeHeadingStep", kind: .integer, fallback: .integer(1),
308                comment: "points a heading is larger than the level below; level 4 and deeper are body size", legacy: ""),
309        Setting(section: "theme", key: "theme-file", defaultsKey: "themeFile", kind: .string, fallback: .string(""),
310                comment: "a theme in its own file in this folder, under the colors set here; colors: see default-theme.toml", legacy: ""),
311        Setting(section: "theme", key: "light-theme", defaultsKey: "themeLight", kind: .string, fallback: .string("default-light"),
312                comment: "the built-in theme for the light appearance: default-light, solarized-light, gruvbox-light, modus-operandi, catppuccin-latte, tomorrow or paper", legacy: ""),
313        Setting(section: "theme", key: "dark-theme", defaultsKey: "themeDark", kind: .string, fallback: .string("default-dark"),
314                comment: "the built-in theme for the dark appearance: default-dark, solarized-dark, gruvbox-dark, modus-vivendi, catppuccin-mocha, nord, dracula, tokyo-night or doom-one", legacy: ""),
315        Setting(section: "orgstar", key: "save", defaultsKey: "saveMode", kind: .choice([("automatic", "automatic"), ("explicit", "explicit")]),
316                fallback: .string("automatic"), comment: "automatic (1 s after typing stops) or explicit (only with ⌘S)", legacy: "general.save"),
317        Setting(section: "orgstar", key: "keymap", defaultsKey: "keymap", kind: .choice([("emacs", "emacs"), ("mac", "mac"), ("doom", "doom")]),
318                fallback: .string("emacs"), comment: "emacs, mac or doom; your own bindings go in keymap.toml", legacy: "general.keymap"),
319        Setting(section: "orgstar", key: "option-as-meta", defaultsKey: "optionAsMeta",
320                kind: .integerChoice([("left", 1), ("right", 2), ("both", 3), ("none", 0)]), fallback: .string("left"),
321                comment: "left, right, both or none", legacy: "general.option-as-meta"),
322        Setting(section: "orgstar", key: "pdf-margin", defaultsKey: "pdfMargin", kind: .integer, fallback: .integer(50),
323                comment: "PDF export's page margins, in points", legacy: ""),
324        Setting(section: "orgstar", key: "pdf-font", defaultsKey: "pdfFont", kind: .string, fallback: .string(""),
325                comment: "a font family for PDF export's text; \"\" for the export's own", legacy: ""),
326        Setting(section: "orgstar", key: "pdf-page-numbers", defaultsKey: "pdfPageNumbers", kind: .bool, fallback: .bool(true),
327                comment: "number PDF export's pages", legacy: ""),
328        Setting(section: "orgstar", key: "tab-bar", defaultsKey: "showTabBar", kind: .bool, fallback: .bool(false),
329                comment: "a tab for each open buffer above the editor (View ▸ Show Tab Bar)", legacy: ""),
330        Setting(section: "orgstar", key: "show-markup", defaultsKey: "showMarkup", kind: .bool, fallback: .bool(false),
331                comment: "show link brackets and emphasis markers (View ▸ Show Markup)", legacy: "editor.show-markup"),
332        Setting(section: "orgstar", key: "show-hidden-files", defaultsKey: "showHiddenFiles", kind: .bool, fallback: .bool(true),
333                comment: "list dotfiles and dot folders in your folders", legacy: ""),
334        Setting(section: "orgstar", key: "ignored-folders", defaultsKey: "ignoredFolders", kind: .string,
335                fallback: .string(ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ")),
336                comment: "folder names never listed or searched, separated by spaces", legacy: ""),
337        Setting(section: "orgstar", key: "agenda-include-subfolders", defaultsKey: "agendaSubfolders", kind: .bool, fallback: .bool(false),
338                comment: "the agenda reads org files in subfolders too", legacy: "agenda.include-subfolders"),
339        Setting(section: "orgstar", key: "reminders", defaultsKey: "reminders", kind: .bool, fallback: .bool(true),
340                comment: "notify before timed entries", legacy: "agenda.reminders"),
341        Setting(section: "orgstar", key: "calendar-events", defaultsKey: "calendarEvents", kind: .bool, fallback: .bool(false),
342                comment: "show events from Calendar in the agenda", legacy: ""),
343        Setting(section: "orgstar", key: "calendar-event-calendars", defaultsKey: "calendarEventCalendars", kind: .string, fallback: .string(""),
344                comment: "the calendars whose events show, by title or identifier, separated by commas; \"\" for all", legacy: ""),
345        Setting(section: "orgstar", key: "agenda-reminders", defaultsKey: "agendaReminders", kind: .bool, fallback: .bool(false),
346                comment: "show incomplete reminders with a due date from Reminders in the agenda, read-only", legacy: ""),
347        Setting(section: "orgstar", key: "agenda-reminder-lists", defaultsKey: "agendaReminderLists", kind: .string, fallback: .string(""),
348                comment: "the Reminders lists shown, by title or identifier, separated by commas; \"\" for all", legacy: ""),
349        Setting(section: "orgstar", key: "global-capture-hotkey", defaultsKey: "globalCapture", kind: .bool, fallback: .bool(true),
350                comment: "⌃⌥Space opens Capture from any app; templates go in capture.toml", legacy: "capture.global-hotkey"),
351    ]
352
353    /// `"-3d"` as -3; nil for anything else.
354    static func dayOffset(_ s: String) -> Int? {
355        guard s.hasSuffix("d"), let n = Int(s.dropLast().replacingOccurrences(of: "+", with: "")) else { return nil }
356        return n
357    }
358
359    // MARK: - Values
360
361    /// The file value for what `defaults` holds, or the fallback.
362    public static func value(_ setting: Setting, in defaults: UserDefaults) -> TOML.Value {
363        guard defaults.object(forKey: setting.defaultsKey) != nil else { return setting.fallback }
364        switch setting.kind {
365        case .bool: return .bool(defaults.bool(forKey: setting.defaultsKey))
366        case .integer: return .integer(defaults.integer(forKey: setting.defaultsKey))
367        case .string: return .string(defaults.string(forKey: setting.defaultsKey) ?? "")
368        case .choice(let choices):
369            let stored = defaults.string(forKey: setting.defaultsKey)
370            return choices.first { $0.stored == stored }.map { .string($0.name) } ?? setting.fallback
371        case .integerChoice(let choices):
372            let stored = defaults.integer(forKey: setting.defaultsKey)
373            return choices.first { $0.stored == stored }.map { .string($0.name) } ?? setting.fallback
374        case .dayOffset:
375            let days = defaults.integer(forKey: setting.defaultsKey)
376            return .string((days < 0 ? "" : "+") + "\(days)d")
377        case .lineNumbers:
378            guard defaults.bool(forKey: setting.defaultsKey) else { return .bool(false) }
379            let type = defaults.string(forKey: "lineNumbersType") ?? ""
380            return ["relative", "visual"].contains(type) ? .string(type) : .bool(true)
381        }
382    }
383
384    /// Stores a file value; a value of the wrong kind is a problem.
385    static func store(_ value: TOML.Value, _ setting: Setting, in defaults: UserDefaults) -> String? {
386        let key = setting.defaultsKey
387        switch (setting.kind, value) {
388        case (.lineNumbers, .bool(let b)):
389            defaults.set(b, forKey: key)
390            defaults.set("t", forKey: "lineNumbersType")
391        case (.lineNumbers, .string(let s)) where ["relative", "visual", "t", "nil"].contains(s):
392            defaults.set(s != "nil", forKey: key)
393            defaults.set(s == "nil" ? "t" : s, forKey: "lineNumbersType")
394        case (.bool, .bool(let b)): defaults.set(b, forKey: key)
395        case (.integer, .integer(let i)): defaults.set(i, forKey: key)
396        case (.string, .string(let s)): defaults.set(s, forKey: key)
397        case (.choice(let choices), .string(let s)):
398            guard let choice = choices.first(where: { $0.name == s }) else {
399                return "\(setting.key) must be one of \(choices.map(\.name).joined(separator: ", "))"
400            }
401            defaults.set(choice.stored, forKey: key)
402        case (.integerChoice(let choices), .string(let s)):
403            guard let choice = choices.first(where: { $0.name == s }) else {
404                return "\(setting.key) must be one of \(choices.map(\.name).joined(separator: ", "))"
405            }
406            defaults.set(choice.stored, forKey: key)
407        case (.dayOffset, .string(let s)):
408            guard let days = dayOffset(s) else { return "\(setting.key) must look like \"-3d\" or \"+0d\"" }
409            defaults.set(days, forKey: key)
410        default:
411            return "\(setting.path) has the wrong kind of value"
412        }
413        return nil
414    }
415
416    /// Applies a file to `defaults`; settings it leaves out go back to their defaults.
417    /// Returns problems.
418    @discardableResult
419    public static func apply(_ text: String, to defaults: UserDefaults) -> [String] {
420        let tables: [TOML.Table]
421        do { tables = try TOML.parse(text) } catch { return ["config.toml: \(error)"] }
422        var problems: [String] = []
423        let present = Set(tables.flatMap { table in table.values.keys.map { path(table.name, $0) } })
424        for setting in settings where !present.contains(setting.path) && !present.contains(setting.legacy) {
425            if defaults.object(forKey: setting.defaultsKey) != nil { defaults.removeObject(forKey: setting.defaultsKey) }
426        }
427        let templates = tables.first { $0.name == structureTemplateTable }
428        if templates == nil, defaults.object(forKey: structureTemplatesKey) != nil { defaults.removeObject(forKey: structureTemplatesKey) }
429        for table in tables {
430            if table.name == structureTemplateTable {
431                var rows: [String] = []
432                for key in table.keys {
433                    guard let type = table.values[key]?.string, !type.isEmpty else {
434                        problems.append("config.toml: \(structureTemplateTable).\(key) must be a block type, such as \"src python\"")
435                        continue
436                    }
437                    rows.append(key + "\t" + type)
438                }
439                if defaults.stringArray(forKey: structureTemplatesKey) != rows { defaults.set(rows, forKey: structureTemplatesKey) }
440                continue
441            }
442            // Colors are the theme's to read; publishing projects are `Publish`'s.
443            if ThemeSpec.isThemeTable(table.name), table.name != "theme" { continue }
444            if table.name == "publish", table.isArrayElement { continue }
445            for (key, value) in table.values.sorted(by: { $0.key < $1.key }) {
446                if table.name == "theme", !ThemeSpec.typeKeys.contains(key) { continue }
447                let name = path(table.name, key)
448                guard let setting = settings.first(where: { $0.path == name || $0.legacy == name }) else {
449                    problems.append("config.toml: unknown setting \(name)")
450                    continue
451                }
452                if let current = currentValue(setting, in: defaults), current == value { continue }
453                if let problem = store(value, setting, in: defaults) { problems.append("config.toml: \(problem)") }
454            }
455        }
456        return problems
457    }
458
459    /// `[org-structure-template-alist]`: block templates by key, over Org's, as
460    /// `key = "type"`. Kept in user defaults under `structureTemplatesKey` as `key<Tab>type`.
461    public static let structureTemplateTable = "org-structure-template-alist"
462    static let structureTemplatesKey = "structureTemplates"
463
464    /// The templates of `[org-structure-template-alist]`.
465    public static func structureTemplates(_ defaults: UserDefaults) -> [StructureTemplate] {
466        (defaults.stringArray(forKey: structureTemplatesKey) ?? []).compactMap { row in
467            guard let tab = row.firstIndex(of: "\t") else { return nil }
468            return StructureTemplate(key: String(row[..<tab]), type: String(row[row.index(after: tab)...]))
469        }
470    }
471
472    public static func setStructureTemplates(_ templates: [StructureTemplate], in defaults: UserDefaults) {
473        defaults.set(templates.map { $0.key + "\t" + $0.type }, forKey: structureTemplatesKey)
474    }
475
476    static func path(_ section: String, _ key: String) -> String { section.isEmpty ? key : section + "." + key }
477
478    /// Whether the file uses names from before settings took Emacs's names.
479    public static func usesLegacyNames(_ text: String) -> Bool {
480        let names = Set(settings.map(\.legacy))
481        return values(in: text).keys.contains { names.contains($0) }
482    }
483
484    /// `text` with settings under their old names moved to their current names and places,
485    /// keeping comments and everything else. A section the move leaves empty is removed.
486    public static func migratingLegacyNames(_ text: String) -> String {
487        let values = values(in: text)
488        var blocks: [[String]] = [[]]
489        for line in text.components(separatedBy: "\n") {
490            if line.trimmingCharacters(in: .whitespaces).hasPrefix("[") { blocks.append([]) }
491            blocks[blocks.count - 1].append(line)
492        }
493        var moves: [(setting: Setting, value: TOML.Value, comment: String)] = []
494        var kept: [String] = []
495        for block in blocks {
496            let header = block.first.map { $0.trimmingCharacters(in: .whitespaces) }.flatMap { $0.hasPrefix("[") ? $0 : nil }
497            let section = header.map { String($0.dropFirst().prefix { $0 != "]" }).trimmingCharacters(in: .whitespaces) } ?? ""
498            var remaining: [String] = []
499            for (index, line) in block.enumerated() {
500                guard header == nil || index > 0, let equals = line.firstIndex(of: "=") else {
501                    remaining.append(line)
502                    continue
503                }
504                let name = path(section, line[..<equals].trimmingCharacters(in: .whitespaces))
505                guard let setting = settings.first(where: { !$0.legacy.isEmpty && $0.legacy == name }), let value = values[name] else {
506                    remaining.append(line)
507                    continue
508                }
509                // A setting also under its new name keeps that one.
510                if values[setting.path] == nil {
511                    moves.append((setting, value, commentStart(line, after: equals).map { String(line[$0...]) } ?? ""))
512                }
513            }
514            let emptied = header != nil && remaining.count < block.count
515                && remaining.dropFirst().allSatisfy { $0.trimmingCharacters(in: .whitespaces).isEmpty }
516            if !emptied { kept += remaining }
517        }
518        var out = kept.joined(separator: "\n")
519        if text.hasSuffix("\n"), !out.isEmpty, !out.hasSuffix("\n") { out += "\n" }
520        for move in moves {
521            out = setting(out, section: move.setting.section, key: move.setting.key, to: move.value)
522            guard !move.comment.isEmpty else { continue }
523            var lines = out.components(separatedBy: "\n")
524            if let index = lines.firstIndex(of: "\(move.setting.key) = \(format(move.value))") {
525                lines[index] += "  " + move.comment
526                out = lines.joined(separator: "\n")
527            }
528        }
529        return out
530    }
531
532    private static func currentValue(_ setting: Setting, in defaults: UserDefaults) -> TOML.Value? {
533        defaults.object(forKey: setting.defaultsKey) == nil ? nil : value(setting, in: defaults)
534    }
535
536    /// The values a file sets, by `section.key`.
537    static func values(in text: String) -> [String: TOML.Value] {
538        guard let tables = try? TOML.parse(text) else { return [:] }
539        var result: [String: TOML.Value] = [:]
540        for table in tables { for (key, value) in table.values { result[path(table.name, key)] = value } }
541        return result
542    }
543
544    // MARK: - Text
545
546    static func format(_ value: TOML.Value) -> String {
547        switch value {
548        case .bool(let b): b ? "true" : "false"
549        case .integer(let i): String(i)
550        case .string(let s):
551            "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")
552                .replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\t", with: "\\t") + "\""
553        }
554    }
555
556    /// A commented file with every setting at its current value.
557    public static func template(from defaults: UserDefaults) -> String {
558        template { value($0, in: defaults) }
559    }
560
561    /// A commented file with every setting at its default.
562    public static var defaultTemplate: String { template(\.fallback) }
563
564    private static func template(_ value: (Setting) -> TOML.Value) -> String {
565        var out = """
566            # orgstar settings. The Settings window writes its changes here, and edits made here
567            # apply while orgstar runs. Keys go in keymap.toml, capture templates in capture.toml
568            # and saved agenda views in views.toml, all in this folder.
569
570            # Emacs variables, by their Emacs names.
571
572            """
573        var section = ""
574        for setting in settings {
575            if setting.section != section {
576                section = setting.section
577                out += "\n[\(section)]\n"
578            }
579            out += "\(setting.key) = \(format(value(setting)))  # \(setting.comment)\n"
580        }
581        return out
582    }
583
584    /// `text` with the sections it lacks entirely added at the end, every setting at its
585    /// value in `defaults`: how a file from an earlier version gets settings added since.
586    /// Single lines left out stay out; they mean the default.
587    public static func addingMissingSections(_ text: String, from defaults: UserDefaults) -> String {
588        let tables = (try? TOML.parse(text)) ?? []
589        let present = Set(tables.filter { !$0.values.isEmpty || $0.name != "" }.map(\.name))
590        var out = text
591        var section: String?
592        for setting in settings where !setting.section.isEmpty && !present.contains(setting.section) {
593            if setting.section != section {
594                section = setting.section
595                if !out.hasSuffix("\n") { out += "\n" }
596                out += "\n[\(setting.section)]\n"
597            }
598            out += "\(setting.key) = \(format(value(setting, in: defaults)))  # \(setting.comment)\n"
599        }
600        return out
601    }
602
603    /// `text` with `section.key` set to `value`: the line's value is replaced (its comment
604    /// stays), or a line is added at the end of the section, or the section at the end.
605    public static func setting(_ text: String, section: String, key: String, to value: TOML.Value) -> String {
606        var lines = text.components(separatedBy: "\n")
607        var current = ""
608        var lastInSection: Int?
609        for (index, line) in lines.enumerated() {
610            let trimmed = line.trimmingCharacters(in: .whitespaces)
611            if trimmed.hasPrefix("[") {
612                // An array of tables, such as `[[publish]]`, is no section a setting is in.
613                current = trimmed.hasPrefix("[[") ? trimmed : String(trimmed.dropFirst().prefix { $0 != "]" }).trimmingCharacters(in: .whitespaces)
614                if current == section { lastInSection = index }
615                continue
616            }
617            guard current == section else { continue }
618            if !trimmed.isEmpty { lastInSection = index }
619            guard let equals = line.firstIndex(of: "="),
620                  line[..<equals].trimmingCharacters(in: .whitespaces) == key else { continue }
621            let comment = commentStart(line, after: equals).map { "  " + line[$0...] } ?? ""
622            lines[index] = line[..<equals] + "= " + format(value) + comment
623            return lines.joined(separator: "\n")
624        }
625        if let lastInSection {
626            lines.insert("\(key) = \(format(value))", at: lastInSection + 1)
627        } else if section.isEmpty {
628            let firstHeader = lines.firstIndex { $0.trimmingCharacters(in: .whitespaces).hasPrefix("[") } ?? lines.count
629            lines.insert(contentsOf: ["\(key) = \(format(value))", ""], at: firstHeader)
630        } else {
631            if lines.last == "" { lines.removeLast() }
632            lines += ["", "[\(section)]", "\(key) = \(format(value))", ""]
633        }
634        return lines.joined(separator: "\n")
635    }
636
637    /// Where a `#` comment starts after the value, outside quotes.
638    private static func commentStart(_ line: String, after equals: String.Index) -> String.Index? {
639        var quote: Character?
640        var index = line.index(after: equals)
641        while index < line.endIndex {
642            let c = line[index]
643            if let q = quote {
644                if c == "\\" && q == "\"" { index = line.index(after: index) } else if c == q { quote = nil }
645            } else if c == "\"" || c == "'" {
646                quote = c
647            } else if c == "#" {
648                return index
649            }
650            if index < line.endIndex { index = line.index(after: index) }
651        }
652        return nil
653    }
654}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form