Sources/OrgApp/EmacsImport.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgApp/EmacsImport.swift history · blame · raw

1096 lines · 67785 bytes

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