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