Sources/OrgApp/EmacsImport.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/OrgApp/EmacsImport.swift history · blame · raw

837 lines · 49723 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    }
 21
 22    public struct Item: Sendable, Identifiable {
 23        public let id: Int
 24        /// The Emacs variable or binding, as it reads in the file.
 25        public let name: String
 26        /// What it becomes in Orgstar, for the review list.
 27        public let summary: String
 28        /// `config.el:27`, or `Doom default` for Doom's own settings.
 29        public let source: String
 30        public let change: Change
 31    }
 32
 33    public struct Note: Sendable, Identifiable {
 34        public let id: Int
 35        public let name: String
 36        public let reason: String
 37        public let source: String
 38    }
 39
 40    public var items: [Item] = []
 41    /// Org settings and bindings Orgstar has no equivalent for.
 42    public var unsupported: [Note] = []
 43    /// Values worked out at run time, which reading can't follow.
 44    public var unreadable: [Note] = []
 45    /// Files that couldn't be read, with why.
 46    public var problems: [String] = []
 47    /// Variables that aren't about org or the editor, left alone.
 48    public var skipped = 0
 49    /// Doom's own org defaults Orgstar has no use for, not listed one by one.
 50    public var doomDefaultsLeftOut = 0
 51    public var isDoom = false
 52
 53    // MARK: - Finding the configuration
 54
 55    /// The configuration files in `folder` (a Doom folder, an `.emacs.d`) or the file itself.
 56    public static func files(in location: URL) -> [URL] {
 57        var isDirectory: ObjCBool = false
 58        guard FileManager.default.fileExists(atPath: location.path, isDirectory: &isDirectory) else { return [] }
 59        guard isDirectory.boolValue else { return [location] }
 60        return ["init.el", "config.el", "custom.el"].map { location.appendingPathComponent($0) }
 61            .filter { FileManager.default.fileExists(atPath: $0.path) }
 62    }
 63
 64    /// Where an Emacs configuration usually is, first found first.
 65    public static func defaultLocations() -> [URL] {
 66        let home = URL(fileURLWithPath: NSHomeDirectory())
 67        let environment = ProcessInfo.processInfo.environment
 68        var candidates: [URL] = []
 69        if let doom = environment["DOOMDIR"] { candidates.append(URL(fileURLWithPath: doom)) }
 70        candidates += [".config/doom", ".doom.d", ".config/emacs", ".emacs.d"].map { home.appendingPathComponent($0) }
 71        candidates.append(home.appendingPathComponent(".emacs"))
 72        return candidates.filter { !files(in: $0).isEmpty && !isDoomInstall($0) }
 73    }
 74
 75    /// Doom's own source folder, which holds `lisp/doom.el`, isn't a user configuration.
 76    static func isDoomInstall(_ url: URL) -> Bool {
 77        FileManager.default.fileExists(atPath: url.appendingPathComponent("lisp/doom.el").path)
 78    }
 79
 80    /// Doom's org module and core defaults, if Doom is installed.
 81    static func doomDefaultFiles() -> [URL] {
 82        let home = URL(fileURLWithPath: NSHomeDirectory())
 83        let environment = ProcessInfo.processInfo.environment
 84        let installs = ([environment["EMACSDIR"]].compactMap { $0 }.map { URL(fileURLWithPath: $0) })
 85            + [".config/emacs", ".emacs.d"].map { home.appendingPathComponent($0) }
 86        guard let install = installs.first(where: isDoomInstall) else { return [] }
 87        var files = [install.appendingPathComponent("lisp/doom-emacs.el")]
 88        var moduleRoots = [install.appendingPathComponent("modules")]
 89        if let sources = try? FileManager.default.contentsOfDirectory(at: install.appendingPathComponent("sources"), includingPropertiesForKeys: nil) {
 90            moduleRoots += sources.map { $0.appendingPathComponent("modules") }
 91        }
 92        if let org = moduleRoots.map({ $0.appendingPathComponent("lang/org/config.el") }).first(where: { FileManager.default.fileExists(atPath: $0.path) }) {
 93            files.insert(org, at: 0)
 94        }
 95        return files.filter { FileManager.default.fileExists(atPath: $0.path) }
 96    }
 97
 98    // MARK: - Reading
 99
