Commit 3f440ee996
Verified · cmc
Layout: unified · split
Sources/OrgApp/ConfigSync.swift +4
| @@ -134,6 +134,10 @@ public final class ConfigSync { | ||
| 134 | 134 | current = UserConfig.setting(current, section: setting.section, key: setting.key, to: value) |
| 135 | 135 | } |
| 136 | 136 | } |
| 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 | } | |
| 137 | 141 | guard current != original else { return } |
| 138 | 142 | text = current |
| 139 | 143 | try? current.write(to: target, atomically: true, encoding: .utf8) |
Sources/OrgApp/EmacsImport.swift +41 −2
| @@ -15,6 +15,8 @@ public struct EmacsImport: Sendable { | ||
| 15 | 15 | case capture(key: String, toml: String) |
| 16 | 16 | /// A `[[bind]]` table for keymap.toml. |
| 17 | 17 | case binding(keys: String, command: String, mode: String?) |
| 18 | /// An `[org-structure-template-alist]` entry for config.toml. | |
| 19 | case structureTemplate(key: String, type: String) | |
| 18 | 20 | } |
| 19 | 21 | |
| 20 | 22 | public struct Item: Sendable, Identifiable { |
| @@ -146,6 +148,8 @@ public struct EmacsImport: Sendable { | ||
| 146 | 148 | struct Scanner { |
| 147 | 149 | var assignments: [Assignment] = [] |
| 148 | 150 | var bindings: [Binding] = [] |
| 151 | /// `(add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp"))` entries. | |
| 152 | var addedTemplates: [(entry: Sexp, source: String)] = [] | |
| 149 | 153 | var usesEvil = false |
| 150 | 154 | var order = 0 |
| 151 | 155 | |
| @@ -166,6 +170,10 @@ public struct EmacsImport: Sendable { | ||
| 166 | 170 | if let name = args[i].symbol { assign(name, args[i + 1], source, priority: priority, deferred: deferred) } |
| 167 | 171 | i += 2 |
| 168 | 172 | } |
| 173 | case "add-to-list": | |
| 174 | if args.count >= 2, unquote(args[0])?.symbol == "org-structure-template-alist", let entry = unquote(args[1]) { | |
| 175 | addedTemplates.append((entry, source)) | |
| 176 | } | |
| 169 | 177 | case "defvar", "defcustom": |
| 170 | 178 | // Only sets a variable nothing set, so under every assignment. |
| 171 | 179 | 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 { | ||
| 436 | 444 | unsupported.removeLast(unsupported.count - before) |
| 437 | 445 | } |
| 438 | 446 | } |
| 447 | for (entry, source) in scanner.addedTemplates { structureTemplates([entry], source: source, id: id) } | |
| 439 | 448 | // One item per folder. |
| 440 | 449 | var folders: Set<String> = [] |
| 441 | 450 | items.removeAll { item in |
| @@ -484,6 +493,8 @@ public struct EmacsImport: Sendable { | ||
| 484 | 493 | add(name, .string(location)) |
| 485 | 494 | case "org-track-ordered-property-with-tag": |
| 486 | 495 | 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) | |
| 487 | 498 | case "org-agenda-dim-blocked-tasks": |
| 488 | 499 | add(name, .string(value.symbol == "invisible" ? "invisible" : truthy ? "t" : "nil")) |
| 489 | 500 | case "org-hide-drawer-startup", "org-hide-block-startup": |
| @@ -562,6 +573,24 @@ public struct EmacsImport: Sendable { | ||
| 562 | 573 | } |
| 563 | 574 | } |
| 564 | 575 | |
| 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 | ||
| 565 | 594 | mutating func captureTemplate(_ entry: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) { |
| 566 | 595 | guard let parts = entry.elements, parts.count >= 2, let key = parts[0].string else { return } |
| 567 | 596 | let name = parts[1].string ?? key |
| @@ -675,7 +704,7 @@ extension EmacsImport { | ||
| 675 | 704 | public static func apply( |
| 676 | 705 | _ items: [Item], defaults: UserDefaults = .standard, workspace: WorkspaceModel?, directory: URL = UserConfig.directory |
| 677 | 706 | ) async -> String { |
| 678 | var settings = 0, folders = 0, templates = 0, bindings = 0 | |
| 707 | var settings = 0, folders = 0, templates = 0, bindings = 0, blocks = 0 | |
| 679 | 708 | var problems: [String] = [] |
| 680 | 709 | for item in items { |
| 681 | 710 | guard case .setting(let key, let value) = item.change, |
| @@ -728,8 +757,18 @@ extension EmacsImport { | ||
| 728 | 757 | keymap += (keymap.isEmpty ? "" : "\n") + "# Imported from Emacs.\n" + addedKeys |
| 729 | 758 | try? keymap.write(to: keymapFile, atomically: true, encoding: .utf8) |
| 730 | 759 | } |
| 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) } | |
| 731 | 769 | 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 } | |
| 733 | 772 | var summary = done.isEmpty ? "Nothing new to import." : "Imported " + done.joined(separator: ", ") + "." |
| 734 | 773 | if !problems.isEmpty { summary += " " + problems.joined(separator: "; ") + "." } |
| 735 | 774 | return summary |
Sources/OrgApp/OrgPreferences.swift +2
| @@ -36,6 +36,8 @@ public enum OrgPreferences { | ||
| 36 | 36 | options.enforceTodoDependencies = bool("enforceTodoDependencies", defaults) |
| 37 | 37 | options.enforceTodoCheckboxDependencies = bool("enforceTodoCheckboxDependencies", defaults) |
| 38 | 38 | options.archiveLocation = string("archiveLocation", defaults).nonEmpty |
| 39 | let templates = UserConfig.structureTemplates(defaults) | |
| 40 | options.structureTemplates = templates.isEmpty ? nil : StructureTemplate.merged(templates) | |
| 39 | 41 | options.trackOrderedPropertyWithTag = switch string("trackOrderedTag", defaults) { |
| 40 | 42 | case "", "nil": nil |
| 41 | 43 | case "t": "ORDERED" |
Sources/OrgApp/UserConfig.swift +31
| @@ -283,7 +283,21 @@ public enum UserConfig { | ||
| 283 | 283 | for setting in settings where !present.contains(setting.path) && !present.contains(setting.legacy) { |
| 284 | 284 | if defaults.object(forKey: setting.defaultsKey) != nil { defaults.removeObject(forKey: setting.defaultsKey) } |
| 285 | 285 | } |
| 286 | let templates = tables.first { $0.name == structureTemplateTable } | |
| 287 | if templates == nil, defaults.object(forKey: structureTemplatesKey) != nil { defaults.removeObject(forKey: structureTemplatesKey) } | |
| 286 | 288 | 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 | } | |
| 287 | 301 | // Colors are the theme's to read. |
| 288 | 302 | if ThemeSpec.isThemeTable(table.name), table.name != "theme" { continue } |
| 289 | 303 | for (key, value) in table.values.sorted(by: { $0.key < $1.key }) { |
| @@ -300,6 +314,23 @@ public enum UserConfig { | ||
| 300 | 314 | return problems |
| 301 | 315 | } |
| 302 | 316 | |
| 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 | ||
| 303 | 334 | static func path(_ section: String, _ key: String) -> String { section.isEmpty ? key : section + "." + key } |
| 304 | 335 | |
| 305 | 336 | /// Whether the file uses names from before settings took Emacs's names. |
Sources/OrgCore/Commands/BlockCommands.swift +81 −10
| @@ -1,27 +1,86 @@ | ||
| 1 | 1 | import Foundation |
| 2 | 2 | |
| 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 | |
| 4 | 4 | // `org-structure-template-alist`, and `org-edit-special` (C-c ') on src, example and export |
| 5 | 5 | // blocks with Doom's `org-src-preserve-indentation` t: the block's lines as they are, commas |
| 6 | 6 | // that protect `*` and `#+` lines taken off while editing and put back after. |
| 7 | 7 | |
| 8 | /// An entry of `org-structure-template-alist`: a key and the block type it inserts. | |
| 9 | public 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 | ||
| 8 | 33 | /// 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). | |
| 10 | 37 | public struct InsertStructureTemplate: OrgCommand { |
| 11 | 38 | public init() {} |
| 12 | 39 | public var id: String { "org.structure-template" } |
| 13 | 40 | public var title: String { "Insert Structure Template" } |
| 14 | 41 | public func applies(in context: EditContext) -> Bool { true } |
| 15 | 42 | |
| 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 | } | |
| 21 | 74 | |
| 22 | 75 | public func run(in context: EditContext) -> CommandStep { |
| 76 | let templates = context.options.structureTemplates ?? StructureTemplate.defaults | |
| 77 | let groups = Self.groups(templates) | |
| 23 | 78 | 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)")] | |
| 25 | 84 | return .prompt(Prompt(key: "template", message: "Insert block: [key] or Tab to type one", fast: FastSelection(items: items, multiple: false))) |
| 26 | 85 | } |
| 27 | 86 | let type: String |
| @@ -30,8 +89,20 @@ public struct InsertStructureTemplate: OrgCommand { | ||
| 30 | 89 | guard !typed.isEmpty else { return .failed("Empty structure type") } |
| 31 | 90 | type = typed |
| 32 | 91 | } 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 | } | |
| 35 | 106 | } |
| 36 | 107 | let region = context.selection.first.flatMap { $0.isEmpty ? nil : $0 } |
| 37 | 108 | return commitBuffer(context) { buffer in |
Sources/OrgCore/Commands/Command.swift +2
| @@ -27,6 +27,8 @@ public struct EditingOptions: Sendable, Equatable, Codable { | ||
| 27 | 27 | public var enforceTodoDependencies = false |
| 28 | 28 | /// `org-enforce-todo-checkbox-dependencies`: an entry can't become done with unchecked boxes. |
| 29 | 29 | public var enforceTodoCheckboxDependencies = false |
| 30 | /// `org-structure-template-alist`, for C-c C-, and `<` completion; nil for Org's. | |
| 31 | public var structureTemplates: [StructureTemplate]? | |
| 30 | 32 | /// `org-archive-location`, for entries without an `ARCHIVE` property or `#+ARCHIVE:`; nil |
| 31 | 33 | /// for Org's default, `%s_archive::`. |
| 32 | 34 | public var archiveLocation: String? |
Sources/OrgCore/Completion/OrgCompletion.swift +19 −12
| @@ -14,16 +14,18 @@ public struct Completion: Sendable, Equatable { | ||
| 14 | 14 | public var range: Range<Int> |
| 15 | 15 | /// Candidates starting with what's typed, sorted. |
| 16 | 16 | public var candidates: [String] |
| 17 | /// The block templates `<` completes, for `.template`. | |
| 18 | public var templates: [StructureTemplate] = [] | |
| 17 | 19 | |
| 18 | 20 | /// How the list shows `candidate`: a template with the block it makes. |
| 19 | 21 | 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 } | |
| 21 | 23 | return candidate + " " + value |
| 22 | 24 | } |
| 23 | 25 | |
| 24 | 26 | /// Text to insert for `candidate`, and where the caret goes in it. |
| 25 | 27 | 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) } | |
| 27 | 29 | return expansion |
| 28 | 30 | } |
| 29 | 31 | } |
| @@ -63,8 +65,10 @@ public enum OrgCompletion { | ||
| 63 | 65 | // Templates (org-tempo): `<` and a key after only blanks. |
| 64 | 66 | if let m = matches("^[ \\t]*<[A-Za-z]*$", toHere, caseInsensitive: false) { |
| 65 | 67 | // 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 }) | |
| 67 | 70 | completion.range = start..<(start + m.range.length) |
| 71 | completion.templates = templates | |
| 68 | 72 | return completion |
| 69 | 73 | } |
| 70 | 74 | if matches("^[ \\t]*#\\+BEGIN: clocktable[ \\t]", line) != nil { |
| @@ -220,18 +224,21 @@ public enum OrgCompletion { | ||
| 220 | 224 | } |
| 221 | 225 | } |
| 222 | 226 | |
| 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 | } | |
| 228 | 234 | |
| 229 | 235 | /// 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)? { | |
| 231 | 237 | 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 { | |
| 235 | 242 | let text = "#+\(value): " |
| 236 | 243 | return (text, text.utf16.count) |
| 237 | 244 | } |
Sources/OrgCore/Keymap/TOML.swift +3
| @@ -33,6 +33,8 @@ public enum TOML { | ||
| 33 | 33 | public var values: [String: Value] |
| 34 | 34 | /// 1-based line of the header. |
| 35 | 35 | public var line: Int |
| 36 | /// The keys in the order they appear. | |
| 37 | public var keys: [String] = [] | |
| 36 | 38 | } |
| 37 | 39 | |
| 38 | 40 | public struct ParseError: Error, Equatable, CustomStringConvertible { |
| @@ -71,6 +73,7 @@ public enum TOML { | ||
| 71 | 73 | guard rest.isEmpty || rest.first == "#" else { throw ParseError(line: number, message: "text after value") } |
| 72 | 74 | guard tables[tables.count - 1].values[key] == nil else { throw ParseError(line: number, message: "duplicate key \(key)") } |
| 73 | 75 | tables[tables.count - 1].values[key] = value |
| 76 | tables[tables.count - 1].keys.append(key) | |
| 74 | 77 | } |
| 75 | 78 | return tables |
| 76 | 79 | } |
Sources/Orgstar/EmacsImportView.swift +1
| @@ -70,6 +70,7 @@ struct EmacsImportView: View { | ||
| 70 | 70 | ("Folders", result.items.filter { if case .folder = $0.change { true } else { false } }), |
| 71 | 71 | ("Capture templates", result.items.filter { if case .capture = $0.change { true } else { false } }), |
| 72 | 72 | ("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 } }), | |
| 73 | 74 | ] |
| 74 | 75 | return List { |
| 75 | 76 | ForEach(groups.filter { !$0.1.isEmpty }, id: \.0) { title, items in |
Tests/OrgAppTests/EmacsImportTests.swift +5 −1
| @@ -21,6 +21,8 @@ struct EmacsImportTests { | ||
| 21 | 21 | (setq org-log-done 'note org-log-into-drawer t org-log-reschedule 'time) |
| 22 | 22 | (setq org-agenda-prefix-format '((agenda . " %i %-12:c%?-12t% s%b") (todo . " %-8:c"))) |
| 23 | 23 | (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"))) | |
| 24 | 26 | (setq org-capture-templates |
| 25 | 27 | '(("t" "Todo" entry (file+headline "~/notes/todo.org" "Inbox") "* TODO %?\n%a") |
| 26 | 28 | ("j" "Journal" entry (file+olp+datetree "~/notes/journal.org") "* %?" :tree-type week :empty-lines 1 :time-prompt t) |
| @@ -179,7 +181,9 @@ struct EmacsImportTests { | ||
| 179 | 181 | let keymap = folder.appendingPathComponent("keymap.toml") |
| 180 | 182 | #expect(KeymapLoader.load(.doom, userFile: keymap).problems.isEmpty) |
| 181 | 183 | #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") | |
| 183 | 187 | #expect(defaults.string(forKey: "themeFont") == "JetBrains Mono") |
| 184 | 188 | #expect(defaults.integer(forKey: "themeFontSize") == 14) |
| 185 | 189 | |
Tests/OrgAppTests/UserConfigTests.swift +26
| @@ -86,6 +86,32 @@ struct UserConfigTests { | ||
| 86 | 86 | #expect(text.contains("\nfill-column = 64") && text.contains("keymap = \"doom\"") && !text.contains("[editor]")) |
| 87 | 87 | } |
| 88 | 88 | |
| 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 | ||
| 89 | 115 | @Test func legacyNamesMoveInPlace() { |
| 90 | 116 | let text = "# mine\n[editor]\n# my editor\nfill-column = 64 # narrow\n\n[agenda]\nspan = 7\n\n[theme]\nfont-size = 15\n" |
| 91 | 117 | let migrated = UserConfig.migratingLegacyNames(text) |
Tests/OrgCoreTests/BlockCommandTests.swift +32 −1
| @@ -41,7 +41,7 @@ struct BlockCommandTests { | ||
| 41 | 41 | } |
| 42 | 42 | |
| 43 | 43 | 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" | |
| 45 | 45 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [selection], answers: ["template": key, "type": type]) |
| 46 | 46 | guard case .commit(let result) = InsertStructureTemplate().run(in: context) else { return (text, 0) } |
| 47 | 47 | var new = text |
| @@ -49,6 +49,37 @@ struct BlockCommandTests { | ||
| 49 | 49 | return (new, result.selection?.first?.lowerBound ?? 0) |
| 50 | 50 | } |
| 51 | 51 | |
| 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 | ||
| 52 | 83 | static let blocks = """ |
| 53 | 84 | * Code |
| 54 | 85 | #+begin_src python :results output |
Tests/OrgCoreTests/CompletionTests.swift +6
| @@ -57,6 +57,12 @@ struct CompletionTests { | ||
| 57 | 57 | #expect(template.kind == .template && template.range == 0..<4 && template.candidates == ["<s"]) |
| 58 | 58 | #expect(template.insertion("<s") == ("#+begin_src \n#+end_src", 12)) |
| 59 | 59 | #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)) | |
| 60 | 66 | #expect(complete("<h")!.insertion("<h") == ("#+begin_export html\n#+end_export", 19)) |
| 61 | 67 | #expect(complete("<L")!.insertion("<L") == ("#+latex: ", 9)) |
| 62 | 68 | #expect(complete("text <s") == nil) |
docs/manual/guide/04-outlines.org +9 −5
| @@ -452,7 +452,7 @@ Text to quote. | ||
| 452 | 452 | ** Structure templates |
| 453 | 453 | |
| 454 | 454 | Insert Structure Template (=org-insert-structure-template=, =C-c C-,= in the Emacs and |
| 455 | Doom presets) asks for a block type, one keystroke: | |
| 455 | Doom presets) asks for a block type by key. Org's default keys are: | |
| 456 | 456 | |
| 457 | 457 | | Key | Block | |
| 458 | 458 | |-----+-----------------| |
| @@ -467,8 +467,11 @@ Doom presets) asks for a block type, one keystroke: | ||
| 467 | 467 | | =s= | =src= | |
| 468 | 468 | | =v= | =verse= | |
| 469 | 469 | |
| 470 | Press =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 | |
| 470 | Press =TAB= to type any other type. =[org-structure-template-alist]= in =config.toml= | |
| 471 | adds templates or changes these (see [[file:13-configuration.org][Configuration]]). As in Org, keys of two letters | |
| 472 | take two keystrokes: when several keys start with the same letter, that letter opens a | |
| 473 | second 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 | |
| 472 | 475 | inserted at the caret's indentation. With a selection, the block wraps the selected |
| 473 | 476 | lines, and for =src=, =example=, =export= and =comment= blocks, lines that would read as |
| 474 | 477 | headings 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: | ||
| 485 | 488 | ,#+end_src |
| 486 | 489 | #+END_SRC |
| 487 | 490 | |
| 488 | with the caret after =begin_src=. The keys are those of the table above, plus =<L=, | |
| 491 | with the caret after =begin_src=. The keys are those of the structure templates above, | |
| 492 | Org's and any in =config.toml=, plus =<L=, | |
| 489 | 493 | =<H=, =<A= and =<i=, which insert =#+latex:=, =#+html:=, =#+ascii:= and =#+index:= |
| 490 | 494 | keyword lines. |
| 491 | 495 | |
| @@ -887,4 +891,4 @@ These Org structure features are not in orgstar: | ||
| 887 | 891 | - The =ORDERED= property, radio lists and timer list items in the list commands. |
| 888 | 892 | - =S-<left>= and =S-<right>= to cycle bullets on an item; use =C-c -=. |
| 889 | 893 | - =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 | ||
| 235 | 235 | |
| 236 | 236 | These 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]]. |
| 237 | 237 | |
| 238 | ** [org-structure-template-alist] | |
| 239 | ||
| 240 | Block 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] | |
| 244 | el = "src emacs-lisp" | |
| 245 | py = "src python" | |
| 246 | #+END_SRC | |
| 247 | ||
| 248 | Keys 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 | ||
| 238 | 250 | ** [theme] |
| 239 | 251 | |
| 240 | 252 | | Key | Type | Default | Effect | |
| @@ -423,6 +435,7 @@ orgstar reads the configuration as Lisp data; it never runs it. It looks at thes | ||
| 423 | 435 | | =defvar=, =defcustom= | The value, below every other assignment | |
| 424 | 436 | | =custom-set-variables= | Each quoted =(variable value)= | |
| 425 | 437 | | =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 | | |
| 426 | 439 | | =use-package=, =use-package!= | Forms in =:config= and =:init=, and pairs in =:custom= | |
| 427 | 440 | | =progn=, =when=, =unless=, =if=, =let=, =let*=, =with-no-warnings= | The forms inside. Conditions aren't evaluated, so every branch is read. | |
| 428 | 441 | | =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=, = | ||
| 439 | 452 | |
| 440 | 453 | | Emacs variable | Becomes | |
| 441 | 454 | |--------------------------------------------------------------------+-----------------------------------------------------------------------------------------------| |
| 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 | | |
| 443 | 456 | | =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= | |
| 444 | 457 | | =org-hide-drawer-startup=, =org-hide-block-startup= | =org-cycle-hide-drawer-startup=, =org-cycle-hide-block-startup= | |
| 445 | 458 | | =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=, = | ||
| 451 | 464 | | =org-clock-idle-time= | Minutes; =nil= becomes =0= (never) | |
| 452 | 465 | | =org-clock-history-length= | The same key, when the value is a positive number | |
| 453 | 466 | | =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 …)= | | |
| 454 | 471 | | =org-todo-keywords= | =org-todo-keywords=, one line per sequence. Keywords with spaces are left out; =type= sequences are read as sequences. | |
| 455 | 472 | | =org-directory= | A folder to add | |
| 456 | 473 | | =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: | ||
| 348 | 348 | - =[theme]= (=font=, =font-size=, =line-spacing=, =heading-size-step=, =theme-file= and colours), =[theme.light]=, =[theme.dark]=, =[theme.todo]=, =[theme.category]= |
| 349 | 349 | - =org-log-done=, =org-log-reschedule=, =org-log-redeadline=, =org-log-into-drawer= |
| 350 | 350 | - =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]= | |
| 352 | 352 | - =org-use-speed-commands=, with a hardware keyboard |
| 353 | 353 | - =electric-pair-mode=, =spell-check= |
| 354 | 354 | - =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= |