Sources/OrgApp/EmacsImport.swift

d85099bc95bf1766aee990d94671dacda0c0686e
orgstar/Sources/OrgApp/EmacsImport.swift history · blame · raw

1001 lines · 61035 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-refile-targets":
 536            switch RefileSettings.parseTargets(value.description) {
 537            case .success: add(name, .string(value.description))
 538            case .failure(.message(let message)): note(message)
 539            }
 540        case "org-refile-use-outline-path":
 541            let mode = value.symbol ?? "nil"
 542            guard RefileSettings.OutlinePath(rawValue: mode) != nil else { return note("unexpected value \(value.description)") }
 543            add(name, .string(mode))
 544        case "org-refile-allow-creating-parent-nodes":
 545            let mode = value.symbol ?? "nil"
 546            add(name, .string(RefileSettings.Creating(rawValue: mode) == nil ? "t" : mode))
 547        case "org-stuck-projects":
 548            // `("+LEVEL=2/-DONE" ("TODO" "NEXT") nil "")`.
 549            guard let parts = value.elements, parts.count == 4, let match = parts[0].string else { return note("not a stuck-projects definition") }
 550            add("org-stuck-projects.match", .string(match))
 551            add("org-stuck-projects.todo", .string((parts[1].elements ?? []).compactMap(\.string).joined(separator: " ")))
 552            add("org-stuck-projects.tags", .string((parts[2].elements ?? []).compactMap(\.string).joined(separator: " ")))
 553            add("org-stuck-projects.regexp", .string(parts[3].string ?? ""))
 554        case "org-agenda-time-grid":
 555            // `((daily today require-timed) (800 1000 …) "......" "----------------")`: the
 556            // strings are how Emacs draws the lines.
 557            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") }
 558            add("org-agenda-time-grid.when", .string(when.compactMap(\.symbol).joined(separator: " ")))
 559            add("org-agenda-time-grid.times", .string(times.compactMap { $0.integer.map(String.init) ?? $0.string }.joined(separator: " ")))
 560        case "org-agenda-sorting-strategy":
 561            // `((agenda habit-down time-up) (todo urgency-down))`, or one list for every view.
 562            func keys(_ items: [Sexp]) -> String? {
 563                let names = items.compactMap(\.symbol)
 564                guard names.count == items.count else { return nil }
 565                if let bad = names.first(where: { !AgendaSort.keys.contains($0) }) { note("\(bad) isn't supported"); return nil }
 566                return names.joined(separator: " ")
 567            }
 568            let entries = value.elements ?? []
 569            if entries.allSatisfy({ $0.symbol != nil }) {
 570                if let s = keys(entries) { for view in ["agenda", "todo", "tags", "search"] { add("org-agenda-sorting-strategy.\(view)", .string(s)) } }
 571            } else {
 572                for entry in entries {
 573                    var items = entry.elements
 574                    if case .dotted(let head, let tail) = entry { items = head + (tail.elements ?? [tail]) }
 575                    guard let items, let view = items.first?.symbol, ["agenda", "todo", "tags", "search"].contains(view) else { continue }
 576                    if let s = keys(Array(items.dropFirst())) { add("org-agenda-sorting-strategy.\(view)", .string(s)) }
 577                }
 578            }
 579        case "org-agenda-prefix-format":
 580            if let s = value.string {
 581                for view in ["agenda", "todo", "tags"] { add("org-agenda-prefix-format.\(view)", .string(s)) }
 582            } else {
 583                for entry in value.elements ?? [] {
 584                    guard case .dotted(let key, let format) = entry, let view = key.first?.symbol, let s = format.string else { continue }
 585                    if ["agenda", "todo", "tags"].contains(view) { add("org-agenda-prefix-format.\(view)", .string(s)) }
 586                }
 587            }
 588        case "org-log-done", "org-log-reschedule", "org-log-redeadline":
 589            switch value.symbol {
 590            case "nil": add(name, .string("nil"))
 591            case "time", "t": add(name, .string("time"))
 592            case "note": add(name, .string("note"))
 593            default: note("unexpected value \(value.description)")
 594            }
 595        case "org-log-into-drawer":
 596            if let s = value.string { add(name, .string(s)) } else { add(name, .string(truthy ? "LOGBOOK" : "")) }
 597        case "display-line-numbers-type":
 598            add(name, .bool(truthy), truthy && value.symbol != "t" ? "display-line-numbers-type = true (orgstar numbers lines absolutely)" : nil)
 599        case "org-agenda-span":
 600            let days: Int? = value.integer ?? ["day": 1, "week": 7, "fortnight": 14, "month": 30, "year": 365][value.symbol ?? ""]
 601            guard let days else { return note("unknown span \(value.description)") }
 602            add(name, .integer(days))
 603        case "org-agenda-start-on-weekday":
 604            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") }
 605        case "org-clock-idle-time":
 606            // nil is never; a number is minutes.
 607            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") }
 608        case "org-clock-rounding-minutes":
 609            guard let n = value.integer, n >= 0 else { return note("not a number of minutes") }
 610            add(name, .integer(n))
 611        case "org-clock-in-switch-to-state":
 612            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") }
 613        case "org-clock-out-when-done":
 614            if let states = value.elements, !states.isEmpty {
 615                let names = states.compactMap(\.string)
 616                guard names.count == states.count else { return note("not a list of keywords") }
 617                add(name, .string(names.joined(separator: " ")))
 618            } else {
 619                add(name, .string(truthy ? "t" : "nil"))
 620            }
 621        case "org-clock-into-drawer":
 622            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")) }
 623        case "org-clock-history-length":
 624            guard let length = value.integer, length > 0 else { return note("not a positive number") }
 625            add(name, .integer(length))
 626        case "org-agenda-start-day":
 627            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") }
 628        case "org-todo-keywords":
 629            let sequences = (value.elements ?? []).compactMap { $0.elements }.filter { $0.count > 1 }.map { $0.dropFirst().compactMap(\.string) }
 630            let lines = sequences.filter { !$0.contains { $0.contains(where: \.isWhitespace) } }.map { $0.joined(separator: " ") }
 631            guard !lines.isEmpty else { return note("unexpected value") }
 632            if lines.count < sequences.count {
 633                note("\(sequences.count - lines.count) sequence(s) with spaces in a keyword left out; #+TODO syntax can't write them")
 634            }
 635            if (value.elements ?? []).contains(where: { $0.elements?.first?.symbol == "type" }) { note("type sequences are read as sequences") }
 636            add(name, .string(lines.joined(separator: "\n")))
 637        case "org-directory":
 638            guard let path = value.string else { return note("not a folder") }
 639            items.append(Item(id: id(), name: name, summary: "add folder \(path)", source: source, change: .folder(path)))
 640        case "org-agenda-files":
 641            let paths = (value.elements ?? [value]).compactMap(\.string)
 642            guard !paths.isEmpty else { return note("not a list of files or folders") }
 643            add(name, .string(paths.joined(separator: "\n")))
 644            // A file listing the files (the variable's string form) gives no folder.
 645            if value.string != nil, !paths[0].hasSuffix(".org") { return }
 646            for path in paths {
 647                let folder = path.hasSuffix(".org") ? (path as NSString).deletingLastPathComponent : path
 648                items.append(Item(id: id(), name: name, summary: "add folder \(folder)", source: source, change: .folder(folder)))
 649            }
 650        case "org-capture-templates":
 651            for entry in value.elements ?? [] { captureTemplate(entry, source: source, env: env, id: id) }
 652        case "org-agenda-custom-commands":
 653            for entry in value.elements ?? [] { agendaCommand(entry, source: source, id: id) }
 654        case "doom-font":
 655            note("not a font-spec orgstar can read")
 656        case "doom-variable-pitch-font":
 657            note("orgstar uses one font; set it with doom-font or [theme] font")
 658        case "doom-theme":
 659            note("Emacs themes aren't read; set colors under [theme] in config.toml")
 660        default:
 661            note("orgstar has no equivalent")
 662        }
 663    }
 664
 665    /// `org-tag-alist` in `#+TAGS` syntax: `("work" . ?w)` is `work(w)`, `(:startgroup)` `{`,
 666    /// `(:startgrouptag)` `[`, `(:grouptags)` `:`, and `(:newline)` a new line.
 667    static func tagAlist(_ entries: [Sexp]) -> String? {
 668        var lines: [[String]] = [[]]
 669        for entry in entries {
 670            let marker = entry.elements?.first?.symbol ?? entry.symbol
 671            switch marker {
 672            case ":startgroup": lines[lines.count - 1].append("{")
 673            case ":endgroup": lines[lines.count - 1].append("}")
 674            case ":startgrouptag": lines[lines.count - 1].append("[")
 675            case ":endgrouptag": lines[lines.count - 1].append("]")
 676            case ":grouptags": lines[lines.count - 1].append(":")
 677            case ":newline": lines.append([])
 678            default:
 679                if let tag = entry.string {
 680                    lines[lines.count - 1].append(tag)
 681                } else if case .dotted(let head, let key) = entry, head.count == 1, let tag = head[0].string {
 682                    guard case .character(let code) = key, let scalar = Unicode.Scalar(code) else {
 683                        lines[lines.count - 1].append(tag)
 684                        continue
 685                    }
 686                    lines[lines.count - 1].append("\(tag)(\(Character(scalar)))")
 687                } else {
 688                    return nil
 689                }
 690            }
 691        }
 692        return lines.map { $0.joined(separator: " ") }.filter { !$0.isEmpty }.joined(separator: "\n")
 693    }
 694
 695    /// `("el" . "src emacs-lisp")` entries that aren't Org's own.
 696    mutating func structureTemplates(_ entries: [Sexp], source: String, id: () -> Int) {
 697        for entry in entries {
 698            guard case .dotted(let head, let tail) = entry, head.count == 1, let key = head[0].string, let type = tail.string else {
 699                unsupported.append(Note(id: id(), name: "org-structure-template-alist", reason: "an entry that isn't (\"key\" . \"type\")", source: source))
 700                continue
 701            }
 702            if StructureTemplate.defaults.contains(StructureTemplate(key: key, type: type)) { continue }
 703            guard !key.isEmpty, key.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }) else {
 704                unsupported.append(Note(id: id(), name: "structure template \"\(key)\"", reason: "config.toml keys are letters, digits, _ and -", source: source))
 705                continue
 706            }
 707            items.removeAll { if case .structureTemplate(key, _) = $0.change { true } else { false } }
 708            items.append(Item(id: id(), name: "structure template \"\(key)\"", summary: "<\(key) inserts a \(type) block", source: source,
 709                              change: .structureTemplate(key: key, type: type)))
 710        }
 711    }
 712
 713    /// An `org-agenda-custom-commands` entry as a `[[view]]` table: `("w" "Work" tags "+work"
 714    /// ((settings)))`, or with a list of blocks in place of the type and match.
 715    mutating func agendaCommand(_ entry: Sexp, source: String, id: () -> Int) {
 716        guard var parts = entry.elements, let key = parts.first?.string else { return }
 717        parts.removeFirst()
 718        let name = parts.first?.string ?? key
 719        if parts.first?.string != nil { parts.removeFirst() }
 720        // A key and a description only: a prefix for other commands.
 721        guard let first = parts.first else { return }
 722        func note(_ reason: String) { unsupported.append(Note(id: id(), name: "agenda command \"\(key)\"", reason: reason, source: source)) }
 723        func quoted(_ s: String) -> String { UserConfig.format(.string(s)) }
 724        func unquote(_ s: Sexp) -> Sexp {
 725            if case .list(let items) = s, items.count == 2, items[0].symbol == "quote" || items[0].symbol == "function" { return items[1] }
 726            return s
 727        }
 728        /// `(type match settings)` as TOML lines, or nil with a note.
 729        func view(_ type: String, _ match: Sexp?, _ settings: Sexp?) -> String? {
 730            var toml = ""
 731            let matchString = match.flatMap { unquote($0).string }.flatMap { $0.isEmpty ? nil : $0 }
 732            switch type {
 733            case "agenda": toml += "type = \"agenda\"\n"
 734            case "alltodo": toml += "type = \"todo\"\n"
 735            case "todo":
 736                toml += "type = \"todo\"\n"
 737                if let matchString { toml += "keywords = \(quoted(matchString))\n" }
 738            case "tags", "tags-todo", "search":
 739                guard let matchString else { note("\(type) needs a match"); return nil }
 740                let kind = ["tags": "match", "tags-todo": "todo-match", "search": "search"][type]!
 741                toml += "type = \"\(kind)\"\nmatch = \(quoted(matchString))\n"
 742            case "stuck": toml += "type = \"stuck\"\n"
 743            default: note("\(type) views aren't supported"); return nil
 744            }
 745            guard let settings = settings.map(unquote), let pairs = settings.elements else { return toml }
 746            for pair in pairs {
 747                guard let items = pair.elements, items.count == 2, let variable = items[0].symbol else { continue }
 748                let value = unquote(items[1])
 749                switch variable {
 750                case "org-agenda-span" where type == "agenda":
 751                    let spans = ["day": 1, "week": 7, "fortnight": 14, "month": 30, "year": 365]
 752                    if let n = value.integer ?? value.symbol.flatMap({ spans[$0] }) { toml += "span = \(n)\n" } else { note("org-agenda-span \(value.description)") }
 753                case "org-agenda-start-day" where type == "agenda":
 754                    if let s = value.string, let n = Int(s.replacingOccurrences(of: "d", with: "").replacingOccurrences(of: "+", with: "")) {
 755                        toml += "start = \(n)\n"
 756                    } else { note("org-agenda-start-day \(value.description)") }
 757                case "org-agenda-overriding-header":
 758                    if let s = value.string { toml += "header = \(quoted(s))\n" }
 759                case "org-agenda-sorting-strategy":
 760                    let keys = (value.elements ?? []).compactMap(\.symbol)
 761                    if !keys.isEmpty, keys.allSatisfy(AgendaSort.keys.contains) { toml += "sorting-strategy = \(quoted(keys.joined(separator: " ")))\n" } else { note("org-agenda-sorting-strategy \(value.description)") }
 762                case "org-agenda-prefix-format":
 763                    if let s = value.string { toml += "prefix-format = \(quoted(s))\n" } else { note("org-agenda-prefix-format as an alist") }
 764                case "org-agenda-skip-function":
 765                    guard let form = value.elements, let head = form.first?.symbol, ["org-agenda-skip-entry-if", "org-agenda-skip-subtree-if"].contains(head) else {
 766                        note("org-agenda-skip-function \(value.description)")
 767                        continue
 768                    }
 769                    let subtree = head == "org-agenda-skip-subtree-if"
 770                    switch AgendaSkip.parse(form.dropFirst().map(\.description).joined(separator: " "), subtree: subtree) {
 771                    case .success(let skip): toml += "\(subtree ? "skip-subtree-if" : "skip-entry-if") = \(quoted(skip.lisp))\n"
 772                    case .failure(.message(let message)): note("org-agenda-skip-function: \(message)")
 773                    }
 774                default:
 775                    note("\(variable) in a view isn't supported")
 776                }
 777            }
 778            return toml
 779        }
 780        var toml = "[[view]]\nname = \(quoted(name))\n"
 781        if let type = first.symbol {
 782            if type == "agenda*" { note("agenda* views aren't supported"); return }
 783            guard let body = view(type, parts.count > 1 ? parts[1] : nil, parts.count > 2 ? parts[2] : nil) else { return }
 784            toml += body
 785            if parts.count > 3 { note("files for a view are ignored") }
 786        } else if let blocks = first.elements {
 787            // Settings for all the blocks come after them.
 788            var common = view("agenda", nil, parts.count > 1 ? parts[1] : nil) ?? ""
 789            common = common.replacingOccurrences(of: "type = \"agenda\"\n", with: "")
 790            toml += common
 791            var count = 0
 792            for block in blocks {
 793                guard let items = block.elements, let type = items.first?.symbol,
 794                      let body = view(type, items.count > 1 ? items[1] : nil, items.count > 2 ? items[2] : nil) else { continue }
 795                toml += "[[view.block]]\n" + body
 796                count += 1
 797            }
 798            guard count > 0 else { return }
 799            if parts.count > 2 { note("files for a view are ignored") }
 800        } else {
 801            return note("not a view orgstar can read")
 802        }
 803        items.append(Item(id: id(), name: "org-agenda-custom-commands \"\(key)\"", summary: "views.toml view \(name)", source: source, change: .view(name: name, toml: toml)))
 804    }
 805
 806    mutating func captureTemplate(_ entry: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) {
 807        guard let parts = entry.elements, parts.count >= 2, let key = parts[0].string else { return }
 808        let name = parts[1].string ?? key
 809        guard parts.count >= 5, let type = parts[2].symbol, let target = parts[3].elements, let kind = target.first?.symbol,
 810              let template = parts[4].string else {
 811            // A key and a name only: a group of templates.
 812            if parts.count == 2 { return }
 813            unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "a template that isn't a string", source: source))
 814            return
 815        }
 816        guard ["entry", "item", "checkitem", "plain", "table-line"].contains(type) else {
 817            unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "\(type) templates aren't supported", source: source))
 818            return
 819        }
 820        func quoted(_ s: String) -> String { UserConfig.format(.string(s)) }
 821        var toml = "[[template]]\nkey = \(quoted(key))\nname = \(quoted(name))\ntype = \(quoted(type))\n"
 822        // `org-capture-expand-file`: a variable's value, or a form evaluated.
 823        let strings = target.dropFirst().compactMap { $0.string ?? Self.evaluate($0, env)?.string }
 824        // Property list after the template: `:prepend t :empty-lines 1 …`.
 825        var properties: [String: Sexp] = [:]
 826        let rest = Array(parts.dropFirst(5))
 827        for i in stride(from: 0, to: rest.count - 1, by: 2) { if let name = rest[i].symbol { properties[name] = rest[i + 1] } }
 828        let allStrings = strings.count == target.count - 1
 829        var treeType = properties[":tree-type"]?.symbol
 830        let place: String? = switch kind {
 831        case "file" where strings.count == 1 && target.count == 2:
 832            "file = \(quoted(strings[0]))\n"
 833        case "file+headline" where strings.count == 2 && target.count == 3:
 834            "file = \(quoted(strings[0]))\nheadline = \(quoted(strings[1]))\n"
 835        case "file+olp" where strings.count >= 2 && allStrings:
 836            "file = \(quoted(strings[0]))\nolp = \(quoted(strings.dropFirst().joined(separator: "/")))\n"
 837        case "file+olp+datetree" where strings.count >= 1 && allStrings:
 838            "file = \(quoted(strings[0]))\ndatetree = true\n" + (strings.count > 1 ? "olp = \(quoted(strings.dropFirst().joined(separator: "/")))\n" : "")
 839        case let legacy where (legacy == "file+datetree" || legacy == "file+weektree") && strings.count == 1 && target.count == 2:
 840            "file = \(quoted(strings[0]))\ndatetree = true\n"
 841        case "id" where strings.count == 1 && target.count == 2:
 842            "id = \(quoted(strings[0]))\n"
 843        case "clock" where target.count == 1:
 844            "clock = true\n"
 845        default:
 846            nil
 847        }
 848        guard let place else {
 849            unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "target \(kind) isn't supported", source: source))
 850            return
 851        }
 852        if kind == "file+weektree" { treeType = "week" }
 853        toml += place
 854        if let treeType {
 855            guard ["day", "week", "month"].contains(treeType) else {
 856                unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: ":tree-type \(treeType) isn't supported", source: source))
 857                return
 858            }
 859            if treeType != "day" { toml += "tree-type = \(quoted(treeType))\n" }
 860        }
 861        for flag in ["prepend", "immediate-finish", "jump-to-captured", "clock-in", "clock-keep", "clock-resume"] {
 862            if let value = properties[":" + flag], value.symbol != "nil" { toml += "\(flag) = true\n" }
 863        }
 864        for count in ["empty-lines", "empty-lines-before", "empty-lines-after"] {
 865            if let n = properties[":" + count]?.integer { toml += "\(count) = \(n)\n" }
 866        }
 867        if let pos = properties[":table-line-pos"]?.string { toml += "table-line-pos = \(quoted(pos))\n" }
 868        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) }
 869        if !ignored.isEmpty {
 870            unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "\(ignored.sorted().joined(separator: ", ")) left out", source: source))
 871        }
 872        toml += "template = \(quoted(template))\n"
 873        items.append(Item(id: id(), name: "capture \"\(key)\" \(name)", summary: "capture template \"\(key)\"", source: source, change: .capture(key: key, toml: toml)))
 874    }
 875
 876    /// Emacs commands and the Orgstar commands that do the same.
 877    static let commands: [String: String] = [
 878        "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",
 879        "org-metaleft": "org.heading.promote", "org-metaright": "org.heading.demote", "org-do-promote": "org.heading.promote", "org-do-demote": "org.heading.demote",
 880        "org-promote-subtree": "org.subtree.promote", "org-demote-subtree": "org.subtree.demote",
 881        "org-shiftmetaleft": "org.subtree.promote", "org-shiftmetaright": "org.subtree.demote",
 882        "org-move-subtree-up": "org.subtree.up", "org-move-subtree-down": "org.subtree.down", "org-metaup": "org.subtree.up", "org-metadown": "org.subtree.down",
 883        "org-insert-heading": "org.heading.insert", "org-meta-return": "org.heading.insert",
 884        "org-insert-heading-respect-content": "org.heading.insert-after-subtree", "+org/insert-item-below": "org.heading.insert-after-subtree",
 885        "org-insert-todo-heading": "org.heading.insert-todo",
 886        "org-next-visible-heading": "org.heading.next", "org-previous-visible-heading": "org.heading.previous",
 887        "org-forward-heading-same-level": "org.heading.forward-same-level", "org-backward-heading-same-level": "org.heading.backward-same-level",
 888        "outline-up-heading": "org.heading.up", "org-up-element": "org.heading.up",
 889        "org-set-tags-command": "org.tags.set", "org-set-property": "org.property.read-and-set",
 890        "org-toggle-checkbox": "org.checkbox.toggle", "org-ctrl-c-ctrl-c": "org.ctrl-c-ctrl-c", "+org/dwim-at-point": "org.dwim",
 891        "org-schedule": "org.schedule", "org-deadline": "org.deadline", "org-time-stamp": "org.timestamp.active", "org-timestamp": "org.timestamp.active",
 892        "org-time-stamp-inactive": "org.timestamp.inactive", "org-timestamp-inactive": "org.timestamp.inactive",
 893        "org-fill-paragraph": "org.fill-paragraph", "org-cycle": "org.cycle", "org-shifttab": "org.cycle-global", "org-global-cycle": "org.cycle-global",
 894        "org-table-create": "org.table.create", "org-table-align": "org.table.align", "org-table-recalculate": "org.table.recalc",
 895        "org-table-insert-row": "org.table.insert-row", "org-table-insert-column": "org.table.insert-column",
 896        "org-table-delete-column": "org.table.delete-column", "org-table-kill-row": "org.table.kill-row", "org-table-insert-hline": "org.table.insert-hline",
 897        "org-babel-execute-src-block": "org.babel.execute", "org-clock-in": "app.clock.in", "org-clock-out": "app.clock.out",
 898        "org-clock-cancel": "app.clock.cancel", "org-clock-goto": "app.clock.goto", "org-clock-in-last": "app.clock.in-last",
 899        "org-resolve-clocks": "app.clock.resolve", "org-clock-mark-default-task": "app.clock.default",
 900        "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",
 901        "org-capture": "app.capture", "org-agenda": "app.agenda", "org-agenda-list": "app.agenda",
 902        "save-buffer": "app.save", "find-file": "app.quick-open", "projectile-find-file": "app.quick-open", "+default/find-file-under-here": "app.quick-open",
 903        "execute-extended-command": "app.palette", "counsel-M-x": "app.palette",
 904        "isearch-forward": "edit.find", "isearch-backward": "edit.find", "consult-line": "edit.find", "+default/search-buffer": "edit.find", "swiper": "edit.find",
 905        "query-replace": "edit.replace", "query-replace-regexp": "edit.replace",
 906        "save-buffers-kill-terminal": "app.quit", "save-buffers-kill-emacs": "app.quit",
 907    ]
 908}
 909
 910extension EmacsImport {
 911    /// Applies `items`: settings to `defaults` (and so config.toml), folders to the workspace,
 912    /// capture templates and key bindings appended to capture.toml and keymap.toml in
 913    /// `directory`, leaving out templates whose key is there already and bindings that are
 914    /// there already. Returns a summary.
 915    @MainActor
 916    public static func apply(
 917        _ items: [Item], defaults: UserDefaults = .standard, workspace: WorkspaceModel?, directory: URL = UserConfig.directory
 918    ) async -> String {
 919        var settings = 0, folders = 0, templates = 0, bindings = 0, blocks = 0, views = 0
 920        var problems: [String] = []
 921        for item in items {
 922            guard case .setting(let key, let value) = item.change,
 923                  let setting = UserConfig.settings.first(where: { $0.path == key || $0.key == key }) else { continue }
 924            if let problem = UserConfig.store(value, setting, in: defaults) { problems.append(problem) } else { settings += 1 }
 925        }
 926        for item in items {
 927            guard case .folder(let path) = item.change else { continue }
 928            let url = URL(fileURLWithPath: (path as NSString).expandingTildeInPath).standardizedFileURL
 929            guard let workspace, FileManager.default.fileExists(atPath: url.path) else {
 930                problems.append("\(path) doesn't exist")
 931                continue
 932            }
 933            if workspace.roots.contains(where: { URL(fileURLWithPath: $0.path).standardizedFileURL.path == url.path }) { continue }
 934            do {
 935                try await workspace.addRoot(url)
 936                folders += 1
 937            } catch {
 938                problems.append("Can't add \(path): \(error.localizedDescription)")
 939            }
 940        }
 941        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
 942        let captureFile = directory.appendingPathComponent("capture.toml")
 943        var capture = (try? String(contentsOf: captureFile, encoding: .utf8)) ?? ""
 944        let existingKeys = Set((try? TOML.parse(capture))?.compactMap { $0.values["key"]?.string } ?? [])
 945        var addedCapture = ""
 946        for item in items {
 947            guard case .capture(let key, let toml) = item.change, !existingKeys.contains(key) else { continue }
 948            addedCapture += "\n" + toml
 949            templates += 1
 950        }
 951        if !addedCapture.isEmpty {
 952            capture += (capture.isEmpty ? "# Capture templates. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedCapture
 953            try? capture.write(to: captureFile, atomically: true, encoding: .utf8)
 954        }
 955        let viewsFile = directory.appendingPathComponent("views.toml")
 956        var viewsText = (try? String(contentsOf: viewsFile, encoding: .utf8)) ?? ""
 957        var viewNames = Set((try? TOML.parse(viewsText))?.filter { $0.name == "view" }.compactMap { $0.values["name"]?.string } ?? [])
 958        var addedViews = ""
 959        for item in items {
 960            guard case .view(let name, let toml) = item.change, viewNames.insert(name).inserted else { continue }
 961            addedViews += "\n" + toml
 962            views += 1
 963        }
 964        if !addedViews.isEmpty {
 965            viewsText += (viewsText.isEmpty ? "# Agenda views. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedViews
 966            try? viewsText.write(to: viewsFile, atomically: true, encoding: .utf8)
 967        }
 968        let keymapFile = directory.appendingPathComponent("keymap.toml")
 969        var keymap = (try? String(contentsOf: keymapFile, encoding: .utf8)) ?? ""
 970        func binding(_ keys: String?, _ command: String?, _ mode: String?) -> String { [keys ?? "", command ?? "", mode ?? ""].joined(separator: "\u{0}") }
 971        var existingBindings = Set((try? TOML.parse(keymap))?.filter { $0.name == "bind" && $0.values["when"] == nil }
 972            .map { binding($0.values["keys"]?.string, $0.values["command"]?.string, $0.values["mode"]?.string) } ?? [])
 973        var addedKeys = ""
 974        for item in items {
 975            guard case .binding(let keys, let command, let mode) = item.change,
 976                  existingBindings.insert(binding(keys, command, mode)).inserted else { continue }
 977            addedKeys += "\n[[bind]]\nkeys = \(UserConfig.format(.string(keys)))\ncommand = \(UserConfig.format(.string(command)))\n"
 978            if let mode { addedKeys += "mode = \(UserConfig.format(.string(mode)))\n" }
 979            bindings += 1
 980        }
 981        if !addedKeys.isEmpty {
 982            keymap += (keymap.isEmpty ? "" : "\n") + "# Imported from Emacs.\n" + addedKeys
 983            try? keymap.write(to: keymapFile, atomically: true, encoding: .utf8)
 984        }
 985        // Into user defaults, from where ConfigSync writes them into config.toml.
 986        var rows = UserConfig.structureTemplates(defaults)
 987        for item in items {
 988            guard case .structureTemplate(let key, let type) = item.change else { continue }
 989            rows.removeAll { $0.key == key }
 990            rows.append(StructureTemplate(key: key, type: type))
 991            blocks += 1
 992        }
 993        if blocks > 0 { UserConfig.setStructureTemplates(rows, in: defaults) }
 994        func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" }
 995        let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"),
 996                    count(blocks, "structure template"), count(views, "agenda view")].compactMap { $0 }
 997        var summary = done.isEmpty ? "Nothing new to import." : "Imported " + done.joined(separator: ", ") + "."
 998        if !problems.isEmpty { summary += " " + problems.joined(separator: "; ") + "." }
 999        return summary
1000    }
1001}