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