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