Configurable structure templates !248

merged merged by cmc on 2026-10-11 08:17 UTC · krz/orgstar:structure-templates into main

16 files changed, +281 −33

Layout: unified · split

Sources/OrgApp/ConfigSync.swift +4
@@ -134,6 +134,10 @@ public final class ConfigSync {
134134 current = UserConfig.setting(current, section: setting.section, key: setting.key, to: value)
135135 }
136136 }
137 // Templates added in the app, as by Emacs import; removing one is done in the file.
138 for template in UserConfig.structureTemplates(defaults) where values[UserConfig.path(UserConfig.structureTemplateTable, template.key)] != .string(template.type) {
139 current = UserConfig.setting(current, section: UserConfig.structureTemplateTable, key: template.key, to: .string(template.type))
140 }
137141 guard current != original else { return }
138142 text = current
139143 try? current.write(to: target, atomically: true, encoding: .utf8)
Sources/OrgApp/EmacsImport.swift +41 −2
@@ -15,6 +15,8 @@ public struct EmacsImport: Sendable {
1515 case capture(key: String, toml: String)
1616 /// A `[[bind]]` table for keymap.toml.
1717 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)
1820 }
1921
2022 public struct Item: Sendable, Identifiable {
@@ -146,6 +148,8 @@ public struct EmacsImport: Sendable {
146148 struct Scanner {
147149 var assignments: [Assignment] = []
148150 var bindings: [Binding] = []
151 /// `(add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp"))` entries.
152 var addedTemplates: [(entry: Sexp, source: String)] = []
149153 var usesEvil = false
150154 var order = 0
151155
@@ -166,6 +170,10 @@ public struct EmacsImport: Sendable {
166170 if let name = args[i].symbol { assign(name, args[i + 1], source, priority: priority, deferred: deferred) }
167171 i += 2
168172 }
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 }
169177 case "defvar", "defcustom":
170178 // Only sets a variable nothing set, so under every assignment.
171179 if args.count >= 2, let name = args[0].symbol { assign(name, args[1], source, priority: -1, deferred: false) }
@@ -436,6 +444,7 @@ public struct EmacsImport: Sendable {
436444 unsupported.removeLast(unsupported.count - before)
437445 }
438446 }
447 for (entry, source) in scanner.addedTemplates { structureTemplates([entry], source: source, id: id) }
439448 // One item per folder.
440449 var folders: Set<String> = []
441450 items.removeAll { item in
@@ -484,6 +493,8 @@ public struct EmacsImport: Sendable {
484493 add(name, .string(location))
485494 case "org-track-ordered-property-with-tag":
486495 if let tag = value.string { add(name, .string(tag)) } else { add(name, .string(truthy ? "t" : "nil")) }
496 case "org-structure-template-alist":
497 structureTemplates(value.elements ?? [], source: source, id: id)
487498 case "org-agenda-dim-blocked-tasks":
488499 add(name, .string(value.symbol == "invisible" ? "invisible" : truthy ? "t" : "nil"))
489500 case "org-hide-drawer-startup", "org-hide-block-startup":
@@ -562,6 +573,24 @@ public struct EmacsImport: Sendable {
562573 }
563574 }
564575
576 /// `("el" . "src emacs-lisp")` entries that aren't Org's own.
577 mutating func structureTemplates(_ entries: [Sexp], source: String, id: () -> Int) {
578 for entry in entries {
579 guard case .dotted(let head, let tail) = entry, head.count == 1, let key = head[0].string, let type = tail.string else {
580 unsupported.append(Note(id: id(), name: "org-structure-template-alist", reason: "an entry that isn't (\"key\" . \"type\")", source: source))
581 continue
582 }
583 if StructureTemplate.defaults.contains(StructureTemplate(key: key, type: type)) { continue }
584 guard !key.isEmpty, key.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }) else {
585 unsupported.append(Note(id: id(), name: "structure template \"\(key)\"", reason: "config.toml keys are letters, digits, _ and -", source: source))
586 continue
587 }
588 items.removeAll { if case .structureTemplate(key, _) = $0.change { true } else { false } }
589 items.append(Item(id: id(), name: "structure template \"\(key)\"", summary: "<\(key) inserts a \(type) block", source: source,
590 change: .structureTemplate(key: key, type: type)))
591 }
592 }
593
565594 mutating func captureTemplate(_ entry: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) {
566595 guard let parts = entry.elements, parts.count >= 2, let key = parts[0].string else { return }
567596 let name = parts[1].string ?? key
@@ -675,7 +704,7 @@ extension EmacsImport {
675704 public static func apply(
676705 _ items: [Item], defaults: UserDefaults = .standard, workspace: WorkspaceModel?, directory: URL = UserConfig.directory
677706 ) async -> String {
678 var settings = 0, folders = 0, templates = 0, bindings = 0
707 var settings = 0, folders = 0, templates = 0, bindings = 0, blocks = 0
679708 var problems: [String] = []
680709 for item in items {
681710 guard case .setting(let key, let value) = item.change,
@@ -728,8 +757,18 @@ extension EmacsImport {
728757 keymap += (keymap.isEmpty ? "" : "\n") + "# Imported from Emacs.\n" + addedKeys
729758 try? keymap.write(to: keymapFile, atomically: true, encoding: .utf8)
730759 }
760 // Into user defaults, from where ConfigSync writes them into config.toml.
761 var rows = UserConfig.structureTemplates(defaults)
762 for item in items {
763 guard case .structureTemplate(let key, let type) = item.change else { continue }
764 rows.removeAll { $0.key == key }
765 rows.append(StructureTemplate(key: key, type: type))
766 blocks += 1
767 }
768 if blocks > 0 { UserConfig.setStructureTemplates(rows, in: defaults) }
731769 func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" }
732 let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding")].compactMap { $0 }
770 let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"),
771 count(blocks, "structure template")].compactMap { $0 }
733772 var summary = done.isEmpty ? "Nothing new to import." : "Imported " + done.joined(separator: ", ") + "."
734773 if !problems.isEmpty { summary += " " + problems.joined(separator: "; ") + "." }
735774 return summary
Sources/OrgApp/OrgPreferences.swift +2
@@ -36,6 +36,8 @@ public enum OrgPreferences {
3636 options.enforceTodoDependencies = bool("enforceTodoDependencies", defaults)
3737 options.enforceTodoCheckboxDependencies = bool("enforceTodoCheckboxDependencies", defaults)
3838 options.archiveLocation = string("archiveLocation", defaults).nonEmpty
39 let templates = UserConfig.structureTemplates(defaults)
40 options.structureTemplates = templates.isEmpty ? nil : StructureTemplate.merged(templates)
3941 options.trackOrderedPropertyWithTag = switch string("trackOrderedTag", defaults) {
4042 case "", "nil": nil
4143 case "t": "ORDERED"
Sources/OrgApp/UserConfig.swift +31
@@ -283,7 +283,21 @@ public enum UserConfig {
283283 for setting in settings where !present.contains(setting.path) && !present.contains(setting.legacy) {
284284 if defaults.object(forKey: setting.defaultsKey) != nil { defaults.removeObject(forKey: setting.defaultsKey) }
285285 }
286 let templates = tables.first { $0.name == structureTemplateTable }
287 if templates == nil, defaults.object(forKey: structureTemplatesKey) != nil { defaults.removeObject(forKey: structureTemplatesKey) }
286288 for table in tables {
289 if table.name == structureTemplateTable {
290 var rows: [String] = []
291 for key in table.keys {
292 guard let type = table.values[key]?.string, !type.isEmpty else {
293 problems.append("config.toml: \(structureTemplateTable).\(key) must be a block type, such as \"src python\"")
294 continue
295 }
296 rows.append(key + "\t" + type)
297 }
298 if defaults.stringArray(forKey: structureTemplatesKey) != rows { defaults.set(rows, forKey: structureTemplatesKey) }
299 continue
300 }
287301 // Colors are the theme's to read.
288302 if ThemeSpec.isThemeTable(table.name), table.name != "theme" { continue }
289303 for (key, value) in table.values.sorted(by: { $0.key < $1.key }) {
@@ -300,6 +314,23 @@ public enum UserConfig {
300314 return problems
301315 }
302316
317 /// `[org-structure-template-alist]`: block templates by key, over Org's, as
318 /// `key = "type"`. Kept in user defaults under `structureTemplatesKey` as `key<Tab>type`.
319 public static let structureTemplateTable = "org-structure-template-alist"
320 static let structureTemplatesKey = "structureTemplates"
321
322 /// The templates of `[org-structure-template-alist]`.
323 public static func structureTemplates(_ defaults: UserDefaults) -> [StructureTemplate] {
324 (defaults.stringArray(forKey: structureTemplatesKey) ?? []).compactMap { row in
325 guard let tab = row.firstIndex(of: "\t") else { return nil }
326 return StructureTemplate(key: String(row[..<tab]), type: String(row[row.index(after: tab)...]))
327 }
328 }
329
330 public static func setStructureTemplates(_ templates: [StructureTemplate], in defaults: UserDefaults) {
331 defaults.set(templates.map { $0.key + "\t" + $0.type }, forKey: structureTemplatesKey)
332 }
333
303334 static func path(_ section: String, _ key: String) -> String { section.isEmpty ? key : section + "." + key }
304335
305336 /// Whether the file uses names from before settings took Emacs's names.
Sources/OrgCore/Commands/BlockCommands.swift +81 −10
@@ -1,27 +1,86 @@
11import Foundation
22
3// Blocks (Org 9.8.7): `org-insert-structure-template` (C-c C-,) with the default
3// Blocks (Org 9.8.7): `org-insert-structure-template` (C-c C-,) with
44// `org-structure-template-alist`, and `org-edit-special` (C-c ') on src, example and export
55// blocks with Doom's `org-src-preserve-indentation` t: the block's lines as they are, commas
66// that protect `*` and `#+` lines taken off while editing and put back after.
77
8/// An entry of `org-structure-template-alist`: a key and the block type it inserts.
9public struct StructureTemplate: Sendable, Equatable, Codable {
10 public var key: String
11 public var type: String
12
13 public init(key: String, type: String) {
14 self.key = key
15 self.type = type
16 }
17
18 /// Org's default `org-structure-template-alist`.
19 public static let defaults: [StructureTemplate] = [
20 .init(key: "a", type: "export ascii"), .init(key: "c", type: "center"), .init(key: "C", type: "comment"),
21 .init(key: "e", type: "example"), .init(key: "E", type: "export"), .init(key: "h", type: "export html"),
22 .init(key: "l", type: "export latex"), .init(key: "q", type: "quote"), .init(key: "s", type: "src"),
23 .init(key: "v", type: "verse"),
24 ]
25
26 /// The defaults with `extra` over them: an entry with a default's key takes its place, the
27 /// others follow.
28 public static func merged(_ extra: [StructureTemplate]) -> [StructureTemplate] {
29 defaults.map { entry in extra.first { $0.key == entry.key } ?? entry } + extra.filter { entry in !defaults.contains { $0.key == entry.key } }
30 }
31}
32
833/// C-c C-,: `org-insert-structure-template`. Asks for a block type by key (Tab to type one),
9/// then inserts an empty block, or wraps the selection.
34/// then inserts an empty block, or wraps the selection. Keys of more than one letter take two
35/// strokes, as `org--insert-structure-template-mks` makes them: the first letter, then the
36/// second (Tab for the one-letter key).
1037public struct InsertStructureTemplate: OrgCommand {
1138 public init() {}
1239 public var id: String { "org.structure-template" }
1340 public var title: String { "Insert Structure Template" }
1441 public func applies(in context: EditContext) -> Bool { true }
1542
16 /// `org-structure-template-alist`.
17 public static let templates: [(key: Character, type: String)] = [
18 ("a", "export ascii"), ("c", "center"), ("C", "comment"), ("e", "example"), ("E", "export"),
19 ("h", "export html"), ("l", "export latex"), ("q", "quote"), ("s", "src"), ("v", "verse"),
20 ]
43 /// The templates under each first letter, in the order the letters first appear.
44 static func groups(_ templates: [StructureTemplate]) -> [(letter: Character, templates: [StructureTemplate])] {
45 var groups: [(letter: Character, templates: [StructureTemplate])] = []
46 for template in templates {
47 guard let letter = template.key.first else { continue }
48 if let index = groups.firstIndex(where: { $0.letter == letter }) {
49 groups[index].templates.append(template)
50 } else {
51 groups.append((letter, [template]))
52 }
53 }
54 return groups
55 }
56
57 /// `org--insert-structure-template-unique-keys`: the second stroke of each key, Tab for a
58 /// one-letter key; nil when keys can't be told apart.
59 static func secondKeys(_ templates: [StructureTemplate]) -> [Character]? {
60 var used: [String: Int] = [:]
61 for (index, template) in templates.enumerated().sorted(by: { ($0.element.key.count, $0.offset) < ($1.element.key.count, $1.offset) }) {
62 let key = Array(template.key)
63 let candidate: String? = switch key.count {
64 case 1: String(key) + "\t"
65 case 2: String(key)
66 default: key.dropFirst().map { String(key[0]) + String($0) }.first { used[$0] == nil }
67 }
68 guard let candidate, used[candidate] == nil else { return nil }
69 used[candidate] = index
70 }
71 let byIndex = Dictionary(uniqueKeysWithValues: used.map { ($1, $0) })
72 return templates.indices.map { Array(byIndex[$0]!)[1] }
73 }
2174
2275 public func run(in context: EditContext) -> CommandStep {
76 let templates = context.options.structureTemplates ?? StructureTemplate.defaults
77 let groups = Self.groups(templates)
2378 guard let key = context.answers["template"] else {
24 let items = Self.templates.map { FastSelection.Item.option(key: $0.key, name: $0.type) } + [.option(key: "\t", name: "other (Tab)")]
79 let items = groups.map { group -> FastSelection.Item in
80 let names = group.templates.map(\.type)
81 let name = names.count == 1 ? names[0] : names.prefix(3).joined(separator: ", ") + (names.count > 3 ? ", ..." : "")
82 return FastSelection.Item.option(key: group.letter, name: name)
83 } + [.option(key: "\t", name: "other (Tab)")]
2584 return .prompt(Prompt(key: "template", message: "Insert block: [key] or Tab to type one", fast: FastSelection(items: items, multiple: false)))
2685 }
2786 let type: String
@@ -30,8 +89,20 @@ public struct InsertStructureTemplate: OrgCommand {
3089 guard !typed.isEmpty else { return .failed("Empty structure type") }
3190 type = typed
3291 } else {
33 guard let found = Self.templates.first(where: { String($0.key) == key }) else { return .failed("Quit") }
34 type = found.type
92 guard let group = groups.first(where: { String($0.letter) == key }) else { return .failed("Quit") }
93 if group.templates.count == 1 {
94 type = group.templates[0].type
95 } else {
96 guard let seconds = Self.secondKeys(group.templates) else {
97 return .failed("Could not make unique key for `\(group.templates.last!.key)'")
98 }
99 guard let second = context.answers["template2"] else {
100 let items = zip(seconds, group.templates).map { FastSelection.Item.option(key: $0, name: $1.type) }
101 return .prompt(Prompt(key: "template2", message: "Insert block: [key]", fast: FastSelection(items: items, multiple: false)))
102 }
103 guard let index = seconds.firstIndex(where: { String($0) == second }) else { return .failed("Quit") }
104 type = group.templates[index].type
105 }
35106 }
36107 let region = context.selection.first.flatMap { $0.isEmpty ? nil : $0 }
37108 return commitBuffer(context) { buffer in
Sources/OrgCore/Commands/Command.swift +2
@@ -27,6 +27,8 @@ public struct EditingOptions: Sendable, Equatable, Codable {
2727 public var enforceTodoDependencies = false
2828 /// `org-enforce-todo-checkbox-dependencies`: an entry can't become done with unchecked boxes.
2929 public var enforceTodoCheckboxDependencies = false
30 /// `org-structure-template-alist`, for C-c C-, and `<` completion; nil for Org's.
31 public var structureTemplates: [StructureTemplate]?
3032 /// `org-archive-location`, for entries without an `ARCHIVE` property or `#+ARCHIVE:`; nil
3133 /// for Org's default, `%s_archive::`.
3234 public var archiveLocation: String?
Sources/OrgCore/Completion/OrgCompletion.swift +19 −12
@@ -14,16 +14,18 @@ public struct Completion: Sendable, Equatable {
1414 public var range: Range<Int>
1515 /// Candidates starting with what's typed, sorted.
1616 public var candidates: [String]
17 /// The block templates `<` completes, for `.template`.
18 public var templates: [StructureTemplate] = []
1719
1820 /// How the list shows `candidate`: a template with the block it makes.
1921 public func label(_ candidate: String) -> String {
20 guard kind == .template, let value = OrgCompletion.templateKeys.first(where: { "<" + $0.key == candidate })?.value else { return candidate }
22 guard kind == .template, let value = OrgCompletion.templateKeys(templates).first(where: { "<" + $0.key == candidate })?.value else { return candidate }
2123 return candidate + " " + value
2224 }
2325
2426 /// Text to insert for `candidate`, and where the caret goes in it.
2527 public func insertion(_ candidate: String) -> (text: String, caret: Int) {
26 guard kind == .template, let expansion = OrgCompletion.templateExpansion(candidate) else { return (candidate, candidate.utf16.count) }
28 guard kind == .template, let expansion = OrgCompletion.templateExpansion(candidate, templates: templates) else { return (candidate, candidate.utf16.count) }
2729 return expansion
2830 }
2931}
@@ -63,8 +65,10 @@ public enum OrgCompletion {
6365 // Templates (org-tempo): `<` and a key after only blanks.
6466 if let m = matches("^[ \\t]*<[A-Za-z]*$", toHere, caseInsensitive: false) {
6567 // The expansion replaces the indentation too.
66 var completion = make(.template, from: start + (toHere as NSString).range(of: "<").location, templateKeys.map { "<" + $0.key })
68 let templates = context.options.structureTemplates ?? StructureTemplate.defaults
69 var completion = make(.template, from: start + (toHere as NSString).range(of: "<").location, templateKeys(templates).map { "<" + $0.key })
6770 completion.range = start..<(start + m.range.length)
71 completion.templates = templates
6872 return completion
6973 }
7074 if matches("^[ \\t]*#\\+BEGIN: clocktable[ \\t]", line) != nil {
@@ -220,18 +224,21 @@ public enum OrgCompletion {
220224 }
221225 }
222226
223 static let templateKeys: [(key: String, value: String)] = [
224 ("a", "export ascii"), ("c", "center"), ("C", "comment"), ("e", "example"), ("E", "export"), ("h", "export html"),
225 ("l", "export latex"), ("q", "quote"), ("s", "src"), ("v", "verse"),
226 ("L", "latex"), ("H", "html"), ("A", "ascii"), ("i", "index"),
227 ]
227 /// `org-tempo-keywords-alist`.
228 static let keywordKeys: [(key: String, value: String)] = [("L", "latex"), ("H", "html"), ("A", "ascii"), ("i", "index")]
229
230 /// org-tempo's keys: the block templates', then the keywords'.
231 static func templateKeys(_ templates: [StructureTemplate]) -> [(key: String, value: String)] {
232 templates.map { ($0.key, $0.type) } + keywordKeys
233 }
228234
229235 /// org-tempo's expansion of `<key`: a block, or for keywords a `#+key: ` line.
230 static func templateExpansion(_ candidate: String) -> (text: String, caret: Int)? {
236 static func templateExpansion(_ candidate: String, templates: [StructureTemplate]) -> (text: String, caret: Int)? {
231237 let key = String(candidate.dropFirst())
232 guard let index = templateKeys.firstIndex(where: { $0.key == key }) else { return nil }
233 let value = templateKeys[index].value
234 if index >= 10 {
238 let keys = templateKeys(templates)
239 guard let index = keys.firstIndex(where: { $0.key == key }) else { return nil }
240 let value = keys[index].value
241 if index >= templates.count {
235242 let text = "#+\(value): "
236243 return (text, text.utf16.count)
237244 }
Sources/OrgCore/Keymap/TOML.swift +3
@@ -33,6 +33,8 @@ public enum TOML {
3333 public var values: [String: Value]
3434 /// 1-based line of the header.
3535 public var line: Int
36 /// The keys in the order they appear.
37 public var keys: [String] = []
3638 }
3739
3840 public struct ParseError: Error, Equatable, CustomStringConvertible {
@@ -71,6 +73,7 @@ public enum TOML {
7173 guard rest.isEmpty || rest.first == "#" else { throw ParseError(line: number, message: "text after value") }
7274 guard tables[tables.count - 1].values[key] == nil else { throw ParseError(line: number, message: "duplicate key \(key)") }
7375 tables[tables.count - 1].values[key] = value
76 tables[tables.count - 1].keys.append(key)
7477 }
7578 return tables
7679 }
Sources/Orgstar/EmacsImportView.swift +1
@@ -70,6 +70,7 @@ struct EmacsImportView: View {
7070 ("Folders", result.items.filter { if case .folder = $0.change { true } else { false } }),
7171 ("Capture templates", result.items.filter { if case .capture = $0.change { true } else { false } }),
7272 ("Key bindings", result.items.filter { if case .binding = $0.change { true } else { false } }),
73 ("Structure templates", result.items.filter { if case .structureTemplate = $0.change { true } else { false } }),
7374 ]
7475 return List {
7576 ForEach(groups.filter { !$0.1.isEmpty }, id: \.0) { title, items in
Tests/OrgAppTests/EmacsImportTests.swift +5 −1
@@ -21,6 +21,8 @@ struct EmacsImportTests {
2121 (setq org-log-done 'note org-log-into-drawer t org-log-reschedule 'time)
2222 (setq org-agenda-prefix-format '((agenda . " %i %-12:c%?-12t% s%b") (todo . " %-8:c")))
2323 (setq fill-column (+ 70 2))
24 (add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp"))
25 (with-eval-after-load 'org (add-to-list 'org-structure-template-alist '("q" . "QUOTE")))
2426 (setq org-capture-templates
2527 '(("t" "Todo" entry (file+headline "~/notes/todo.org" "Inbox") "* TODO %?\n%a")
2628 ("j" "Journal" entry (file+olp+datetree "~/notes/journal.org") "* %?" :tree-type week :empty-lines 1 :time-prompt t)
@@ -179,7 +181,9 @@ struct EmacsImportTests {
179181 let keymap = folder.appendingPathComponent("keymap.toml")
180182 #expect(KeymapLoader.load(.doom, userFile: keymap).problems.isEmpty)
181183 #expect(KeymapLoader.load(.doom, userFile: keymap).keymap.keyLabels(for: "app.agenda", modes: ["normal"]).contains("C-c a"))
182 #expect(summary.hasPrefix("Imported 23 settings, 3 capture templates, 3 key bindings."), "\(summary)")
184 #expect(summary.hasPrefix("Imported 23 settings, 3 capture templates, 3 key bindings, 2 structure templates."), "\(summary)")
185 #expect(UserConfig.structureTemplates(defaults) == [.init(key: "el", type: "src emacs-lisp"), .init(key: "q", type: "QUOTE")])
186 #expect(OrgPreferences.options(defaults).structureTemplates?.first { $0.key == "q" }?.type == "QUOTE")
183187 #expect(defaults.string(forKey: "themeFont") == "JetBrains Mono")
184188 #expect(defaults.integer(forKey: "themeFontSize") == 14)
185189
Tests/OrgAppTests/UserConfigTests.swift +26
@@ -86,6 +86,32 @@ struct UserConfigTests {
8686 #expect(text.contains("\nfill-column = 64") && text.contains("keymap = \"doom\"") && !text.contains("[editor]"))
8787 }
8888
89 @Test func structureTemplatesTable() throws {
90 let store = defaults()
91 #expect(OrgPreferences.options(store).structureTemplates == nil)
92 let problems = UserConfig.apply("fill-column = 70\n[org-structure-template-alist]\npy = \"src python\"\ns = \"src sh\"\nn = 3\n", to: store)
93 #expect(problems == ["config.toml: org-structure-template-alist.n must be a block type, such as \"src python\""])
94 let templates = try #require(OrgPreferences.options(store).structureTemplates)
95 #expect(templates.first { $0.key == "s" }?.type == "src sh" && templates.last == StructureTemplate(key: "py", type: "src python"))
96 #expect(templates.count == StructureTemplate.defaults.count + 1)
97 // Without the table, Org's templates.
98 #expect(UserConfig.apply("fill-column = 70\n", to: store).isEmpty)
99 #expect(OrgPreferences.options(store).structureTemplates == nil)
100
101 // One added in the app goes into the file.
102 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-config-\(UUID().uuidString)")
103 defer { try? FileManager.default.removeItem(at: folder) }
104 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
105 let url = folder.appendingPathComponent("config.toml")
106 try "fill-column = 70\n[org-structure-template-alist]\npy = \"src python\"\n".write(to: url, atomically: true, encoding: .utf8)
107 let synced = defaults()
108 let sync = ConfigSync(url: url, defaults: synced)
109 sync.start(watch: false)
110 UserConfig.setStructureTemplates(UserConfig.structureTemplates(synced) + [.init(key: "el", type: "src emacs-lisp")], in: synced)
111 let text = try String(contentsOf: url, encoding: .utf8)
112 #expect(text.contains("[org-structure-template-alist]\npy = \"src python\"\nel = \"src emacs-lisp\"\n"), "\(text)")
113 }
114
89115 @Test func legacyNamesMoveInPlace() {
90116 let text = "# mine\n[editor]\n# my editor\nfill-column = 64 # narrow\n\n[agenda]\nspan = 7\n\n[theme]\nfont-size = 15\n"
91117 let migrated = UserConfig.migratingLegacyNames(text)
Tests/OrgCoreTests/BlockCommandTests.swift +32 −1
@@ -41,7 +41,7 @@ struct BlockCommandTests {
4141 }
4242
4343 static func run(_ type: String, _ selection: Range<Int>) -> (String, Int) {
44 let key = InsertStructureTemplate.templates.first { $0.type == type }.map { String($0.key) } ?? "\t"
44 let key = StructureTemplate.defaults.first { $0.type == type }?.key ?? "\t"
4545 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [selection], answers: ["template": key, "type": type])
4646 guard case .commit(let result) = InsertStructureTemplate().run(in: context) else { return (text, 0) }
4747 var new = text
@@ -49,6 +49,37 @@ struct BlockCommandTests {
4949 return (new, result.selection?.first?.lowerBound ?? 0)
5050 }
5151
52 /// Keys of two letters take a second stroke; Tab picks the one-letter key of the same letter.
53 @Test func configuredTemplatesTakeTwoStrokes() throws {
54 var options = EditingOptions.org
55 options.structureTemplates = StructureTemplate.merged([.init(key: "el", type: "src emacs-lisp"), .init(key: "q", type: "QUOTE")])
56 func step(_ answers: [String: String]) -> CommandStep {
57 InsertStructureTemplate().run(in: EditContext(revision: 0, text: "x\n", tree: OrgParser.parse("x\n"), selection: [0..<0], answers: answers, options: options))
58 }
59 guard case .prompt(let top) = step([:]) else { Issue.record("no prompt"); return }
60 #expect(top.fast?.items.contains(.option(key: "e", name: "example, src emacs-lisp")) == true)
61 #expect(top.fast?.items.contains(.option(key: "q", name: "QUOTE")) == true)
62 guard case .prompt(let second) = step(["template": "e"]) else { Issue.record("no second prompt"); return }
63 #expect(second.key == "template2" && second.fast?.items == [.option(key: "\t", name: "example"), .option(key: "l", name: "src emacs-lisp")])
64 guard case .commit(let result) = step(["template": "e", "template2": "l"]) else { Issue.record("no commit"); return }
65 #expect(result.edits.reduce("x\n") { $1.apply(to: $0) } == "#+begin_src emacs-lisp\n#+end_src\nx\n")
66 guard case .commit(let quote) = step(["template": "q"]) else { Issue.record("no commit"); return }
67 #expect(quote.edits.reduce("x\n") { $1.apply(to: $0) }.hasPrefix("#+BEGIN_QUOTE\n"))
68 }
69
70 /// `org--insert-structure-template-unique-keys`.
71 @Test(.enabled(if: oracle))
72 func secondKeysLikeOrg() throws {
73 let sets = [["e", "el"], ["e", "el", "elisp", "ex"], ["py", "pl", "p"], ["abc", "abd", "ab"]]
74 for keys in sets {
75 let ours = InsertStructureTemplate.secondKeys(keys.map { StructureTemplate(key: $0, type: "x") })
76 .map { zip(keys, $0).map { String($0.first!) + String($1) } }
77 let form = "(list (mapconcat #'identity (org--insert-structure-template-unique-keys '(\(keys.map { lispString($0) }.joined(separator: " ")))) \"|\"))"
78 let theirs = try EmacsOracle.evaluate("", form)
79 #expect(ours?.joined(separator: "|") == theirs.first, "\(keys)")
80 }
81 }
82
5283 static let blocks = """
5384 * Code
5485 #+begin_src python :results output
Tests/OrgCoreTests/CompletionTests.swift +6
@@ -57,6 +57,12 @@ struct CompletionTests {
5757 #expect(template.kind == .template && template.range == 0..<4 && template.candidates == ["<s"])
5858 #expect(template.insertion("<s") == ("#+begin_src \n#+end_src", 12))
5959 #expect(complete("<q")!.insertion("<q") == ("#+begin_quote\n#+end_quote", 13))
60 var options = EditingOptions.org
61 options.structureTemplates = StructureTemplate.merged([.init(key: "el", type: "src emacs-lisp")])
62 let configured = OrgCompletion.at(EditContext(revision: 0, text: "<e", tree: OrgParser.parse("<e"), selection: [2..<2], options: options))!
63 #expect(configured.candidates == ["<e", "<el"] && configured.label("<el") == "<el src emacs-lisp")
64 #expect(configured.insertion("<el") == ("#+begin_src emacs-lisp\n#+end_src", 22))
65 #expect(configured.insertion("<L") == ("#+latex: ", 9))
6066 #expect(complete("<h")!.insertion("<h") == ("#+begin_export html\n#+end_export", 19))
6167 #expect(complete("<L")!.insertion("<L") == ("#+latex: ", 9))
6268 #expect(complete("text <s") == nil)
docs/manual/guide/04-outlines.org +9 −5
@@ -452,7 +452,7 @@ Text to quote.
452452** Structure templates
453453
454454Insert Structure Template (=org-insert-structure-template=, =C-c C-,= in the Emacs and
455Doom presets) asks for a block type, one keystroke:
455Doom presets) asks for a block type by key. Org's default keys are:
456456
457457| Key | Block |
458458|-----+-----------------|
@@ -467,8 +467,11 @@ Doom presets) asks for a block type, one keystroke:
467467| =s= | =src= |
468468| =v= | =verse= |
469469
470Press =TAB= to type any other type. These are Org's default
471=org-structure-template-alist=; orgstar does not read a custom one. The block is
470Press =TAB= to type any other type. =[org-structure-template-alist]= in =config.toml=
471adds templates or changes these (see [[file:13-configuration.org][Configuration]]). As in Org, keys of two letters
472take two keystrokes: when several keys start with the same letter, that letter opens a
473second choice, where =TAB= picks the one-letter key, so with =el= for =src emacs-lisp=,
474=e TAB= inserts an example block and =e l= the Emacs Lisp block. The block is
472475inserted at the caret's indentation. With a selection, the block wraps the selected
473476lines, and for =src=, =example=, =export= and =comment= blocks, lines that would read as
474477headings or keywords are protected with a leading comma. For =src= and =export=, the
@@ -485,7 +488,8 @@ expands it as =org-tempo= does. =<s= becomes:
485488,#+end_src
486489#+END_SRC
487490
488with the caret after =begin_src=. The keys are those of the table above, plus =<L=,
491with the caret after =begin_src=. The keys are those of the structure templates above,
492Org's and any in =config.toml=, plus =<L=,
489493=<H=, =<A= and =<i=, which insert =#+latex:=, =#+html:=, =#+ascii:= and =#+index:=
490494keyword lines.
491495
@@ -887,4 +891,4 @@ These Org structure features are not in orgstar:
887891- The =ORDERED= property, radio lists and timer list items in the list commands.
888892- =S-<left>= and =S-<right>= to cycle bullets on an item; use =C-c -=.
889893- =org-drag-element= (=M-<up>= and =M-<down>= on paragraphs).
890- Custom =org-structure-template-alist= and =org-refile-targets=.
894- Custom =org-refile-targets=.
docs/manual/guide/13-configuration.org +18 −1
@@ -235,6 +235,18 @@ The startup settings (=org-startup-*=, =org-hide-leading-stars=, =org-cycle-hide
235235
236236These mirror the entries of =org-agenda-prefix-format=. The agenda's rows don't show a prefix, so the formats don't change how the agenda looks. The one effect left is that a time written in heading text leaves the title when the =agenda= format contains =%t=. See [[file:07-agenda.org][The agenda]].
237237
238** [org-structure-template-alist]
239
240Block templates for Insert Structure Template (=C-c C-,=) and =<= completion, each a key and the block type it inserts. They go over Org's default =org-structure-template-alist=: a key Org has (=s=, =q=, …) gets the new type, and other keys are added after Org's.
241
242#+BEGIN_SRC toml
243[org-structure-template-alist]
244el = "src emacs-lisp"
245py = "src python"
246#+END_SRC
247
248Keys are letters, digits, =_= and =-=. Without the table, Org's templates apply. Emacs import adds entries here and so does nothing else in the app; remove one by deleting its line.
249
238250** [theme]
239251
240252| Key | Type | Default | Effect |
@@ -423,6 +435,7 @@ orgstar reads the configuration as Lisp data; it never runs it. It looks at thes
423435| =defvar=, =defcustom= | The value, below every other assignment |
424436| =custom-set-variables= | Each quoted =(variable value)= |
425437| =after!=, =with-eval-after-load=, =eval-after-load= | The forms inside, ranked above plain assignments |
438| =add-to-list= on =org-structure-template-alist= | The entry added |
426439| =use-package=, =use-package!= | Forms in =:config= and =:init=, and pairs in =:custom= |
427440| =progn=, =when=, =unless=, =if=, =let=, =let*=, =with-no-warnings= | The forms inside. Conditions aren't evaluated, so every branch is read. |
428441| =map!= (Doom) | Bindings, with =:leader= (=SPC=), =:localleader= (=SPC m=), =:prefix=, and state keywords such as =:n=, =:i=, =:v=, =:nv= |
@@ -439,7 +452,7 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, =
439452
440453| Emacs variable | Becomes |
441454|--------------------------------------------------------------------+-----------------------------------------------------------------------------------------------|
442| =fill-column=, =org-tags-column=, =appt-message-warning-time= | The same key, when the value is a number |
455| =fill-column=, =org-tags-column=, =appt-message-warning-time=, =org-deadline-warning-days= | The same key, when the value is a number |
443456| =org-insert-heading-respect-content=, =org-list-allow-alphabetical=, =org-hide-emphasis-markers=, =org-pretty-entities=, =org-cycle-hide-drawer-startup=, =org-cycle-hide-block-startup=, =org-use-speed-commands=, =org-startup-with-inline-images=, =org-startup-indented=, =org-hide-leading-stars=, =org-startup-align-all-tables=, =org-startup-truncated= | The same key: =nil= or an empty list is =false=, anything else =true= |
444457| =org-hide-drawer-startup=, =org-hide-block-startup= | =org-cycle-hide-drawer-startup=, =org-cycle-hide-block-startup= |
445458| =org-M-RET-may-split-line= | =org-M-RET-may-split-line=, from the =default= entry of an alist; other per-context entries aren't supported |
@@ -451,6 +464,10 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, =
451464| =org-clock-idle-time= | Minutes; =nil= becomes =0= (never) |
452465| =org-clock-history-length= | The same key, when the value is a positive number |
453466| =org-agenda-start-day= | A day offset such as ="-3d"=; =nil= becomes ="+0d"=. Other forms aren't supported. |
467| =org-agenda-start-on-weekday= | ="0"= to ="6"=, or ="nil"= |
468| =org-track-ordered-property-with-tag= | A tag name as given; =t= becomes ="t"=, =nil= ="nil"= |
469| =org-archive-location= | The same key, when the value is a =file::heading= string |
470| =org-structure-template-alist= | =[org-structure-template-alist]=: each =("key" . "type")= entry that isn't one of Org's, from =setq= or =(add-to-list 'org-structure-template-alist …)= |
454471| =org-todo-keywords= | =org-todo-keywords=, one line per sequence. Keywords with spaces are left out; =type= sequences are read as sequences. |
455472| =org-directory= | A folder to add |
456473| =org-agenda-files= | A folder for each entry; for a =.org= file, its folder |
docs/manual/guide/14-ios.org +1 −1
@@ -348,7 +348,7 @@ These settings from =config.toml= apply on iOS:
348348- =[theme]= (=font=, =font-size=, =line-spacing=, =heading-size-step=, =theme-file= and colours), =[theme.light]=, =[theme.dark]=, =[theme.todo]=, =[theme.category]=
349349- =org-log-done=, =org-log-reschedule=, =org-log-redeadline=, =org-log-into-drawer=
350350- =org-enforce-todo-dependencies=, =org-enforce-todo-checkbox-dependencies=, =org-track-ordered-property-with-tag=, =org-agenda-dim-blocked-tasks=
351- =org-archive-location=
351- =org-archive-location=, =[org-structure-template-alist]=
352352- =org-use-speed-commands=, with a hardware keyboard
353353- =electric-pair-mode=, =spell-check=
354354- =org-agenda-span=, =org-agenda-start-day=, =org-agenda-start-on-weekday=, =org-deadline-warning-days=, =agenda-include-subfolders=, =org-agenda-show-all-dates=, =org-agenda-skip-scheduled-if-done=, =org-agenda-skip-deadline-if-done=, =org-agenda-search-view-always-boolean=, =org-agenda-search-view-force-full-words=