Sources/OrgConfig/OrgPreferences.swift
297 lines · 21300 bytes
61 symbols in this file
OrgPreferencesorgSettingsexportLanguageoptionscompletionchoiceshowMarkupagendaSpanagendaStartOffsetagendaStartOnWeekdayclockOutWhenDoneagendaSubfoldersagendaExcludeArchivesagendaShowAllDatesagendaSkipScheduledIfDonehabitsOnlyForTodayagendaSkipDeadlineIfDoneagendaSearchAlwaysBooleanagendaSearchForceFullWordsagendaOptionsagendaFilesrefileSettingsicalendarOptionsroamDirectorydailiesDirectorydailiesFiledailiesHeaddailiesEntryusesDenotedenoteSiloDirectoriesdenoteDirectorydenoteJournalDirectorydenoteJournalKeyworddenoteJournalTitledenoteJournalIntervaldenoteSequenceSchemedenoteFileTypedenotePromptsattachIDDirattachUseInheritanceciteGlobalBibliographyfcReviewHistoryFileyankImageSaveMethodcryptTagcryptBeforeSaveicalendarCombinedFilestuckProjectswordssortingStrategycalendarEventscalendarEventCalendarsagendaRemindersagendaReminderListsremindersreminderLeadclockIdleTimeclockHistoryLengthfallbackboolstringinteger
1import Foundation
2import OrgCore
3
4/// The Org settings `config.toml` holds, read from user defaults with the file's fallbacks, for
5/// both apps.
6public enum OrgPreferences {
7 public static let defaultTodoKeywords = "TODO | DONE"
8
9 /// TODO keywords for files without `#+TODO`, and alphabetical lists.
10 public static func orgSettings(_ defaults: UserDefaults = .standard) -> OrgSettings {
11 let line = defaults.string(forKey: "todoKeywords") ?? defaultTodoKeywords
12 var settings = OrgSettings.default.withTodoKeywords(line) ?? .default
13 settings.listAllowAlphabetical = bool("alphabeticalLists", defaults)
14 settings.propertyInheritance = .init(string("propertyInheritance", defaults))
15 settings.deadlineWarningDays = integer("deadlineWarningDays", defaults)
16 settings.tagInheritance = .init(string("tagInheritance", defaults))
17 settings.tagsExcludedFromInheritance = Set(string("tagsExcludedFromInheritance", defaults).split(whereSeparator: \.isWhitespace).map(String.init))
18 settings.attachIDDir = attachIDDir(defaults)
19 settings.attachUseInheritance = attachUseInheritance(defaults)
20 settings.citeGlobalBibliography = citeGlobalBibliography(defaults)
21 return settings
22 }
23
24 /// The editing options, as the Mac's Settings apply them.
25 /// `org-export-default-language`.
26 public static func exportLanguage(_ defaults: UserDefaults = .standard) -> String { string("exportLanguage", defaults).nonEmpty ?? "en" }
27
28 public static func options(_ defaults: UserDefaults = .standard) -> EditingOptions {
29 var options = EditingOptions(
30 tagsColumn: integer("tagsColumn", defaults), insertHeadingRespectContent: bool("headingAfterSubtree", defaults),
31 metaReturnMaySplitLine: bool("splitLine", defaults),
32 listAllowAlphabetical: bool("alphabeticalLists", defaults), fillColumn: integer("fillColumn", defaults),
33 hideEmphasisMarkers: bool("hiddenMarkers", defaults), prettyEntities: bool("prettyEntities", defaults), subSuperscriptsNeedBraces: true,
34 logDone: LogHow(rawValue: string("logDone", defaults)), logIntoDrawer: string("logIntoDrawer", defaults).nonEmpty,
35 hideDrawerStartup: bool("hideDrawerStartup", defaults), hideBlockStartup: bool("hideBlockStartup", defaults),
36 logReschedule: LogHow(rawValue: string("logReschedule", defaults)), logRedeadline: LogHow(rawValue: string("logRedeadline", defaults)),
37 useSpeedCommands: bool("useSpeedCommands", defaults), startupWithInlineImages: bool("startupWithInlineImages", defaults),
38 startupIndented: bool("startupIndented", defaults), hideLeadingStars: bool("hideLeadingStars", defaults),
39 startupAlignAllTables: bool("startupAlignAllTables", defaults), startupTruncated: bool("startupTruncated", defaults),
40 spellCheck: bool("spellCheck", defaults)
41 )
42 options.electricPair = bool("electricPair", defaults)
43 options.autoFill = bool("autoFill", defaults)
44 options.startupWithLatexPreview = bool("startupWithLatexPreview", defaults)
45 options.remoteInlineImages = string("remoteInlineImages", defaults)
46 options.enforceTodoDependencies = bool("enforceTodoDependencies", defaults)
47 options.enforceTodoCheckboxDependencies = bool("enforceTodoCheckboxDependencies", defaults)
48 options.archiveLocation = string("archiveLocation", defaults).nonEmpty
49 options.exportLanguage = exportLanguage(defaults)
50 options.clockIntoDrawer = string("clockIntoDrawer", defaults).nonEmpty
51 options.tagAlist = string("tagAlist", defaults).nonEmpty
52 options.clockRoundingMinutes = integer("clockRoundingMinutes", defaults)
53 options.clockOutRemoveZeroTimeClocks = bool("clockRemoveZeroTime", defaults)
54 options.clockInSwitchToState = string("clockInSwitchToState", defaults).nonEmpty
55 options.timerFormat = string("timerFormat", defaults).contains("%s") ? string("timerFormat", defaults) : "%s "
56 options.timerDefault = string("timerDefault", defaults).nonEmpty ?? "0"
57 options.completion = completion(defaults)
58 let templates = UserConfig.structureTemplates(defaults)
59 options.structureTemplates = templates.isEmpty ? nil : StructureTemplate.merged(templates)
60 options.trackOrderedPropertyWithTag = switch string("trackOrderedTag", defaults) {
61 case "", "nil": nil
62 case "t": "ORDERED"
63 case let tag: tag
64 }
65 return options
66 }
67
68 /// The completion settings, `preset` resolved by the keymap preset: Doom's corfu opens
69 /// the list by itself and matches with orderless; Emacs and the Mac keys do neither.
70 public static func completion(_ defaults: UserDefaults = .standard) -> CompletionOptions {
71 let doom = string("keymap", defaults) == "doom"
72 func choice(_ key: String, on: String) -> Bool {
73 let value = string(key, defaults)
74 return value == "preset" ? doom : value == on
75 }
76 return CompletionOptions(
77 auto: choice("completionAuto", on: "on"), delay: Double(max(0, integer("completionAutoDelay", defaults))) / 1000,
78 prefix: max(1, integer("completionAutoPrefix", defaults)), fuzzy: choice("completionStyle", on: "fuzzy"), words: bool("completionWords", defaults)
79 )
80 }
81
82
83 /// `show-markup`: link brackets and emphasis markers shown.
84 public static func showMarkup(_ defaults: UserDefaults = .standard) -> Bool { bool("showMarkup", defaults) }
85
86 public static func agendaSpan(_ defaults: UserDefaults = .standard) -> Int { integer("agendaSpan", defaults) }
87 public static func agendaStartOffset(_ defaults: UserDefaults = .standard) -> Int { integer("agendaStartOffset", defaults) }
88 /// `org-agenda-start-on-weekday`: 0 is Sunday; nil for `nil`.
89 public static func agendaStartOnWeekday(_ defaults: UserDefaults = .standard) -> Int? { Int(string("agendaStartOnWeekday", defaults)) }
90 /// `org-clock-out-when-done`: nil when marking an entry done doesn't clock out, an empty
91 /// set for any done keyword, else the keywords that do.
92 public static func clockOutWhenDone(_ defaults: UserDefaults = .standard) -> Set<String>? {
93 let words = string("clockOutWhenDone", defaults).split(whereSeparator: \.isWhitespace).map(String.init)
94 if words == ["nil"] { return nil }
95 return words == ["t"] || words.isEmpty ? [] : Set(words)
96 }
97 public static func agendaSubfolders(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaSubfolders", defaults) }
98 /// The agenda leaves out the files other agenda files archive to.
99 public static func agendaExcludeArchives(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaExcludeArchives", defaults) }
100 /// `org-agenda-show-all-dates`: days without entries show.
101 public static func agendaShowAllDates(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaShowAllDates", defaults) }
102 public static func agendaSkipScheduledIfDone(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaSkipScheduledIfDone", defaults) }
103 public static func habitsOnlyForToday(_ defaults: UserDefaults = .standard) -> Bool { bool("habitsOnlyForToday", defaults) }
104 public static func agendaSkipDeadlineIfDone(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaSkipDeadlineIfDone", defaults) }
105 public static func agendaSearchAlwaysBoolean(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaSearchAlwaysBoolean", defaults) }
106 public static func agendaSearchForceFullWords(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaSearchForceFullWords", defaults) }
107 /// `options` with the deadline warning, skip-if-done, search and blocked-entry settings.
108 public static func agendaOptions(_ options: AgendaOptions, _ defaults: UserDefaults = .standard) -> AgendaOptions {
109 var options = options
110 options.deadlineWarningDays = integer("deadlineWarningDays", defaults)
111 options.skipScheduledIfDone = agendaSkipScheduledIfDone(defaults)
112 options.skipDeadlineIfDone = agendaSkipDeadlineIfDone(defaults)
113 options.habitsOnlyForToday = habitsOnlyForToday(defaults)
114 options.searchAlwaysBoolean = agendaSearchAlwaysBoolean(defaults)
115 options.searchForceFullWords = agendaSearchForceFullWords(defaults)
116 options.enforceTodoDependencies = bool("enforceTodoDependencies", defaults)
117 options.enforceTodoCheckboxDependencies = bool("enforceTodoCheckboxDependencies", defaults)
118 options.dimBlockedTasks = AgendaOptions.DimBlocked(rawValue: string("agendaDimBlockedTasks", defaults)) ?? .dim
119 options.logItems = Set(string("agendaLogModeItems", defaults).split(whereSeparator: \.isWhitespace).map(String.init))
120 options.todoIgnoreWithDate = bool("agendaTodoIgnoreWithDate", defaults)
121 options.todoIgnoreScheduled = AgendaOptions.TodoIgnore(string("agendaTodoIgnoreScheduled", defaults)) ?? .off
122 options.todoIgnoreDeadlines = AgendaOptions.TodoIgnore(string("agendaTodoIgnoreDeadlines", defaults), deadlines: true) ?? .off
123 options.todoIgnoreTimestamp = AgendaOptions.TodoIgnore(string("agendaTodoIgnoreTimestamp", defaults)) ?? .off
124 options.tagsTodoHonorIgnoreOptions = bool("agendaTagsTodoHonorIgnore", defaults)
125 for (view, key) in [("agenda", "agendaPrefixAgenda"), ("todo", "agendaPrefixTodo"), ("tags", "agendaPrefixTags")] {
126 options.prefixFormat[view] = string(key, defaults)
127 }
128 for (view, key) in [("agenda", "agendaSortAgenda"), ("todo", "agendaSortTodo"), ("tags", "agendaSortTags"), ("search", "agendaSortSearch")] {
129 options.sortingStrategy[view] = sortingStrategy(string(key, defaults))
130 }
131 options.useTimeGrid = bool("agendaUseTimeGrid", defaults)
132 options.showCurrentTimeInGrid = bool("agendaShowCurrentTime", defaults)
133 options.gridWhen = Set(string("agendaTimeGridWhen", defaults).split(whereSeparator: \.isWhitespace).map(String.init))
134 options.gridTimes = string("agendaTimeGridTimes", defaults).split(whereSeparator: \.isWhitespace).compactMap { Int($0) }
135 options.stuckProjects = stuckProjects(defaults)
136 options.sortNotimeIsLate = bool("agendaSortNotimeIsLate", defaults)
137 options.sortNoeffortIsHigh = bool("agendaSortNoeffortIsHigh", defaults)
138 return options
139 }
140 /// `org-agenda-files`, one entry per line.
141 public static func agendaFiles(_ defaults: UserDefaults = .standard) -> [String] {
142 string("agendaFiles", defaults).components(separatedBy: .newlines).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
143 }
144 /// `org-refile-targets`, `org-refile-use-outline-path` and
145 /// `org-refile-allow-creating-parent-nodes`; targets that can't be read are orgstar's default.
146 public static func refileSettings(_ defaults: UserDefaults = .standard) -> RefileSettings {
147 let targets = (try? RefileSettings.parseTargets(string("refileTargets", defaults)).get()) ?? RefileSettings.workspaceTargets
148 return RefileSettings(targets: targets, outlinePath: RefileSettings.OutlinePath(rawValue: string("refileUseOutlinePath", defaults)) ?? .file,
149 creating: RefileSettings.Creating(rawValue: string("refileAllowCreatingParentNodes", defaults)) ?? .no)
150 }
151 /// `org-icalendar-use-deadline`, `-use-scheduled` and `-include-todo`; the owner is the
152 /// user's full name.
153 public static func icalendarOptions(_ defaults: UserDefaults = .standard) -> ICalendarOptions {
154 var options = ICalendarOptions()
155 options.useDeadline = words(string("icalendarUseDeadline", defaults))
156 options.useScheduled = words(string("icalendarUseScheduled", defaults))
157 options.includeTodo = switch string("icalendarIncludeTodo", defaults).trimmingCharacters(in: .whitespaces) {
158 case "", "nil": .none
159 case "t": .unfinished
160 case "all": .all
161 case "unblocked": .unblocked
162 case let list: .keywords(words(list))
163 }
164 options.userFullName = NSFullUserName()
165 return options
166 }
167 /// `org-roam-directory`; empty for the first folder.
168 public static func roamDirectory(_ defaults: UserDefaults = .standard) -> String { string("roamDirectory", defaults) }
169 /// `org-roam-dailies-directory`, relative to `org-roam-directory` unless absolute.
170 public static func dailiesDirectory(_ defaults: UserDefaults = .standard) -> String { string("dailiesDirectory", defaults).nonEmpty ?? "daily/" }
171 /// The daily capture template's file name, head and entry.
172 public static func dailiesFile(_ defaults: UserDefaults = .standard) -> String { string("dailiesFile", defaults).nonEmpty ?? "%<%Y-%m-%d>.org" }
173 public static func dailiesHead(_ defaults: UserDefaults = .standard) -> String { string("dailiesHead", defaults).nonEmpty ?? "#+title: %<%Y-%m-%d>\n" }
174 public static func dailiesEntry(_ defaults: UserDefaults = .standard) -> String { string("dailiesEntry", defaults).nonEmpty ?? "* %?" }
175 /// Whether the note and daily-note commands follow Denote rather than org-roam.
176 public static func usesDenote(_ defaults: UserDefaults = .standard) -> Bool { string("notesPackage", defaults) == "denote" }
177 /// `denote-silo-directories`, separated by `:`; empty for `denote-directory`'s.
178 public static func denoteSiloDirectories(_ defaults: UserDefaults = .standard) -> String { string("denoteSiloDirectories", defaults) }
179 /// `denote-directory`, folders separated by `:`; empty for the first folder.
180 public static func denoteDirectory(_ defaults: UserDefaults = .standard) -> String { string("denoteDirectory", defaults) }
181 /// `denote-journal-directory`, relative to `denote-directory` unless absolute.
182 public static func denoteJournalDirectory(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalDirectory", defaults).nonEmpty ?? "journal" }
183 public static func denoteJournalKeyword(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalKeyword", defaults).nonEmpty ?? "journal" }
184 /// `denote-journal-title-format`, a `format-time-string` format.
185 public static func denoteJournalTitle(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalTitle", defaults).nonEmpty ?? "%A %-e %B %Y %H:%M" }
186 /// `denote-journal-interval`.
187 public static func denoteJournalInterval(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalInterval", defaults) }
188 /// `denote-sequence-scheme`.
189 public static func denoteSequenceScheme(_ defaults: UserDefaults = .standard) -> DenoteSequence.Scheme {
190 DenoteSequence.Scheme(rawValue: string("denoteSequenceScheme", defaults)) ?? .numeric
191 }
192 /// `denote-file-type`: the file type of new notes.
193 public static func denoteFileType(_ defaults: UserDefaults = .standard) -> Denote.FileType {
194 Denote.FileType(rawValue: string("denoteFileType", defaults)) ?? .org
195 }
196 /// `denote-prompts`: what a new note asks after its title, in order.
197 public static func denotePrompts(_ defaults: UserDefaults = .standard) -> [String] {
198 string("denotePrompts", defaults).split(whereSeparator: \.isWhitespace).map(String.init)
199 }
200 /// `org-attach-id-dir`, relative to an org file's folder unless absolute.
201 public static func attachIDDir(_ defaults: UserDefaults = .standard) -> String {
202 let dir = string("attachIDDir", defaults)
203 return dir.isEmpty ? "data/" : dir
204 }
205 /// `org-attach-use-inheritance`: nil for `selective`, else whether DIR and ID inherit.
206 public static func attachUseInheritance(_ defaults: UserDefaults = .standard) -> Bool? {
207 switch string("attachUseInheritance", defaults) {
208 case "t": true
209 case "nil": false
210 default: nil
211 }
212 }
213 /// `org-cite-global-bibliography`: bibliography files, separated by `:`.
214 public static func citeGlobalBibliography(_ defaults: UserDefaults = .standard) -> [String] {
215 string("citeGlobalBibliography", defaults).split(separator: ":").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
216 }
217 /// `org-fc-review-history-file`: relative to the configuration folder unless absolute;
218 /// empty for `org-fc-reviews.tsv` there.
219 public static func fcReviewHistoryFile(_ defaults: UserDefaults = .standard) -> URL {
220 let path = OrgPaths.expandingTilde(string("fcReviewHistoryFile", defaults).nonEmpty ?? "org-fc-reviews.tsv")
221 return path.hasPrefix("/") ? URL(fileURLWithPath: path) : UserConfig.directory.appendingPathComponent(path)
222 }
223 /// `org-yank-image-save-method`: "attach", or the folder pasted images go in.
224 public static func yankImageSaveMethod(_ defaults: UserDefaults = .standard) -> String {
225 string("yankImageSaveMethod", defaults).nonEmpty ?? "attach"
226 }
227 /// `org-crypt-tag-matcher`, a tag.
228 public static func cryptTag(_ defaults: UserDefaults = .standard) -> String {
229 let tag = string("cryptTagMatcher", defaults).trimmingCharacters(in: .whitespaces)
230 return tag.isEmpty ? "crypt" : tag
231 }
232 /// `org-crypt-use-before-save-magic`.
233 public static func cryptBeforeSave(_ defaults: UserDefaults = .standard) -> Bool {
234 bool("cryptBeforeSave", defaults)
235 }
236 /// `org-icalendar-combined-agenda-file`, `~` expanded.
237 public static func icalendarCombinedFile(_ defaults: UserDefaults = .standard) -> String {
238 OrgPaths.expandingTilde(string("icalendarCombinedAgendaFile", defaults))
239 }
240 /// `org-stuck-projects`.
241 public static func stuckProjects(_ defaults: UserDefaults = .standard) -> StuckProjects {
242 StuckProjects(match: string("stuckProjectsMatch", defaults), todo: words(string("stuckProjectsTodo", defaults)),
243 tags: words(string("stuckProjectsTags", defaults)), regexp: string("stuckProjectsRegexp", defaults))
244 }
245 /// Words separated by spaces.
246 public static func words(_ text: String) -> [String] { text.split(whereSeparator: \.isWhitespace).map(String.init) }
247 /// An `org-agenda-sorting-strategy` entry, keys separated by spaces; unknown keys are left out.
248 public static func sortingStrategy(_ text: String) -> [String] {
249 text.split(whereSeparator: \.isWhitespace).map(String.init).filter(AgendaSort.keys.contains)
250 }
251 /// `calendar-events`: Calendar's events show in the agenda.
252 public static func calendarEvents(_ defaults: UserDefaults = .standard) -> Bool { bool("calendarEvents", defaults) }
253 /// `calendar-event-calendars`: the calendars chosen, by title or identifier; empty for all.
254 public static func calendarEventCalendars(_ defaults: UserDefaults = .standard) -> [String] {
255 string("calendarEventCalendars", defaults).split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
256 }
257 /// `agenda-reminders`: Reminders' incomplete reminders show in the agenda.
258 public static func agendaReminders(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaReminders", defaults) }
259 /// `agenda-reminder-lists`: the lists chosen, by title or identifier; empty for all.
260 public static func agendaReminderLists(_ defaults: UserDefaults = .standard) -> [String] {
261 string("agendaReminderLists", defaults).split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
262 }
263 public static func reminders(_ defaults: UserDefaults = .standard) -> Bool { bool("reminders", defaults) }
264 /// `appt-message-warning-time`, in minutes.
265 public static func reminderLead(_ defaults: UserDefaults = .standard) -> Int { integer("reminderLead", defaults) }
266 /// `org-clock-idle-time` in minutes; 0 is nil (never).
267 public static func clockIdleTime(_ defaults: UserDefaults = .standard) -> Int { integer("clockIdleTime", defaults) }
268 /// `org-clock-history-length`.
269 public static func clockHistoryLength(_ defaults: UserDefaults = .standard) -> Int { integer("clockHistoryLength", defaults) }
270
271 private static func fallback(_ key: String) -> TOML.Value? {
272 UserConfig.settings.first { $0.defaultsKey == key }?.fallback
273 }
274
275 /// A setting by its user-defaults key, the file's fallback when it isn't set.
276 public static func bool(_ key: String, _ defaults: UserDefaults) -> Bool {
277 defaults.object(forKey: key) as? Bool ?? fallback(key)?.bool ?? false
278 }
279
280 public static func string(_ key: String, _ defaults: UserDefaults) -> String {
281 defaults.string(forKey: key) ?? fallback(key)?.string ?? ""
282 }
283
284 /// Integers, and day offsets stored as integers with a string such as `"+0d"` as the fallback.
285 public static func integer(_ key: String, _ defaults: UserDefaults) -> Int {
286 if let value = defaults.object(forKey: key) as? Int { return value }
287 switch fallback(key) {
288 case .integer(let value)?: return value
289 case .string(let text)?: return Int(text.trimmingCharacters(in: CharacterSet(charactersIn: "+d"))) ?? 0
290 default: return 0
291 }
292 }
293}
294
295private extension String {
296 var nonEmpty: String? { isEmpty ? nil : self }
297}