Sources/OrgApp/EmacsImport.swift
1402 lines · 87140 bytes
54 symbols in this file
EmacsImportChangeItemNotefilesdefaultLocationspickerLocationdoomInstallLocationsisDoomInstalldoomDefaultFilesdoomDefaultFilesscanAssignmentBindingScannerassignvisitbodyevilStateskeyStringmapBindingsfontSpecunquoteevaluatebackquotebuildidconvertaddnotekeystagAliststructureTemplatesagendaCommandnotequotedunquoteviewpublishProjectnotequotedcaptureTemplatequotedroamTemplatequotedfoldersToAddagendaFilesstandardisRootapplyreadwritebindingcount
1import Foundation
2import OrgCore
3
4/// Settings, folders, capture templates and key bindings read from an Emacs configuration
5/// without running it: `setq`-style forms with values Orgstar can work out, inside `after!`,
6/// `with-eval-after-load`, `use-package` and the like. For Doom, Doom's own org defaults are
7/// read first, as they apply under your config.
8public struct EmacsImport: Sendable {
9 public enum Change: Sendable, Equatable {
10 /// A `config.toml` setting.
11 case setting(key: String, value: TOML.Value)
12 /// A folder to add (`org-directory`, folders of `org-agenda-files`).
13 case folder(String)
14 /// A `[[template]]` table for capture.toml.
15 case capture(key: String, toml: String)
16 /// A `[[roam-template]]`, `[[roam-dailies-template]]` or `[[roam-ref-template]]` table
17 /// for capture.toml, by its table name.
18 case roamTemplate(set: String, key: String, toml: String)
19 /// A `[[bind]]` table for keymap.toml.
20 case binding(keys: String, command: String, mode: String?)
21 /// An `[org-structure-template-alist]` entry for config.toml.
22 case structureTemplate(key: String, type: String)
23 /// A `[[view]]` table, with its blocks, for views.toml.
24 case view(name: String, toml: String)
25 /// A `[[publish]]` table for config.toml.
26 case publish(name: String, toml: String)
27 /// A `[denote-templates]` entry for config.toml.
28 case denoteTemplate(key: String, text: String)
29 /// A yasnippet snippet as a `[[snippet]]` table for snippets.toml.
30 case snippet(trigger: String, toml: String)
31 }
32
33 public struct Item: Sendable, Identifiable {
34 public let id: Int
35 /// The Emacs variable or binding, as it reads in the file.
36 public let name: String
37 /// What it becomes in Orgstar, for the review list.
38 public let summary: String
39 /// `config.el:27`, or `Doom default` for Doom's own settings.
40 public let source: String
41 public let change: Change
42 }
43
44 public struct Note: Sendable, Identifiable {
45 public let id: Int
46 public let name: String
47 public let reason: String
48 public let source: String
49 }
50
51 public var items: [Item] = []
52 /// Org settings and bindings Orgstar has no equivalent for.
53 public var unsupported: [Note] = []
54 /// Values worked out at run time, which reading can't follow.
55 public var unreadable: [Note] = []
56 /// Files that couldn't be read, with why.
57 public var problems: [String] = []
58 /// Variables that aren't about org or the editor, left alone.
59 public var skipped = 0
60 /// Doom's own org defaults Orgstar has no use for, not listed one by one.
61 public var doomDefaultsLeftOut = 0
62 public var isDoom = false
63 /// Doom's own org defaults were found and read.
64 public var doomDefaultsRead = false
65 /// yasnippet snippets left out, as they hold Emacs Lisp.
66 public var snippetsSkipped = 0
67
68 // MARK: - Finding the configuration
69
70 /// The configuration files in `folder` (a Doom folder, an `.emacs.d`) or the file itself.
71 /// A literate `config.org` is read when there's no `config.el` tangled from it.
72 public static func files(in location: URL) -> [URL] {
73 var isDirectory: ObjCBool = false
74 guard FileManager.default.fileExists(atPath: location.path, isDirectory: &isDirectory) else { return [] }
75 guard isDirectory.boolValue else { return [location] }
76 let exists = { (name: String) in FileManager.default.fileExists(atPath: location.appendingPathComponent(name).path) }
77 let names = ["init.el", exists("config.el") ? "config.el" : "config.org", "custom.el"]
78 return names.filter(exists).map { location.appendingPathComponent($0) }
79 }
80
81 /// Where an Emacs configuration usually is, first found first.
82 public static func defaultLocations() -> [URL] {
83 let home = URL(fileURLWithPath: OrgPaths.home)
84 let environment = ProcessInfo.processInfo.environment
85 var candidates: [URL] = []
86 if let doom = environment["DOOMDIR"] { candidates.append(URL(fileURLWithPath: doom)) }
87 candidates += [".config/doom", ".doom.d", ".config/emacs", ".emacs.d"].map { home.appendingPathComponent($0) }
88 candidates.append(home.appendingPathComponent(".emacs"))
89 return candidates.filter { !files(in: $0).isEmpty && !isDoomInstall($0) }
90 }
91
92 /// Where an open panel for the configuration starts: the first configuration found, or the
93 /// home folder.
94 public static func pickerLocation() -> URL {
95 defaultLocations().first ?? URL(fileURLWithPath: OrgPaths.home)
96 }
97
98 /// Where Doom is usually installed, `EMACSDIR` first.
99 public static func doomInstallLocations() -> [URL] {
100 let home = URL(fileURLWithPath: OrgPaths.home)
101 return [ProcessInfo.processInfo.environment["EMACSDIR"]].compactMap { $0 }.map { URL(fileURLWithPath: $0) }
102 + [".config/emacs", ".emacs.d"].map { home.appendingPathComponent($0) }
103 }
104
105 /// Doom's own source folder, which holds `lisp/doom.el`, isn't a user configuration.
106 static func isDoomInstall(_ url: URL) -> Bool {
107 FileManager.default.fileExists(atPath: url.appendingPathComponent("lisp/doom.el").path)
108 }
109
110 /// Doom's org module and core defaults, if Doom is installed.
111 static func doomDefaultFiles() -> [URL] {
112 guard let install = doomInstallLocations().first(where: isDoomInstall) else { return [] }
113 return doomDefaultFiles(in: install)
114 }
115
116 /// Doom's org module and core defaults in `install`, Doom's own folder; empty when it isn't one.
117 public static func doomDefaultFiles(in install: URL) -> [URL] {
118 guard isDoomInstall(install) else { return [] }
119 var files = [install.appendingPathComponent("lisp/doom-emacs.el")]
120 var moduleRoots = [install.appendingPathComponent("modules")]
121 if let sources = try? FileManager.default.contentsOfDirectory(at: install.appendingPathComponent("sources"), includingPropertiesForKeys: nil) {
122 moduleRoots += sources.map { $0.appendingPathComponent("modules") }
123 }
124 if let org = moduleRoots.map({ $0.appendingPathComponent("lang/org/config.el") }).first(where: { FileManager.default.fileExists(atPath: $0.path) }) {
125 files.insert(org, at: 0)
126 }
127 return files.filter { FileManager.default.fileExists(atPath: $0.path) }
128 }
129
130 // MARK: - Reading
131
132 /// Reads `files`, and for a Doom configuration Doom's own defaults under them.
133 public static func scan(_ files: [URL], doomDefaults: [URL]? = nil) -> EmacsImport {
134 var sources: [(name: String, text: String, priority: Int)] = []
135 var result = EmacsImport()
136 for url in files {
137 guard let text = try? String(contentsOf: url, encoding: .utf8) else {
138 result.problems.append("Can't read \(url.path)")
139 continue
140 }
141 sources.append((url.lastPathComponent, url.pathExtension == "org" ? Tangle.literateLisp(text) : text, 1))
142 }
143 result.isDoom = sources.contains { $0.text.contains("(doom!") || $0.text.contains("(map! ") || $0.text.contains("(after! ") }
144 if result.isDoom {
145 for url in doomDefaults ?? doomDefaultFiles() {
146 if let text = try? String(contentsOf: url, encoding: .utf8) {
147 sources.insert(("Doom", text, 0), at: 0)
148 result.doomDefaultsRead = true
149 }
150 }
151 }
152 var scanner = Scanner()
153 for source in sources {
154 do {
155 let forms = try LispReader.read(source.text)
156 for form in forms {
157 scanner.visit(form.sexp, source: source.priority == 0 ? "Doom default" : "\(source.name):\(form.line)",
158 priority: source.priority, deferred: false, insideDefun: false, doom: source.priority == 0)
159 }
160 } catch {
161 result.problems.append("\(source.name): \(error)")
162 }
163 }
164 result.build(from: scanner)
165 result.addSnippets(from: snippetFolders(files.map { $0.deletingLastPathComponent() }))
166 return result
167 }
168
169 struct Assignment {
170 let name: String
171 let value: Sexp
172 let source: String
173 /// Doom defaults, then the config, then what runs after a package loads.
174 let rank: Int
175 }
176
177 struct Binding {
178 let keys: String
179 let command: Sexp
180 let modes: [String?]
181 let source: String
182 }
183
184 struct Scanner {
185 var assignments: [Assignment] = []
186 var bindings: [Binding] = []
187 /// `(add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp"))` entries.
188 var addedTemplates: [(entry: Sexp, source: String)] = []
189 /// `(add-to-list 'org-agenda-custom-commands '("w" "Work" tags "work"))` entries.
190 var addedCommands: [(entry: Sexp, source: String)] = []
191 var usesEvil = false
192 var order = 0
193
194 mutating func assign(_ name: String, _ value: Sexp, _ source: String, priority: Int, deferred: Bool) {
195 assignments.append(Assignment(name: name, value: value, source: source, rank: priority * 2 + (deferred ? 1 : 0)))
196 }
197
198 mutating func visit(_ form: Sexp, source: String, priority: Int, deferred: Bool, insideDefun: Bool, doom: Bool) {
199 guard let items = form.elements, let head = form.head else { return }
200 let args = Array(items.dropFirst())
201 func body(_ forms: ArraySlice<Sexp>, deferred: Bool) {
202 for f in forms { visit(f, source: source, priority: priority, deferred: deferred, insideDefun: insideDefun, doom: doom) }
203 }
204 switch head {
205 case "setq", "setq-default", "setq!", "setopt", "csetq":
206 var i = 0
207 while i + 1 < args.count {
208 if let name = args[i].symbol { assign(name, args[i + 1], source, priority: priority, deferred: deferred) }
209 i += 2
210 }
211 case "add-to-list":
212 if args.count >= 2, unquote(args[0])?.symbol == "org-structure-template-alist", let entry = unquote(args[1]) {
213 addedTemplates.append((entry, source))
214 }
215 if args.count >= 2, unquote(args[0])?.symbol == "org-agenda-custom-commands", let entry = unquote(args[1]) {
216 addedCommands.append((entry, source))
217 }
218 case "defvar", "defcustom":
219 // Only sets a variable nothing set, so under every assignment.
220 if args.count >= 2, let name = args[0].symbol { assign(name, args[1], source, priority: -1, deferred: false) }
221 case "custom-set-variables":
222 for arg in args {
223 guard let entry = unquote(arg)?.elements, entry.count >= 2, let name = entry[0].symbol else { continue }
224 assign(name, .list([.symbol("quote"), entry[1]]), source, priority: priority, deferred: deferred)
225 }
226 case "after!", "with-eval-after-load", "eval-after-load", "use-package!", "use-package":
227 if head.hasPrefix("use-package") {
228 var i = 1
229 var section = ""
230 while i < args.count {
231 if let keyword = args[i].symbol, keyword.hasPrefix(":") {
232 section = keyword
233 } else if section == ":config" || section == ":init" {
234 visit(args[i], source: source, priority: priority, deferred: true, insideDefun: insideDefun, doom: doom)
235 } else if section == ":custom", let pair = args[i].elements, pair.count >= 2, let name = pair[0].symbol {
236 assign(name, pair[1], source, priority: priority, deferred: true)
237 }
238 i += 1
239 }
240 } else {
241 let forms = head == "eval-after-load" ? args.dropFirst().compactMap(unquote) : Array(args.dropFirst())
242 body(forms[...], deferred: true)
243 }
244 case "progn", "when", "unless", "if", "let", "let*", "with-no-warnings":
245 let skip = ["let", "let*", "when", "unless", "if"].contains(head) ? 1 : 0
246 body(args.dropFirst(skip), deferred: deferred)
247 case "add-hook":
248 // `auto-fill-mode` turned on for Org or text buffers.
249 if args.count >= 2, let hook = unquote(args[0])?.symbol, ["org-mode-hook", "text-mode-hook"].contains(hook),
250 let function = unquote(args[1])?.symbol, ["auto-fill-mode", "turn-on-auto-fill"].contains(function) {
251 assign("auto-fill-mode", .symbol("t"), source, priority: priority, deferred: deferred)
252 }
253 case "defun", "defun!", "add-hook!":
254 // Doom sets org's defaults in the functions its module runs when org loads.
255 if doom, head == "defun" { body(args.dropFirst(2), deferred: true) }
256 case "doom!":
257 usesEvil = args.contains { $0.symbol == "evil" || $0.head == "evil" }
258 case "map!":
259 if !doom { bindings += mapBindings(args, prefix: "", modes: [nil], source: source) }
260 case "define-key", "keymap-set", "evil-define-key", "evil-define-key*", "global-set-key", "keymap-global-set":
261 guard !doom else { break }
262 var rest = args
263 var modes: [String?] = [nil]
264 if head.hasPrefix("evil-define-key"), let state = rest.first {
265 modes = evilStates(state)
266 rest = Array(rest.dropFirst())
267 }
268 if !head.hasPrefix("global"), head != "keymap-global-set" { rest = Array(rest.dropFirst()) }
269 var i = 0
270 while i + 1 < rest.count {
271 if let keys = keyString(rest[i]) { bindings.append(Binding(keys: keys, command: rest[i + 1], modes: modes, source: source)) }
272 i += 2
273 }
274 default:
275 break
276 }
277 }
278
279 func evilStates(_ sexp: Sexp) -> [String?] {
280 let names = (unquote(sexp)?.elements ?? [unquote(sexp) ?? sexp]).compactMap(\.symbol)
281 let modes = names.compactMap { name -> String? in
282 switch name {
283 case "normal", "motion": "normal"
284 case "insert": "insert"
285 case "visual": "visual"
286 default: nil
287 }
288 }
289 return modes.isEmpty ? [nil] : modes
290 }
291
292 /// `(kbd "C-c x")` or `"C-c x"` (keymap-set); key vectors such as `[f5]` are skipped.
293 func keyString(_ sexp: Sexp) -> String? {
294 if let s = sexp.string { return s }
295 if sexp.head == "kbd", let s = sexp.elements?.dropFirst().first?.string { return s }
296 return nil
297 }
298
299 /// Doom's `map!`: `:leader`, `:localleader`, `:prefix`, state keywords such as `:n`
300 /// and `:nv`, `:map`, `:desc`, and nested groups.
301 func mapBindings(_ args: [Sexp], prefix: String, modes: [String?], source: String) -> [Binding] {
302 var result: [Binding] = []
303 var prefix = prefix
304 var modes = modes
305 var i = 0
306 while i < args.count {
307 let arg = args[i]
308 if let keyword = arg.symbol, keyword.hasPrefix(":") {
309 switch keyword {
310 case ":leader":
311 prefix = "SPC"
312 modes = ["normal"]
313 case ":localleader":
314 prefix = "SPC m"
315 modes = ["normal"]
316 case ":prefix", ":prefix-map":
317 if i + 1 < args.count {
318 let p = args[i + 1].string ?? args[i + 1].elements?.first?.string ?? ""
319 prefix = [prefix, p].filter { !$0.isEmpty }.joined(separator: " ")
320 }
321 i += 1
322 case ":desc", ":map", ":mode", ":after", ":when", ":unless":
323 i += 1
324 default:
325 let states = keyword.dropFirst()
326 let mapped = states.compactMap { c -> String? in
327 switch c {
328 case "n", "m": "normal"
329 case "i": "insert"
330 case "v": "visual"
331 default: nil
332 }
333 }
334 if !mapped.isEmpty { modes = Array(Set(mapped)).sorted() }
335 }
336 } else if let group = arg.elements, arg.head?.hasPrefix(":") == true || group.first?.string != nil && group.count > 2 {
337 result += mapBindings(group, prefix: prefix, modes: modes, source: source)
338 } else if let key = arg.string, i + 1 < args.count {
339 let keys = [prefix, key].filter { !$0.isEmpty }.joined(separator: " ")
340 result.append(Binding(keys: keys, command: args[i + 1], modes: modes, source: source))
341 i += 1
342 }
343 i += 1
344 }
345 return result
346 }
347 }
348
349 // MARK: - Values
350
351 /// `(font-spec :family "JetBrains Mono" :size 14)`, or `"JetBrains Mono-14"`.
352 static func fontSpec(_ sexp: Sexp) -> (family: String?, size: Int?)? {
353 if let name = sexp.string {
354 let parts = name.split(separator: "-")
355 if parts.count > 1, let size = Int(parts.last!) { return (parts.dropLast().joined(separator: "-"), size) }
356 return (name, nil)
357 }
358 guard sexp.head == "font-spec", let args = sexp.elements?.dropFirst() else { return nil }
359 let list = Array(args)
360 var family: String?
361 var size: Int?
362 var i = 0
363 while i + 1 < list.count {
364 switch list[i].symbol {
365 case ":family": family = list[i + 1].string
366 case ":size":
367 if let n = list[i + 1].integer { size = n }
368 if case .float(let d) = list[i + 1] { size = Int(d.rounded()) }
369 default: break
370 }
371 i += 2
372 }
373 return family == nil && size == nil ? nil : (family, size)
374 }
375
376 static func unquote(_ sexp: Sexp) -> Sexp? {
377 if let items = sexp.elements, items.count == 2, items[0].symbol == "quote" || items[0].symbol == "function" { return items[1] }
378 if case .list(let items) = sexp, items.count == 2, items[0].symbol == "\\`" { return items[1] }
379 return nil
380 }
381
382 /// What a form evaluates to, for the few forms configurations build values with; nil
383 /// when reading can't tell.
384 static func evaluate(_ sexp: Sexp, _ env: [String: Sexp]) -> Sexp? {
385 switch sexp {
386 case .string, .integer, .float, .character, .vector: return sexp
387 case .symbol(let name):
388 if name == "t" || name == "nil" || name.hasPrefix(":") { return sexp }
389 return env[name]
390 case .dotted: return nil
391 case .list(let items):
392 guard let head = items.first?.symbol else { return nil }
393 let args = Array(items.dropFirst())
394 switch head {
395 case "quote", "function": return args.first
396 case "\\`":
397 guard let inner = args.first else { return nil }
398 return backquote(inner, env)
399 case "list":
400 let values = args.compactMap { evaluate($0, env) }
401 return values.count == args.count ? .list(values) : nil
402 case "concat":
403 let parts = args.compactMap { evaluate($0, env)?.string }
404 return parts.count == args.count ? .string(parts.joined()) : nil
405 case "expand-file-name", "file-name-concat":
406 let parts = args.compactMap { evaluate($0, env)?.string }
407 guard parts.count == args.count, !parts.isEmpty else { return nil }
408 if head == "expand-file-name" {
409 let name = parts[0]
410 if name.hasPrefix("/") || name.hasPrefix("~") || parts.count == 1 { return .string(name) }
411 return .string((parts[1] as NSString).appendingPathComponent(name))
412 }
413 return .string(parts.dropFirst().reduce(parts[0]) { ($0 as NSString).appendingPathComponent($1) })
414 case "file-name-as-directory":
415 guard let s = args.first.flatMap({ evaluate($0, env)?.string }) else { return nil }
416 return .string(s.hasSuffix("/") ? s : s + "/")
417 default:
418 return nil
419 }
420 }
421 }
422
423 /// A backquoted form with its `,` and `,@` parts evaluated.
424 static func backquote(_ sexp: Sexp, _ env: [String: Sexp]) -> Sexp? {
425 guard case .list(let items) = sexp else {
426 if case .dotted(let items, let last) = sexp {
427 let values = items.compactMap { backquote($0, env) }
428 guard values.count == items.count, let tail = backquote(last, env) else { return nil }
429 return .dotted(values, tail)
430 }
431 return sexp
432 }
433 if items.count == 2, items[0].symbol == "," { return evaluate(items[1], env) }
434 var out: [Sexp] = []
435 for item in items {
436 if case .list(let parts) = item, parts.count == 2, parts[0].symbol == ",@" {
437 guard let spliced = evaluate(parts[1], env)?.elements else { return nil }
438 out += spliced
439 } else {
440 guard let value = backquote(item, env) else { return nil }
441 out.append(value)
442 }
443 }
444 return .list(out)
445 }
446
447 // MARK: - Results
448
449 static let orgRelated = ["org-", "denote-", "appt-", "display-line-numbers", "fill-column", "evil-", "doom-font", "doom-variable-pitch-font", "doom-theme", "calendar-week-start-day"]
450
451 mutating func build(from scanner: Scanner) {
452 var next = 0
453 func id() -> Int { next += 1; return next }
454 // The last assignment of each variable wins, those after a package loads over the rest.
455 var winners: [String: Assignment] = [:]
456 var env: [String: Sexp] = [:]
457 for assignment in scanner.assignments.enumerated().sorted(by: { ($0.element.rank, $0.offset) < ($1.element.rank, $1.offset) }).map(\.element) {
458 winners[assignment.name] = assignment
459 if let value = Self.evaluate(assignment.value, env) { env[assignment.name] = value }
460 }
461 if isDoom || scanner.usesEvil {
462 items.append(Item(id: id(), name: isDoom ? "Doom Emacs" : "evil-mode", summary: "keymap = \"doom\"", source: "", change: .setting(key: "keymap", value: .string("doom"))))
463 }
464 for name in winners.keys.sorted() {
465 let assignment = winners[name]!
466 guard Self.orgRelated.contains(where: { name.hasPrefix($0) }) else {
467 if assignment.rank >= 2 { skipped += 1 }
468 continue
469 }
470 if name == "doom-font", let spec = Self.fontSpec(assignment.value) {
471 if let family = spec.family {
472 items.append(Item(id: id(), name: name, summary: "font = \"\(family)\"", source: assignment.source, change: .setting(key: "font", value: .string(family))))
473 }
474 if let size = spec.size {
475 items.append(Item(id: id(), name: name, summary: "font-size = \(size)", source: assignment.source, change: .setting(key: "font-size", value: .integer(size))))
476 }
477 continue
478 }
479 guard let value = Self.evaluate(assignment.value, env) else {
480 if assignment.rank < 2 {
481 doomDefaultsLeftOut += 1
482 continue
483 }
484 unreadable.append(Note(id: id(), name: name, reason: "worked out when Emacs runs: \(assignment.value.description.prefix(80))", source: assignment.source))
485 continue
486 }
487 let before = unsupported.count
488 convert(name, value, source: assignment.source, env: env, id: id)
489 if assignment.rank < 2, unsupported.count > before {
490 doomDefaultsLeftOut += unsupported.count - before
491 unsupported.removeLast(unsupported.count - before)
492 }
493 }
494 for (entry, source) in scanner.addedTemplates { structureTemplates([entry], source: source, id: id) }
495 for (entry, source) in scanner.addedCommands { agendaCommand(entry, source: source, id: id) }
496 // One item per folder.
497 var folders: Set<String> = []
498 items.removeAll { item in
499 guard case .folder(let path) = item.change else { return false }
500 let key = OrgPaths.expandingTilde(path).trimmingCharacters(in: CharacterSet(charactersIn: "/"))
501 return !folders.insert(key).inserted
502 }
503 for binding in scanner.bindings {
504 guard let commandName = Self.unquote(binding.command)?.symbol ?? binding.command.symbol else {
505 unsupported.append(Note(id: id(), name: binding.keys, reason: "bound to code, not a command", source: binding.source))
506 continue
507 }
508 guard let command = Self.commands[commandName] else {
509 unsupported.append(Note(id: id(), name: "\(binding.keys) → \(commandName)", reason: "orgstar has no such command", source: binding.source))
510 continue
511 }
512 guard let keys = KeySequence.parse(binding.keys).map(KeySequence.format) else {
513 unsupported.append(Note(id: id(), name: binding.keys, reason: "keys orgstar can't read", source: binding.source))
514 continue
515 }
516 let modes = isDoom ? binding.modes.map { $0 ?? "normal" } : binding.modes
517 for mode in Array(Set(modes.map { $0 ?? "" })).sorted() {
518 items.append(Item(id: id(), name: "\(keys) → \(commandName)", summary: mode.isEmpty ? command : "\(command) in \(mode) state",
519 source: binding.source, change: .binding(keys: keys, command: command, mode: mode.isEmpty ? nil : mode)))
520 }
521 }
522 }
523
524 mutating func convert(_ name: String, _ value: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) {
525 func add(_ key: String, _ toml: TOML.Value, _ summary: String? = nil) {
526 items.append(Item(id: id(), name: name, summary: summary ?? "\(key) = \(UserConfig.format(toml))", source: source, change: .setting(key: key, value: toml)))
527 }
528 func note(_ reason: String) { unsupported.append(Note(id: id(), name: name, reason: reason, source: source)) }
529 let truthy = value.symbol != "nil" && value.elements?.isEmpty != true
530 switch name {
531 case "fill-column", "org-tags-column", "appt-message-warning-time", "org-deadline-warning-days":
532 guard let n = value.integer else { return note("not a number") }
533 add(name, .integer(n))
534 case "org-insert-heading-respect-content", "org-list-allow-alphabetical", "org-hide-emphasis-markers", "org-pretty-entities",
535 "org-cycle-hide-drawer-startup", "org-cycle-hide-block-startup", "org-use-speed-commands", "org-startup-with-inline-images", "org-startup-with-latex-preview",
536 "org-startup-indented", "org-hide-leading-stars", "org-startup-align-all-tables", "org-startup-truncated", "auto-fill-mode",
537 "org-enforce-todo-dependencies", "org-enforce-todo-checkbox-dependencies",
538 "org-agenda-todo-ignore-with-date", "org-agenda-tags-todo-honor-ignore-options", "org-clock-out-remove-zero-time-clocks",
539 "org-agenda-sort-notime-is-late", "org-agenda-sort-noeffort-is-high", "org-agenda-use-time-grid", "org-agenda-show-current-time-in-grid",
540 "org-habit-show-habits-only-for-today":
541 add(name, .bool(truthy))
542 case "org-archive-location":
543 guard let location = value.string, location.contains("::") else { return note("not a file::heading location") }
544 add(name, .string(location))
545 case "org-use-tag-inheritance":
546 if let regexp = value.string { add(name, .string("{\(regexp)}")) } else if let tags = value.elements, !tags.isEmpty {
547 add(name, .string(tags.compactMap(\.string).joined(separator: " ")))
548 } else { add(name, .string(truthy ? "t" : "nil")) }
549 case "org-tags-exclude-from-inheritance":
550 add(name, .string((value.elements ?? []).compactMap(\.string).joined(separator: " ")))
551 case "org-tag-alist":
552 guard let alist = Self.tagAlist(value.elements ?? []) else { return note("entries orgstar can't read") }
553 add(name, .string(alist))
554 case "org-track-ordered-property-with-tag":
555 if let tag = value.string { add(name, .string(tag)) } else { add(name, .string(truthy ? "t" : "nil")) }
556 case "org-agenda-log-mode-items":
557 let items = (value.elements ?? []).compactMap(\.symbol).filter { ["closed", "clock", "state"].contains($0) }
558 guard !items.isEmpty || value.symbol == "nil" else { return note("not a list of closed, clock and state") }
559 add(name, .string(items.joined(separator: " ")))
560 case "org-agenda-todo-ignore-scheduled", "org-agenda-todo-ignore-deadlines", "org-agenda-todo-ignore-timestamp":
561 if let days = value.integer { add(name, .string("\(days)")) } else if let symbol = value.symbol, AgendaOptions.TodoIgnore(symbol) != nil { add(name, .string(symbol)) } else { note("unexpected value \(value.description)") }
562 case "org-structure-template-alist":
563 structureTemplates(value.elements ?? [], source: source, id: id)
564 case "org-agenda-dim-blocked-tasks":
565 add(name, .string(value.symbol == "invisible" ? "invisible" : truthy ? "t" : "nil"))
566 case "org-hide-drawer-startup", "org-hide-block-startup":
567 add(name == "org-hide-drawer-startup" ? "org-cycle-hide-drawer-startup" : "org-cycle-hide-block-startup", .bool(truthy))
568 case "org-M-RET-may-split-line":
569 if let alist = value.elements, !alist.isEmpty {
570 // `((default . nil))`: the default entry, as most configurations write it.
571 let entry = alist.first { if case .dotted(let k, _) = $0 { return k.first?.symbol == "default" } else { return false } }
572 if case .dotted(_, let v)? = entry { add(name, .bool(v.symbol != "nil")) } else { note("per-context values aren't supported") }
573 } else {
574 add(name, .bool(truthy))
575 }
576 case "org-icalendar-use-deadline", "org-icalendar-use-scheduled":
577 let symbols = (value.elements ?? []).compactMap(\.symbol)
578 guard symbols.count == value.elements?.count || value.symbol == "nil" else { return note("not a list of symbols") }
579 add(name, .string(symbols.joined(separator: " ")))
580 case "org-icalendar-include-todo":
581 if let symbol = value.symbol, ["nil", "t", "all", "unblocked"].contains(symbol) { add(name, .string(symbol)) }
582 else if let keywords = value.elements?.compactMap(\.string), !keywords.isEmpty, keywords.count == value.elements?.count {
583 add(name, .string(keywords.joined(separator: " ")))
584 } else { note("unexpected value \(value.description)") }
585 case "org-timer-format":
586 guard let format = value.string, format.contains("%s") else { return note("not a string with %s") }
587 add(name, .string(format))
588 case "org-timer-default-timer":
589 if let text = value.string { add(name, .string(text)) } else if let number = value.integer { add(name, .string(String(number))) } else { note("not a string or number") }
590 case "denote-directory" where value.elements?.isEmpty == false, "denote-silo-directories":
591 guard let folders = value.elements?.compactMap(\.string), folders.count == value.elements?.count, !folders.contains(where: { $0.contains(":") }) else {
592 return note("not a list of folders without :")
593 }
594 add(name, .string(folders.joined(separator: ":")))
595 case "denote-directory", "denote-journal-directory", "denote-journal-keyword":
596 guard let text = value.string else { return note("not a string") }
597 add(name, .string(text))
598 case "denote-sequence-scheme":
599 guard let scheme = value.symbol, DenoteSequence.Scheme(rawValue: scheme) != nil else { return note("not numeric, alphanumeric or alphanumeric-delimited") }
600 add(name, .string(scheme))
601 case "denote-journal-interval":
602 guard let interval = value.symbol, ["daily", "weekly", "monthly", "yearly"].contains(interval) else { return note("not daily, weekly, monthly or yearly") }
603 add(name, .string(interval))
604 case "denote-journal-title-format":
605 let formats = ["day-date-month-year": "%A %-e %B %Y", "day-date-month-year-24h": "%A %-e %B %Y %H:%M",
606 "day-date-month-year-12h": "%A %-e %B %Y %I:%M %p", "day": "%A"]
607 if let format = value.string ?? value.symbol.flatMap({ formats[$0] }) { add(name, .string(format)) } else { note("not a format or a known style") }
608 case "denote-prompts":
609 guard let prompts = value.elements, prompts.allSatisfy({ $0.symbol != nil }) else { return note("not a list of prompts") }
610 add(name, .string(prompts.compactMap(\.symbol).joined(separator: " ")))
611 case "denote-templates":
612 guard let entries = value.elements else { return note("not a list of (KEY . TEXT)") }
613 for entry in entries {
614 guard case .dotted(let head, let tail) = entry, head.count == 1, let key = head[0].symbol else {
615 note("an entry that isn't (KEY . TEXT)")
616 continue
617 }
618 guard let text = tail.string else {
619 unsupported.append(Note(id: id(), name: "Denote template \(key)", reason: "a function, which only Emacs can run", source: source))
620 continue
621 }
622 guard key.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }) else {
623 unsupported.append(Note(id: id(), name: "Denote template \(key)", reason: "config.toml keys are letters, digits, _ and -", source: source))
624 continue
625 }
626 items.removeAll { if case .denoteTemplate(key, _) = $0.change { true } else { false } }
627 items.append(Item(id: id(), name: "Denote template \(key)", summary: "denote-templates.\(key) = \(UserConfig.format(.string(text)).prefix(60))",
628 source: source, change: .denoteTemplate(key: key, text: text)))
629 }
630 case "org-roam-directory", "org-roam-dailies-directory":
631 guard let dir = value.string else { return note("not a string") }
632 add(name, .string(dir))
633 case "org-roam-dailies-capture-templates":
634 // One template with a `(file+head NAME HEAD)` target: the settings; otherwise each
635 // template as a table.
636 let templates = value.elements ?? []
637 guard templates.count == 1, let first = templates[0].elements, first.count >= 4, let entry = first[3].string,
638 let at = first.firstIndex(of: .symbol(":target")), at + 1 < first.count, let target = first[at + 1].elements,
639 target.count == 3, target[0].symbol == "file+head", let file = target[1].string, let head = target[2].string else {
640 for template in templates { roamTemplate(template, set: .dailies, variable: name, source: source, id: id) }
641 return
642 }
643 add("org-roam-dailies-file", .string(file))
644 add("org-roam-dailies-head", .string(head))
645 add("org-roam-dailies-entry", .string(entry))
646 case "org-roam-capture-templates":
647 for template in value.elements ?? [] { roamTemplate(template, set: .node, variable: name, source: source, id: id) }
648 case "org-roam-capture-ref-templates":
649 for template in value.elements ?? [] { roamTemplate(template, set: .ref, variable: name, source: source, id: id) }
650 case "org-attach-id-dir":
651 guard let dir = value.string else { return note("not a string") }
652 add(name, .string(dir))
653 case "org-cite-global-bibliography":
654 guard let files = value.elements?.compactMap(\.string), files.count == value.elements?.count, !files.contains(where: { $0.contains(":") }) else {
655 return note("not a list of files without :")
656 }
657 add(name, .string(files.joined(separator: ":")))
658 case "org-attach-use-inheritance":
659 if value.symbol == "selective" { add(name, .string("selective")) } else { add(name, .string(truthy ? "t" : "nil")) }
660 case "org-yank-image-save-method":
661 if value.symbol == "attach" { add(name, .string("attach")) } else if let dir = value.string { add(name, .string(dir)) } else { note("not attach or a folder") }
662 case "org-yank-dnd-method":
663 guard let method = value.symbol, ["ask", "attach", "open", "file-link"].contains(method) else { return note("not ask, attach, open or file-link") }
664 add(name, .string(method))
665 case "org-crypt-tag-matcher":
666 guard let tag = value.string, tag.range(of: "^[\\w@#%]+$", options: .regularExpression) != nil else { return note("not a single tag") }
667 add(name, .string(tag))
668 case "org-display-remote-inline-images":
669 guard let mode = value.symbol, ["skip", "download", "cache"].contains(mode) else { return note("not skip, download or cache") }
670 add(name, .string(mode))
671 case "org-icalendar-combined-agenda-file":
672 guard let file = value.string ?? Self.evaluate(value, env)?.string else { return note("not a file name") }
673 add(name, .string(file))
674 case "org-refile-targets":
675 switch RefileSettings.parseTargets(value.description) {
676 case .success: add(name, .string(value.description))
677 case .failure(.message(let message)): note(message)
678 }
679 case "org-refile-use-outline-path":
680 let mode = value.symbol ?? "nil"
681 guard RefileSettings.OutlinePath(rawValue: mode) != nil else { return note("unexpected value \(value.description)") }
682 add(name, .string(mode))
683 case "org-refile-allow-creating-parent-nodes":
684 let mode = value.symbol ?? "nil"
685 add(name, .string(RefileSettings.Creating(rawValue: mode) == nil ? "t" : mode))
686 case "org-stuck-projects":
687 // `("+LEVEL=2/-DONE" ("TODO" "NEXT") nil "")`.
688 guard let parts = value.elements, parts.count == 4, let match = parts[0].string else { return note("not a stuck-projects definition") }
689 add("org-stuck-projects.match", .string(match))
690 add("org-stuck-projects.todo", .string((parts[1].elements ?? []).compactMap(\.string).joined(separator: " ")))
691 add("org-stuck-projects.tags", .string((parts[2].elements ?? []).compactMap(\.string).joined(separator: " ")))
692 add("org-stuck-projects.regexp", .string(parts[3].string ?? ""))
693 case "org-agenda-time-grid":
694 // `((daily today require-timed) (800 1000 …) "......" "----------------")`: the
695 // strings are how Emacs draws the lines.
696 guard let parts = value.elements, parts.count >= 2, let when = parts[0].elements, let times = parts[1].elements else { return note("not a time grid") }
697 add("org-agenda-time-grid.when", .string(when.compactMap(\.symbol).joined(separator: " ")))
698 add("org-agenda-time-grid.times", .string(times.compactMap { $0.integer.map(String.init) ?? $0.string }.joined(separator: " ")))
699 case "org-agenda-sorting-strategy":
700 // `((agenda habit-down time-up) (todo urgency-down))`, or one list for every view.
701 func keys(_ items: [Sexp]) -> String? {
702 let names = items.compactMap(\.symbol)
703 guard names.count == items.count else { return nil }
704 if let bad = names.first(where: { !AgendaSort.keys.contains($0) }) { note("\(bad) isn't supported"); return nil }
705 return names.joined(separator: " ")
706 }
707 let entries = value.elements ?? []
708 if entries.allSatisfy({ $0.symbol != nil }) {
709 if let s = keys(entries) { for view in ["agenda", "todo", "tags", "search"] { add("org-agenda-sorting-strategy.\(view)", .string(s)) } }
710 } else {
711 for entry in entries {
712 var items = entry.elements
713 if case .dotted(let head, let tail) = entry { items = head + (tail.elements ?? [tail]) }
714 guard let items, let view = items.first?.symbol, ["agenda", "todo", "tags", "search"].contains(view) else { continue }
715 if let s = keys(Array(items.dropFirst())) { add("org-agenda-sorting-strategy.\(view)", .string(s)) }
716 }
717 }
718 case "org-agenda-prefix-format":
719 if let s = value.string {
720 for view in ["agenda", "todo", "tags"] { add("org-agenda-prefix-format.\(view)", .string(s)) }
721 } else {
722 for entry in value.elements ?? [] {
723 guard case .dotted(let key, let format) = entry, let view = key.first?.symbol, let s = format.string else { continue }
724 if ["agenda", "todo", "tags"].contains(view) { add("org-agenda-prefix-format.\(view)", .string(s)) }
725 }
726 }
727 case "org-log-done", "org-log-reschedule", "org-log-redeadline":
728 switch value.symbol {
729 case "nil": add(name, .string("nil"))
730 case "time", "t": add(name, .string("time"))
731 case "note": add(name, .string("note"))
732 default: note("unexpected value \(value.description)")
733 }
734 case "org-log-into-drawer":
735 if let s = value.string { add(name, .string(s)) } else { add(name, .string(truthy ? "LOGBOOK" : "")) }
736 case "display-line-numbers-type":
737 if let type = value.symbol, ["relative", "visual"].contains(type) { add(name, .string(type)) } else { add(name, .bool(truthy)) }
738 case "org-agenda-span":
739 let days: Int? = value.integer ?? ["day": 1, "week": 7, "fortnight": 14, "month": 30, "year": 365][value.symbol ?? ""]
740 guard let days else { return note("unknown span \(value.description)") }
741 add(name, .integer(days))
742 case "org-agenda-start-on-weekday":
743 if value.symbol == "nil" { add(name, .string("nil")) } else if let day = value.integer, (0...6).contains(day) { add(name, .string("\(day)")) } else { note("not nil or a weekday from 0 to 6") }
744 case "org-clock-idle-time":
745 // nil is never; a number is minutes.
746 if value.symbol == "nil" { add(name, .integer(0)) } else if let minutes = value.integer, minutes > 0 { add(name, .integer(minutes)) } else { note("not a number of minutes") }
747 case "org-clock-rounding-minutes":
748 guard let n = value.integer, n >= 0 else { return note("not a number of minutes") }
749 add(name, .integer(n))
750 case "org-clock-in-switch-to-state":
751 if let state = value.string { add(name, .string(state)) } else if value.symbol == "nil" { add(name, .string("")) } else { note("a function isn't supported; use a keyword") }
752 case "org-clock-out-when-done":
753 if let states = value.elements, !states.isEmpty {
754 let names = states.compactMap(\.string)
755 guard names.count == states.count else { return note("not a list of keywords") }
756 add(name, .string(names.joined(separator: " ")))
757 } else {
758 add(name, .string(truthy ? "t" : "nil"))
759 }
760 case "org-clock-into-drawer":
761 if let drawer = value.string { add(name, .string(drawer)) } else if let n = value.integer { add(name, .string("\(n)")) } else { add(name, .string(truthy ? "t" : "nil")) }
762 case "org-clock-history-length":
763 guard let length = value.integer, length > 0 else { return note("not a positive number") }
764 add(name, .integer(length))
765 case "org-agenda-start-day":
766 if value.symbol == "nil" { add(name, .string("+0d")) } else if let s = value.string, UserConfig.dayOffset(s) != nil { add(name, .string(s)) } else { note("only day offsets such as \"-3d\" are supported") }
767 case "org-todo-keywords":
768 let sequences = (value.elements ?? []).compactMap { $0.elements }.filter { $0.count > 1 }.map { $0.dropFirst().compactMap(\.string) }
769 let lines = sequences.filter { !$0.contains { $0.contains(where: \.isWhitespace) } }.map { $0.joined(separator: " ") }
770 guard !lines.isEmpty else { return note("unexpected value") }
771 if lines.count < sequences.count {
772 note("\(sequences.count - lines.count) sequence(s) with spaces in a keyword left out; #+TODO syntax can't write them")
773 }
774 if (value.elements ?? []).contains(where: { $0.elements?.first?.symbol == "type" }) { note("type sequences are read as sequences") }
775 add(name, .string(lines.joined(separator: "\n")))
776 case "org-directory":
777 guard let path = value.string else { return note("not a folder") }
778 items.append(Item(id: id(), name: name, summary: "add folder \(path)", source: source, change: .folder(path)))
779 case "org-agenda-files":
780 let paths = (value.elements ?? [value]).compactMap(\.string)
781 guard !paths.isEmpty else { return note("not a list of files or folders") }
782 add(name, .string(paths.joined(separator: "\n")))
783 // A file listing the files (the variable's string form) gives no folder.
784 if value.string != nil, !paths[0].hasSuffix(".org") { return }
785 // A relative entry counts from org-directory, so it has no folder of its own.
786 for path in paths where OrgPaths.expandingTilde(path).hasPrefix("/") {
787 let folder = path.hasSuffix(".org") ? (path as NSString).deletingLastPathComponent : path
788 items.append(Item(id: id(), name: name, summary: "add folder \(folder)", source: source, change: .folder(folder)))
789 }
790 case "org-capture-templates":
791 for entry in value.elements ?? [] { captureTemplate(entry, source: source, env: env, id: id) }
792 case "org-agenda-custom-commands":
793 for entry in value.elements ?? [] { agendaCommand(entry, source: source, id: id) }
794 case "org-publish-project-alist":
795 for entry in value.elements ?? [] { publishProject(entry, source: source, env: env, id: id) }
796 case "doom-font":
797 note("not a font-spec orgstar can read")
798 case "doom-variable-pitch-font":
799 note("orgstar uses one font; set it with doom-font or [theme] font")
800 case "doom-theme":
801 note("Emacs themes aren't read; set colors under [theme] in config.toml")
802 default:
803 note("orgstar has no equivalent")
804 }
805 }
806
807 /// `org-tag-alist` in `#+TAGS` syntax: `("work" . ?w)` is `work(w)`, `(:startgroup)` `{`,
808 /// `(:startgrouptag)` `[`, `(:grouptags)` `:`, and `(:newline)` a new line.
809 static func tagAlist(_ entries: [Sexp]) -> String? {
810 var lines: [[String]] = [[]]
811 for entry in entries {
812 let marker = entry.elements?.first?.symbol ?? entry.symbol
813 switch marker {
814 case ":startgroup": lines[lines.count - 1].append("{")
815 case ":endgroup": lines[lines.count - 1].append("}")
816 case ":startgrouptag": lines[lines.count - 1].append("[")
817 case ":endgrouptag": lines[lines.count - 1].append("]")
818 case ":grouptags": lines[lines.count - 1].append(":")
819 case ":newline": lines.append([])
820 default:
821 if let tag = entry.string {
822 lines[lines.count - 1].append(tag)
823 } else if case .dotted(let head, let key) = entry, head.count == 1, let tag = head[0].string {
824 guard case .character(let code) = key, let scalar = Unicode.Scalar(code) else {
825 lines[lines.count - 1].append(tag)
826 continue
827 }
828 lines[lines.count - 1].append("\(tag)(\(Character(scalar)))")
829 } else {
830 return nil
831 }
832 }
833 }
834 return lines.map { $0.joined(separator: " ") }.filter { !$0.isEmpty }.joined(separator: "\n")
835 }
836
837 /// `("el" . "src emacs-lisp")` entries that aren't Org's own.
838 mutating func structureTemplates(_ entries: [Sexp], source: String, id: () -> Int) {
839 for entry in entries {
840 guard case .dotted(let head, let tail) = entry, head.count == 1, let key = head[0].string, let type = tail.string else {
841 unsupported.append(Note(id: id(), name: "org-structure-template-alist", reason: "an entry that isn't (\"key\" . \"type\")", source: source))
842 continue
843 }
844 if StructureTemplate.defaults.contains(StructureTemplate(key: key, type: type)) { continue }
845 guard !key.isEmpty, key.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }) else {
846 unsupported.append(Note(id: id(), name: "structure template \"\(key)\"", reason: "config.toml keys are letters, digits, _ and -", source: source))
847 continue
848 }
849 items.removeAll { if case .structureTemplate(key, _) = $0.change { true } else { false } }
850 items.append(Item(id: id(), name: "structure template \"\(key)\"", summary: "<\(key) inserts a \(type) block", source: source,
851 change: .structureTemplate(key: key, type: type)))
852 }
853 }
854
855 /// An `org-agenda-custom-commands` entry as a `[[view]]` table: `("w" "Work" tags "+work"
856 /// ((settings)))`, or with a list of blocks in place of the type and match.
857 mutating func agendaCommand(_ entry: Sexp, source: String, id: () -> Int) {
858 guard var parts = entry.elements, let key = parts.first?.string else { return }
859 parts.removeFirst()
860 let name = parts.first?.string ?? key
861 if parts.first?.string != nil { parts.removeFirst() }
862 // A key and a description only: a prefix for other commands.
863 guard let first = parts.first else { return }
864 func note(_ reason: String) { unsupported.append(Note(id: id(), name: "agenda command \"\(key)\"", reason: reason, source: source)) }
865 func quoted(_ s: String) -> String { UserConfig.format(.string(s)) }
866 func unquote(_ s: Sexp) -> Sexp {
867 if case .list(let items) = s, items.count == 2, items[0].symbol == "quote" || items[0].symbol == "function" { return items[1] }
868 return s
869 }
870 /// `(type match settings)` as TOML lines, or nil with a note.
871 func view(_ type: String, _ match: Sexp?, _ settings: Sexp?) -> String? {
872 var toml = ""
873 let matchString = match.flatMap { unquote($0).string }.flatMap { $0.isEmpty ? nil : $0 }
874 switch type {
875 case "agenda": toml += "type = \"agenda\"\n"
876 case "alltodo": toml += "type = \"todo\"\n"
877 case "todo":
878 toml += "type = \"todo\"\n"
879 if let matchString { toml += "keywords = \(quoted(matchString))\n" }
880 case "tags", "tags-todo", "search":
881 guard let matchString else { note("\(type) needs a match"); return nil }
882 let kind = ["tags": "match", "tags-todo": "todo-match", "search": "search"][type]!
883 toml += "type = \"\(kind)\"\nmatch = \(quoted(matchString))\n"
884 case "stuck": toml += "type = \"stuck\"\n"
885 default: note("\(type) views aren't supported"); return nil
886 }
887 guard let settings = settings.map(unquote), let pairs = settings.elements else { return toml }
888 for pair in pairs {
889 guard let items = pair.elements, items.count == 2, let variable = items[0].symbol else { continue }
890 let value = unquote(items[1])
891 switch variable {
892 case "org-agenda-span" where type == "agenda":
893 let spans = ["day": 1, "week": 7, "fortnight": 14, "month": 30, "year": 365]
894 if let n = value.integer ?? value.symbol.flatMap({ spans[$0] }) { toml += "span = \(n)\n" } else { note("org-agenda-span \(value.description)") }
895 case "org-agenda-start-day" where type == "agenda":
896 if let s = value.string, let n = Int(s.replacingOccurrences(of: "d", with: "").replacingOccurrences(of: "+", with: "")) {
897 toml += "start = \(n)\n"
898 } else { note("org-agenda-start-day \(value.description)") }
899 case "org-agenda-overriding-header":
900 if let s = value.string { toml += "header = \(quoted(s))\n" }
901 case "org-agenda-sorting-strategy":
902 let keys = (value.elements ?? []).compactMap(\.symbol)
903 if !keys.isEmpty, keys.allSatisfy(AgendaSort.keys.contains) { toml += "sorting-strategy = \(quoted(keys.joined(separator: " ")))\n" } else { note("org-agenda-sorting-strategy \(value.description)") }
904 case "org-agenda-prefix-format":
905 if let s = value.string { toml += "prefix-format = \(quoted(s))\n" } else { note("org-agenda-prefix-format as an alist") }
906 case "org-agenda-skip-function":
907 guard let form = value.elements, let head = form.first?.symbol, ["org-agenda-skip-entry-if", "org-agenda-skip-subtree-if"].contains(head) else {
908 note("org-agenda-skip-function \(value.description)")
909 continue
910 }
911 let subtree = head == "org-agenda-skip-subtree-if"
912 switch AgendaSkip.parse(form.dropFirst().map(\.description).joined(separator: " "), subtree: subtree) {
913 case .success(let skip): toml += "\(subtree ? "skip-subtree-if" : "skip-entry-if") = \(quoted(skip.lisp))\n"
914 case .failure(.message(let message)): note("org-agenda-skip-function: \(message)")
915 }
916 default:
917 note("\(variable) in a view isn't supported")
918 }
919 }
920 return toml
921 }
922 var toml = "[[view]]\nname = \(quoted(name))\n"
923 if let type = first.symbol {
924 if type == "agenda*" { note("agenda* views aren't supported"); return }
925 guard let body = view(type, parts.count > 1 ? parts[1] : nil, parts.count > 2 ? parts[2] : nil) else { return }
926 toml += body
927 if parts.count > 3 { note("files for a view are ignored") }
928 } else if let blocks = first.elements {
929 // Settings for all the blocks come after them.
930 var common = view("agenda", nil, parts.count > 1 ? parts[1] : nil) ?? ""
931 common = common.replacingOccurrences(of: "type = \"agenda\"\n", with: "")
932 toml += common
933 var count = 0
934 for block in blocks {
935 guard let items = block.elements, let type = items.first?.symbol,
936 let body = view(type, items.count > 1 ? items[1] : nil, items.count > 2 ? items[2] : nil) else { continue }
937 toml += "[[view.block]]\n" + body
938 count += 1
939 }
940 guard count > 0 else { return }
941 if parts.count > 2 { note("files for a view are ignored") }
942 } else {
943 return note("not a view orgstar can read")
944 }
945 items.append(Item(id: id(), name: "org-agenda-custom-commands \"\(key)\"", summary: "views.toml view \(name)", source: source, change: .view(name: name, toml: toml)))
946 }
947
948 /// An `org-publish-project-alist` entry as a `[[publish]]` table, when its publishing
949 /// functions are ones orgstar has.
950 mutating func publishProject(_ entry: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) {
951 guard let parts = entry.elements, let name = parts.first?.string else { return }
952 func note(_ reason: String) { unsupported.append(Note(id: id(), name: "publishing project \"\(name)\"", reason: reason, source: source)) }
953 func quoted(_ s: String) -> String { UserConfig.format(.string(s)) }
954 var toml = "[[publish]]\nname = \(quoted(name))\n"
955 var left: [String] = []
956 let rest = Array(parts.dropFirst())
957 for i in stride(from: 0, to: rest.count - 1, by: 2) {
958 guard let key = rest[i].symbol else { continue }
959 let value = rest[i + 1]
960 let truthy = value.symbol != "nil" && value.elements?.isEmpty != true
961 let strings = value.elements?.compactMap { $0.string ?? Self.evaluate($0, env)?.string }
962 let symbols = value.symbol.map { [$0] } ?? value.elements?.compactMap(\.symbol)
963 switch key {
964 case ":base-directory", ":publishing-directory", ":exclude", ":sitemap-filename", ":sitemap-title":
965 guard let s = value.string ?? Self.evaluate(value, env)?.string else { return note("\(key) isn't a string") }
966 toml += "\(key.dropFirst()) = \(quoted(s))\n"
967 case ":base-extension":
968 guard let s = value.string ?? value.symbol else { return note(":base-extension isn't a string") }
969 toml += "base-extension = \(quoted(s))\n"
970 case ":recursive", ":auto-sitemap", ":sitemap-ignore-case", ":body-only":
971 toml += "\(key.dropFirst()) = \(truthy)\n"
972 case ":include", ":components":
973 guard let strings, strings.count == value.elements?.count else { return note("\(key) isn't a list of names") }
974 toml += "\(key.dropFirst()) = \(quoted(strings.joined(separator: " ")))\n"
975 case ":publishing-function":
976 guard let symbols, !symbols.isEmpty, symbols.allSatisfy(PublishProject.functions.contains) else {
977 return note("publishing function \(value.description) isn't one orgstar has")
978 }
979 toml += "publishing-function = \(quoted(symbols.joined(separator: " ")))\n"
980 case ":sitemap-style", ":sitemap-sort-files", ":sitemap-sort-folders":
981 guard let s = value.symbol else { return note("\(key) isn't a symbol") }
982 toml += "\(key.dropFirst()) = \(quoted(s))\n"
983 default:
984 left.append(key)
985 }
986 }
987 if !left.isEmpty { note("\(left.joined(separator: ", ")) left out") }
988 items.append(Item(id: id(), name: "publishing project \"\(name)\"", summary: "config.toml [[publish]] \(name)", source: source, change: .publish(name: name, toml: toml)))
989 }
990
991 mutating func captureTemplate(_ entry: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) {
992 guard let parts = entry.elements, parts.count >= 2, let key = parts[0].string else { return }
993 let name = parts[1].string ?? key
994 func quoted(_ s: String) -> String { UserConfig.format(.string(s)) }
995 guard parts.count >= 5, let type = parts[2].symbol, let target = parts[3].elements, let kind = target.first?.symbol,
996 let template = parts[4].string else {
997 // A key and a name only: a group of templates.
998 if parts.count == 2 {
999 let toml = "[[template]]\nkey = \(quoted(key))\nname = \(quoted(name))\n"
1000 items.append(Item(id: id(), name: "capture \"\(key)\" \(name)", summary: "capture group \"\(key)\"", source: source, change: .capture(key: key, toml: toml)))
1001 }
1002 if parts.count == 2 { return }
1003 unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "a template that isn't a string", source: source))
1004 return
1005 }
1006 guard ["entry", "item", "checkitem", "plain", "table-line"].contains(type) else {
1007 unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "\(type) templates aren't supported", source: source))
1008 return
1009 }
1010 var toml = "[[template]]\nkey = \(quoted(key))\nname = \(quoted(name))\ntype = \(quoted(type))\n"
1011 // `org-capture-expand-file`: a variable's value, or a form evaluated.
1012 let strings = target.dropFirst().compactMap { $0.string ?? Self.evaluate($0, env)?.string }
1013 // Property list after the template: `:prepend t :empty-lines 1 …`.
1014 var properties: [String: Sexp] = [:]
1015 let rest = Array(parts.dropFirst(5))
1016 for i in stride(from: 0, to: rest.count - 1, by: 2) { if let name = rest[i].symbol { properties[name] = rest[i + 1] } }
1017 let allStrings = strings.count == target.count - 1
1018 // A symbol, or a list of groups such as `(year quarter)`.
1019 var treeType = properties[":tree-type"].flatMap { value in
1020 value.symbol ?? value.elements.flatMap { list in
1021 let words = list.compactMap(\.symbol)
1022 return words.count == list.count ? words.joined(separator: " ") : nil
1023 }
1024 }
1025 let place: String? = switch kind {
1026 case "file" where strings.count == 1 && target.count == 2:
1027 "file = \(quoted(strings[0]))\n"
1028 case "file+headline" where strings.count == 2 && target.count == 3:
1029 "file = \(quoted(strings[0]))\nheadline = \(quoted(strings[1]))\n"
1030 case "file+regexp" where strings.count == 2 && target.count == 3:
1031 "file = \(quoted(strings[0]))\nregexp = \(quoted(strings[1]))\n"
1032 case "file+olp" where strings.count >= 2 && allStrings:
1033 "file = \(quoted(strings[0]))\nolp = \(quoted(strings.dropFirst().joined(separator: "/")))\n"
1034 case "file+olp+datetree" where strings.count >= 1 && allStrings:
1035 "file = \(quoted(strings[0]))\ndatetree = true\n" + (strings.count > 1 ? "olp = \(quoted(strings.dropFirst().joined(separator: "/")))\n" : "")
1036 case let legacy where (legacy == "file+datetree" || legacy == "file+weektree") && strings.count == 1 && target.count == 2:
1037 "file = \(quoted(strings[0]))\ndatetree = true\n"
1038 case "id" where strings.count == 1 && target.count == 2:
1039 "id = \(quoted(strings[0]))\n"
1040 case "clock" where target.count == 1:
1041 "clock = true\n"
1042 default:
1043 nil
1044 }
1045 guard let place else {
1046 unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "target \(kind) isn't supported", source: source))
1047 return
1048 }
1049 if kind == "file+weektree" { treeType = "week" }
1050 toml += place
1051 if let treeType {
1052 guard let tree = CaptureTemplate.TreeType(rawValue: treeType) else {
1053 unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: ":tree-type \(treeType) isn't supported", source: source))
1054 return
1055 }
1056 if tree != .day { toml += "tree-type = \(quoted(tree.rawValue))\n" }
1057 }
1058 for flag in ["prepend", "immediate-finish", "jump-to-captured", "clock-in", "clock-keep", "clock-resume", "time-prompt"] {
1059 if let value = properties[":" + flag], value.symbol != "nil" { toml += "\(flag) = true\n" }
1060 }
1061 for count in ["empty-lines", "empty-lines-before", "empty-lines-after"] {
1062 if let n = properties[":" + count]?.integer { toml += "\(count) = \(n)\n" }
1063 }
1064 if let pos = properties[":table-line-pos"]?.string { toml += "table-line-pos = \(quoted(pos))\n" }
1065 let ignored = properties.keys.filter { ![":prepend", ":immediate-finish", ":jump-to-captured", ":clock-in", ":clock-keep", ":clock-resume", ":empty-lines", ":empty-lines-before", ":empty-lines-after", ":tree-type", ":table-line-pos", ":time-prompt"].contains($0) }
1066 if !ignored.isEmpty {
1067 unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "\(ignored.sorted().joined(separator: ", ")) left out", source: source))
1068 }
1069 toml += "template = \(quoted(template))\n"
1070 items.append(Item(id: id(), name: "capture \"\(key)\" \(name)", summary: "capture template \"\(key)\"", source: source, change: .capture(key: key, toml: toml)))
1071 }
1072
1073 /// An org-roam capture template, `(KEY NAME TYPE TEMPLATE :target TARGET …)`, as a table:
1074 /// targets `file`, `file+head`, `file+olp` and `file+head+olp` (`:if-new` too, as org-roam
1075 /// 2.0 named it).
1076 mutating func roamTemplate(_ entry: Sexp, set: RoamTemplate.Set, variable: String, source: String, id: () -> Int) {
1077 func quoted(_ s: String) -> String { UserConfig.format(.string(s)) }
1078 guard let parts = entry.elements, parts.count >= 4, let key = parts[0].string, let type = parts[2].symbol, let template = parts[3].string else {
1079 unsupported.append(Note(id: id(), name: variable, reason: "a template that isn't (KEY NAME TYPE \"TEMPLATE\" …)", source: source))
1080 return
1081 }
1082 let name = "\(variable) \"\(key)\""
1083 guard ["entry", "item", "checkitem", "plain", "table-line"].contains(type) else {
1084 unsupported.append(Note(id: id(), name: name, reason: "\(type) templates aren't supported", source: source))
1085 return
1086 }
1087 var properties: [String: Sexp] = [:]
1088 let rest = Array(parts.dropFirst(4))
1089 for i in stride(from: 0, to: rest.count - 1, by: 2) { if let name = rest[i].symbol { properties[name] = rest[i + 1] } }
1090 var toml = "[[\(set.rawValue)]]\nkey = \(quoted(key))\nname = \(quoted(parts[1].string ?? key))\ntype = \(quoted(type))\n"
1091 let target = (properties[":target"] ?? properties[":if-new"])?.elements ?? []
1092 let olp = target.last?.elements.flatMap { list in list.allSatisfy { $0.string != nil } ? list.compactMap(\.string).joined(separator: "/") : nil }
1093 switch (target.first?.symbol, target.count) {
1094 case ("file", 2) where target[1].string != nil:
1095 toml += "file = \(quoted(target[1].string!))\n"
1096 case ("file+head", 3) where target[1].string != nil && target[2].string != nil:
1097 toml += "file = \(quoted(target[1].string!))\nhead = \(quoted(target[2].string!))\n"
1098 case ("file+olp", 3) where target[1].string != nil && olp != nil:
1099 toml += "file = \(quoted(target[1].string!))\nolp = \(quoted(olp!))\n"
1100 case ("file+head+olp", 4) where target[1].string != nil && target[2].string != nil && olp != nil:
1101 toml += "file = \(quoted(target[1].string!))\nhead = \(quoted(target[2].string!))\nolp = \(quoted(olp!))\n"
1102 default:
1103 let kind = target.first?.symbol.map { "target \($0) isn't supported" } ?? "no :target"
1104 unsupported.append(Note(id: id(), name: name, reason: kind, source: source))
1105 return
1106 }
1107 for flag in ["prepend", "immediate-finish", "jump-to-captured"] {
1108 if let value = properties[":" + flag], value.symbol != "nil" { toml += "\(flag) = true\n" }
1109 }
1110 for count in ["empty-lines", "empty-lines-before", "empty-lines-after"] {
1111 if let n = properties[":" + count]?.integer { toml += "\(count) = \(n)\n" }
1112 }
1113 // The capture window shows the template's text whether or not it's narrowed.
1114 let known = [":target", ":if-new", ":unnarrowed", ":prepend", ":immediate-finish", ":jump-to-captured", ":empty-lines", ":empty-lines-before", ":empty-lines-after"]
1115 let ignored = properties.keys.filter { !known.contains($0) }
1116 if !ignored.isEmpty {
1117 unsupported.append(Note(id: id(), name: name, reason: "\(ignored.sorted().joined(separator: ", ")) left out", source: source))
1118 }
1119 toml += "template = \(quoted(template))\n"
1120 items.append(Item(id: id(), name: name, summary: "\(set.rawValue) \"\(key)\"", source: source, change: .roamTemplate(set: set.rawValue, key: key, toml: toml)))
1121 }
1122
1123 /// Emacs commands and the Orgstar commands that do the same.
1124 static let commands: [String: String] = [
1125 "org-todo": "org.todo.cycle", "org-shiftright": "org.todo.next", "org-shiftleft": "org.todo.previous", "org-priority-up": "org.priority.up", "org-priority-down": "org.priority.down",
1126 "org-metaleft": "org.heading.promote", "org-metaright": "org.heading.demote", "org-do-promote": "org.heading.promote", "org-do-demote": "org.heading.demote",
1127 "org-promote-subtree": "org.subtree.promote", "org-demote-subtree": "org.subtree.demote",
1128 "org-shiftmetaleft": "org.subtree.promote", "org-shiftmetaright": "org.subtree.demote",
1129 "org-move-subtree-up": "org.subtree.up", "org-move-subtree-down": "org.subtree.down", "org-metaup": "org.subtree.up", "org-metadown": "org.subtree.down",
1130 "org-insert-heading": "org.heading.insert", "org-meta-return": "org.heading.insert",
1131 "org-insert-heading-respect-content": "org.heading.insert-after-subtree", "+org/insert-item-below": "org.heading.insert-after-subtree",
1132 "org-insert-todo-heading": "org.heading.insert-todo",
1133 "org-next-visible-heading": "org.heading.next", "org-previous-visible-heading": "org.heading.previous",
1134 "org-forward-heading-same-level": "org.heading.forward-same-level", "org-backward-heading-same-level": "org.heading.backward-same-level",
1135 "outline-up-heading": "org.heading.up", "org-up-element": "org.heading.up",
1136 "org-set-tags-command": "org.tags.set", "org-set-property": "org.property.read-and-set",
1137 "org-toggle-checkbox": "org.checkbox.toggle", "org-ctrl-c-ctrl-c": "org.ctrl-c-ctrl-c", "+org/dwim-at-point": "org.dwim",
1138 "org-schedule": "org.schedule", "org-deadline": "org.deadline", "org-time-stamp": "org.timestamp.active", "org-timestamp": "org.timestamp.active",
1139 "org-time-stamp-inactive": "org.timestamp.inactive", "org-timestamp-inactive": "org.timestamp.inactive",
1140 "org-fill-paragraph": "org.fill-paragraph", "org-cycle": "org.cycle", "org-shifttab": "org.cycle-global", "org-global-cycle": "org.cycle-global",
1141 "org-table-create": "org.table.create", "org-table-align": "org.table.align", "org-table-recalculate": "org.table.recalc",
1142 "org-table-insert-row": "org.table.insert-row", "org-table-insert-column": "org.table.insert-column",
1143 "org-table-delete-column": "org.table.delete-column", "org-table-kill-row": "org.table.kill-row", "org-table-insert-hline": "org.table.insert-hline",
1144 "org-babel-execute-src-block": "org.babel.execute", "org-clock-in": "app.clock.in", "org-clock-out": "app.clock.out",
1145 "org-clock-cancel": "app.clock.cancel", "org-clock-goto": "app.clock.goto", "org-clock-in-last": "app.clock.in-last",
1146 "org-resolve-clocks": "app.clock.resolve", "org-clock-mark-default-task": "app.clock.default",
1147 "org-refile": "app.refile", "org-copy": "app.refile.copy", "org-refile-copy": "app.refile.copy", "org-archive-subtree": "app.archive", "org-archive-subtree-default": "app.archive",
1148 "org-capture": "app.capture", "org-agenda": "app.agenda", "org-agenda-list": "app.agenda",
1149 "save-buffer": "app.save", "find-file": "app.quick-open", "projectile-find-file": "app.quick-open", "+default/find-file-under-here": "app.quick-open",
1150 "execute-extended-command": "app.palette", "counsel-M-x": "app.palette",
1151 "isearch-forward": "edit.find", "isearch-backward": "edit.find", "consult-line": "edit.find", "+default/search-buffer": "edit.find", "swiper": "edit.find",
1152 "query-replace": "edit.replace", "query-replace-regexp": "edit.replace",
1153 "save-buffers-kill-terminal": "app.quit", "save-buffers-kill-emacs": "app.quit",
1154 ]
1155}
1156
1157extension EmacsImport {
1158 /// The paths of `items`' folders that aren't in the sidebar yet, as written.
1159 @MainActor
1160 public static func foldersToAdd(_ items: [Item], workspace: WorkspaceModel?) -> [String] {
1161 items.compactMap { item in
1162 guard case .folder(let path) = item.change else { return nil }
1163 let url = URL(fileURLWithPath: OrgPaths.expandingTilde(path)).standardizedFileURL
1164 if let workspace, isRoot(url, in: workspace) { return nil }
1165 return path
1166 }
1167 }
1168
1169 /// `org-agenda-files` (one path a line) with each path below a folder in `chosenFolders` moved
1170 /// to the folder chosen for it. Relative paths are kept as written; they count from the first
1171 /// folder, standing in for `org-directory`. Other paths with no chosen folder that don't exist
1172 /// here are left out; nil when none remain. With `keepingOriginals`, for a config.toml the Mac reads too,
1173 /// the Mac's paths are all kept, a moved one beside its new path; each device skips the paths
1174 /// it doesn't have.
1175 static func agendaFiles(_ list: String, chosenFolders: [String: URL], keepingOriginals: Bool = false) -> String? {
1176 func standard(_ path: String) -> String { URL(fileURLWithPath: OrgPaths.expandingTilde(path)).standardizedFileURL.path }
1177 let folders = chosenFolders.map { (standard($0.key), $0.value.standardizedFileURL.path) }.sorted { $0.0.count > $1.0.count }
1178 var here: [String] = [], all: [String] = []
1179 for path in list.split(separator: "\n").map(String.init) {
1180 guard OrgPaths.expandingTilde(path).hasPrefix("/") else {
1181 here.append(path)
1182 all.append(path)
1183 continue
1184 }
1185 let full = standard(path)
1186 if let (mac, device) = folders.first(where: { full == $0.0 || full.hasPrefix($0.0 + "/") }) {
1187 let moved = device + full.dropFirst(mac.count)
1188 here.append(moved)
1189 all += moved == full ? [path] : [path, moved]
1190 } else {
1191 if FileManager.default.fileExists(atPath: full) { here.append(path) }
1192 all.append(path)
1193 }
1194 }
1195 guard !here.isEmpty else { return nil }
1196 return (keepingOriginals ? all : here).joined(separator: "\n")
1197 }
1198
1199 @MainActor
1200 static func isRoot(_ url: URL, in workspace: WorkspaceModel) -> Bool {
1201 workspace.roots.contains { URL(fileURLWithPath: $0.path).standardizedFileURL.path == url.path }
1202 }
1203
1204 /// Applies `items`: settings to `defaults` (and so config.toml), folders to the workspace,
1205 /// capture templates and key bindings appended to capture.toml and keymap.toml in
1206 /// `directory`, leaving out templates whose key is there already and bindings that are
1207 /// there already. A file that is there but can't be read is left as it is. Returns a summary,
1208 /// which counts only what was written.
1209 @MainActor
1210 /// With `writeConfig`, settings and structure templates are written into `config.toml` too,
1211 /// for where nothing syncs user defaults into it (iOS). With `chosenFolders`, folders chosen in
1212 /// open panels by the path of their item, a folder item is added only as the folder chosen for it.
1213 /// `org-agenda-files` paths below a chosen folder are moved into it; see `agendaFiles`.
1214 public static func apply(
1215 _ items: [Item], defaults: UserDefaults = .standard, workspace: WorkspaceModel?, directory: URL = UserConfig.directory,
1216 writeConfig: Bool = false, chosenFolders: [String: URL]? = nil
1217 ) async -> String {
1218 var stored: [UserConfig.Setting] = []
1219 var settings = 0, folders = 0, templates = 0, bindings = 0, blocks = 0, views = 0, projects = 0
1220 var problems: [String] = []
1221 for item in items {
1222 guard case .setting(let key, var value) = item.change,
1223 let setting = UserConfig.settings.first(where: { $0.path == key || $0.key == key }) else { continue }
1224 if key == "org-agenda-files", let chosenFolders {
1225 guard let paths = Self.agendaFiles(value.string ?? "", chosenFolders: chosenFolders, keepingOriginals: writeConfig) else {
1226 problems.append("org-agenda-files wasn't set: no folder was chosen for its files")
1227 continue
1228 }
1229 value = .string(paths)
1230 }
1231 if let problem = UserConfig.store(value, setting, in: defaults) {
1232 problems.append(problem)
1233 } else {
1234 settings += 1
1235 stored.append(setting)
1236 }
1237 }
1238 for item in items {
1239 guard case .folder(let path) = item.change else { continue }
1240 var url = URL(fileURLWithPath: OrgPaths.expandingTilde(path)).standardizedFileURL
1241 var picked: URL?
1242 if let chosenFolders {
1243 if let workspace, Self.isRoot(url, in: workspace) { continue }
1244 guard let chosen = chosenFolders[path] else {
1245 problems.append("\(path) wasn't added")
1246 continue
1247 }
1248 url = chosen.standardizedFileURL
1249 picked = chosen
1250 }
1251 // A folder from a picker is security-scoped; the root's bookmark keeps its own access.
1252 let accessing = picked?.startAccessingSecurityScopedResource() ?? false
1253 defer { if accessing { picked?.stopAccessingSecurityScopedResource() } }
1254 guard let workspace, FileManager.default.fileExists(atPath: url.path) else {
1255 problems.append("\(path) doesn't exist")
1256 continue
1257 }
1258 if Self.isRoot(url, in: workspace) { continue }
1259 do {
1260 try await workspace.addRoot(picked ?? url)
1261 folders += 1
1262 } catch {
1263 problems.append("Can't add \(path): \(error.localizedDescription)")
1264 }
1265 }
1266 try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
1267 // Files that are there but can't be read; nothing is written to them.
1268 var unreadable: Set<URL> = []
1269 func read(_ file: URL) -> String {
1270 do {
1271 return try UserFile.text(at: file) ?? ""
1272 } catch {
1273 if unreadable.insert(file).inserted { problems.append("\(file.lastPathComponent) wasn't changed: \(error.localizedDescription)") }
1274 return ""
1275 }
1276 }
1277 func write(_ text: String, to file: URL) -> Bool {
1278 guard !unreadable.contains(file) else { return false }
1279 do {
1280 try text.write(to: file, atomically: true, encoding: .utf8)
1281 return true
1282 } catch {
1283 problems.append("\(file.lastPathComponent) wasn't written: \(error.localizedDescription)")
1284 return false
1285 }
1286 }
1287 let captureFile = directory.appendingPathComponent("capture.toml")
1288 var capture = read(captureFile)
1289 let existingKeys = Set((try? TOML.parse(capture))?.compactMap { $0.values["key"]?.string } ?? [])
1290 var addedCapture = ""
1291 for item in items {
1292 guard case .capture(let key, let toml) = item.change, !existingKeys.contains(key) else { continue }
1293 addedCapture += "\n" + toml
1294 if toml.contains("\ntemplate = ") { templates += 1 }
1295 }
1296 var roamKeys = Set((try? TOML.parse(capture))?.compactMap { table in table.values["key"]?.string.map { table.name + " " + $0 } } ?? [])
1297 for item in items {
1298 guard case .roamTemplate(let set, let key, let toml) = item.change, roamKeys.insert(set + " " + key).inserted else { continue }
1299 addedCapture += "\n" + toml
1300 templates += 1
1301 }
1302 if !addedCapture.isEmpty {
1303 capture += (capture.isEmpty ? "# Capture templates. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedCapture
1304 if !write(capture, to: captureFile) { templates = 0 }
1305 }
1306 let snippetsFile = directory.appendingPathComponent(Snippets.fileName)
1307 var snippetsText = read(snippetsFile)
1308 var triggers = Set((try? TOML.parse(snippetsText))?.filter { $0.name == "snippet" }.compactMap { $0.values["trigger"]?.string } ?? [])
1309 var addedSnippets = "", snippets = 0
1310 for item in items {
1311 guard case .snippet(let trigger, let toml) = item.change, triggers.insert(trigger).inserted else { continue }
1312 addedSnippets += "\n" + toml
1313 snippets += 1
1314 }
1315 if !addedSnippets.isEmpty {
1316 snippetsText += (snippetsText.isEmpty ? "# Snippets. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedSnippets
1317 if !write(snippetsText, to: snippetsFile) { snippets = 0 }
1318 }
1319 let viewsFile = directory.appendingPathComponent("views.toml")
1320 var viewsText = read(viewsFile)
1321 var viewNames = Set((try? TOML.parse(viewsText))?.filter { $0.name == "view" }.compactMap { $0.values["name"]?.string } ?? [])
1322 var addedViews = ""
1323 for item in items {
1324 guard case .view(let name, let toml) = item.change, viewNames.insert(name).inserted else { continue }
1325 addedViews += "\n" + toml
1326 views += 1
1327 }
1328 if !addedViews.isEmpty {
1329 viewsText += (viewsText.isEmpty ? "# Agenda views. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedViews
1330 if !write(viewsText, to: viewsFile) { views = 0 }
1331 }
1332 let configFile = directory.appendingPathComponent("config.toml")
1333 var config = read(configFile)
1334 var projectNames = Set((try? TOML.parse(config))?.filter { $0.name == "publish" }.compactMap { $0.values["name"]?.string } ?? [])
1335 var addedProjects = ""
1336 for item in items {
1337 guard case .publish(let name, let toml) = item.change, projectNames.insert(name).inserted else { continue }
1338 addedProjects += "\n" + toml
1339 projects += 1
1340 }
1341 if !addedProjects.isEmpty {
1342 config += (config.isEmpty || config.hasSuffix("\n") ? "" : "\n") + "\n# Publishing projects. Imported from Emacs.\n" + addedProjects
1343 if !write(config, to: configFile) { projects = 0 }
1344 }
1345 let keymapFile = directory.appendingPathComponent("keymap.toml")
1346 var keymap = read(keymapFile)
1347 func binding(_ keys: String?, _ command: String?, _ mode: String?) -> String { [keys ?? "", command ?? "", mode ?? ""].joined(separator: "\u{0}") }
1348 var existingBindings = Set((try? TOML.parse(keymap))?.filter { $0.name == "bind" && $0.values["when"] == nil }
1349 .map { binding($0.values["keys"]?.string, $0.values["command"]?.string, $0.values["mode"]?.string) } ?? [])
1350 var addedKeys = ""
1351 for item in items {
1352 guard case .binding(let keys, let command, let mode) = item.change,
1353 existingBindings.insert(binding(keys, command, mode)).inserted else { continue }
1354 addedKeys += "\n[[bind]]\nkeys = \(UserConfig.format(.string(keys)))\ncommand = \(UserConfig.format(.string(command)))\n"
1355 if let mode { addedKeys += "mode = \(UserConfig.format(.string(mode)))\n" }
1356 bindings += 1
1357 }
1358 if !addedKeys.isEmpty {
1359 keymap += (keymap.isEmpty ? "" : "\n") + "# Imported from Emacs.\n" + addedKeys
1360 if !write(keymap, to: keymapFile) { bindings = 0 }
1361 }
1362 // Into user defaults, from where ConfigSync writes them into config.toml.
1363 var rows = UserConfig.structureTemplates(defaults)
1364 for item in items {
1365 guard case .structureTemplate(let key, let type) = item.change else { continue }
1366 rows.removeAll { $0.key == key }
1367 rows.append(StructureTemplate(key: key, type: type))
1368 blocks += 1
1369 }
1370 if blocks > 0 { UserConfig.setStructureTemplates(rows, in: defaults) }
1371 var notes = UserConfig.denoteTemplates(defaults), noteTemplates = 0
1372 for item in items {
1373 guard case .denoteTemplate(let key, let text) = item.change else { continue }
1374 notes.removeAll { $0.key == key }
1375 notes.append((key, text))
1376 noteTemplates += 1
1377 }
1378 if noteTemplates > 0 { UserConfig.setDenoteTemplates(notes, in: defaults) }
1379 if writeConfig, settings + blocks + noteTemplates > 0 {
1380 var text = read(configFile)
1381 for setting in stored {
1382 text = UserConfig.setting(text, section: setting.section, key: setting.key, to: UserConfig.value(setting, in: defaults))
1383 }
1384 for item in items {
1385 guard case .structureTemplate(let key, let type) = item.change else { continue }
1386 text = UserConfig.setting(text, section: UserConfig.structureTemplateTable, key: key, to: .string(type))
1387 }
1388 for item in items {
1389 guard case .denoteTemplate(let key, let template) = item.change else { continue }
1390 text = UserConfig.setting(text, section: UserConfig.denoteTemplateTable, key: key, to: .string(template))
1391 }
1392 // Here config.toml holds the settings, so one that isn't in it wasn't imported.
1393 if !write(text, to: configFile) { (settings, blocks, noteTemplates) = (0, 0, 0) }
1394 }
1395 func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" }
1396 let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"),
1397 count(blocks, "structure template"), count(noteTemplates, "Denote template"), count(views, "agenda view"), count(projects, "publishing project"), count(snippets, "snippet")].compactMap { $0 }
1398 var summary = done.isEmpty ? "Nothing new to import." : "Imported " + done.joined(separator: ", ") + "."
1399 if !problems.isEmpty { summary += " " + problems.joined(separator: "; ") + "." }
1400 return summary
1401 }
1402}