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