Sources/OrgApp/EmacsImport.swift

2cef47f82373d81f99d371b9aceb8bdc702f54c1
orgstar/Sources/OrgApp/EmacsImport.swift history · blame · raw

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