Commit 67fadc8623

67fadc8623384f6d91328737ca7ed676afd81653

parent: 5a8fa2470f

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 16:08 UTC

Emacs import: config.org and iOS

Import reads a literate config.org (emacs-lisp and elisp blocks, :tangle no and COMMENT/ARCHIVE excluded, line numbers kept) when there is no config.el. iOS gets Settings ▸ Import from Emacs for a chosen folder; settings and structure templates go into the configuration folder's config.toml.

Closes #59

Layout: unified · split

Sources/OrgApp/EmacsImport.swift +27 −5
@@ -57,12 +57,14 @@ public struct EmacsImport: Sendable {
5757 // MARK: - Finding the configuration
5858
5959 /// The configuration files in `folder` (a Doom folder, an `.emacs.d`) or the file itself.
60 /// A literate `config.org` is read when there's no `config.el` tangled from it.
6061 public static func files(in location: URL) -> [URL] {
6162 var isDirectory: ObjCBool = false
6263 guard FileManager.default.fileExists(atPath: location.path, isDirectory: &isDirectory) else { return [] }
6364 guard isDirectory.boolValue else { return [location] }
64 return ["init.el", "config.el", "custom.el"].map { location.appendingPathComponent($0) }
65 .filter { FileManager.default.fileExists(atPath: $0.path) }
65 let exists = { (name: String) in FileManager.default.fileExists(atPath: location.appendingPathComponent(name).path) }
66 let names = ["init.el", exists("config.el") ? "config.el" : "config.org", "custom.el"]
67 return names.filter(exists).map { location.appendingPathComponent($0) }
6668 }
6769
6870 /// Where an Emacs configuration usually is, first found first.
@@ -110,7 +112,7 @@ public struct EmacsImport: Sendable {
110112 result.problems.append("Can't read \(url.path)")
111113 continue
112114 }
113 sources.append((url.lastPathComponent, text, 1))
115 sources.append((url.lastPathComponent, url.pathExtension == "org" ? Tangle.literateLisp(text) : text, 1))
114116 }
115117 result.isDoom = sources.contains { $0.text.contains("(doom!") || $0.text.contains("(map! ") || $0.text.contains("(after! ") }
116118 if result.isDoom {
@@ -1019,15 +1021,24 @@ extension EmacsImport {
10191021 /// `directory`, leaving out templates whose key is there already and bindings that are
10201022 /// there already. Returns a summary.
10211023 @MainActor
1024 /// With `writeConfig`, settings and structure templates are written into `config.toml` too,
1025 /// for where nothing syncs user defaults into it (iOS).
10221026 public static func apply(
1023 _ items: [Item], defaults: UserDefaults = .standard, workspace: WorkspaceModel?, directory: URL = UserConfig.directory
1027 _ items: [Item], defaults: UserDefaults = .standard, workspace: WorkspaceModel?, directory: URL = UserConfig.directory,
1028 writeConfig: Bool = false
10241029 ) async -> String {
1030 var stored: [UserConfig.Setting] = []
10251031 var settings = 0, folders = 0, templates = 0, bindings = 0, blocks = 0, views = 0, projects = 0
10261032 var problems: [String] = []
10271033 for item in items {
10281034 guard case .setting(let key, let value) = item.change,
10291035 let setting = UserConfig.settings.first(where: { $0.path == key || $0.key == key }) else { continue }
1030 if let problem = UserConfig.store(value, setting, in: defaults) { problems.append(problem) } else { settings += 1 }
1036 if let problem = UserConfig.store(value, setting, in: defaults) {
1037 problems.append(problem)
1038 } else {
1039 settings += 1
1040 stored.append(setting)
1041 }
10311042 }
10321043 for item in items {
10331044 guard case .folder(let path) = item.change else { continue }
@@ -1110,6 +1121,17 @@ extension EmacsImport {
11101121 blocks += 1
11111122 }
11121123 if blocks > 0 { UserConfig.setStructureTemplates(rows, in: defaults) }
1124 if writeConfig, settings + blocks > 0 {
1125 var text = (try? String(contentsOf: configFile, encoding: .utf8)) ?? ""
1126 for setting in stored {
1127 text = UserConfig.setting(text, section: setting.section, key: setting.key, to: UserConfig.value(setting, in: defaults))
1128 }
1129 for item in items {
1130 guard case .structureTemplate(let key, let type) = item.change else { continue }
1131 text = UserConfig.setting(text, section: UserConfig.structureTemplateTable, key: key, to: .string(type))
1132 }
1133 try? text.write(to: configFile, atomically: true, encoding: .utf8)
1134 }
11131135 func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" }
11141136 let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"),
11151137 count(blocks, "structure template"), count(views, "agenda view"), count(projects, "publishing project")].compactMap { $0 }
Sources/OrgCore/Compute/LiterateConfig.swift added +23
@@ -0,0 +1,23 @@
1import Foundation
2
3extension Tangle {
4 /// The Emacs Lisp a literate configuration (`config.org`) tangles to, as
5 /// `org-babel-load-file` and Doom's literate module do: `emacs-lisp` and `elisp` blocks,
6 /// with `:tangle` defaulting to the target, so only `:tangle no` leaves a block out, and
7 /// none under COMMENT or ARCHIVE headings. Other lines are blank, so that a line of the
8 /// result is the same line of `text`.
9 public static func literateLisp(_ text: String) -> String {
10 let ns = text as NSString
11 let model = DocumentModel(tree: OrgParser.parse(text))
12 var lines = Array(repeating: "", count: text.components(separatedBy: "\n").count)
13 for block in model.srcBlocks where ["emacs-lisp", "elisp"].contains(block.language ?? "") && !excluded(block, model: model) {
14 guard let params = try? Babel.Params(block: block, model: model, text: ns, defaults: [(":tangle", "yes")]),
15 params.single[":tangle"] != "no" else { continue }
16 let first = ns.substring(to: block.range.lowerBound).components(separatedBy: "\n").count
17 for (i, line) in block.body.components(separatedBy: "\n").enumerated() where first + i < lines.count {
18 lines[first + i] = line
19 }
20 }
21 return lines.joined(separator: "\n")
22 }
23}
Sources/OrgstarMobile/EmacsImportScreen.swift added +102
@@ -0,0 +1,102 @@
1#if os(iOS)
2import OrgApp
3import OrgCore
4import SwiftUI
5
6/// Import from Emacs: a configuration folder (a synced `~/.config/doom` or `~/.emacs.d`), read
7/// and picked from before anything changes. Settings go into the configuration
8/// folder's config.toml when there is one; agenda folders, which name the Mac's paths, are left
9/// out.
10struct EmacsImportScreen: View {
11 let model: MobileModel
12 @State private var location: URL?
13 @State private var result: EmacsImport?
14 @State private var selected: Set<Int> = []
15 @State private var choosing = false
16 @State private var summary: String?
17 @State private var importing = false
18
19 var body: some View {
20 List {
21 Section {
22 Button(location == nil ? "Choose Folder…" : "Choose Another Folder…") { choosing = true }
23 } footer: {
24 Text(location.map { "Reading \($0.lastPathComponent)" + ((result?.isDoom ?? false) ? ", a Doom configuration" : "") + "." }
25 ?? "The folder holding init.el, config.el or config.org.")
26 }
27 if let summary {
28 Section { Text(summary) }
29 } else if let result {
30 ForEach(groups(result), id: \.0) { title, items in
31 Section(title) {
32 ForEach(items) { item in
33 Toggle(isOn: Binding { selected.contains(item.id) } set: { on in
34 if on { selected.insert(item.id) } else { selected.remove(item.id) }
35 }) {
36 VStack(alignment: .leading, spacing: 1) {
37 Text(item.summary).font(.system(.callout, design: .monospaced))
38 Text([item.name == item.summary ? nil : item.name, item.source.isEmpty ? nil : item.source].compactMap { $0 }.joined(separator: " · "))
39 .font(.caption).foregroundStyle(.secondary)
40 }
41 }
42 }
43 }
44 }
45 let notes = result.unsupported.map { ($0.id, $0.name, $0.reason, $0.source) } + result.unreadable.map { ($0.id, $0.name, $0.reason, $0.source) }
46 if !notes.isEmpty || !result.problems.isEmpty {
47 Section("Not imported") {
48 ForEach(result.problems, id: \.self) { Text($0).foregroundStyle(.red) }
49 ForEach(notes, id: \.0) { note in
50 VStack(alignment: .leading, spacing: 1) {
51 Text(note.1).font(.system(.callout, design: .monospaced))
52 Text("\(note.2) · \(note.3)").font(.caption).foregroundStyle(.secondary)
53 }
54 }
55 }
56 }
57 }
58 }
59 .navigationTitle("Import from Emacs")
60 .toolbar {
61 if result != nil, summary == nil {
62 Button("Import") { runImport() }.disabled(selected.isEmpty || importing)
63 }
64 }
65 .fileImporter(isPresented: $choosing, allowedContentTypes: [.folder]) { chosen in
66 if case .success(let url) = chosen { read(url) }
67 }
68 }
69
70 private func groups(_ result: EmacsImport) -> [(String, [EmacsImport.Item])] {
71 [
72 ("Settings", result.items.filter { if case .setting = $0.change { true } else { false } }),
73 ("Capture templates", result.items.filter { if case .capture = $0.change { true } else { false } }),
74 ("Key bindings", result.items.filter { if case .binding = $0.change { true } else { false } }),
75 ("Structure templates", result.items.filter { if case .structureTemplate = $0.change { true } else { false } }),
76 ("Agenda views", result.items.filter { if case .view = $0.change { true } else { false } }),
77 ].filter { !$0.1.isEmpty }
78 }
79
80 private func read(_ url: URL) {
81 let accessing = url.startAccessingSecurityScopedResource()
82 defer { if accessing { url.stopAccessingSecurityScopedResource() } }
83 location = url
84 let scanned = EmacsImport.scan(EmacsImport.files(in: url))
85 result = scanned
86 selected = Set(groups(scanned).flatMap(\.1).map(\.id))
87 summary = nil
88 }
89
90 private func runImport() {
91 guard let result else { return }
92 importing = true
93 let chosen = result.items.filter { selected.contains($0.id) }
94 Task {
95 summary = await EmacsImport.apply(chosen, workspace: nil, directory: model.configFolder ?? UserConfig.directory,
96 writeConfig: model.configFolder != nil)
97 model.reloadConfig()
98 importing = false
99 }
100 }
101}
102#endif
Sources/OrgstarMobile/SettingsScreen.swift +3
@@ -28,6 +28,9 @@ struct SettingsScreen: View {
2828 Button(model.configFolder == nil ? "Choose Folder…" : "Choose Another Folder…") { choosing = true }
2929 if model.configFolder != nil {
3030 NavigationLink("Edit config.toml") { ConfigFileEditor(model: model) }
31 }
32 NavigationLink("Import from Emacs") { EmacsImportScreen(model: model) }
33 if model.configFolder != nil {
3134 Button("Stop Using This Folder", role: .destructive) { model.setConfigFolder(nil) }
3235 }
3336 ForEach(model.configProblems, id: \.self) { Text($0).foregroundStyle(.red) }
Tests/OrgAppTests/EmacsImportTests.swift +51
@@ -183,6 +183,57 @@ struct EmacsImportTests {
183183 #expect(s["org-icalendar-combined-agenda-file"] == .string("~/cal/org.ics"))
184184 }
185185
186 @Test func readsLiterateConfig() throws {
187 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)")
188 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
189 defer { try? FileManager.default.removeItem(at: folder) }
190 try "(doom! :lang org)".write(to: folder.appendingPathComponent("init.el"), atomically: true, encoding: .utf8)
191 try #"""
192 #+title: Config
193 * Org
194 #+begin_src emacs-lisp
195 (setq org-tags-column 0)
196 #+end_src
197 #+begin_src emacs-lisp :tangle no
198 (setq org-log-done 'note)
199 #+end_src
200 * COMMENT Old
201 #+begin_src emacs-lisp
202 (setq org-startup-folded t)
203 #+end_src
204 """#.write(to: folder.appendingPathComponent("config.org"), atomically: true, encoding: .utf8)
205 #expect(EmacsImport.files(in: folder).map(\.lastPathComponent) == ["init.el", "config.org"])
206 let result = EmacsImport.scan(EmacsImport.files(in: folder), doomDefaults: [])
207 #expect(result.problems.isEmpty, "\(result.problems)")
208 #expect(result.isDoom)
209 let s = settings(result)
210 #expect(s["org-tags-column"] == .integer(0))
211 #expect(s["org-log-done"] == nil && s["org-startup-folded"] == nil)
212 #expect(result.items.first { $0.name == "org-tags-column" }?.source == "config.org:4")
213 // A config.el tangled from it is read instead.
214 try "(setq org-tags-column 4)".write(to: folder.appendingPathComponent("config.el"), atomically: true, encoding: .utf8)
215 #expect(EmacsImport.files(in: folder).map(\.lastPathComponent) == ["init.el", "config.el"])
216 }
217
218 @MainActor
219 @Test func writesSettingsIntoConfigFile() async throws {
220 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-out-\(UUID().uuidString)")
221 defer { try? FileManager.default.removeItem(at: folder) }
222 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
223 try "(setq org-tags-column 0 org-log-done 'time)\n(add-to-list 'org-structure-template-alist '(\"el\" . \"src emacs-lisp\"))"
224 .write(to: folder.appendingPathComponent("init.el"), atomically: true, encoding: .utf8)
225 let result = EmacsImport.scan(EmacsImport.files(in: folder))
226 let name = "orgstar-import-\(UUID().uuidString)"
227 let defaults = UserDefaults(suiteName: name)!
228 defer { defaults.removePersistentDomain(forName: name) }
229 _ = await EmacsImport.apply(result.items, defaults: defaults, workspace: nil, directory: folder, writeConfig: true)
230 let config = try String(contentsOf: folder.appendingPathComponent("config.toml"), encoding: .utf8)
231 let values = UserConfig.values(in: config)
232 #expect(values["org-tags-column"] == .integer(0), "\(config)")
233 #expect(values["org-log-done"] == .string("time"), "\(config)")
234 #expect(values["org-structure-template-alist.el"] == .string("src emacs-lisp"), "\(config)")
235 }
236
186237 @Test func readsDailies() throws {
187238 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)")
188239 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
Tests/OrgCoreTests/LiterateConfigTests.swift added +46
@@ -0,0 +1,46 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// A literate configuration's Emacs Lisp, against `org-babel-tangle-file` with a target file
6/// and `emacs-lisp\|elisp`, as `org-babel-load-file` calls it.
7struct LiterateConfigTests {
8 static let texts = [
9 "#+title: Config\n\n* Org\n#+begin_src emacs-lisp\n(setq org-tags-column 0)\n#+end_src\n\n#+begin_src emacs-lisp :tangle no\n(setq org-log-done 'time)\n#+end_src\n",
10 "* Shell\n#+begin_src sh\necho no\n#+end_src\n* Lisp\n#+begin_src elisp\n (setq a 1)\n (setq b 2)\n#+end_src\n",
11 "* COMMENT Off\n#+begin_src emacs-lisp\n(setq off t)\n#+end_src\n* On\n#+begin_src emacs-lisp\n(setq on t)\n#+end_src\n",
12 "* Skipped\n:PROPERTIES:\n:header-args:emacs-lisp: :tangle no\n:END:\n#+begin_src emacs-lisp\n(setq skipped t)\n#+end_src\n* Kept\n#+begin_src emacs-lisp\n(setq kept t)\n#+end_src\n",
13 "#+PROPERTY: header-args :tangle no\n#+begin_src emacs-lisp\n(setq none t)\n#+end_src\n#+begin_src emacs-lisp :tangle yes\n(setq yes t)\n#+end_src\n",
14 "#+header: :tangle no\n#+begin_src emacs-lisp\n(setq header t)\n#+end_src\n* Archived :ARCHIVE:\n#+begin_src emacs-lisp\n(setq archived t)\n#+end_src\n",
15 ]
16
17 static func lines(_ text: String) -> [String] {
18 text.components(separatedBy: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
19 }
20
21 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
22 func matchesEmacs() throws {
23 let cases = Self.texts.map { text in
24 EmacsOracle.Case(text: text, point: 1, form: """
25 (let* ((dir (make-temp-file "literate" t)) (org (expand-file-name "config.org" dir)) (el (expand-file-name "config.el" dir)))
26 (write-region (point-min) (point-max) org)
27 (org-babel-tangle-file org el "emacs-lisp\\\\|elisp")
28 (erase-buffer)
29 (when (file-exists-p el) (insert-file-contents el)))
30 """)
31 }
32 let results = try EmacsOracle.run(cases)
33 #expect(Self.lines(results[0].text) == ["(setq org-tags-column 0)"])
34 for (text, theirs) in zip(Self.texts, results) {
35 #expect(Self.lines(Tangle.literateLisp(text)) == Self.lines(theirs.text), "\(text)\n\(theirs.error)")
36 }
37 }
38
39 @Test func keepsLineNumbers() {
40 let text = Self.texts[0]
41 let lisp = Tangle.literateLisp(text).components(separatedBy: "\n")
42 #expect(lisp.count == text.components(separatedBy: "\n").count)
43 #expect(lisp[4] == "(setq org-tags-column 0)")
44 #expect(lisp.filter { !$0.isEmpty } == ["(setq org-tags-column 0)"])
45 }
46}
docs/manual/guide/13-configuration.org +5 −3
@@ -495,8 +495,8 @@ Import from Emacs reads your Emacs or Doom Emacs configuration and offers to car
495495** Running it
496496
4974971. Open Settings ▸ General and click Import from Emacs…, or run Import from Emacs… from the command palette (=⇧⌘P=).
4982. orgstar looks for a configuration in these places, in order, and reads the first it finds: =$DOOMDIR=, =~/.config/doom=, =~/.doom.d=, =~/.config/emacs=, =~/.emacs.d=, =~/.emacs=. A folder counts when it holds =init.el=, =config.el= or =custom.el=. Doom's own installation folder (one with =lisp/doom.el=) is skipped.
4993. To read another configuration, click Choose… and pick a file or a folder. For a folder, orgstar reads =init.el=, =config.el= and =custom.el= in it.
4982. orgstar looks for a configuration in these places, in order, and reads the first it finds: =$DOOMDIR=, =~/.config/doom=, =~/.doom.d=, =~/.config/emacs=, =~/.emacs.d=, =~/.emacs=. A folder counts when it holds =init.el=, =config.el=, =config.org= or =custom.el=. Doom's own installation folder (one with =lisp/doom.el=) is skipped.
4993. To read another configuration, click Choose… and pick a file or a folder. For a folder, orgstar reads =init.el=, =config.el= (or =config.org= when there is no =config.el=) and =custom.el= in it.
5005004. The sheet lists what it found under Settings, Folders, Capture templates, Key bindings, Structure templates and Agenda views, each with the line it came from (=config.el:27=, or =Doom default=). Everything is selected; clear what you don't want.
5015015. Click Import. The sheet then summarizes what was imported and any problems.
502502
@@ -510,7 +510,9 @@ What Import does with each kind of item:
510510
511511The Not imported section lists what orgstar read but can't use, with the reason: settings it has no equivalent for, values it can't work out without running Emacs, bindings to code rather than a command, and files it couldn't read. The footer counts variables that aren't about org, which are left alone.
512512
513A literate configuration (=config.org=) isn't read. Point Choose… at the =config.el= it tangles to.
513A literate configuration (=config.org=) is read as =org-babel-load-file= and Doom tangle it: its =emacs-lisp= and =elisp= blocks, except blocks whose =:tangle= is =no= (set on the block, in a =#+HEADER:= line, in a =header-args= property or in =#+PROPERTY:=) and blocks under a COMMENT or =:ARCHIVE:= heading. Items show the line of =config.org= they came from. When the folder also has a =config.el=, it is read instead, as the file =config.org= tangles to.
514
515On iOS, Settings ▸ Import from Emacs reads a configuration folder you choose; see [[file:14-ios.org][iOS]].
514516
515517** Doom Emacs
516518
docs/manual/guide/14-ios.org +9 −1
@@ -338,6 +338,14 @@ Edit config.toml opens the folder's =config.toml= as plain text, with smart quot
338338
339339Stop Using This Folder returns every setting to its default.
340340
341Import from Emacs reads an Emacs or Doom configuration folder, such as a synced =~/.config/doom= or =~/.emacs.d=, as the Mac's import does (see [[file:13-configuration.org][Configuration]]):
342
3431. Tap Import from Emacs, then Choose Folder…, and choose the folder holding =init.el=, =config.el= or =config.org=.
3442. The screen lists the settings, capture templates, key bindings, structure templates and agenda views it found, each with the line it came from, all selected. Clear what you don't want.
3453. Tap Import. The screen then summarizes what was imported and any problems.
346
347With a configuration folder, settings and structure templates are written to its =config.toml=, and capture templates, key bindings and agenda views to its =capture.toml=, =keymap.toml= and =views.toml=, so the Mac reads them too. Without one, settings are kept on the device. Folders from =org-agenda-files= name the Mac's paths and aren't offered.
348
341349The Agenda, TODO Dependencies and Calendar sections are the only places the app changes a setting itself:
342350
343351- Show days without entries :: turns =org-agenda-show-all-dates= on or off.
@@ -383,7 +391,7 @@ Quick Look in the Files app shows org files as the HTML export renders them.
383391- Running code blocks in languages other than Emacs Lisp, Emacs Lisp beyond orgstar's interpreter, and tables that need Emacs.
384392- ODT, LaTeX, ASCII and LaTeX-made PDF export, and publishing.
385393- Idle detection while a clock runs.
386- Import from Emacs.
394- Import from Emacs of agenda folders.
387395- The Columns inspector, and the buffer list and tab bar. The board and column view are there (see [[file:07-agenda.org][The agenda]] and [[file:04-outlines.org][Outlines]]).
388396- The global capture hotkey and the Settings window.
389397- Explicit saving.