Sources/OrgApp/EmacsImport.swift

8f2ce3e9aea5e545a257dab3e7600f258daab10b
orgstar/Sources/OrgApp/EmacsImport.swift

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

Global

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

Repository & editor

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