Sources/OrgApp/EmacsImport.swift

c396b3453f7cf76ac49e5e2707e01bf5c5753508
orgstar/Sources/OrgApp/EmacsImport.swift

1155 lines · 72017 bytes

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