Sources/OrgApp/EmacsImport.swift

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