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