100    /// Reads `files`, and for a Doom configuration Doom's own defaults under them.
101    public static func scan(_ files: [URL], doomDefaults: [URL]? = nil) -> EmacsImport {
102        var sources: [(name: String, text: String, priority: Int)] = []
103        var result = EmacsImport()
104        for url in files {
105            guard let text = try? String(contentsOf: url, encoding: .utf8) else {
106                result.problems.append("Can't read \(url.path)")
107                continue
108            }
109            sources.append((url.lastPathComponent, text, 1))
110        }
111        result.isDoom = sources.contains { $0.text.contains("(doom!") || $0.text.contains("(map! ") || $0.text.contains("(after! ") }
112        if result.isDoom {
113            for url in doomDefaults ?? doomDefaultFiles() {
114                if let text = try? String(contentsOf: url, encoding: .utf8) { sources.insert(("Doom", text, 0), at: 0) }
115            }
116        }
117        var scanner = Scanner()
118        for source in sources {
119            do {
120                let forms = try LispReader.read(source.text)
121                for form in forms {
122                    scanner.visit(form.sexp, source: source.priority == 0 ? "Doom default" : "\(source.name):\(form.line)",
123                                  priority: source.priority, deferred: false, insideDefun: false, doom: source.priority == 0)
124                }
125            } catch {
126                result.problems.append("\(source.name): \(error)")
127            }
128        }
129        result.build(from: scanner)
130        return result
131    }
132
133    struct Assignment {
134        let name: String
135        let value: Sexp
136        let source: String
137        /// Doom defaults, then the config, then what runs after a package loads.
138        let rank: Int
139    }
140
141    struct Binding {
142        let keys: String
143        let command: Sexp
144        let modes: [String?]
145        let source: String
146    }
147
148    struct Scanner {
149        var assignments: [Assignment] = []
150        var bindings: [Binding] = []
151        /// `(add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp"))` entries.
152        var addedTemplates: [(entry: Sexp, source: String)] = []
153        var usesEvil = false
154        var order = 0
155
156        mutating func assign(_ name: String, _ value: Sexp, _ source: String, priority: Int, deferred: Bool) {
157            assignments.append(Assignment(name: name, value: value, source: source, rank: priority * 2 + (deferred ? 1 : 0)))
158        }
159
160        mutating func visit(_ form: Sexp, source: String, priority: Int, deferred: Bool, insideDefun: Bool, doom: Bool) {
161            guard let items = form.elements, let head = form.head else { return }
162            let args = Array(items.dropFirst())
163            func body(_ forms: ArraySlice<Sexp>, deferred: Bool) {
164                for f in forms { visit(f, source: source, priority: priority, deferred: deferred, insideDefun: insideDefun, doom: doom) }
165            }
166            switch head {
167            case "setq", "setq-default", "setq!", "setopt", "csetq":
168                var i = 0
169                while i + 1 < args.count {
170                    if let name = args[i].symbol { assign(name, args[i + 1], source, priority: priority, deferred: deferred) }
171                    i += 2
172                }
173            case "add-to-list":
174                if args.count >= 2, unquote(args[0])?.symbol == "org-structure-template-alist", let entry = unquote(args[1]) {
175                    addedTemplates.append((entry, source))
176                }
177            case "defvar", "defcustom":
178                // Only sets a variable nothing set, so under every assignment.
179                if args.count >= 2, let name = args[0].symbol { assign(name, args[1], source, priority: -1, deferred: false) }
180            case "custom-set-variables":
181                for arg in args {
182                    guard let entry = unquote(arg)?.elements, entry.count >= 2, let name = entry[0].symbol else { continue }
183                    assign(name, .list([.symbol("quote"), entry[1]]), source, priority: priority, deferred: deferred)
184                }
185            case "after!", "with-eval-after-load", "eval-after-load", "use-package!", "use-package":
186                if head.hasPrefix("use-package") {
187                    var i = 1
188                    var section = ""
189                    while i < args.count {
190                        if let keyword = args[i].symbol, keyword.hasPrefix(":") {
191                            section = keyword
192                        } else if section == ":config" || section == ":init" {
193                            visit(args[i], source: source, priority: priority, deferred: true, insideDefun: insideDefun, doom: doom)
194                        } else if section == ":custom", let pair = args[i].elements, pair.count >= 2, let name = pair[0].symbol {
195                            assign(name, pair[1], source, priority: priority, deferred: true)
196                        }
197                        i += 1
198                    }
199                } else {
200                    let forms = head == "eval-after-load" ? args.dropFirst().compactMap(unquote) : Array(args.dropFirst())
201                    body(forms[...], deferred: true)
202                }
203            case "progn", "when", "unless", "if", "let", "let*", "with-no-warnings":
204                let skip = ["let", "let*", "when", "unless", "if"].contains(head) ? 1 : 0
205                body(args.dropFirst(skip), deferred: deferred)
206            case "defun", "defun!", "add-hook!":
207                // Doom sets org's defaults in the functions its module runs when org loads.
208                if doom, head == "defun" { body(args.dropFirst(2), deferred: true) }
209            case "doom!":
210                usesEvil = args.contains { $0.symbol == "evil" || $0.head == "evil" }
211            case "map!":
212                if !doom { bindings += mapBindings(args, prefix: "", modes: [nil], source: source) }
213            case "define-key", "keymap-set", "evil-define-key", "evil-define-key*", "global-set-key", "keymap-global-set":
214                guard !doom else { break }
215                var rest = args
216                var modes: [String?] = [nil]
217                if head.hasPrefix("evil-define-key"), let state = rest.first {
218                    modes = evilStates(state)
219                    rest = Array(rest.dropFirst())
220                }
221                if !head.hasPrefix("global"), head != "keymap-global-set" { rest = Array(rest.dropFirst()) }
222                var i = 0
223                while i + 1 < rest.count {
224                    if let keys = keyString(rest[i]) { bindings.append(Binding(keys: keys, command: rest[i + 1], modes: modes, source: source)) }
225                    i += 2
226                }
227            default:
228                break
229            }
230        }
231
232        func evilStates(_ sexp: Sexp) -> [String?] {
233            let names = (unquote(sexp)?.elements ?? [unquote(sexp) ?? sexp]).compactMap(\.symbol)
234            let modes = names.compactMap { name -> String? in
235                switch name {
236                case "normal", "motion": "normal"
237                case "insert": "insert"
238                case "visual": "visual"
239                default: nil
240                }
241            }
242            return modes.isEmpty ? [nil] : modes
243        }
244
245        /// `(kbd "C-c x")` or `"C-c x"` (keymap-set); key vectors such as `[f5]` are skipped.
246        func keyString(_ sexp: Sexp) -> String? {
247            if let s = sexp.string { return s }
248            if sexp.head == "kbd", let s = sexp.elements?.dropFirst().first?.string { return s }
249            return nil
250        }
251
252        /// Doom's `map!`: `:leader`, `:localleader`, `:prefix`, state keywords such as `:n`
253        /// and `:nv`, `:map`, `:desc`, and nested groups.
254        func mapBindings(_ args: [Sexp], prefix: String, modes: [String?], source: String) -> [Binding] {
255            var result: [Binding] = []
256            var prefix = prefix
257            var modes = modes
258            var i = 0
259            while i < args.count {
260                let arg = args[i]
261                if let keyword = arg.symbol, keyword.hasPrefix(":") {
262                    switch keyword {
263                    case ":leader":
264                        prefix = "SPC"
265                        modes = ["normal"]
266                    case ":localleader":
267                        prefix = "SPC m"
268                        modes = ["normal"]
269                    case ":prefix", ":prefix-map":
270                        if i + 1 < args.count {
271                            let p = args[i + 1].string ?? args[i + 1].elements?.first?.string ?? ""
272                            prefix = [prefix, p].filter { !$0.isEmpty }.joined(separator: " ")
273                        }
274                        i += 1
275                    case ":desc", ":map", ":mode", ":after", ":when", ":unless":
276                        i += 1
277                    default:
278                        let states = keyword.dropFirst()
279                        let mapped = states.compactMap { c -> String? in
280                            switch c {
281                            case "n", "m": "normal"
282                            case "i": "insert"
283                            case "v": "visual"
284                            default: nil
285                            }
286                        }
287                        if !mapped.isEmpty { modes = Array(Set(mapped)).sorted() }
288                    }
289                } else if let group = arg.elements, arg.head?.hasPrefix(":") == true || group.first?.string != nil && group.count > 2 {
290                    result += mapBindings(group, prefix: prefix, modes: modes, source: source)
291                } else if let key = arg.string, i + 1 < args.count {
292                    let keys = [prefix, key].filter { !$0.isEmpty }.joined(separator: " ")
293                    result.append(Binding(keys: keys, command: args[i + 1], modes: modes, source: source))
294                    i += 1
295                }
296                i += 1
297            }
298            return result
299        }
300    }
301
302    // MARK: - Values
303
304    /// `(font-spec :family "JetBrains Mono" :size 14)`, or `"JetBrains Mono-14"`.
305    static func fontSpec(_ sexp: Sexp) -> (family: String?, size: Int?)? {
306        if let name = sexp.string {
307            let parts = name.split(separator: "-")
308            if parts.count > 1, let size = Int(parts.last!) { return (parts.dropLast().joined(separator: "-"), size) }
309            return (name, nil)
310        }
311        guard sexp.head == "font-spec", let args = sexp.elements?.dropFirst() else { return nil }
312        let list = Array(args)
313        var family: String?
314        var size: Int?
315        var i = 0
316        while i + 1 < list.count {
317            switch list[i].symbol {
318            case ":family": family = list[i + 1].string
319            case ":size":
320                if let n = list[i + 1].integer { size = n }
321                if case .float(let d) = list[i + 1] { size = Int(d.rounded()) }
322            default: break
323            }
324            i += 2
325        }
326        return family == nil && size == nil ? nil : (family, size)
327    }
328
329    static func unquote(_ sexp: Sexp) -> Sexp? {
330        if let items = sexp.elements, items.count == 2, items[0].symbol == "quote" || items[0].symbol == "function" { return items[1] }
331        if case .list(let items) = sexp, items.count == 2, items[0].symbol == "\\`" { return items[1] }
332        return nil
333    }
334
335    /// What a form evaluates to, for the few forms configurations build values with; nil
336    /// when reading can't tell.
337    static func evaluate(_ sexp: Sexp, _ env: [String: Sexp]) -> Sexp? {
338        switch sexp {
339        case .string, .integer, .float, .character, .vector: return sexp
340        case .symbol(let name):
341            if name == "t" || name == "nil" || name.hasPrefix(":") { return sexp }
342            return env[name]
343        case .dotted: return nil
344        case .list(let items):
345            guard let head = items.first?.symbol else { return nil }
346            let args = Array(items.dropFirst())
347            switch head {
348            case "quote", "function": return args.first
349            case "\\`":
350                guard let inner = args.first else { return nil }
351                return backquote(inner, env)
352            case "list":
353                let values = args.compactMap { evaluate($0, env) }
354                return values.count == args.count ? .list(values) : nil
355            case "concat":
356                let parts = args.compactMap { evaluate($0, env)?.string }
357                return parts.count == args.count ? .string(parts.joined()) : nil
358            case "expand-file-name", "file-name-concat":
359                let parts = args.compactMap { evaluate($0, env)?.string }
360                guard parts.count == args.count, !parts.isEmpty else { return nil }
361                if head == "expand-file-name" {
362                    let name = parts[0]
363                    if name.hasPrefix("/") || name.hasPrefix("~") || parts.count == 1 { return .string(name) }
364                    return .string((parts[1] as NSString).appendingPathComponent(name))
365                }
366                return .string(parts.dropFirst().reduce(parts[0]) { ($0 as NSString).appendingPathComponent($1) })
367            case "file-name-as-directory":
368                guard let s = args.first.flatMap({ evaluate($0, env)?.string }) else { return nil }
369                return .string(s.hasSuffix("/") ? s : s + "/")
370            default:
371                return nil
372            }
373        }
374    }
375
376    /// A backquoted form with its `,` and `,@` parts evaluated.
377    static func backquote(_ sexp: Sexp, _ env: [String: Sexp]) -> Sexp? {
378        guard case .list(let items) = sexp else {
379            if case .dotted(let items, let last) = sexp {
380                let values = items.compactMap { backquote($0, env) }
381                guard values.count == items.count, let tail = backquote(last, env) else { return nil }
382                return .dotted(values, tail)
383            }
384            return sexp
385        }
386        if items.count == 2, items[0].symbol == "," { return evaluate(items[1], env) }
387        var out: [Sexp] = []
388        for item in items {
389            if case .list(let parts) = item, parts.count == 2, parts[0].symbol == ",@" {
390                guard let spliced = evaluate(parts[1], env)?.elements else { return nil }
391                out += spliced
392            } else {
393                guard let value = backquote(item, env) else { return nil }
394                out.append(value)
395            }
396        }
397        return .list(out)
398    }
399
400    // MARK: - Results
401
402    static let orgRelated = ["org-", "appt-", "display-line-numbers", "fill-column", "evil-", "doom-font", "doom-variable-pitch-font", "doom-theme", "calendar-week-start-day"]
403
404    mutating func build(from scanner: Scanner) {
405        var next = 0
406        func id() -> Int { next += 1; return next }
407        // The last assignment of each variable wins, those after a package loads over the rest.
408        var winners: [String: Assignment] = [:]
409        var env: [String: Sexp] = [:]
410        for assignment in scanner.assignments.enumerated().sorted(by: { ($0.element.rank, $0.offset) < ($1.element.rank, $1.offset) }).map(\.element) {
411            winners[assignment.name] = assignment
412            if let value = Self.evaluate(assignment.value, env) { env[assignment.name] = value }
413        }
414        if isDoom || scanner.usesEvil {
415            items.append(Item(id: id(), name: isDoom ? "Doom Emacs" : "evil-mode", summary: "keymap = \"doom\"", source: "", change: .setting(key: "keymap", value: .string("doom"))))
416        }
417        for name in winners.keys.sorted() {
418            let assignment = winners[name]!
419            guard Self.orgRelated.contains(where: { name.hasPrefix($0) }) else {
420                if assignment.rank >= 2 { skipped += 1 }
421                continue
422            }
423            if name == "doom-font", let spec = Self.fontSpec(assignment.value) {
424                if let family = spec.family {
425                    items.append(Item(id: id(), name: name, summary: "font = \"\(family)\"", source: assignment.source, change: .setting(key: "font", value: .string(family))))
426                }
427                if let size = spec.size {
428                    items.append(Item(id: id(), name: name, summary: "font-size = \(size)", source: assignment.source, change: .setting(key: "font-size", value: .integer(size))))
429                }
430                continue
431            }
432            guard let value = Self.evaluate(assignment.value, env) else {
433                if assignment.rank < 2 {
434                    doomDefaultsLeftOut += 1
435                    continue
436                }
437                unreadable.append(Note(id: id(), name: name, reason: "worked out when Emacs runs: \(assignment.value.description.prefix(80))", source: assignment.source))
438                continue
439            }
440            let before = unsupported.count
441            convert(name, value, source: assignment.source, env: env, id: id)
442            if assignment.rank < 2, unsupported.count > before {
443                doomDefaultsLeftOut += unsupported.count - before
444                unsupported.removeLast(unsupported.count - before)
445            }
446        }
447        for (entry, source) in scanner.addedTemplates { structureTemplates([entry], source: source, id: id) }
448        // One item per folder.
449        var folders: Set<String> = []
450        items.removeAll { item in
451            guard case .folder(let path) = item.change else { return false }
452            let key = (path as NSString).expandingTildeInPath.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
453            return !folders.insert(key).inserted
454        }
455        for binding in scanner.bindings {
456            guard let commandName = Self.unquote(binding.command)?.symbol ?? binding.command.symbol else {
457                unsupported.append(Note(id: id(), name: binding.keys, reason: "bound to code, not a command", source: binding.source))
458                continue
459            }
460            guard let command = Self.commands[commandName] else {
461                unsupported.append(Note(id: id(), name: "\(binding.keys) → \(commandName)", reason: "orgstar has no such command", source: binding.source))
462                continue
463            }
464            guard let keys = KeySequence.parse(binding.keys).map(KeySequence.format) else {
465                unsupported.append(Note(id: id(), name: binding.keys, reason: "keys orgstar can't read", source: binding.source))
466                continue
467            }
468            let modes = isDoom ? binding.modes.map { $0 ?? "normal" } : binding.modes
469            for mode in Array(Set(modes.map { $0 ?? "" })).sorted() {
470                items.append(Item(id: id(), name: "\(keys) → \(commandName)", summary: mode.isEmpty ? command : "\(command) in \(mode) state",
471                                  source: binding.source, change: .binding(keys: keys, command: command, mode: mode.isEmpty ? nil : mode)))
472            }
473        }
474    }
475
476    mutating func convert(_ name: String, _ value: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) {
477        func add(_ key: String, _ toml: TOML.Value, _ summary: String? = nil) {
478            items.append(Item(id: id(), name: name, summary: summary ?? "\(key) = \(UserConfig.format(toml))", source: source, change: .setting(key: key, value: toml)))
479        }
480        func note(_ reason: String) { unsupported.append(Note(id: id(), name: name, reason: reason, source: source)) }
481        let truthy = value.symbol != "nil" && value.elements?.isEmpty != true
482        switch name {
483        case "fill-column", "org-tags-column", "appt-message-warning-time", "org-deadline-warning-days":
484            guard let n = value.integer else { return note("not a number") }
485            add(name, .integer(n))
486        case "org-insert-heading-respect-content", "org-list-allow-alphabetical", "org-hide-emphasis-markers", "org-pretty-entities",
487             "org-cycle-hide-drawer-startup", "org-cycle-hide-block-startup", "org-use-speed-commands", "org-startup-with-inline-images",
488             "org-startup-indented", "org-hide-leading-stars", "org-startup-align-all-tables", "org-startup-truncated",
489             "org-enforce-todo-dependencies", "org-enforce-todo-checkbox-dependencies",
490             "org-agenda-todo-ignore-with-date", "org-agenda-tags-todo-honor-ignore-options", "org-clock-out-remove-zero-time-clocks":
491            add(name, .bool(truthy))
492        case "org-archive-location":
493            guard let location = value.string, location.contains("::") else { return note("not a file::heading location") }
494            add(name, .string(location))
495        case "org-use-tag-inheritance":
496            if let regexp = value.string { add(name, .string("{\(regexp)}")) } else if let tags = value.elements, !tags.isEmpty {
497                add(name, .string(tags.compactMap(\.string).joined(separator: " ")))
498            } else { add(name, .string(truthy ? "t" : "nil")) }
499        case "org-tags-exclude-from-inheritance":
500            add(name, .string((value.elements ?? []).compactMap(\.string).joined(separator: " ")))
501        case "org-tag-alist":
502            guard let alist = Self.tagAlist(value.elements ?? []) else { return note("entries orgstar can't read") }
503            add(name, .string(alist))
504        case "org-track-ordered-property-with-tag":
505            if let tag = value.string { add(name, .string(tag)) } else { add(name, .string(truthy ? "t" : "nil")) }
506        case "org-agenda-log-mode-items":
507            let items = (value.elements ?? []).compactMap(\.symbol).filter { ["closed", "clock", "state"].contains($0) }
508            guard !items.isEmpty || value.symbol == "nil" else { return note("not a list of closed, clock and state") }
509            add(name, .string(items.joined(separator: " ")))
510        case "org-agenda-todo-ignore-scheduled", "org-agenda-todo-ignore-deadlines", "org-agenda-todo-ignore-timestamp":
511            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)") }
512        case "org-structure-template-alist":
513            structureTemplates(value.elements ?? [], source: source, id: id)
514        case "org-agenda-dim-blocked-tasks":
515            add(name, .string(value.symbol == "invisible" ? "invisible" : truthy ? "t" : "nil"))
516        case "org-hide-drawer-startup", "org-hide-block-startup":
517            add(name == "org-hide-drawer-startup" ? "org-cycle-hide-drawer-startup" : "org-cycle-hide-block-startup", .bool(truthy))
518        case "org-M-RET-may-split-line":
519            if let alist = value.elements, !alist.isEmpty {
520                // `((default . nil))`: the default entry, as most configurations write it.
521                let entry = alist.first { if case .dotted(let k, _) = $0 { return k.first?.symbol == "default" } else { return false } }
522                if case .dotted(_, let v)? = entry { add(name, .bool(v.symbol != "nil")) } else { note("per-context values aren't supported") }
523            } else {
524                add(name, .bool(truthy))
525            }
526        case "org-agenda-prefix-format":
527            if let s = value.string {
528                for view in ["agenda", "todo", "tags"] { add("org-agenda-prefix-format.\(view)", .string(s)) }
529            } else {
530                for entry in value.elements ?? [] {
531                    guard case .dotted(let key, let format) = entry, let view = key.first?.symbol, let s = format.string else { continue }
532                    if ["agenda", "todo", "tags"].contains(view) { add("org-agenda-prefix-format.\(view)", .string(s)) }
533                }
534            }
535        case "org-log-done", "org-log-reschedule", "org-log-redeadline":
536            switch value.symbol {
537            case "nil": add(name, .string("nil"))
538            case "time", "t": add(name, .string("time"))
539            case "note": add(name, .string("note"))
540            default: note("unexpected value \(value.description)")
541            }
542        case "org-log-into-drawer":
543            if let s = value.string { add(name, .string(s)) } else { add(name, .string(truthy ? "LOGBOOK" : "")) }
544        case "display-line-numbers-type":
545            add(name, .bool(truthy), truthy && value.symbol != "t" ? "display-line-numbers-type = true (orgstar numbers lines absolutely)" : nil)
546        case "org-agenda-span":
547            let days: Int? = value.integer ?? ["day": 1, "week": 7, "fortnight": 14, "month": 30, "year": 365][value.symbol ?? ""]
548            guard let days else { return note("unknown span \(value.description)") }
549            add(name, .integer(days))
550        case "org-agenda-start-on-weekday":
551            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") }
552        case "org-clock-idle-time":
553            // nil is never; a number is minutes.
554            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") }
555        case "org-clock-rounding-minutes":
556            guard let n = value.integer, n >= 0 else { return note("not a number of minutes") }
557            add(name, .integer(n))
558        case "org-clock-in-switch-to-state":
559            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") }
560        case "org-clock-out-when-done":
561            if let states = value.elements, !states.isEmpty {
562                let names = states.compactMap(\.string)
563                guard names.count == states.count else { return note("not a list of keywords") }
564                add(name, .string(names.joined(separator: " ")))
565            } else {
566                add(name, .string(truthy ? "t" : "nil"))
567            }
568        case "org-clock-into-drawer":
569            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")) }
570        case "org-clock-history-length":
571            guard let length = value.integer, length > 0 else { return note("not a positive number") }
572            add(name, .integer(length))
573        case "org-agenda-start-day":
574            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") }
575        case "org-todo-keywords":
576            let sequences = (value.elements ?? []).compactMap { $0.elements }.filter { $0.count > 1 }.map { $0.dropFirst().compactMap(\.string) }
577            let lines = sequences.filter { !$0.contains { $0.contains(where: \.isWhitespace) } }.map { $0.joined(separator: " ") }
578            guard !lines.isEmpty else { return note("unexpected value") }
579            if lines.count < sequences.count {
580                note("\(sequences.count - lines.count) sequence(s) with spaces in a keyword left out; #+TODO syntax can't write them")
581            }
582            if (value.elements ?? []).contains(where: { $0.elements?.first?.symbol == "type" }) { note("type sequences are read as sequences") }
583            add(name, .string(lines.joined(separator: "\n")))
584        case "org-directory":
585            guard let path = value.string else { return note("not a folder") }
586            items.append(Item(id: id(), name: name, summary: "add folder \(path)", source: source, change: .folder(path)))
587        case "org-agenda-files":
588            let paths = (value.elements ?? [value]).compactMap(\.string)
589            guard !paths.isEmpty else { return note("not a list of files or folders") }
590            for path in paths {
591                let folder = path.hasSuffix(".org") ? (path as NSString).deletingLastPathComponent : path
592                items.append(Item(id: id(), name: name, summary: "add folder \(folder)", source: source, change: .folder(folder)))
593            }
594        case "org-capture-templates":
595            for entry in value.elements ?? [] { captureTemplate(entry, source: source, env: env, id: id) }
596        case "doom-font":
597            note("not a font-spec orgstar can read")
598        case "doom-variable-pitch-font":
599            note("orgstar uses one font; set it with doom-font or [theme] font")
600        case "doom-theme":
601            note("Emacs themes aren't read; set colors under [theme] in config.toml")
602        default:
603            note("orgstar has no equivalent")
604        }
605    }
606
607    /// `org-tag-alist` in `#+TAGS` syntax: `("work" . ?w)` is `work(w)`, `(:startgroup)` `{`,
608    /// `(:startgrouptag)` `[`, `(:grouptags)` `:`, and `(:newline)` a new line.
609    static func tagAlist(_ entries: [Sexp]) -> String? {
610        var lines: [[String]] = [[]]
611        for entry in entries {
612            let marker = entry.elements?.first?.symbol ?? entry.symbol
613            switch marker {
614            case ":startgroup": lines[lines.count - 1].append("{")
615            case ":endgroup": lines[lines.count - 1].append("}")
616            case ":startgrouptag": lines[lines.count - 1].append("[")
617            case ":endgrouptag": lines[lines.count - 1].append("]")
618            case ":grouptags": lines[lines.count - 1].append(":")
619            case ":newline": lines.append([])
620            default:
621                if let tag = entry.string {
622                    lines[lines.count - 1].append(tag)
623                } else if case .dotted(let head, let key) = entry, head.count == 1, let tag = head[0].string {
624                    guard case .character(let code) = key, let scalar = Unicode.Scalar(code) else {
625                        lines[lines.count - 1].append(tag)
626                        continue
627                    }
628                    lines[lines.count - 1].append("\(tag)(\(Character(scalar)))")
629                } else {
630                    return nil
631                }
632            }
633        }
634        return lines.map { $0.joined(separator: " ") }.filter { !$0.isEmpty }.joined(separator: "\n")
635    }
636
637    /// `("el" . "src emacs-lisp")` entries that aren't Org's own.
638    mutating func structureTemplates(_ entries: [Sexp], source: String, id: () -> Int) {
639        for entry in entries {
640            guard case .dotted(let head, let tail) = entry, head.count == 1, let key = head[0].string, let type = tail.string else {
641                unsupported.append(Note(id: id(), name: "org-structure-template-alist", reason: "an entry that isn't (\"key\" . \"type\")", source: source))
642                continue
643            }
644            if StructureTemplate.defaults.contains(StructureTemplate(key: key, type: type)) { continue }
645            guard !key.isEmpty, key.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }) else {
646                unsupported.append(Note(id: id(), name: "structure template \"\(key)\"", reason: "config.toml keys are letters, digits, _ and -", source: source))
647                continue
648            }
649            items.removeAll { if case .structureTemplate(key, _) = $0.change { true } else { false } }
650            items.append(Item(id: id(), name: "structure template \"\(key)\"", summary: "<\(key) inserts a \(type) block", source: source,
651                              change: .structureTemplate(key: key, type: type)))
652        }
653    }
654
655    mutating func captureTemplate(_ entry: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) {
656        guard let parts = entry.elements, parts.count >= 2, let key = parts[0].string else { return }
657        let name = parts[1].string ?? key
658        guard parts.count >= 5, let type = parts[2].symbol, let target = parts[3].elements, let kind = target.first?.symbol,
659              let template = parts[4].string else {
660            // A key and a name only: a group of templates.
661            if parts.count == 2 { return }
662            unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "a template that isn't a string", source: source))
663            return
664        }
665        guard ["entry", "item", "checkitem", "plain", "table-line"].contains(type) else {
666            unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "\(type) templates aren't supported", source: source))
667            return
668        }
669        func quoted(_ s: String) -> String { UserConfig.format(.string(s)) }
670        var toml = "[[template]]\nkey = \(quoted(key))\nname = \(quoted(name))\ntype = \(quoted(type))\n"
671        // `org-capture-expand-file`: a variable's value, or a form evaluated.
672        let strings = target.dropFirst().compactMap { $0.string ?? Self.evaluate($0, env)?.string }
673        // Property list after the template: `:prepend t :empty-lines 1 …`.
674        var properties: [String: Sexp] = [:]
675        let rest = Array(parts.dropFirst(5))
676        for i in stride(from: 0, to: rest.count - 1, by: 2) { if let name = rest[i].symbol { properties[name] = rest[i + 1] } }
677        let allStrings = strings.count == target.count - 1
678        var treeType = properties[":tree-type"]?.symbol
679        let place: String? = switch kind {
680        case "file" where strings.count == 1 && target.count == 2:
681            "file = \(quoted(strings[0]))\n"
682        case "file+headline" where strings.count == 2 && target.count == 3:
683            "file = \(quoted(strings[0]))\nheadline = \(quoted(strings[1]))\n"
684        case "file+olp" where strings.count >= 2 && allStrings:
685            "file = \(quoted(strings[0]))\nolp = \(quoted(strings.dropFirst().joined(separator: "/")))\n"
686        case "file+olp+datetree" where strings.count >= 1 && allStrings:
687            "file = \(quoted(strings[0]))\ndatetree = true\n" + (strings.count > 1 ? "olp = \(quoted(strings.dropFirst().joined(separator: "/")))\n" : "")
688        case let legacy where (legacy == "file+datetree" || legacy == "file+weektree") && strings.count == 1 && target.count == 2:
689            "file = \(quoted(strings[0]))\ndatetree = true\n"
690        case "id" where strings.count == 1 && target.count == 2:
691            "id = \(quoted(strings[0]))\n"
692        case "clock" where target.count == 1:
693            "clock = true\n"
694        default:
695            nil
696        }
697        guard let place else {
698            unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "target \(kind) isn't supported", source: source))
699            return
700        }
701        if kind == "file+weektree" { treeType = "week" }
702        toml += place
703        if let treeType {
704            guard ["day", "week", "month"].contains(treeType) else {
705                unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: ":tree-type \(treeType) isn't supported", source: source))
706                return
707            }
708            if treeType != "day" { toml += "tree-type = \(quoted(treeType))\n" }
709        }
710        for flag in ["prepend", "immediate-finish", "jump-to-captured", "clock-in", "clock-keep", "clock-resume"] {
711            if let value = properties[":" + flag], value.symbol != "nil" { toml += "\(flag) = true\n" }
712        }
713        for count in ["empty-lines", "empty-lines-before", "empty-lines-after"] {
714            if let n = properties[":" + count]?.integer { toml += "\(count) = \(n)\n" }
715        }
716        if let pos = properties[":table-line-pos"]?.string { toml += "table-line-pos = \(quoted(pos))\n" }
717        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"].contains($0) }
718        if !ignored.isEmpty {
719            unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "\(ignored.sorted().joined(separator: ", ")) left out", source: source))
720        }
721        toml += "template = \(quoted(template))\n"
722        items.append(Item(id: id(), name: "capture \"\(key)\" \(name)", summary: "capture template \"\(key)\"", source: source, change: .capture(key: key, toml: toml)))
723    }
724
725    /// Emacs commands and the Orgstar commands that do the same.
726    static let commands: [String: String] = [
727        "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",
728        "org-metaleft": "org.heading.promote", "org-metaright": "org.heading.demote", "org-do-promote": "org.heading.promote", "org-do-demote": "org.heading.demote",
729        "org-promote-subtree": "org.subtree.promote", "org-demote-subtree": "org.subtree.demote",
730        "org-shiftmetaleft": "org.subtree.promote", "org-shiftmetaright": "org.subtree.demote",
731        "org-move-subtree-up": "org.subtree.up", "org-move-subtree-down": "org.subtree.down", "org-metaup": "org.subtree.up", "org-metadown": "org.subtree.down",
732        "org-insert-heading": "org.heading.insert", "org-meta-return": "org.heading.insert",
733        "org-insert-heading-respect-content": "org.heading.insert-after-subtree", "+org/insert-item-below": "org.heading.insert-after-subtree",
734        "org-insert-todo-heading": "org.heading.insert-todo",
735        "org-next-visible-heading": "org.heading.next", "org-previous-visible-heading": "org.heading.previous",
736        "org-forward-heading-same-level": "org.heading.forward-same-level", "org-backward-heading-same-level": "org.heading.backward-same-level",
737        "outline-up-heading": "org.heading.up", "org-up-element": "org.heading.up",
738        "org-set-tags-command": "org.tags.set", "org-set-property": "org.property.read-and-set",
739        "org-toggle-checkbox": "org.checkbox.toggle", "org-ctrl-c-ctrl-c": "org.ctrl-c-ctrl-c", "+org/dwim-at-point": "org.dwim",
740        "org-schedule": "org.schedule", "org-deadline": "org.deadline", "org-time-stamp": "org.timestamp.active", "org-timestamp": "org.timestamp.active",
741        "org-time-stamp-inactive": "org.timestamp.inactive", "org-timestamp-inactive": "org.timestamp.inactive",
742        "org-fill-paragraph": "org.fill-paragraph", "org-cycle": "org.cycle", "org-shifttab": "org.cycle-global", "org-global-cycle": "org.cycle-global",
743        "org-table-create": "org.table.create", "org-table-align": "org.table.align", "org-table-recalculate": "org.table.recalc",
744        "org-table-insert-row": "org.table.insert-row", "org-table-insert-column": "org.table.insert-column",
745        "org-table-delete-column": "org.table.delete-column", "org-table-kill-row": "org.table.kill-row", "org-table-insert-hline": "org.table.insert-hline",
746        "org-babel-execute-src-block": "org.babel.execute", "org-clock-in": "app.clock.in", "org-clock-out": "app.clock.out",
747        "org-clock-cancel": "app.clock.cancel", "org-clock-goto": "app.clock.goto", "org-clock-in-last": "app.clock.in-last",
748        "org-resolve-clocks": "app.clock.resolve", "org-clock-mark-default-task": "app.clock.default",
749        "org-refile": "app.refile", "org-archive-subtree": "app.archive", "org-archive-subtree-default": "app.archive",
750        "org-capture": "app.capture", "org-agenda": "app.agenda", "org-agenda-list": "app.agenda",
751        "save-buffer": "app.save", "find-file": "app.quick-open", "projectile-find-file": "app.quick-open", "+default/find-file-under-here": "app.quick-open",
752        "execute-extended-command": "app.palette", "counsel-M-x": "app.palette",
753        "isearch-forward": "edit.find", "isearch-backward": "edit.find", "consult-line": "edit.find", "+default/search-buffer": "edit.find", "swiper": "edit.find",
754        "query-replace": "edit.replace", "query-replace-regexp": "edit.replace",
755        "save-buffers-kill-terminal": "app.quit", "save-buffers-kill-emacs": "app.quit",
756    ]
757}
758
759extension EmacsImport {
760    /// Applies `items`: settings to `defaults` (and so config.toml), folders to the workspace,
761    /// capture templates and key bindings appended to capture.toml and keymap.toml in
762    /// `directory`, leaving out templates whose key is there already and bindings that are
763    /// there already. Returns a summary.
764    @MainActor
765    public static func apply(
766        _ items: [Item], defaults: UserDefaults = .standard, workspace: WorkspaceModel?, directory: URL = UserConfig.directory
767    ) async -> String {
768        var settings = 0, folders = 0, templates = 0, bindings = 0, blocks = 0
769        var problems: [String] = []
770        for item in items {
771            guard case .setting(let key, let value) = item.change,
772                  let setting = UserConfig.settings.first(where: { $0.path == key || $0.key == key }) else { continue }
773            if let problem = UserConfig.store(value, setting, in: defaults) { problems.append(problem) } else { settings += 1 }
774        }
775        for item in items {
776            guard case .folder(let path) = item.change else { continue }
777            let url = URL(fileURLWithPath: (path as NSString).expandingTildeInPath).standardizedFileURL
778            guard let workspace, FileManager.default.fileExists(atPath: url.path) else {
779                problems.append("\(path) doesn't exist")
780                continue
781            }
782            if workspace.roots.contains(where: { URL(fileURLWithPath: $0.path).standardizedFileURL.path == url.path }) { continue }
783            do {
784                try await workspace.addRoot(url)
785                folders += 1
786            } catch {
787                problems.append("Can't add \(path): \(error.localizedDescription)")
788            }
789        }
790        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
791        let captureFile = directory.appendingPathComponent("capture.toml")
792        var capture = (try? String(contentsOf: captureFile, encoding: .utf8)) ?? ""
793        let existingKeys = Set((try? TOML.parse(capture))?.compactMap { $0.values["key"]?.string } ?? [])
794        var addedCapture = ""
795        for item in items {
796            guard case .capture(let key, let toml) = item.change, !existingKeys.contains(key) else { continue }
797            addedCapture += "\n" + toml
798            templates += 1
799        }
800        if !addedCapture.isEmpty {
801            capture += (capture.isEmpty ? "# Capture templates. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedCapture
802            try? capture.write(to: captureFile, atomically: true, encoding: .utf8)
803        }
804        let keymapFile = directory.appendingPathComponent("keymap.toml")
805        var keymap = (try? String(contentsOf: keymapFile, encoding: .utf8)) ?? ""
806        func binding(_ keys: String?, _ command: String?, _ mode: String?) -> String { [keys ?? "", command ?? "", mode ?? ""].joined(separator: "\u{0}") }
807        var existingBindings = Set((try? TOML.parse(keymap))?.filter { $0.name == "bind" && $0.values["when"] == nil }
808            .map { binding($0.values["keys"]?.string, $0.values["command"]?.string, $0.values["mode"]?.string) } ?? [])
809        var addedKeys = ""
810        for item in items {
811            guard case .binding(let keys, let command, let mode) = item.change,
812                  existingBindings.insert(binding(keys, command, mode)).inserted else { continue }
813            addedKeys += "\n[[bind]]\nkeys = \(UserConfig.format(.string(keys)))\ncommand = \(UserConfig.format(.string(command)))\n"
814            if let mode { addedKeys += "mode = \(UserConfig.format(.string(mode)))\n" }
815            bindings += 1
816        }
817        if !addedKeys.isEmpty {
818            keymap += (keymap.isEmpty ? "" : "\n") + "# Imported from Emacs.\n" + addedKeys
819            try? keymap.write(to: keymapFile, atomically: true, encoding: .utf8)
820        }
821        // Into user defaults, from where ConfigSync writes them into config.toml.
822        var rows = UserConfig.structureTemplates(defaults)
823        for item in items {
824            guard case .structureTemplate(let key, let type) = item.change else { continue }
825            rows.removeAll { $0.key == key }
826            rows.append(StructureTemplate(key: key, type: type))
827            blocks += 1
828        }
829        if blocks > 0 { UserConfig.setStructureTemplates(rows, in: defaults) }
830        func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" }
831        let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"),
832                    count(blocks, "structure template")].compactMap { $0 }
833        var summary = done.isEmpty ? "Nothing new to import." : "Imported " + done.joined(separator: ", ") + "."
834        if !problems.isEmpty { summary += " " + problems.joined(separator: "; ") + "." }
835        return summary
836    }
837}