Sources/OrgApp/EmacsImport.swift

4b342a9cb3f2e971a53b0cf377e203da855fad8b
orgstar/Sources/OrgApp/EmacsImport.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form