Sources/OrgApp/EmacsImport.swift

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