Commit 8c691f1229

8c691f12299d61cfcb74e8583609abd3243a5140

parent: 9c8e4f9667

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-26 03:37 UTC

Snippets with tab stops, and templates for new files

snippets.toml in the configuration folder holds [[snippet]] tables
(trigger, body, description, file) with yasnippet's tab stops and the
capture escapes for dates and prompts. It reloads with the other files;
a broken file is reported and the snippets read before stay. TOML
reading gains multi-line strings.

TAB expands a trigger before the caret where no binding of TAB runs,
so org-cycle, table navigation and Doom's insert-state TAB keep
working. TAB, S-TAB and Escape move through fields; mirrors follow
their field. Snippets are in the completion list and in Insert
Snippet…; org.snippet:<trigger> expands one by name.

New File from Template… (Mac File menu, iOS Folders) creates a file
and expands a file = true snippet in it. Import from Emacs reads
yasnippet's snippets/org-mode, skipping those with Emacs Lisp.

Closes #142
Closes #156

Layout: unified · split

Changed files (43)
Sources/OrgApp/CommandTitles.swift +5 · view
@@ -83,6 +83,7 @@ enum CommandTitles {
83 String(localized: "End of Buffer", comment: "Command title"), 83 String(localized: "End of Buffer", comment: "Command title"),
84 String(localized: "End of Line", comment: "Command title"), 84 String(localized: "End of Line", comment: "Command title"),
85 String(localized: "Evaluate Time Range", comment: "Command title"), 85 String(localized: "Evaluate Time Range", comment: "Command title"),
86 String(localized: "Expand Snippet", comment: "Command title"),
86 String(localized: "Expand Table Columns", comment: "Command title"), 87 String(localized: "Expand Table Columns", comment: "Command title"),
87 String(localized: "Export Agenda Files to iCalendar", comment: "Command title"), 88 String(localized: "Export Agenda Files to iCalendar", comment: "Command title"),
88 String(localized: "Export Table to File…", comment: "Command title"), 89 String(localized: "Export Table to File…", comment: "Command title"),
@@ -146,6 +147,7 @@ enum CommandTitles {
146 String(localized: "Insert Link…", comment: "Command title"), 147 String(localized: "Insert Link…", comment: "Command title"),
147 String(localized: "Insert Node Link…", comment: "Command title"), 148 String(localized: "Insert Node Link…", comment: "Command title"),
148 String(localized: "Insert Sequence Link…", comment: "Command title"), 149 String(localized: "Insert Sequence Link…", comment: "Command title"),
150 String(localized: "Insert Snippet…", comment: "Command title"),
149 String(localized: "Insert Structure Template", comment: "Command title"), 151 String(localized: "Insert Structure Template", comment: "Command title"),
150 String(localized: "Insert TODO Heading", comment: "Command title"), 152 String(localized: "Insert TODO Heading", comment: "Command title"),
151 String(localized: "Insert Table Column", comment: "Command title"), 153 String(localized: "Insert Table Column", comment: "Command title"),
@@ -182,6 +184,7 @@ enum CommandTitles {
182 String(localized: "New Attachment…", comment: "Command title"), 184 String(localized: "New Attachment…", comment: "Command title"),
183 String(localized: "New Child Sequence Note…", comment: "Command title"), 185 String(localized: "New Child Sequence Note…", comment: "Command title"),
184 String(localized: "New Child of This Note…", comment: "Command title"), 186 String(localized: "New Child of This Note…", comment: "Command title"),
187 String(localized: "New File from Template…", comment: "Command title"),
185 String(localized: "New Note in Silo…", comment: "Command title"), 188 String(localized: "New Note in Silo…", comment: "Command title"),
186 String(localized: "New Sequence Note…", comment: "Command title"), 189 String(localized: "New Sequence Note…", comment: "Command title"),
187 String(localized: "New Sibling Sequence Note…", comment: "Command title"), 190 String(localized: "New Sibling Sequence Note…", comment: "Command title"),
@@ -196,6 +199,7 @@ enum CommandTitles {
196 String(localized: "Next Line", comment: "Command title"), 199 String(localized: "Next Line", comment: "Command title"),
197 String(localized: "Next Pane", comment: "Command title"), 200 String(localized: "Next Pane", comment: "Command title"),
198 String(localized: "Next Sibling Note", comment: "Command title"), 201 String(localized: "Next Sibling Note", comment: "Command title"),
202 String(localized: "Next Snippet Field", comment: "Command title"),
199 String(localized: "Next TODO Keyword", comment: "Command title"), 203 String(localized: "Next TODO Keyword", comment: "Command title"),
200 String(localized: "Next Table Field", comment: "Command title"), 204 String(localized: "Next Table Field", comment: "Command title"),
201 String(localized: "Next Table Row", comment: "Command title"), 205 String(localized: "Next Table Row", comment: "Command title"),
@@ -218,6 +222,7 @@ enum CommandTitles {
218 String(localized: "Previous Heading at Same Level", comment: "Command title"), 222 String(localized: "Previous Heading at Same Level", comment: "Command title"),
219 String(localized: "Previous Line", comment: "Command title"), 223 String(localized: "Previous Line", comment: "Command title"),
220 String(localized: "Previous Sibling Note", comment: "Command title"), 224 String(localized: "Previous Sibling Note", comment: "Command title"),
225 String(localized: "Previous Snippet Field", comment: "Command title"),
221 String(localized: "Previous TODO Keyword", comment: "Command title"), 226 String(localized: "Previous TODO Keyword", comment: "Command title"),
222 String(localized: "Previous Table Field", comment: "Command title"), 227 String(localized: "Previous Table Field", comment: "Command title"),
223 String(localized: "Previous table.el Cell", comment: "Command title"), 228 String(localized: "Previous table.el Cell", comment: "Command title"),
Sources/OrgApp/ConfigSync.swift +17 −2 · view
@@ -22,10 +22,13 @@ public final class ConfigSync {
22 22
23 @ObservationIgnored private var url: URL 23 @ObservationIgnored private var url: URL
24 private let defaults: UserDefaults 24 private let defaults: UserDefaults
25 /// Where `snippets.toml` beside the file is read into.
26 private let snippets: SnippetLibrary
25 @ObservationIgnored private var text: String? 27 @ObservationIgnored private var text: String?
26 @ObservationIgnored private var configProblems: [String] = [] 28 @ObservationIgnored private var configProblems: [String] = []
27 @ObservationIgnored private var themeProblems: [String] = [] 29 @ObservationIgnored private var themeProblems: [String] = []
28 @ObservationIgnored private var macroProblems: [String] = [] 30 @ObservationIgnored private var macroProblems: [String] = []
31 @ObservationIgnored private var snippetProblems: [String] = []
29 /// Why the file couldn't be read or written, the last time a setting was to go into it. 32 /// Why the file couldn't be read or written, the last time a setting was to go into it.
30 @ObservationIgnored private var fileProblem: String? 33 @ObservationIgnored private var fileProblem: String?
31 @ObservationIgnored private var applying = false 34 @ObservationIgnored private var applying = false
@@ -37,9 +40,10 @@ public final class ConfigSync {
37 /// Where `url` leads: a symlinked config.toml is written through, not replaced by a file. 40 /// Where `url` leads: a symlinked config.toml is written through, not replaced by a file.
38 private var target: URL { url.resolvingSymlinksInPath() } 41 private var target: URL { url.resolvingSymlinksInPath() }
39 42
40 public init(url: URL = UserConfig.configFile, defaults: UserDefaults = .standard) { 43 public init(url: URL = UserConfig.configFile, defaults: UserDefaults = .standard, snippets: SnippetLibrary = .shared) {
41 self.url = url 44 self.url = url
42 self.defaults = defaults 45 self.defaults = defaults
46 self.snippets = snippets
43 } 47 }
44 48
45 public func start(watch: Bool = true) { 49 public func start(watch: Bool = true) {
@@ -64,6 +68,7 @@ public final class ConfigSync {
64 if write(template) { text = template } 68 if write(template) { text = template }
65 } 69 }
66 loadMacros() 70 loadMacros()
71 readSnippets()
67 observer = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: defaults, queue: .main) { [weak self] _ in 72 observer = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: defaults, queue: .main) { [weak self] _ in
68 MainActor.assumeIsolated { self?.writeBack() } 73 MainActor.assumeIsolated { self?.writeBack() }
69 } 74 }
@@ -89,6 +94,7 @@ public final class ConfigSync {
89 if name == self.url.lastPathComponent { self.reload() } 94 if name == self.url.lastPathComponent { self.reload() }
90 if self.isThemeFile(file) { self.readTheme() } 95 if self.isThemeFile(file) { self.readTheme() }
91 if name == NamedMacros.fileName { self.loadMacros() } 96 if name == NamedMacros.fileName { self.loadMacros() }
97 if name == Snippets.fileName { self.readSnippets() }
92 self.serial += 1 98 self.serial += 1
93 self.changedFile = (name, self.serial) 99 self.changedFile = (name, self.serial)
94 } 100 }
@@ -109,6 +115,7 @@ public final class ConfigSync {
109 configProblems = [] 115 configProblems = []
110 themeProblems = [] 116 themeProblems = []
111 macroProblems = [] 117 macroProblems = []
118 snippetProblems = []
112 fileProblem = nil 119 fileProblem = nil
113 self.url = url 120 self.url = url
114 start(watch: watches) 121 start(watch: watches)
@@ -158,8 +165,16 @@ public final class ConfigSync {
158 updateProblems() 165 updateProblems()
159 } 166 }
160 167
168 /// `snippets.toml` beside the file.
169 private func readSnippets() {
170 let file = url.deletingLastPathComponent().appendingPathComponent(Snippets.fileName)
171 snippets.reload(from: url == UserConfig.configFile ? SnippetLibrary.userFile : file)
172 snippetProblems = snippets.problems
173 updateProblems()
174 }
175
161 private func updateProblems() { 176 private func updateProblems() {
162 let all = (fileProblem.map { [$0] } ?? []) + configProblems + themeProblems + macroProblems 177 let all = (fileProblem.map { [$0] } ?? []) + configProblems + themeProblems + macroProblems + snippetProblems
163 if all != problems { problems = all } 178 if all != problems { problems = all }
164 } 179 }
165 180
Sources/OrgApp/EmacsImport.swift +19 −1 · view
@@ -23,6 +23,8 @@ public struct EmacsImport: Sendable {
23 case publish(name: String, toml: String) 23 case publish(name: String, toml: String)
24 /// A `[denote-templates]` entry for config.toml. 24 /// A `[denote-templates]` entry for config.toml.
25 case denoteTemplate(key: String, text: String) 25 case denoteTemplate(key: String, text: String)
26 /// A yasnippet snippet as a `[[snippet]]` table for snippets.toml.
27 case snippet(trigger: String, toml: String)
26 } 28 }
27 29
28 public struct Item: Sendable, Identifiable { 30 public struct Item: Sendable, Identifiable {
@@ -57,6 +59,8 @@ public struct EmacsImport: Sendable {
57 public var isDoom = false 59 public var isDoom = false
58 /// Doom's own org defaults were found and read. 60 /// Doom's own org defaults were found and read.
59 public var doomDefaultsRead = false 61 public var doomDefaultsRead = false
62 /// yasnippet snippets left out, as they hold Emacs Lisp.
63 public var snippetsSkipped = 0
60 64
61 // MARK: - Finding the configuration 65 // MARK: - Finding the configuration
62 66
@@ -155,6 +159,7 @@ public struct EmacsImport: Sendable {
155 } 159 }
156 } 160 }
157 result.build(from: scanner) 161 result.build(from: scanner)
162 result.addSnippets(from: snippetFolders(files.map { $0.deletingLastPathComponent() }))
158 return result 163 return result
159 } 164 }
160 165
@@ -1227,6 +1232,19 @@ extension EmacsImport {
1227 capture += (capture.isEmpty ? "# Capture templates. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedCapture 1232 capture += (capture.isEmpty ? "# Capture templates. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedCapture
1228 if !write(capture, to: captureFile) { templates = 0 } 1233 if !write(capture, to: captureFile) { templates = 0 }
1229 } 1234 }
1235 let snippetsFile = directory.appendingPathComponent(Snippets.fileName)
1236 var snippetsText = read(snippetsFile)
1237 var triggers = Set((try? TOML.parse(snippetsText))?.filter { $0.name == "snippet" }.compactMap { $0.values["trigger"]?.string } ?? [])
1238 var addedSnippets = "", snippets = 0
1239 for item in items {
1240 guard case .snippet(let trigger, let toml) = item.change, triggers.insert(trigger).inserted else { continue }
1241 addedSnippets += "\n" + toml
1242 snippets += 1
1243 }
1244 if !addedSnippets.isEmpty {
1245 snippetsText += (snippetsText.isEmpty ? "# Snippets. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedSnippets
1246 if !write(snippetsText, to: snippetsFile) { snippets = 0 }
1247 }
1230 let viewsFile = directory.appendingPathComponent("views.toml") 1248 let viewsFile = directory.appendingPathComponent("views.toml")
1231 var viewsText = read(viewsFile) 1249 var viewsText = read(viewsFile)
1232 var viewNames = Set((try? TOML.parse(viewsText))?.filter { $0.name == "view" }.compactMap { $0.values["name"]?.string } ?? []) 1250 var viewNames = Set((try? TOML.parse(viewsText))?.filter { $0.name == "view" }.compactMap { $0.values["name"]?.string } ?? [])
@@ -1305,7 +1323,7 @@ extension EmacsImport {
1305 } 1323 }
1306 func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" } 1324 func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" }
1307 let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"), 1325 let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"),
1308 count(blocks, "structure template"), count(noteTemplates, "Denote template"), count(views, "agenda view"), count(projects, "publishing project")].compactMap { $0 } 1326 count(blocks, "structure template"), count(noteTemplates, "Denote template"), count(views, "agenda view"), count(projects, "publishing project"), count(snippets, "snippet")].compactMap { $0 }
1309 var summary = done.isEmpty ? "Nothing new to import." : "Imported " + done.joined(separator: ", ") + "." 1327 var summary = done.isEmpty ? "Nothing new to import." : "Imported " + done.joined(separator: ", ") + "."
1310 if !problems.isEmpty { summary += " " + problems.joined(separator: "; ") + "." } 1328 if !problems.isEmpty { summary += " " + problems.joined(separator: "; ") + "." }
1311 return summary 1329 return summary
Sources/OrgApp/EmacsImportSections.swift +1 · view
@@ -11,6 +11,7 @@ extension EmacsImport {
11 (String(localized: "Structure Templates", bundle: .main), items.filter { if case .structureTemplate = $0.change { true } else { false } }), 11 (String(localized: "Structure Templates", bundle: .main), items.filter { if case .structureTemplate = $0.change { true } else { false } }),
12 (String(localized: "Denote Templates", bundle: .main), items.filter { if case .denoteTemplate = $0.change { true } else { false } }), 12 (String(localized: "Denote Templates", bundle: .main), items.filter { if case .denoteTemplate = $0.change { true } else { false } }),
13 (String(localized: "Agenda Views", bundle: .main), items.filter { if case .view = $0.change { true } else { false } }), 13 (String(localized: "Agenda Views", bundle: .main), items.filter { if case .view = $0.change { true } else { false } }),
14 (String(localized: "Snippets", bundle: .main), items.filter { if case .snippet = $0.change { true } else { false } }),
14 ].filter { !$0.1.isEmpty } 15 ].filter { !$0.1.isEmpty }
15 } 16 }
16} 17}
Sources/OrgApp/EmacsImportSnippets.swift added +102 · view
@@ -0,0 +1,102 @@
1import Foundation
2import OrgCore
3
4/// yasnippet's org-mode snippets, from `snippets/org-mode/` beside the configuration read.
5extension EmacsImport {
6 /// One yasnippet file: `# key:`, `# name:` and the body after `# --`. A file without that
7 /// line is all body, keyed by its name, as yasnippet reads it.
8 public struct Yasnippet: Sendable, Equatable {
9 public var key: String
10 public var name: String
11 public var body: String
12 /// Why it can't be used without Emacs, or nil.
13 public var lisp: String?
14 }
15
16 public static func yasnippet(_ text: String, fileName: String) -> Yasnippet {
17 var key: String?
18 var name: String?
19 var type: String?
20 var body = text
21 let lines = text.components(separatedBy: "\n")
22 if let separator = lines.firstIndex(where: { $0.range(of: "^#[ \\t]*--[ \\t]*$", options: .regularExpression) != nil }) {
23 for line in lines[..<separator] {
24 guard line.hasPrefix("#"), let colon = line.firstIndex(of: ":") else { continue }
25 let field = line[line.index(after: line.startIndex)..<colon].trimmingCharacters(in: .whitespaces)
26 let value = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)
27 switch field {
28 case "key": key = value
29 case "name": name = value
30 case "type": type = value
31 default: break
32 }
33 }
34 body = lines[(separator + 1)...].joined(separator: "\n")
35 }
36 let trigger = key ?? fileName
37 var lisp: String?
38 if type == "command" {
39 lisp = "a command snippet, which is Emacs Lisp"
40 } else if body.range(of: "(?<!\\\\)`", options: .regularExpression) != nil {
41 lisp = "has Emacs Lisp in backquotes"
42 } else if body.contains("$(") {
43 lisp = "has an Emacs Lisp transformation"
44 }
45 return Yasnippet(key: trigger, name: name ?? trigger, body: body, lisp: lisp)
46 }
47
48 /// The `[[snippet]]` table for `snippet`.
49 static func snippetTable(_ snippet: Yasnippet) -> String {
50 var out = "[[snippet]]\ntrigger = \(UserConfig.format(.string(snippet.key)))\n"
51 if snippet.name != snippet.key { out += "description = \(UserConfig.format(.string(snippet.name)))\n" }
52 // A literal multi-line string keeps the body as it is, unless it holds the delimiter.
53 if snippet.body.contains("'''") || snippet.body.contains("\r") {
54 out += "body = \(UserConfig.format(.string(snippet.body)))\n"
55 } else {
56 out += "body = '''\n\(snippet.body)'''\n"
57 }
58 return out
59 }
60
61 /// Where yasnippet keeps org-mode snippets for a configuration in `folders`.
62 static func snippetFolders(_ folders: [URL]) -> [URL] {
63 var seen: Set<String> = []
64 return folders.map { $0.appendingPathComponent("snippets/org-mode") }
65 .filter { seen.insert($0.standardizedFileURL.path).inserted && FileManager.default.fileExists(atPath: $0.path) }
66 }
67
68 /// Reads the snippets in `folders` into items; those with Emacs Lisp are listed as not
69 /// imported.
70 mutating func addSnippets(from folders: [URL]) {
71 var next = (items.map(\.id) + unsupported.map(\.id) + unreadable.map(\.id)).max() ?? 0
72 func id() -> Int { next += 1; return next }
73 var triggers: Set<String> = []
74 for folder in folders {
75 let files = ((try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isRegularFileKey])) ?? [])
76 .filter { !$0.lastPathComponent.hasPrefix(".") && (try? $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true }
77 .sorted { $0.lastPathComponent < $1.lastPathComponent }
78 for file in files {
79 let source = "snippets/org-mode/" + file.lastPathComponent
80 guard let text = try? String(contentsOf: file, encoding: .utf8) else {
81 problems.append("Can't read \(file.path)")
82 continue
83 }
84 let snippet = Self.yasnippet(text, fileName: file.lastPathComponent)
85 if let reason = snippet.lisp {
86 unsupported.append(Note(id: id(), name: "snippet \(snippet.key)", reason: reason, source: source))
87 snippetsSkipped += 1
88 continue
89 }
90 let parsed = try? Snippets.parse(Self.snippetTable(snippet))
91 guard let parsed, parsed.problems.isEmpty else {
92 let problem = parsed?.problems.first.map { $0.replacingOccurrences(of: "^line [0-9]+: ", with: "", options: .regularExpression) }
93 unsupported.append(Note(id: id(), name: "snippet \(snippet.key)", reason: problem ?? "not readable", source: source))
94 snippetsSkipped += 1
95 continue
96 }
97 guard triggers.insert(snippet.key).inserted else { continue }
98 items.append(Item(id: id(), name: snippet.key, summary: snippet.name, source: source, change: .snippet(trigger: snippet.key, toml: Self.snippetTable(snippet))))
99 }
100 }
101 }
102}
Sources/OrgApp/SnippetLibrary.swift added +80 · view
@@ -0,0 +1,80 @@
1import Foundation
2import Observation
3import OrgCore
4
5/// The snippets of `snippets.toml` in the configuration folder, read at launch and whenever
6/// the file changes. A file that isn't valid TOML is reported and the snippets read before
7/// stay; a snippet with a problem is reported and left out.
8///
9/// For the iOS key bar and other places that offer snippets: `snippets` lists them, and
10/// `Snippet.commandID` (`org.snippet:<trigger>`) is a command any editor runs to expand one at
11/// the caret. `org.snippet.next-field` and `org.snippet.previous-field` move between fields.
12@MainActor
13@Observable
14public final class SnippetLibrary {
15 public static let shared = SnippetLibrary()
16
17 /// Snippets and file templates, in the file's order.
18 public private(set) var snippets: [Snippet] = []
19 /// Problems in the file, from the last time it was read, each starting with its name.
20 public private(set) var problems: [String] = []
21 /// File templates waiting for their new file to open in an editor, by path.
22 @ObservationIgnored private var pending: [String: Snippet] = [:]
23
24 public init() {}
25
26 public static var userFile: URL { UserConfig.file(Snippets.fileName) }
27
28 /// The snippets typed in files, without the file templates.
29 public var typed: [Snippet] { snippets.filter { !$0.file } }
30 /// The templates New File from Template… offers.
31 public var templates: [Snippet] { snippets.filter(\.file) }
32
33 /// Reads `file`; `read` returns nil when there is none, which leaves no snippets.
34 public func reload(from file: URL = userFile, read: (URL) -> String? = { try? String(contentsOf: $0, encoding: .utf8) }) {
35 guard let text = read(file) else {
36 snippets = []
37 problems = []
38 return
39 }
40 do {
41 let parsed = try Snippets.parse(text)
42 if parsed.snippets != snippets { snippets = parsed.snippets }
43 problems = parsed.problems.map { "\(Snippets.fileName) \($0)" }
44 } catch {
45 problems = ["\(Snippets.fileName) \(error)"]
46 }
47 }
48
49 /// Notes that the new file at `path` is to be filled from `template` when it opens.
50 public func expand(_ template: Snippet, intoNewFile path: String) {
51 pending[URL(fileURLWithPath: path).standardizedFileURL.path] = template
52 }
53
54 /// The template that fills the new file at `path`, once; nil for other files. Its editor
55 /// performs `ExpandNamedSnippet(snippet:)` at the start.
56 public func takeTemplate(for path: String) -> Snippet? {
57 pending.removeValue(forKey: URL(fileURLWithPath: path).standardizedFileURL.path)
58 }
59
60 /// The folders a new file can go in: the added folders and the folders holding their files,
61 /// each with its name below its added folder's.
62 public static func folders(in workspace: WorkspaceModel) -> [(path: String, title: String)] {
63 let roots = workspace.rootPaths
64 var paths = Set(roots)
65 for file in workspace.files { paths.insert((file.path as NSString).deletingLastPathComponent) }
66 return paths.compactMap { path -> (path: String, title: String)? in
67 guard let root = roots.first(where: { path == $0 || path.hasPrefix($0 + "/") }) else { return nil }
68 let name = (root as NSString).lastPathComponent
69 return (path, path == root ? name : name + "/" + path.dropFirst(root.count + 1))
70 }.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
71 }
72
73 /// Creates the file `name` in `folder`, as New File does, and notes that `template` fills
74 /// it when it opens. Returns its path.
75 public func createFile(named name: String, in folder: String, from template: Snippet, workspace: WorkspaceModel) async throws -> String {
76 let path = try await workspace.createFile(named: name, in: folder)
77 expand(template, intoNewFile: path)
78 return path
79 }
80}
Sources/OrgApp/UserConfig.swift +2 −2 · view
@@ -640,8 +640,8 @@ public enum UserConfig {
640 private static func template(_ value: (Setting) -> TOML.Value) -> String { 640 private static func template(_ value: (Setting) -> TOML.Value) -> String {
641 var out = """ 641 var out = """
642 # orgstar settings. The Settings window writes its changes here, and edits made here 642 # orgstar settings. The Settings window writes its changes here, and edits made here
643 # apply while orgstar runs. Keys go in keymap.toml, capture templates in capture.toml 643 # apply while orgstar runs. Keys go in keymap.toml, capture templates in capture.toml,
644 # and saved agenda views in views.toml, all in this folder. 644 # saved agenda views in views.toml and snippets in snippets.toml, all in this folder.
645 645
646 # Emacs variables, by their Emacs names. 646 # Emacs variables, by their Emacs names.
647 647
Sources/OrgCore/Commands/Command.swift +5 · view
@@ -97,6 +97,8 @@ public struct EditingOptions: Sendable, Equatable, Codable {
97 public var timerFormat = "%s " 97 public var timerFormat = "%s "
98 /// `org-timer-default-timer`. 98 /// `org-timer-default-timer`.
99 public var timerDefault = "0" 99 public var timerDefault = "0"
100 /// The snippets and file templates of `snippets.toml`.
101 public var snippets: [Snippet] = []
100 102
101 public init( 103 public init(
102 tagsColumn: Int = -77, insertHeadingRespectContent: Bool = false, metaReturnMaySplitLine: Bool = true, 104 tagsColumn: Int = -77, insertHeadingRespectContent: Bool = false, metaReturnMaySplitLine: Bool = true,
@@ -268,6 +270,8 @@ public enum Effect: Sendable, Equatable {
268 case refreshSetup 270 case refreshSetup
269 /// The org-timer becomes this; nil stops it. 271 /// The org-timer becomes this; nil stops it.
270 case timer(OrgTimer?) 272 case timer(OrgTimer?)
273 /// A snippet was expanded; its fields are filled in next.
274 case snippet(SnippetSession)
271} 275}
272 276
273public struct EditResult: Sendable, Equatable { 277public struct EditResult: Sendable, Equatable {
@@ -352,6 +356,7 @@ public enum Commands {
352 UpdateDynamicBlock(), ClockReportTable(), InsertDenoteBlock(.links), InsertDenoteBlock(.missingLinks), InsertDenoteBlock(.backlinks), InsertDenoteBlock(.files), InsertDenoteBlock(.filesAsHeadings), InsertDenoteBlock(.sequence), SetEffort(), CtrlCCtrlC(), EvaluateTimeRange(), FootnoteAction(), FootnoteAction(special: true), TableEvalFormula(named: false), TableEvalFormula(named: true), SortTableLines(), TransposeTable(), GotoHeading(), SparseTreeCommand(), SetPriority(), SetPriority(value: "A"), SetPriority(value: "B"), SetPriority(value: "C"), SetPriority(value: " "), ReadAndSetProperty(), DeleteProperty(), DeleteProperty(globally: true), PropertyAction(), NextAllowedValue(previous: false), NextAllowedValue(previous: true), InsertColumnView(), ShowColumnView(), ShowColumnView(global: true), ToggleArchiveTag(), ArchiveToSibling(), ToggleOrderedProperty(), 356 UpdateDynamicBlock(), ClockReportTable(), InsertDenoteBlock(.links), InsertDenoteBlock(.missingLinks), InsertDenoteBlock(.backlinks), InsertDenoteBlock(.files), InsertDenoteBlock(.filesAsHeadings), InsertDenoteBlock(.sequence), SetEffort(), CtrlCCtrlC(), EvaluateTimeRange(), FootnoteAction(), FootnoteAction(special: true), TableEvalFormula(named: false), TableEvalFormula(named: true), SortTableLines(), TransposeTable(), GotoHeading(), SparseTreeCommand(), SetPriority(), SetPriority(value: "A"), SetPriority(value: "B"), SetPriority(value: "C"), SetPriority(value: " "), ReadAndSetProperty(), DeleteProperty(), DeleteProperty(globally: true), PropertyAction(), NextAllowedValue(previous: false), NextAllowedValue(previous: true), InsertColumnView(), ShowColumnView(), ShowColumnView(global: true), ToggleArchiveTag(), ArchiveToSibling(), ToggleOrderedProperty(),
353 InsertDrawer(), DragElement(forward: true), DragElement(forward: false), CycleBullet(previous: false), CycleBullet(previous: true), 357 InsertDrawer(), DragElement(forward: true), DragElement(forward: false), CycleBullet(previous: false), CycleBullet(previous: true),
354 Emphasize(), Emphasize(marker: "*"), Emphasize(marker: "/"), Emphasize(marker: "_"), Emphasize(marker: "="), Emphasize(marker: "~"), Emphasize(marker: "+"), 358 Emphasize(), Emphasize(marker: "*"), Emphasize(marker: "/"), Emphasize(marker: "_"), Emphasize(marker: "="), Emphasize(marker: "~"), Emphasize(marker: "+"),
359 ExpandSnippet(), InsertSnippet(),
355 ] 360 ]
356 361
357 public static var everything: [any OrgCommand] { all + TableCommand.Action.allCases.map(TableCommand.init) } 362 public static var everything: [any OrgCommand] { all + TableCommand.Action.allCases.map(TableCommand.init) }
Sources/OrgCore/Completion/OrgCompletion.swift +29 −2 · view
@@ -2,11 +2,12 @@ import Foundation
2 2
3// Completion at point (Org 9.8.7's org-pcomplete): `org-thing-at-point` picks what the caret 3// Completion at point (Org 9.8.7's org-pcomplete): `org-thing-at-point` picks what the caret
4// is on, and each context offers what its `pcomplete/org-mode/…` function does. Link types 4// is on, and each context offers what its `pcomplete/org-mode/…` function does. Link types
5// after `[[`, workspace tags and org-tempo's `<` templates are added. 5// after `[[`, workspace tags and org-tempo's `<` templates are added, and snippet triggers
6// where no org context offers anything.
6 7
7public struct Completion: Sendable, Equatable { 8public struct Completion: Sendable, Equatable {
8 public enum Kind: String, Sendable { 9 public enum Kind: String, Sendable {
9 case keyword, keywordValue, link, entity, tag, todo, heading, drawer, property, srcLanguage, srcHeader, clocktable, template 10 case keyword, keywordValue, link, entity, tag, todo, heading, drawer, property, srcLanguage, srcHeader, clocktable, template, snippet
10 } 11 }
11 12
12 public var kind: Kind 13 public var kind: Kind
@@ -16,9 +17,14 @@ public struct Completion: Sendable, Equatable {
16 public var candidates: [String] 17 public var candidates: [String]
17 /// The block templates `<` completes, for `.template`. 18 /// The block templates `<` completes, for `.template`.
18 public var templates: [StructureTemplate] = [] 19 public var templates: [StructureTemplate] = []
20 /// The snippets whose triggers are the candidates, for `.snippet`; choosing one expands it.
21 public var snippets: [Snippet] = []
19 22
20 /// How the list shows `candidate`: a template with the block it makes. 23 /// How the list shows `candidate`: a template with the block it makes.
21 public func label(_ candidate: String) -> String { 24 public func label(_ candidate: String) -> String {
25 if kind == .snippet, let snippet = snippets.first(where: { $0.trigger == candidate }), snippet.name != candidate {
26 return candidate + " " + snippet.name
27 }
22 guard kind == .template, let value = OrgCompletion.templateKeys(templates).first(where: { "<" + $0.key == candidate })?.value else { return candidate } 28 guard kind == .template, let value = OrgCompletion.templateKeys(templates).first(where: { "<" + $0.key == candidate })?.value else { return candidate }
23 return candidate + " " + value 29 return candidate + " " + value
24 } 30 }
@@ -32,6 +38,27 @@ public struct Completion: Sendable, Equatable {
32 38
33public enum OrgCompletion { 39public enum OrgCompletion {
34 public static func at(_ context: EditContext) -> Completion? { 40 public static func at(_ context: EditContext) -> Completion? {
41 let org = orgAt(context)
42 if let org, !org.candidates.isEmpty { return org }
43 return snippets(context) ?? org
44 }
45
46 /// Snippet triggers starting with the text from the last blank to the caret.
47 static func snippets(_ context: EditContext) -> Completion? {
48 let snippets = context.options.snippets.filter { !$0.file }
49 guard !snippets.isEmpty else { return nil }
50 let ns = context.text as NSString
51 let caret = min(context.caret, ns.length)
52 var start = caret
53 while start > 0, let scalar = UnicodeScalar(ns.character(at: start - 1)), !CharacterSet.whitespacesAndNewlines.contains(scalar) { start -= 1 }
54 guard start < caret else { return nil }
55 let typed = ns.substring(with: NSRange(location: start, length: caret - start))
56 let matching = snippets.filter { $0.trigger.hasPrefix(typed) }
57 guard !matching.isEmpty else { return nil }
58 return Completion(kind: .snippet, range: start..<caret, candidates: matching.map(\.trigger).sorted { $0.localizedStandardCompare($1) == .orderedAscending }, snippets: matching)
59 }
60
61 static func orgAt(_ context: EditContext) -> Completion? {
35 let ns = context.text as NSString 62 let ns = context.text as NSString
36 let caret = min(context.caret, ns.length) 63 let caret = min(context.caret, ns.length)
37 let lineRange = ns.lineRange(for: NSRange(location: caret, length: 0)) 64 let lineRange = ns.lineRange(for: NSRange(location: caret, length: 0))
Sources/OrgCore/Keymap/Keymap.swift +2 −2 · view
@@ -33,7 +33,7 @@ public struct Keymap: Sendable, Equatable {
33 33
34 /// Reads `[[bind]]` tables. Entries that can't be used are skipped and reported in 34 /// Reads `[[bind]]` tables. Entries that can't be used are skipped and reported in
35 /// `problems`; a file that isn't valid TOML throws. With `commands`, a command id outside 35 /// `problems`; a file that isn't valid TOML throws. With `commands`, a command id outside
36 /// it (other than `none`) is such an entry. 36 /// it (other than `none` and a snippet's `org.snippet:` id) is such an entry.
37 public init(toml: String, problems: inout [String], commands: Set<String>? = nil) throws { 37 public init(toml: String, problems: inout [String], commands: Set<String>? = nil) throws {
38 bindings = [] 38 bindings = []
39 for table in try TOML.parse(toml) where !(table.name.isEmpty && table.values.isEmpty) { 39 for table in try TOML.parse(toml) where !(table.name.isEmpty && table.values.isEmpty) {
@@ -49,7 +49,7 @@ public struct Keymap: Sendable, Equatable {
49 problems.append("line \(table.line): missing command") 49 problems.append("line \(table.line): missing command")
50 continue 50 continue
51 } 51 }
52 if let commands, command != "none", !commands.contains(command) { 52 if let commands, command != "none", Snippets.trigger(ofCommand: command) == nil, !commands.contains(command) {
53 problems.append("line \(table.line): unknown command \(command)") 53 problems.append("line \(table.line): unknown command \(command)")
54 continue 54 continue
55 } 55 }
Sources/OrgCore/Keymap/TOML.swift +61 −5 · view
@@ -1,8 +1,8 @@
1import Foundation 1import Foundation
2 2
3/// The part of TOML keymaps use: `[table]` and `[[array-of-tables]]` headers, and 3/// The part of TOML keymaps use: `[table]` and `[[array-of-tables]]` headers, and
4/// `key = value` lines with basic or literal strings, booleans and integers. Comments start 4/// `key = value` lines with basic or literal strings (multi-line ones too), booleans and
5/// with `#` outside strings. 5/// integers. Comments start with `#` outside strings.
6public enum TOML { 6public enum TOML {
7 public enum Value: Sendable, Equatable { 7 public enum Value: Sendable, Equatable {
8 case string(String) 8 case string(String)
@@ -46,9 +46,12 @@ public enum TOML {
46 /// Tables in file order. 46 /// Tables in file order.
47 public static func parse(_ text: String) throws -> [Table] { 47 public static func parse(_ text: String) throws -> [Table] {
48 var tables = [Table(name: "", isArrayElement: false, values: [:], line: 0)] 48 var tables = [Table(name: "", isArrayElement: false, values: [:], line: 0)]
49 for (index, rawLine) in text.split(separator: "\n", omittingEmptySubsequences: false).enumerated() { 49 let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
50 var index = 0
51 while index < lines.count {
50 let number = index + 1 52 let number = index + 1
51 let line = rawLine.trimmingCharacters(in: [" ", "\t", "\r"]) 53 let line = lines[index].trimmingCharacters(in: [" ", "\t", "\r"])
54 index += 1
52 if line.isEmpty || line.hasPrefix("#") { continue } 55 if line.isEmpty || line.hasPrefix("#") { continue }
53 if line.hasPrefix("[") { 56 if line.hasPrefix("[") {
54 let isArray = line.hasPrefix("[[") 57 let isArray = line.hasPrefix("[[")
@@ -68,7 +71,21 @@ public enum TOML {
68 throw ParseError(line: number, message: "bad key") 71 throw ParseError(line: number, message: "bad key")
69 } 72 }
70 var rest = Substring(line[line.index(after: equals)...]).drop { $0 == " " || $0 == "\t" } 73 var rest = Substring(line[line.index(after: equals)...]).drop { $0 == " " || $0 == "\t" }
71 let value = try parseValue(&rest, line: number) 74 let value: Value
75 if let delimiter = ["\"\"\"", "\'\'\'"].first(where: { rest.hasPrefix($0) }) {
76 // A multi-line string runs to the next delimiter, on this line or a later one.
77 var body = String(rest.dropFirst(3))
78 while body.range(of: delimiter) == nil {
79 guard index < lines.count else { throw ParseError(line: number, message: "unclosed string") }
80 body += "\n" + lines[index].replacingOccurrences(of: "\r", with: "")
81 index += 1
82 }
83 let end = body.range(of: delimiter)!
84 value = .string(try multiline(String(body[..<end.lowerBound]), literal: delimiter == "\'\'\'", line: number))
85 rest = body[end.upperBound...]
86 } else {
87 value = try parseValue(&rest, line: number)
88 }
72 rest = rest.drop { $0 == " " || $0 == "\t" } 89 rest = rest.drop { $0 == " " || $0 == "\t" }
73 guard rest.isEmpty || rest.first == "#" else { throw ParseError(line: number, message: "text after value") } 90 guard rest.isEmpty || rest.first == "#" else { throw ParseError(line: number, message: "text after value") }
74 guard tables[tables.count - 1].values[key] == nil else { throw ParseError(line: number, message: "duplicate key \(key)") } 91 guard tables[tables.count - 1].values[key] == nil else { throw ParseError(line: number, message: "duplicate key \(key)") }
@@ -78,6 +95,45 @@ public enum TOML {
78 return tables 95 return tables
79 } 96 }
80 97
98 /// The body of a multi-line string: a newline right after the opening delimiter is
99 /// dropped; in a basic one escapes apply, and a backslash at the end of a line joins it to
100 /// the next non-blank text.
101 private static func multiline(_ raw: String, literal: Bool, line: Int) throws -> String {
102 let body = raw.hasPrefix("\n") ? String(raw.dropFirst()) : raw
103 if literal { return body }
104 var out = ""
105 var rest = Substring(body)
106 while let c = rest.first {
107 rest = rest.dropFirst()
108 guard c == "\\" else {
109 out.append(c)
110 continue
111 }
112 let blanks = rest.prefix { $0 == " " || $0 == "\t" }
113 if rest.dropFirst(blanks.count).first == "\n" {
114 rest = rest.drop { $0.isWhitespace }
115 continue
116 }
117 guard let escaped = rest.first else { throw ParseError(line: line, message: "bad escape") }
118 rest = rest.dropFirst()
119 switch escaped {
120 case "\"": out.append("\"")
121 case "\\": out.append("\\")
122 case "n": out.append("\n")
123 case "t": out.append("\t")
124 case "u", "U":
125 let digits = escaped == "u" ? 4 : 8
126 guard rest.count >= digits, let code = UInt32(rest.prefix(digits), radix: 16), let scalar = Unicode.Scalar(code) else {
127 throw ParseError(line: line, message: "bad unicode escape")
128 }
129 out.unicodeScalars.append(scalar)
130 rest = rest.dropFirst(digits)
131 default: throw ParseError(line: line, message: "bad escape \\\(escaped)")
132 }
133 }
134 return out
135 }
136
81 private static func parseValue(_ rest: inout Substring, line: Int) throws -> Value { 137 private static func parseValue(_ rest: inout Substring, line: Int) throws -> Value {
82 switch rest.first { 138 switch rest.first {
83 case "\"": 139 case "\"":
Sources/OrgCore/Snippets/Snippet.swift added +385 · view
@@ -0,0 +1,385 @@
1import Foundation
2
3/// A snippet from `snippets.toml`:
4///
5/// ```toml
6/// [[snippet]]
7/// trigger = "meet"
8/// description = "Meeting notes"
9/// body = """
10/// * Meeting with ${1:someone} %U
11/// - $0
12/// """
13/// ```
14///
15/// The body has yasnippet's tab stops (`$1`, `${1:default}`, `$0`; a number used twice is a
16/// mirror) and the capture escapes that need no capture (`%t`, `%U`, `%<…>`, `%^{prompt}`,
17/// `%i` for the selected text). With `file = true` it is a template for New File from
18/// Template… instead.
19public struct Snippet: Sendable, Equatable, Hashable, Codable {
20 public var trigger: String
21 /// The description, or the trigger when there is none.
22 public var name: String
23 public var body: String
24 /// A template for a new file rather than a snippet typed in one.
25 public var file: Bool
26
27 public init(trigger: String, name: String? = nil, body: String, file: Bool = false) {
28 self.trigger = trigger
29 self.name = name ?? trigger
30 self.body = body
31 self.file = file
32 }
33
34 /// The command that expands this snippet at the caret, for keys and the iOS key bar.
35 public var commandID: String { Snippets.commandPrefix + trigger }
36}
37
38/// What a snippet's body expands to: its text, its fields and where the caret goes last, in
39/// UTF-16 offsets into `text`.
40public struct SnippetExpansion: Sendable, Equatable {
41 public struct Field: Sendable, Equatable {
42 public let number: Int
43 /// The field first, then its mirrors.
44 public var ranges: [Range<Int>]
45 }
46
47 public var text: String
48 /// By number, `$0` left out.
49 public var fields: [Field]
50 /// `$0`, or the end of the text; not empty for `${0:text}`, which is selected.
51 public var exit: Range<Int>
52}
53
54public enum Snippets {
55 public static let fileName = "snippets.toml"
56 static let commandPrefix = "org.snippet:"
57
58 /// The trigger of a `commandID`, or nil for another command.
59 public static func trigger(ofCommand id: String) -> String? {
60 id.hasPrefix(commandPrefix) ? String(id.dropFirst(commandPrefix.count)) : nil
61 }
62
63 public struct Problem: Error, Equatable, CustomStringConvertible {
64 public let line: Int
65 public let message: String
66 public var description: String { "line \(line): \(message)" }
67 }
68
69 /// The snippets in a `snippets.toml`, and problems with single snippets, which are left
70 /// out. Throws when the file isn't valid TOML.
71 public static func parse(_ text: String) throws -> (snippets: [Snippet], problems: [String]) {
72 let tables = try TOML.parse(text)
73 var snippets: [Snippet] = []
74 var problems: [String] = []
75 var triggers: Set<String> = []
76 for table in tables where !(table.name.isEmpty && table.values.isEmpty) {
77 guard table.name == "snippet", table.isArrayElement else {
78 problems.append("line \(table.line): expected [[snippet]]")
79 continue
80 }
81 let values = table.values
82 guard let trigger = values["trigger"]?.string, !trigger.isEmpty, let body = values["body"]?.string else {
83 problems.append("line \(table.line): a snippet needs trigger and body")
84 continue
85 }
86 guard !trigger.contains(where: \.isWhitespace) else {
87 problems.append("line \(table.line): a trigger has no spaces")
88 continue
89 }
90 for key in table.keys where !["trigger", "body", "description", "file"].contains(key) {
91 problems.append("line \(table.line): unknown key \(key)")
92 }
93 do {
94 _ = try parseBody(body)
95 } catch let problem as Problem {
96 problems.append("line \(table.line): \(problem.message)")
97 continue
98 }
99 guard triggers.insert(trigger).inserted else {
100 problems.append("line \(table.line): trigger \(trigger) is used twice")
101 continue
102 }
103 snippets.append(Snippet(trigger: trigger, name: values["description"]?.string, body: body, file: values["file"]?.bool ?? false))
104 }
105 return (snippets, problems)
106 }
107
108 // MARK: - Triggers
109
110 /// The snippet whose trigger is just before `caret`, and the trigger's range. As
111 /// yasnippet's `yas-key-syntaxes`, the longest text back to a blank is tried first, then
112 /// shorter ones starting after a character that isn't part of a word.
113 public static func trigger(before caret: Int, in text: String, snippets: [Snippet]) -> (snippet: Snippet, range: Range<Int>)? {
114 let candidates = snippets.filter { !$0.file }
115 guard !candidates.isEmpty else { return nil }
116 let ns = text as NSString
117 guard caret > 0, caret <= ns.length else { return nil }
118 var start = caret
119 while start > 0, let scalar = UnicodeScalar(ns.character(at: start - 1)), !CharacterSet.whitespacesAndNewlines.contains(scalar) { start -= 1 }
120 guard start < caret else { return nil }
121 var from = start
122 while from < caret {
123 let typed = ns.substring(with: NSRange(location: from, length: caret - from))
124 if let snippet = candidates.first(where: { $0.trigger == typed }) { return (snippet, from..<caret) }
125 // The next start: after the next character that isn't a letter, digit or `_`.
126 from += 1
127 while from < caret, let scalar = UnicodeScalar(ns.character(at: from - 1)), CharacterSet.alphanumerics.contains(scalar) || scalar == "_" { from += 1 }
128 }
129 return nil
130 }
131
132 // MARK: - Bodies
133
134 /// Tab stops and text, as `parseBody` reads a body.
135 indirect enum Node: Equatable {
136 case text(String)
137 /// `$N` (no children) or `${N:…}`.
138 case stop(Int, [Node]?)
139 }
140
141 /// Reads yasnippet's tab stops: `$N`, `${N}`, `${N:default}` with stops nested in the
142 /// default, and the escapes `\$`, `\\`, `` \` `` and, in a default, `\}`.
143 static func parseBody(_ body: String) throws -> [Node] {
144 let chars = Array(body)
145 var i = 0
146 func parse(inDefault: Bool) throws -> [Node] {
147 var nodes: [Node] = []
148 var text = ""
149 func flush() {
150 if !text.isEmpty { nodes.append(.text(text)) }
151 text = ""
152 }
153 while i < chars.count {
154 let c = chars[i]
155 if c == "\\", i + 1 < chars.count, "$\\`".contains(chars[i + 1]) || (inDefault && chars[i + 1] == "}") {
156 text.append(chars[i + 1])
157 i += 2
158 continue
159 }
160 if inDefault, c == "}" {
161 i += 1
162 flush()
163 return nodes
164 }
165 guard c == "$", i + 1 < chars.count else {
166 text.append(c)
167 i += 1
168 continue
169 }
170 if chars[i + 1].isASCII, chars[i + 1].isNumber {
171 var j = i + 1
172 while j < chars.count, chars[j].isASCII, chars[j].isNumber { j += 1 }
173 flush()
174 nodes.append(.stop(Int(String(chars[(i + 1)..<j]))!, nil))
175 i = j
176 continue
177 }
178 if chars[i + 1] == "{", i + 2 < chars.count, chars[i + 2].isASCII, chars[i + 2].isNumber {
179 var j = i + 2
180 while j < chars.count, chars[j].isASCII, chars[j].isNumber { j += 1 }
181 let number = Int(String(chars[(i + 2)..<j]))!
182 guard j < chars.count, chars[j] == ":" || chars[j] == "}" else {
183 throw Problem(line: 0, message: "expected : or } after ${\(number)")
184 }
185 flush()
186 if chars[j] == "}" {
187 nodes.append(.stop(number, []))
188 i = j + 1
189 continue
190 }
191 if j + 2 < chars.count, chars[j + 1] == "$", chars[j + 2] == "(" {
192 throw Problem(line: 0, message: "Emacs Lisp in a field isn't supported")
193 }
194 i = j + 1
195 nodes.append(.stop(number, try parse(inDefault: true)))
196 continue
197 }
198 text.append(c)
199 i += 1
200 }
201 if inDefault { throw Problem(line: 0, message: "a ${ isn't closed") }
202 flush()
203 return nodes
204 }
205 return try parse(inDefault: false)
206 }
207
208 /// Marks in the text a body becomes before the capture escapes are filled. Capture leaves
209 /// characters in the private use area alone.
210 static let fieldOpen: Character = "\u{E020}"
211 static let fieldSeparator: Character = "\u{E021}"
212 static let mirrorSeparator: Character = "\u{E026}"
213 static let fieldClose: Character = "\u{E022}"
214 static let edge: Character = "\u{E023}"
215 static let tab: Character = "\u{E024}"
216 static let backslash: Character = "\u{E025}"
217
218 /// The body with its stops as marks: the first `${N:…}` of a number (else its first `$N`)
219 /// is the field, the others mirrors. Tabs and literal backslashes are marked too, so that
220 /// filling leaves them.
221 static func marked(_ nodes: [Node]) -> String {
222 var primaries: [Int: Int] = [:]
223 var occurrence = 0
224 var withDefault: Set<Int> = []
225 func scan(_ nodes: [Node]) {
226 for node in nodes {
227 guard case .stop(let number, let children) = node else { continue }
228 if let children {
229 if !withDefault.contains(number) {
230 withDefault.insert(number)
231 primaries[number] = occurrence
232 }
233 occurrence += 1
234 scan(children)
235 } else {
236 if primaries[number] == nil { primaries[number] = occurrence }
237 occurrence += 1
238 }
239 }
240 }
241 scan(nodes)
242 occurrence = 0
243 func emit(_ nodes: [Node]) -> String {
244 var out = ""
245 for node in nodes {
246 switch node {
247 case .text(let text):
248 // Backslashes in capture escapes (`\\%t`, `%\\1`) stay for capture.
249 out += text.replacingOccurrences(of: "(?<!%)\\\\(?!%)", with: String(backslash), options: .regularExpression)
250 .replacingOccurrences(of: "\t", with: String(tab))
251 case .stop(let number, let children):
252 let primary = primaries[number] == occurrence
253 occurrence += 1
254 out += String(fieldOpen) + String(number) + String(primary ? fieldSeparator : mirrorSeparator)
255 if primary, let children { out += emit(children) } else if let children { _ = emit(children) }
256 out += String(fieldClose)
257 }
258 }
259 return out
260 }
261 return emit(nodes)
262 }
263
264 /// The `%?` of capture as `$0`, unless escaped.
265 static func captureCaret(_ body: String) -> String {
266 body.replacingOccurrences(of: "(?<!\\\\)%\\?", with: "\\$0", options: .regularExpression)
267 }
268
269 /// The capture prompts the body asks, in order.
270 public static func questions(_ snippet: Snippet, context: CaptureContext) -> [Capture.Question] {
271 guard let nodes = try? parseBody(captureCaret(snippet.body)) else { return [] }
272 return Capture.questions(String(edge) + marked(nodes) + String(edge), context: context)
273 }
274
275 /// The snippet expanded with `answers` to its `questions`; lines after the first start
276 /// with `indentation`.
277 public static func expand(_ snippet: Snippet, context: CaptureContext, answers: [String] = [], indentation: String = "") -> Result<SnippetExpansion, Capture.Failure> {
278 let nodes: [Node]
279 do {
280 nodes = try parseBody(captureCaret(snippet.body))
281 } catch {
282 return .failure(.message("\(snippet.trigger): \(error)"))
283 }
284 let filled: String
285 switch Capture.fill(String(edge) + marked(nodes) + String(edge), context: context, answers: answers) {
286 case .failure(let failure): return .failure(failure)
287 case .success(let result): filled = result.text
288 }
289 guard let first = filled.firstIndex(of: edge), let last = filled.lastIndex(of: edge), first < last else {
290 return .failure(.message("\(snippet.trigger) couldn't be expanded"))
291 }
292 var inner = String(filled[filled.index(after: first)..<last])
293 if !indentation.isEmpty { inner = inner.replacingOccurrences(of: "\n", with: "\n" + indentation) }
294 return .success(extract(inner))
295 }
296
297 /// Reads the marks out of filled text: the text with mirrors showing their field's text,
298 /// and the ranges.
299 static func extract(_ marked: String) -> SnippetExpansion {
300 // Pieces: text, or a stop with its number, whether it is the field, and its pieces.
301 indirect enum Piece {
302 case text(String)
303 case stop(Int, Bool, [Piece])
304 }
305 let chars = Array(marked)
306 var i = 0
307 func read() -> [Piece] {
308 var pieces: [Piece] = []
309 var text = ""
310 while i < chars.count {
311 let c = chars[i]
312 if c == fieldClose {
313 i += 1
314 break
315 }
316 if c == fieldOpen {
317 if !text.isEmpty { pieces.append(.text(text)) }
318 text = ""
319 var j = i + 1
320 while j < chars.count, chars[j] != fieldSeparator, chars[j] != mirrorSeparator { j += 1 }
321 let number = Int(String(chars[(i + 1)..<j])) ?? 0
322 let primary = j < chars.count && chars[j] == fieldSeparator
323 i = j + 1
324 pieces.append(.stop(number, primary, read()))
325 continue
326 }
327 text.append(c == tab ? "\t" : c == backslash ? "\\" : c)
328 i += 1
329 }
330 if !text.isEmpty { pieces.append(.text(text)) }
331 return pieces
332 }
333 let pieces = read()
334 // Each field's text, for its mirrors.
335 var values: [Int: String] = [:]
336 func flatten(_ pieces: [Piece], depth: Int = 0) -> String {
337 pieces.map { piece -> String in
338 switch piece {
339 case .text(let text): return text
340 case .stop(let number, let primary, let children):
341 if primary { return flatten(children, depth: depth) }
342 return depth > 8 ? "" : (values[number] ?? "")
343 }
344 }.joined()
345 }
346 func collect(_ pieces: [Piece]) {
347 for case .stop(let number, let primary, let children) in pieces where primary {
348 collect(children)
349 values[number] = flatten(children)
350 }
351 }
352 collect(pieces)
353 // Mirrors inside defaults show values found after them; one more pass settles those.
354 collect(pieces)
355 var text = ""
356 var length = 0
357 var fields: [Int: (primary: Range<Int>?, mirrors: [Range<Int>])] = [:]
358 func render(_ pieces: [Piece]) {
359 for piece in pieces {
360 switch piece {
361 case .text(let s):
362 text += s
363 length += s.utf16.count
364 case .stop(let number, let primary, let children):
365 let start = length
366 if primary {
367 render(children)
368 fields[number, default: (nil, [])].primary = start..<length
369 } else {
370 let value = values[number] ?? ""
371 text += value
372 length += value.utf16.count
373 fields[number, default: (nil, [])].mirrors.append(start..<length)
374 }
375 }
376 }
377 }
378 render(pieces)
379 let exit = fields[0]?.primary ?? fields[0]?.mirrors.first ?? length..<length
380 let list = fields.filter { $0.key != 0 }.sorted { $0.key < $1.key }.map { number, ranges in
381 SnippetExpansion.Field(number: number, ranges: [ranges.primary ?? ranges.mirrors[0]] + (ranges.primary == nil ? Array(ranges.mirrors.dropFirst()) : ranges.mirrors))
382 }
383 return SnippetExpansion(text: text, fields: list, exit: exit)
384 }
385}
Sources/OrgCore/Snippets/SnippetCommands.swift added +116 · view
@@ -0,0 +1,116 @@
1import Foundation
2
3/// TAB after a trigger, where TAB means nothing else, and any key bound to it: `yas-expand`.
4public struct ExpandSnippet: OrgCommand {
5 public init() {}
6 public var id: String { "org.snippet.expand" }
7 public var title: String { "Expand Snippet" }
8 public func applies(in context: EditContext) -> Bool {
9 context.selection.allSatisfy(\.isEmpty) && Snippets.trigger(before: context.caret, in: context.text, snippets: context.options.snippets) != nil
10 }
11 public func run(in context: EditContext) -> CommandStep {
12 guard context.selection.allSatisfy(\.isEmpty),
13 let found = Snippets.trigger(before: context.caret, in: context.text, snippets: context.options.snippets) else {
14 return .failed("No snippet to expand")
15 }
16 return Snippets.step(found.snippet, replacing: found.range, in: context)
17 }
18}
19
20/// Insert Snippet…: one chosen by name replaces the selection, which `%i` inserts
21/// (`yas-insert-snippet`).
22public struct InsertSnippet: OrgCommand {
23 public init() {}
24 public var id: String { "org.snippet.insert" }
25 public var title: String { "Insert Snippet…" }
26 public func applies(in context: EditContext) -> Bool { context.options.snippets.contains { !$0.file } }
27 public func run(in context: EditContext) -> CommandStep {
28 let snippets = context.options.snippets.filter { !$0.file }
29 guard !snippets.isEmpty else { return .failed("No snippets in \(Snippets.fileName)") }
30 guard let answer = context.answers["snippet"] else {
31 return .prompt(Prompt(key: "snippet", message: "Choose snippet: ", choices: snippets.map(Snippets.label)))
32 }
33 guard let snippet = snippets.first(where: { Snippets.label($0) == answer || $0.trigger == answer }) else {
34 return .failed("No snippet \(answer)")
35 }
36 let selected = context.selection.first ?? context.caret..<context.caret
37 return Snippets.step(snippet, replacing: selected, in: context)
38 }
39}
40
41/// A snippet or file template by trigger, at the caret: the command `Snippet.commandID` names.
42public struct ExpandNamedSnippet: OrgCommand {
43 public let trigger: String
44 /// The snippet itself, for a template expanded before the editor has the snippets.
45 let snippet: Snippet?
46 public init(trigger: String) {
47 self.trigger = trigger
48 snippet = nil
49 }
50 public init(snippet: Snippet) {
51 trigger = snippet.trigger
52 self.snippet = snippet
53 }
54 public var id: String { Snippets.commandPrefix + trigger }
55 public var title: String { "Expand Snippet" }
56 public func applies(in context: EditContext) -> Bool { snippet != nil || context.options.snippets.contains { $0.trigger == trigger } }
57 public func run(in context: EditContext) -> CommandStep {
58 guard let snippet = snippet ?? context.options.snippets.first(where: { $0.trigger == trigger }) else { return .failed("No snippet \(trigger)") }
59 let selected = context.selection.first ?? context.caret..<context.caret
60 return Snippets.step(snippet, replacing: selected, in: context)
61 }
62}
63
64extension Snippets {
65 /// How Insert Snippet… lists a snippet.
66 public static func label(_ snippet: Snippet) -> String {
67 snippet.name == snippet.trigger ? snippet.trigger : "\(snippet.name) (\(snippet.trigger))"
68 }
69
70 /// The command for an id of the form `Snippet.commandID`.
71 public static func command(_ id: String) -> (any OrgCommand)? {
72 trigger(ofCommand: id).map(ExpandNamedSnippet.init)
73 }
74
75 /// Asks the body's prompts one at a time, then replaces `range` with the expansion and
76 /// starts a session on its fields.
77 static func step(_ snippet: Snippet, replacing range: Range<Int>, in context: EditContext) -> CommandStep {
78 let ns = context.text as NSString
79 var capture = CaptureContext(now: context.now, calendar: context.calendar,
80 initial: range.isEmpty ? "" : ns.substring(with: NSRange(location: range.lowerBound, length: range.count)),
81 file: context.options.filePath ?? "")
82 capture.tagsColumn = context.options.tagsColumn
83 let questions = questions(snippet, context: capture)
84 var answers: [String] = []
85 for (index, question) in questions.enumerated() {
86 let key = "snippet-\(index)"
87 guard let answer = context.answers[key] else { return .prompt(prompt(question, key: key)) }
88 answers.append(answer)
89 }
90 let lineStart = ns.lineRange(for: NSRange(location: range.lowerBound, length: 0)).location
91 let indentation = String(ns.substring(with: NSRange(location: lineStart, length: range.lowerBound - lineStart)).prefix { $0 == " " || $0 == "\t" })
92 switch expand(snippet, context: capture, answers: answers, indentation: indentation) {
93 case .failure(.message(let message)):
94 return .failed(message)
95 case .success(let expansion):
96 let session = SnippetSession(expansion, at: range.lowerBound)
97 let exit = (expansion.exit.lowerBound + range.lowerBound)..<(expansion.exit.upperBound + range.lowerBound)
98 return .commit(EditResult(
99 baseRevision: context.revision, edits: [TextEdit(range: range, replacement: expansion.text)],
100 selection: [session?.selection ?? exit], effects: session.map { [.snippet($0)] } ?? []
101 ))
102 }
103 }
104
105 static func prompt(_ question: Capture.Question, key: String) -> Prompt {
106 switch question.kind {
107 case .date(_, let inactive):
108 return Prompt(key: key, message: question.prompt + ": ", date: .init(defaultDate: nil, inactive: inactive))
109 case .tags:
110 return Prompt(key: key, message: question.prompt + ": ", choices: question.choices, requireMatch: false, completionSeparator: ":")
111 case .text, .clipboard, .property:
112 return Prompt(key: key, message: question.prompt + (question.defaultValue.isEmpty ? ": " : " (\(question.defaultValue)): "),
113 choices: question.choices, requireMatch: false)
114 }
115 }
116}
Sources/OrgCore/Snippets/SnippetSession.swift added +121 · view
@@ -0,0 +1,121 @@
1import Foundation
2
3/// An expanded snippet while its fields are filled in: TAB and S-TAB move between fields,
4/// typing in a field changes its mirrors, and leaving the last field, Escape, or an edit or
5/// caret outside the snippet ends it. Offsets are UTF-16 into the buffer.
6public struct SnippetSession: Sendable, Equatable {
7 public struct Field: Sendable, Equatable {
8 public let number: Int
9 /// The field first, then its mirrors.
10 public var ranges: [Range<Int>]
11 }
12
13 public private(set) var fields: [Field]
14 /// Where the caret goes when the last field is left.
15 public private(set) var exit: Range<Int>
16 /// From the start of the snippet to its end.
17 public private(set) var extent: Range<Int>
18 /// The field being filled in.
19 public private(set) var active = 0
20
21 /// The session for `expansion` inserted at `offset`; nil when it has no fields.
22 public init?(_ expansion: SnippetExpansion, at offset: Int) {
23 guard !expansion.fields.isEmpty else { return nil }
24 func shifted(_ range: Range<Int>) -> Range<Int> { (range.lowerBound + offset)..<(range.upperBound + offset) }
25 fields = expansion.fields.map { Field(number: $0.number, ranges: $0.ranges.map(shifted)) }
26 exit = shifted(expansion.exit)
27 extent = offset..<(offset + expansion.text.utf16.count)
28 }
29
30 /// The active field's text range, which is selected on entering it.
31 public var selection: Range<Int> { fields[active].ranges[0] }
32
33 public enum Step: Sendable, Equatable {
34 /// Select this field.
35 case field(Range<Int>)
36 /// The snippet is done; select `exit`.
37 case exit(Range<Int>)
38 }
39
40 /// TAB: the next field, or the exit after the last.
41 public mutating func next() -> Step {
42 guard active + 1 < fields.count else { return .exit(exit) }
43 active += 1
44 return .field(selection)
45 }
46
47 /// S-TAB: the field before, or the first again.
48 public mutating func previous() -> Range<Int> {
49 if active > 0 { active -= 1 }
50 return selection
51 }
52
53 /// Whether `offset` is in the snippet, its ends included.
54 public func contains(_ offset: Int) -> Bool { extent.lowerBound <= offset && offset <= extent.upperBound }
55
56 /// Follows `edit` of the buffer; false when the edit is outside the snippet, which ends it.
57 /// Text typed at either end of the active field goes into it, and an edit replacing a
58 /// mirror exactly becomes the mirror's text.
59 public mutating func map(_ edit: TextEdit) -> Bool {
60 let a = edit.range.lowerBound, b = edit.range.upperBound
61 let n = edit.replacement.utf16.count
62 let delta = n - (b - a)
63 let primary = fields[active].ranges[0]
64 let inActive = primary.lowerBound <= a && b <= primary.upperBound
65 guard inActive || (extent.lowerBound <= a && b <= extent.upperBound) else { return false }
66 // Replacing the whole snippet, as undoing its expansion does, ends it.
67 if !inActive, a == extent.lowerBound, b == extent.upperBound, !extent.isEmpty { return false }
68 /// A position; `right` keeps it after text inserted there.
69 func point(_ p: Int, right: Bool) -> Int {
70 if p < a { return p }
71 if p > b { return p + delta }
72 if a == b { return right ? p + n : p }
73 if p == a { return p }
74 if p == b { return p + delta }
75 return right ? a + n : a
76 }
77 func range(_ r: Range<Int>, grows: Bool) -> Range<Int> {
78 if grows { return point(r.lowerBound, right: false)..<point(r.upperBound, right: true) }
79 if r.isEmpty {
80 let p = point(r.lowerBound, right: true)
81 return p..<p
82 }
83 let lower = point(r.lowerBound, right: true), upper = point(r.upperBound, right: false)
84 return lower..<max(lower, upper)
85 }
86 var mirrorGrown = false
87 for f in fields.indices {
88 for r in fields[f].ranges.indices {
89 let old = fields[f].ranges[r]
90 var grows = false
91 if inActive {
92 grows = f == active && r == 0
93 } else if !mirrorGrown, r > 0, old == edit.range {
94 grows = true
95 mirrorGrown = true
96 }
97 fields[f].ranges[r] = range(old, grows: grows)
98 }
99 }
100 exit = range(exit, grows: false)
101 extent = point(extent.lowerBound, right: false)..<point(extent.upperBound, right: true)
102 return true
103 }
104
105 /// Edits that make every mirror show its field's text in `text`, the buffer as it is now.
106 public func mirrorEdits(in text: String) -> [TextEdit] {
107 let ns = text as NSString
108 func substring(_ r: Range<Int>) -> String? {
109 guard r.upperBound <= ns.length else { return nil }
110 return ns.substring(with: NSRange(location: r.lowerBound, length: r.count))
111 }
112 var edits: [TextEdit] = []
113 for field in fields {
114 guard let value = substring(field.ranges[0]) else { continue }
115 for mirror in field.ranges.dropFirst() where substring(mirror) != value && mirror.upperBound <= ns.length {
116 edits.append(TextEdit(range: mirror, replacement: value))
117 }
118 }
119 return edits.sorted { $0.range.lowerBound < $1.range.lowerBound }
120 }
121}
Sources/OrgEditorAppKit/CompletionPopup.swift +3 −2 · view
@@ -56,7 +56,7 @@ final class CompletionPopup {
56 let first = max(0, min((selection ?? 0) - Self.rows + 1, candidates.count - Self.rows)) 56 let first = max(0, min((selection ?? 0) - Self.rows + 1, candidates.count - Self.rows))
57 var width: CGFloat = 80 57 var width: CGFloat = 80
58 for (index, candidate) in candidates.enumerated().dropFirst(first).prefix(Self.rows) { 58 for (index, candidate) in candidates.enumerated().dropFirst(first).prefix(Self.rows) {
59 let label = NSTextField(labelWithString: " " + completion.label(candidate) + " ") 59 let label = NSTextField(labelWithString: " " + completion.label(candidate) + (completion.kind == .snippet ? " " + String(localized: "snippet", comment: "Marks a snippet in the completion list") : "") + " ")
60 label.font = font 60 label.font = font
61 label.drawsBackground = index == selection 61 label.drawsBackground = index == selection
62 label.backgroundColor = .selectedContentBackgroundColor 62 label.backgroundColor = .selectedContentBackgroundColor
@@ -139,6 +139,7 @@ extension OrgEditor {
139 } 139 }
140 140
141 func insertCompletion(_ completion: Completion, _ candidate: String) { 141 func insertCompletion(_ completion: Completion, _ candidate: String) {
142 if completion.kind == .snippet { return expandCompleted(completion, candidate) }
142 let (text, caret) = completion.insertion(candidate) 143 let (text, caret) = completion.insertion(candidate)
143 let range = NSRange(location: completion.range.lowerBound, length: completion.range.count) 144 let range = NSRange(location: completion.range.lowerBound, length: completion.range.count)
144 guard textView.shouldChangeText(in: range, replacementString: text) else { return } 145 guard textView.shouldChangeText(in: range, replacementString: text) else { return }
@@ -166,7 +167,7 @@ extension OrgEditor {
166 insertCompletion(completion, completion.candidates[0]) 167 insertCompletion(completion, completion.candidates[0])
167 } else { 168 } else {
168 let common = completion.candidates.dropFirst().reduce(completion.candidates[0]) { $0.commonPrefix(with: $1) } 169 let common = completion.candidates.dropFirst().reduce(completion.candidates[0]) { $0.commonPrefix(with: $1) }
169 if common.utf16.count > completion.range.count, completion.kind != .template { 170 if common.utf16.count > completion.range.count, completion.kind != .template, completion.kind != .snippet {
170 insertCompletion(completion, common) 171 insertCompletion(completion, common)
171 refreshCompletion() 172 refreshCompletion()
172 } 173 }
Sources/OrgEditorAppKit/EditorCommands.swift +3 · view
@@ -59,6 +59,9 @@ public enum EditorCommands {
59 EditorCommand(id: "org.toggle-inline-images-linked", title: "Show or Hide Inline Images, Including Described Links", action: .view), 59 EditorCommand(id: "org.toggle-inline-images-linked", title: "Show or Hide Inline Images, Including Described Links", action: .view),
60 EditorCommand(id: "org.latex-preview", title: "Show or Hide LaTeX Previews", action: .view), 60 EditorCommand(id: "org.latex-preview", title: "Show or Hide LaTeX Previews", action: .view),
61 EditorCommand(id: "editor.complete", title: "Complete at Point", action: .view), 61 EditorCommand(id: "editor.complete", title: "Complete at Point", action: .view),
62 EditorCommand(id: "org.snippet.next-field", title: "Next Snippet Field", action: .view),
63 EditorCommand(id: "org.snippet.previous-field", title: "Previous Snippet Field", action: .view),
64 EditorCommand(id: "app.new-file-from-template", title: "New File from Template…", action: .app),
62 EditorCommand(id: "editor.toggle-spell-check", title: "Check Spelling While Typing", action: .view), 65 EditorCommand(id: "editor.toggle-spell-check", title: "Check Spelling While Typing", action: .view),
63 EditorCommand(id: "editor.toggle-truncate-lines", title: "Truncate or Wrap Long Lines", action: .view), 66 EditorCommand(id: "editor.toggle-truncate-lines", title: "Truncate or Wrap Long Lines", action: .view),
64 EditorCommand(id: "editor.toggle-auto-fill", title: "Turn Auto Fill On or Off", action: .view), 67 EditorCommand(id: "editor.toggle-auto-fill", title: "Turn Auto Fill On or Off", action: .view),
Sources/OrgEditorAppKit/Modal.swift +2 · view
@@ -44,6 +44,7 @@ extension OrgEditor {
44 updateCursor() 44 updateCursor()
45 return true 45 return true
46 } 46 }
47 if keys.count == 1, vim.mode == .insert, snippetTab(chord) { return true }
47 return feedVim(keys) 48 return feedVim(keys)
48 case .undefined(let keys): 49 case .undefined(let keys):
49 onKeysPending?(nil, []) 50 onKeysPending?(nil, [])
@@ -55,6 +56,7 @@ extension OrgEditor {
55 } 56 }
56 return feedVim(keys) 57 return feedVim(keys)
57 case .unbound: 58 case .unbound:
59 if vim.mode == .insert, snippetTab(chord) { return true }
58 return feedVim([chord]) 60 return feedVim([chord])
59 } 61 }
60 } 62 }
Sources/OrgEditorAppKit/OrgEditor+Snippets.swift added +142 · view
@@ -0,0 +1,142 @@
1#if os(macOS)
2import AppKit
3import OrgCore
4
5/// Snippets: TAB after a trigger where TAB means nothing else expands it, then TAB and S-TAB
6/// move between its fields until the last is left, Escape is pressed, or the caret or an edit
7/// leaves the snippet. The active field has a band behind it, the others a fainter one.
8extension OrgEditor {
9 /// TAB with no binding that runs here: expands the trigger before the caret, if any.
10 func snippetTab(_ chord: KeyChord) -> Bool {
11 guard isOrg, chord == KeyChord("TAB"), !textView.hasMarkedText() else { return false }
12 let expand = ExpandSnippet()
13 guard expand.applies(in: context()) else { return false }
14 perform(expand)
15 return true
16 }
17
18 /// Keys while a snippet's fields are filled in; nil lets the key through.
19 func snippetKey(_ chord: KeyChord) -> Bool? {
20 guard snippetSession != nil else { return nil }
21 switch chord {
22 case KeyChord("TAB"):
23 nextSnippetField()
24 return true
25 case KeyChord("TAB", .shift):
26 previousSnippetField()
27 return true
28 case KeyChord("ESC"):
29 endSnippet()
30 // Doom leaves insert state as well.
31 return modal ? nil : true
32 default:
33 return nil
34 }
35 }
36
37 func nextSnippetField() {
38 guard var session = snippetSession else { return }
39 switch session.next() {
40 case .field(let range):
41 snippetSession = session
42 select(range)
43 case .exit(let range):
44 endSnippet()
45 select(range)
46 }
47 }
48
49 func previousSnippetField() {
50 guard var session = snippetSession else { return }
51 let range = session.previous()
52 snippetSession = session
53 select(range)
54 }
55
56 func startSnippet(_ session: SnippetSession) {
57 snippetSession = session
58 highlightSnippet()
59 }
60
61 func endSnippet() {
62 snippetSession = nil
63 highlightSnippet()
64 }
65
66 private func select(_ range: Range<Int>) {
67 if hidden.containing(range.lowerBound) != nil { unfold(around: range.lowerBound) }
68 setCaret(range.lowerBound)
69 if !range.isEmpty { textView.setSelectedRange(NSRange(range)) }
70 highlightSnippet()
71 }
72
73 /// An edit of the buffer; one outside the snippet ends it.
74 func snippetEdited(_ edit: TextEdit) {
75 guard var session = snippetSession else { return }
76 snippetSession = session.map(edit) ? session : nil
77 }
78
79 /// After a change: mirrors take their field's new text.
80 func updateSnippetMirrors() {
81 guard let session = snippetSession, !updatingMirrors, !textView.hasMarkedText() else { return highlightSnippet() }
82 let edits = session.mirrorEdits(in: document.text)
83 if !edits.isEmpty {
84 updatingMirrors = true
85 let selected = textView.selectedRange()
86 let caret = selected.location
87 applyEdits(edits)
88 updatingMirrors = false
89 // The caret stays in the field, moved by mirrors before it.
90 let shift = edits.filter { $0.range.upperBound <= caret }.reduce(0) { $0 + $1.replacement.utf16.count - $1.range.count }
91 textView.setSelectedRange(NSRange(location: caret + shift, length: selected.length))
92 }
93 highlightSnippet()
94 }
95
96 /// The caret moved: outside the snippet, it ends.
97 func snippetSelectionChanged() {
98 guard let session = snippetSession, !updatingMirrors else { return }
99 let selected = textView.selectedRange()
100 if !session.contains(selected.location) || !session.contains(NSMaxRange(selected)) { endSnippet() }
101 }
102
103 /// Draws the fields of the session, and removes what was drawn for the last one.
104 func highlightSnippet() {
105 let length = utf16Length
106 var covered = snippetHighlight.flatMap { $0.upperBound <= length ? $0 : $0.lowerBound < length ? $0.lowerBound..<length : nil }
107 if let extent = snippetSession?.extent, extent.upperBound <= length {
108 covered = covered.map { min($0.lowerBound, extent.lowerBound)..<max($0.upperBound, extent.upperBound) } ?? extent
109 }
110 for manager in layoutManagers {
111 if let covered, let range = textRange(covered) {
112 manager.removeRenderingAttribute(.backgroundColor, for: range)
113 }
114 guard let session = snippetSession else { continue }
115 for (index, field) in session.fields.enumerated() {
116 for (n, r) in field.ranges.enumerated() where !r.isEmpty && r.upperBound <= length {
117 guard let range = textRange(r) else { continue }
118 if index == session.active, n == 0 {
119 manager.addRenderingAttribute(.backgroundColor, value: NSColor.findHighlightColor.withAlphaComponent(0.35), for: range)
120 } else {
121 manager.addRenderingAttribute(.backgroundColor, value: NSColor.gray.withAlphaComponent(0.2), for: range)
122 }
123 }
124 }
125 }
126 snippetHighlight = snippetSession?.extent
127 }
128
129 private func textRange(_ r: Range<Int>) -> NSTextRange? {
130 let manager = textContentStorage
131 guard let start = manager.location(manager.documentRange.location, offsetBy: r.lowerBound),
132 let end = manager.location(start, offsetBy: r.count) else { return nil }
133 return NSTextRange(location: start, end: end)
134 }
135
136 /// Chosen from the completion list: the trigger typed so far becomes the snippet.
137 func expandCompleted(_ completion: Completion, _ trigger: String) {
138 textView.setSelectedRange(NSRange(location: completion.range.lowerBound, length: completion.range.count))
139 perform(ExpandNamedSnippet(trigger: trigger))
140 }
141}
142#endif
Sources/OrgEditorAppKit/OrgEditor.swift +17 −2 · view
@@ -87,6 +87,10 @@ public final class OrgEditor: NSObject {
87 /// The open completion list, and the pause before one opens by itself. 87 /// The open completion list, and the pause before one opens by itself.
88 var completionPopup: CompletionPopup? 88 var completionPopup: CompletionPopup?
89 var completionTimer: DispatchWorkItem? 89 var completionTimer: DispatchWorkItem?
90 /// The snippet whose fields are being filled in, and the range drawn for it last.
91 var snippetSession: SnippetSession?
92 var snippetHighlight: Range<Int>?
93 var updatingMirrors = false
90 /// The spell checker's skipped ranges and the text they were found in. 94 /// The spell checker's skipped ranges and the text they were found in.
91 var spellSkipCache: (text: String, ranges: [Range<Int>])? 95 var spellSkipCache: (text: String, ranges: [Range<Int>])?
92 /// Highlights of the whole file in plain mode, and the revision they were made for. 96 /// Highlights of the whole file in plain mode, and the revision they were made for.
@@ -507,6 +511,7 @@ public final class OrgEditor: NSObject {
507 } 511 }
508 if isearch != nil, isearchKey(chord) { return true } 512 if isearch != nil, isearchKey(chord) { return true }
509 if let handled = completionKey(chord) { return handled } 513 if let handled = completionKey(chord) { return handled }
514 if let handled = snippetKey(chord) { return handled }
510 if modal { return handleModal(chord) } 515 if modal { return handleModal(chord) }
511 switch dispatcher.feed(chord) { 516 switch dispatcher.feed(chord) {
512 case .pending(let keys): 517 case .pending(let keys):
@@ -525,7 +530,7 @@ public final class OrgEditor: NSObject {
525 fail("\(KeySequence.format(keys)) is undefined") 530 fail("\(KeySequence.format(keys)) is undefined")
526 return true 531 return true
527 case .unbound: 532 case .unbound:
528 return electricPair(chord) || autoFill(chord) 533 return snippetTab(chord) || electricPair(chord) || autoFill(chord)
529 case .complete(let keys, let candidates): 534 case .complete(let keys, let candidates):
530 let argument = dispatcher.argument != nil 535 let argument = dispatcher.argument != nil
531 if keys.count > 1 || argument { onKeysPending?(nil, []) } 536 if keys.count > 1 || argument { onKeysPending?(nil, []) }
@@ -542,7 +547,7 @@ public final class OrgEditor: NSObject {
542 run(binding.command) 547 run(binding.command)
543 return true 548 return true
544 } 549 }
545 return keys.count == 1 && (electricPair(chord) || autoFill(chord)) 550 return keys.count == 1 && (snippetTab(chord) || electricPair(chord) || autoFill(chord))
546 } 551 }
547 } 552 }
548 553
@@ -583,6 +588,7 @@ public final class OrgEditor: NSObject {
583 return switch EditorCommands.command(id)?.action { 588 return switch EditorCommands.command(id)?.action {
584 case .text(let command): command.applies(in: context) 589 case .text(let command): command.applies(in: context)
585 case .view where id.hasPrefix("org.table."): KeyContext.holds("table", in: context) 590 case .view where id.hasPrefix("org.table."): KeyContext.holds("table", in: context)
591 case .view where id.hasPrefix("org.snippet."): snippetSession != nil
586 case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: context.tree) != nil 592 case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: context.tree) != nil
587 || Wrappers.toggleable(at: context.caret, in: context.tree) != nil 593 || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
588 case .edit, .mark, .app, .find: true 594 case .edit, .mark, .app, .find: true
@@ -596,6 +602,10 @@ public final class OrgEditor: NSObject {
596 /// Runs a command by id, as a key, a menu item or the palette would. 602 /// Runs a command by id, as a key, a menu item or the palette would.
597 public func run(_ id: String) { 603 public func run(_ id: String) {
598 defer { lastCommand = (id, document.revision) } 604 defer { lastCommand = (id, document.revision) }
605 if let snippet = Snippets.command(id), isOrg {
606 perform(snippet)
607 return
608 }
599 guard let command = EditorCommands.command(id) else { 609 guard let command = EditorCommands.command(id) else {
600 fail("Unknown command \(id)") 610 fail("Unknown command \(id)")
601 return 611 return
@@ -624,6 +634,8 @@ public final class OrgEditor: NSObject {
624 case "org.latex-preview": toggleLatex() 634 case "org.latex-preview": toggleLatex()
625 case "editor.toggle-spell-check": toggleSpellCheck() 635 case "editor.toggle-spell-check": toggleSpellCheck()
626 case "editor.complete": completeAtPoint() 636 case "editor.complete": completeAtPoint()
637 case "org.snippet.next-field": nextSnippetField()
638 case "org.snippet.previous-field": previousSnippetField()
627 case "editor.toggle-truncate-lines": toggleTruncateLines() 639 case "editor.toggle-truncate-lines": toggleTruncateLines()
628 case "editor.toggle-auto-fill": toggleAutoFill() 640 case "editor.toggle-auto-fill": toggleAutoFill()
629 case "edit.isearch-forward": startISearch(forward: true) 641 case "edit.isearch-forward": startISearch(forward: true)
@@ -691,6 +703,7 @@ public final class OrgEditor: NSObject {
691 var state = foldState 703 var state = foldState
692 state.folds.insert(start) 704 state.folds.insert(start)
693 setFolds(state) 705 setFolds(state)
706 case .snippet(let session): startSnippet(session)
694 default: onEffect?(effect) 707 default: onEffect?(effect)
695 } 708 }
696 } 709 }
@@ -826,6 +839,7 @@ public final class OrgEditor: NSObject {
826 if let narrowed { self.narrowed = ViewState(selection: [narrowed]).mapped(through: [edit]).selection[0] } 839 if let narrowed { self.narrowed = ViewState(selection: [narrowed]).mapped(through: [edit]).selection[0] }
827 mapVimPositions(through: edit) 840 mapVimPositions(through: edit)
828 vim.changed(edit) 841 vim.changed(edit)
842 snippetEdited(edit)
829 if let sparse = sparseHidden { sparseHidden = ViewState(selection: sparse).mapped(through: [edit]).selection.filter { !$0.isEmpty } } 843 if let sparse = sparseHidden { sparseHidden = ViewState(selection: sparse).mapped(through: [edit]).selection.filter { !$0.isEmpty } }
830 let oldHighlights = ViewState(selection: highlights).mapped(through: [edit]).selection 844 let oldHighlights = ViewState(selection: highlights).mapped(through: [edit]).selection
831 highlights = [] 845 highlights = []
@@ -893,6 +907,7 @@ public final class OrgEditor: NSObject {
893 guard !isLoading else { return } 907 guard !isLoading else { return }
894 let selection = textView.selectedRange() 908 let selection = textView.selectedRange()
895 defer { previousSelection = selection.location } 909 defer { previousSelection = selection.location }
910 snippetSelectionChanged()
896 redrawShadedSelection(selection) 911 redrawShadedSelection(selection)
897 onSelectionChange?(selection) 912 onSelectionChange?(selection)
898 revealCaretLine() 913 revealCaretLine()
Sources/OrgEditorAppKit/ViewToggles.swift +1 · view
@@ -101,6 +101,7 @@ extension OrgEditor: NSTextViewDelegate {
101 } 101 }
102 102
103 public func textDidChange(_ notification: Notification) { 103 public func textDidChange(_ notification: Notification) {
104 updateSnippetMirrors()
104 textTyped() 105 textTyped()
105 } 106 }
106 107
Sources/Orgstar/ContentView.swift +6 · view
@@ -81,6 +81,7 @@ struct ContentView: View {
81 options.agendaFiles = workspace.agendaFilePaths() 81 options.agendaFiles = workspace.agendaFilePaths()
82 options.denoteDirectories = DenoteNote.directories(roots: workspace.rootPaths) 82 options.denoteDirectories = DenoteNote.directories(roots: workspace.rootPaths)
83 options.denoteSequenceScheme = OrgPreferences.denoteSequenceScheme() 83 options.denoteSequenceScheme = OrgPreferences.denoteSequenceScheme()
84 options.snippets = SnippetLibrary.shared.snippets
84 options.timer = TimerModel.shared.timer 85 options.timer = TimerModel.shared.timer
85 return options 86 return options
86 } 87 }
@@ -122,6 +123,7 @@ struct ContentView: View {
122 /// The outline for a file that isn't org, off until asked for. 123 /// The outline for a file that isn't org, off until asked for.
123 @State private var plainOutlineShown = false 124 @State private var plainOutlineShown = false
124 @State private var showingImport = false 125 @State private var showingImport = false
126 @State private var showingTemplate = false
125 @AppStorage("showTabBar") private var showTabBar = false 127 @AppStorage("showTabBar") private var showTabBar = false
126 /// This window's panes. 128 /// This window's panes.
127 @State private var window: WindowModel? 129 @State private var window: WindowModel?
@@ -394,6 +396,9 @@ struct ContentView: View {
394 .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in defaultsChanges += 1 } 396 .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in defaultsChanges += 1 }
395 .onChange(of: preset, initial: true) { loadKeymap() } 397 .onChange(of: preset, initial: true) { loadKeymap() }
396 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) } 398 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
399 .sheet(isPresented: $showingTemplate) {
400 TemplateSheet(workspace: workspace, folder: session.path.map { ($0 as NSString).deletingLastPathComponent }) { selectedFile = $0 }
401 }
397 .sheet(item: $panel) { panel in panelView(panel) } 402 .sheet(item: $panel) { panel in panelView(panel) }
398 .sheet(item: Bindable(ProAccess.shared).paywall) { feature in 403 .sheet(item: Bindable(ProAccess.shared).paywall) { feature in
399 #if APPSTORE 404 #if APPSTORE
@@ -1333,6 +1338,7 @@ struct ContentView: View {
1333 case "app.toggle-markup": showMarkup.toggle() 1338 case "app.toggle-markup": showMarkup.toggle()
1334 case "app.toggle-line-numbers": showLineNumbers.toggle() 1339 case "app.toggle-line-numbers": showLineNumbers.toggle()
1335 case "app.import-emacs": showingImport = true 1340 case "app.import-emacs": showingImport = true
1341 case "app.new-file-from-template": showingTemplate = true
1336 case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0) 1342 case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
1337 case "app.quick-open": commands.showingQuickOpen = true 1343 case "app.quick-open": commands.showingQuickOpen = true
1338 case "app.palette": commands.showingPalette = true 1344 case "app.palette": commands.showingPalette = true
Sources/Orgstar/EmacsImportView.swift +1 · view
@@ -135,6 +135,7 @@ struct EmacsImportView: View {
135 private func footnote(_ result: EmacsImport) -> String { 135 private func footnote(_ result: EmacsImport) -> String {
136 var parts = ["\(result.skipped) variables not about org left alone"] 136 var parts = ["\(result.skipped) variables not about org left alone"]
137 if result.doomDefaultsLeftOut > 0 { parts.append("\(result.doomDefaultsLeftOut) Doom defaults orgstar has no use for") } 137 if result.doomDefaultsLeftOut > 0 { parts.append("\(result.doomDefaultsLeftOut) Doom defaults orgstar has no use for") }
138 if result.snippetsSkipped > 0 { parts.append("\(result.snippetsSkipped) snippets with Emacs Lisp skipped") }
138 #if APPSTORE 139 #if APPSTORE
139 if result.isDoom, !result.doomDefaultsRead { parts.append("Doom's own org defaults skipped") } 140 if result.isDoom, !result.doomDefaultsRead { parts.append("Doom's own org defaults skipped") }
140 #endif 141 #endif
Sources/Orgstar/OrgstarApp.swift +1 · view
@@ -575,6 +575,7 @@ struct OrgstarApp: App {
575 CommandGroup(after: .newItem) { 575 CommandGroup(after: .newItem) {
576 Button("Capture…") { commands.run("app.capture") } 576 Button("Capture…") { commands.run("app.capture") }
577 .keyboardShortcut("n", modifiers: [.command, .shift]) 577 .keyboardShortcut("n", modifiers: [.command, .shift])
578 Button("New File from Template…") { commands.run("app.new-file-from-template") }
578 Button("New Window") { commands.run("app.window-new") } 579 Button("New Window") { commands.run("app.window-new") }
579 .keyboardShortcut("n", modifiers: [.command, .option]) 580 .keyboardShortcut("n", modifiers: [.command, .option])
580 } 581 }
Sources/Orgstar/PaneView.swift +4 −1 · view
@@ -140,10 +140,13 @@ struct PaneView: NSViewRepresentable {
140 NSPasteboard.general.setString(text, forType: .string) 140 NSPasteboard.general.setString(text, forType: .string)
141 case .refreshSetup: session?.refreshSetup() 141 case .refreshSetup: session?.refreshSetup()
142 case .timer(let timer): TimerModel.shared.set(timer) 142 case .timer(let timer): TimerModel.shared.set(timer)
143 case .message, .sparseTree, .fold: break 143 case .message, .sparseTree, .fold, .snippet: break
144 } 144 }
145 } 145 }
146 session.attach(editor, for: path) 146 session.attach(editor, for: path)
147 if let template = SnippetLibrary.shared.takeTemplate(for: path) {
148 DispatchQueue.main.async { editor.perform(ExpandNamedSnippet(snippet: template)) }
149 }
147 return editor 150 return editor
148 } 151 }
149} 152}
Sources/Orgstar/TemplateSheet.swift added +72 · view
@@ -0,0 +1,72 @@
1import OrgApp
2import OrgCore
3import SwiftUI
4
5/// New File from Template…: a template from `snippets.toml`, a folder and a name. The file is
6/// created as New File creates one and opens with the template expanded in it.
7struct TemplateSheet: View {
8 let workspace: WorkspaceModel
9 /// The folder of the file shown, which the folder menu starts on.
10 let folder: String?
11 let open: (String) -> Void
12 @Environment(\.dismiss) private var dismiss
13 @State private var template = ""
14 @State private var chosenFolder = ""
15 @State private var name = ""
16 @State private var failure: String?
17
18 var body: some View {
19 let templates = SnippetLibrary.shared.templates
20 let folders = SnippetLibrary.folders(in: workspace)
21 VStack(alignment: .leading, spacing: 12) {
22 Text("New File from Template").font(.headline)
23 if templates.isEmpty {
24 Text("No templates yet. A snippet in snippets.toml with file = true is one.")
25 .foregroundStyle(.secondary)
26 } else if folders.isEmpty {
27 Text("Add a folder first.").foregroundStyle(.secondary)
28 } else {
29 Form {
30 Picker("Template", selection: $template) {
31 ForEach(templates, id: \.trigger) { Text($0.name).tag($0.trigger) }
32 }
33 Picker("Folder", selection: $chosenFolder) {
34 ForEach(folders, id: \.path) { Text($0.title).tag($0.path) }
35 }
36 TextField("Name", text: $name)
37 }
38 Text("A name without an extension gets .org. Use folder/name to make folders.")
39 .font(.caption).foregroundStyle(.secondary)
40 }
41 if let failure {
42 Text(failure).font(.caption).foregroundStyle(.red)
43 }
44 HStack {
45 Spacer()
46 Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction)
47 Button("Create") { create() }
48 .keyboardShortcut(.defaultAction)
49 .disabled(templates.isEmpty || folders.isEmpty || name.trimmingCharacters(in: .whitespaces).isEmpty)
50 }
51 }
52 .padding(20)
53 .frame(width: 440)
54 .onAppear {
55 template = templates.first?.trigger ?? ""
56 chosenFolder = folders.first { $0.path == folder }?.path ?? folders.first?.path ?? ""
57 }
58 }
59
60 private func create() {
61 guard let chosen = SnippetLibrary.shared.templates.first(where: { $0.trigger == template }) else { return }
62 Task {
63 do {
64 let path = try await SnippetLibrary.shared.createFile(named: name, in: chosenFolder, from: chosen, workspace: workspace)
65 dismiss()
66 open(path)
67 } catch {
68 failure = error.localizedDescription
69 }
70 }
71 }
72}
Sources/OrgstarMobile/EditorScreen.swift +1 · view
@@ -444,6 +444,7 @@ struct EditorScreen: View {
444 self.editor = editor 444 self.editor = editor
445 textView = view 445 textView = view
446 if let offset { editor.reveal(offset) } 446 if let offset { editor.reveal(offset) }
447 if let template = SnippetLibrary.shared.takeTemplate(for: path) { DispatchQueue.main.async { _ = editor.perform(ExpandNamedSnippet(snippet: template)) } }
447 if pane.conflict != nil { 448 if pane.conflict != nil {
448 sheet = .conflict 449 sheet = .conflict
449 } else if case let copies = session.syncConflictCopies().count, copies > 0 { 450 } else if case let copies = session.syncConflictCopies().count, copies > 0 {
Sources/OrgstarMobile/FoldersScreen.swift +6 · view
@@ -12,6 +12,7 @@ struct FoldersScreen: View {
12 /// Counts deletions and new folders, so the list reads the empty folders on disk again. 12 /// Counts deletions and new folders, so the list reads the empty folders on disk again.
13 @State private var changes = 0 13 @State private var changes = 0
14 @State private var creating: NewItem? 14 @State private var creating: NewItem?
15 @State private var templating: TemplateFolder?
15 /// The added folder whose deletion from disk is being confirmed. 16 /// The added folder whose deletion from disk is being confirmed.
16 @State private var deletingRoot: String? 17 @State private var deletingRoot: String?
17 /// The added folder whose removal from orgstar is being confirmed. 18 /// The added folder whose removal from orgstar is being confirmed.
@@ -79,6 +80,7 @@ struct FoldersScreen: View {
79 } 80 }
80 .confirmDeletion($deleting, workspace: workspace, session: session) { changes += 1 } 81 .confirmDeletion($deleting, workspace: workspace, session: session) { changes += 1 }
81 .createItem($creating, workspace: workspace) { changes += 1 } 82 .createItem($creating, workspace: workspace) { changes += 1 }
83 .newFromTemplate($templating, workspace: workspace, session: session)
82 .overlay { 84 .overlay {
83 if workspace.rootPaths.isEmpty { 85 if workspace.rootPaths.isEmpty {
84 ContentUnavailableView { 86 ContentUnavailableView {
@@ -153,6 +155,7 @@ struct FolderPage: View {
153 @State private var deleting: String? 155 @State private var deleting: String?
154 @State private var changes = 0 156 @State private var changes = 0
155 @State private var creating: NewItem? 157 @State private var creating: NewItem?
158 @State private var templating: TemplateFolder?
156 159
157 var body: some View { 160 var body: some View {
158 let folder = route.folder.isEmpty ? route.root : route.root + "/" + route.folder 161 let folder = route.folder.isEmpty ? route.root : route.root + "/" + route.folder
@@ -160,10 +163,12 @@ struct FolderPage: View {
160 .navigationTitle(((route.folder.isEmpty ? route.root : route.folder) as NSString).lastPathComponent) 163 .navigationTitle(((route.folder.isEmpty ? route.root : route.folder) as NSString).lastPathComponent)
161 .confirmDeletion($deleting, workspace: workspace, session: session) { changes += 1 } 164 .confirmDeletion($deleting, workspace: workspace, session: session) { changes += 1 }
162 .createItem($creating, workspace: workspace) { changes += 1 } 165 .createItem($creating, workspace: workspace) { changes += 1 }
166 .newFromTemplate($templating, workspace: workspace, session: session)
163 .toolbar { 167 .toolbar {
164 ToolbarItem(placement: .primaryAction) { 168 ToolbarItem(placement: .primaryAction) {
165 Menu("New", systemImage: "plus") { 169 Menu("New", systemImage: "plus") {
166 Button("New File…", systemImage: "doc.badge.plus") { creating = NewItem(folder: folder, isFolder: false) } 170 Button("New File…", systemImage: "doc.badge.plus") { creating = NewItem(folder: folder, isFolder: false) }
171 Button("New File from Template…", systemImage: "doc.on.doc") { templating = TemplateFolder(path: folder) }
167 Button("New Folder…", systemImage: "folder.badge.plus") { creating = NewItem(folder: folder, isFolder: true) } 172 Button("New Folder…", systemImage: "folder.badge.plus") { creating = NewItem(folder: folder, isFolder: true) }
168 } 173 }
169 } 174 }
@@ -255,6 +260,7 @@ extension FoldersScreen {
255 @ViewBuilder 260 @ViewBuilder
256 private func newItems(in folder: String) -> some View { 261 private func newItems(in folder: String) -> some View {
257 Button("New File…", systemImage: "doc.badge.plus") { creating = NewItem(folder: folder, isFolder: false) } 262 Button("New File…", systemImage: "doc.badge.plus") { creating = NewItem(folder: folder, isFolder: false) }
263 Button("New File from Template…", systemImage: "doc.on.doc") { templating = TemplateFolder(path: folder) }
258 Button("New Folder…", systemImage: "folder.badge.plus") { creating = NewItem(folder: folder, isFolder: true) } 264 Button("New Folder…", systemImage: "folder.badge.plus") { creating = NewItem(folder: folder, isFolder: true) }
259 } 265 }
260} 266}
Sources/OrgstarMobile/MobileEditor+Display.swift +1 · view
@@ -266,6 +266,7 @@ extension MobileEditor {
266 func selectionChanged() { 266 func selectionChanged() {
267 let interval = Perf.begin("editor.selection") 267 let interval = Perf.begin("editor.selection")
268 defer { interval.end() } 268 defer { interval.end() }
269 snippetSelectionChanged()
269 redrawSelectedBlocks() 270 redrawSelectedBlocks()
270 let caret = textView.selectedRange.location 271 let caret = textView.selectedRange.location
271 defer { 272 defer {
Sources/OrgstarMobile/MobileEditor+Modal.swift +2 · view
@@ -27,6 +27,7 @@ extension MobileEditor {
27 updateCursor() 27 updateCursor()
28 return true 28 return true
29 } 29 }
30 if keys.count == 1, vim.mode == .insert, snippetTab(chord) { return true }
30 return feedVim(keys) 31 return feedVim(keys)
31 case .undefined(let keys): 32 case .undefined(let keys):
32 // The leader and Emacs prefixes mean nothing to evil, as on the Mac. 33 // The leader and Emacs prefixes mean nothing to evil, as on the Mac.
@@ -36,6 +37,7 @@ extension MobileEditor {
36 } 37 }
37 return feedVim(keys) 38 return feedVim(keys)
38 case .unbound: 39 case .unbound:
40 if vim.mode == .insert, snippetTab(chord) { return true }
39 return feedVim([chord]) 41 return feedVim([chord])
40 } 42 }
41 } 43 }
Sources/OrgstarMobile/MobileEditor+Snippets.swift added +140 · view
@@ -0,0 +1,140 @@
1#if os(iOS)
2import OrgCore
3import UIKit
4
5/// Snippets, as on the Mac: TAB on a hardware keyboard after a trigger where TAB means nothing
6/// else expands it, then TAB and S-TAB (or `org.snippet.next-field` and
7/// `org.snippet.previous-field`) move between its fields. Leaving the last field, Escape, or
8/// the caret or an edit leaving the snippet ends it.
9extension MobileEditor {
10 /// TAB with no binding that runs here: expands the trigger before the caret, if any.
11 func snippetTab(_ chord: KeyChord) -> Bool {
12 guard chord == KeyChord("TAB"), textView.markedTextRange == nil else { return false }
13 let expand = ExpandSnippet()
14 guard expand.applies(in: editContext()) else { return false }
15 _ = perform(expand)
16 return true
17 }
18
19 /// Keys while a snippet's fields are filled in; nil lets the key through.
20 func snippetKey(_ chord: KeyChord) -> Bool? {
21 guard snippetSession != nil else { return nil }
22 switch chord {
23 case KeyChord("TAB"):
24 nextSnippetField()
25 return true
26 case KeyChord("TAB", .shift):
27 previousSnippetField()
28 return true
29 case KeyChord("ESC"):
30 endSnippet()
31 return modal ? nil : true
32 default:
33 return nil
34 }
35 }
36
37 func nextSnippetField() {
38 guard var session = snippetSession else { return }
39 switch session.next() {
40 case .field(let range):
41 snippetSession = session
42 selectSnippet(range)
43 case .exit(let range):
44 endSnippet()
45 selectSnippet(range)
46 }
47 }
48
49 func previousSnippetField() {
50 guard var session = snippetSession else { return }
51 let range = session.previous()
52 snippetSession = session
53 selectSnippet(range)
54 }
55
56 func startSnippet(_ session: SnippetSession) {
57 snippetSession = session
58 highlightSnippet()
59 }
60
61 func endSnippet() {
62 snippetSession = nil
63 highlightSnippet()
64 }
65
66 private func selectSnippet(_ range: Range<Int>) {
67 unfold(around: range.lowerBound)
68 textView.selectedRange = NSRange(range)
69 textView.scrollRangeToVisible(textView.selectedRange)
70 highlightSnippet()
71 }
72
73 /// An edit of the buffer; one outside the snippet ends it.
74 func snippetEdited(_ edit: TextEdit) {
75 guard var session = snippetSession else { return }
76 snippetSession = session.map(edit) ? session : nil
77 }
78
79 /// After typing: mirrors take their field's new text.
80 func updateSnippetMirrors() {
81 guard let session = snippetSession, !updatingMirrors, textView.markedTextRange == nil else { return highlightSnippet() }
82 let edits = session.mirrorEdits(in: document.text)
83 if !edits.isEmpty {
84 updatingMirrors = true
85 let selected = textView.selectedRange
86 applyEdits(edits)
87 updatingMirrors = false
88 let shift = edits.filter { $0.range.upperBound <= selected.location }.reduce(0) { $0 + $1.replacement.utf16.count - $1.range.count }
89 textView.selectedRange = NSRange(location: selected.location + shift, length: selected.length)
90 }
91 highlightSnippet()
92 }
93
94 /// The caret moved: outside the snippet, it ends.
95 func snippetSelectionChanged() {
96 guard let session = snippetSession, !updatingMirrors else { return }
97 let selected = textView.selectedRange
98 if !session.contains(selected.location) || !session.contains(NSMaxRange(selected)) { endSnippet() }
99 }
100
101 /// Draws the active field with a band and the others with a fainter one.
102 func highlightSnippet() {
103 let length = (textView.textStorage.string as NSString).length
104 var covered = snippetHighlight.flatMap { $0.upperBound <= length ? $0 : $0.lowerBound < length ? $0.lowerBound..<length : nil }
105 if let extent = snippetSession?.extent, extent.upperBound <= length {
106 covered = covered.map { min($0.lowerBound, extent.lowerBound)..<max($0.upperBound, extent.upperBound) } ?? extent
107 }
108 for manager in layoutManagers {
109 func textRange(_ r: Range<Int>) -> NSTextRange? {
110 guard let content = manager.textContentManager,
111 let start = content.location(content.documentRange.location, offsetBy: r.lowerBound),
112 let end = content.location(start, offsetBy: r.count) else { return nil }
113 return NSTextRange(location: start, end: end)
114 }
115 if let covered, let range = textRange(covered) {
116 manager.removeRenderingAttribute(.backgroundColor, for: range)
117 }
118 guard let session = snippetSession else { continue }
119 for (index, field) in session.fields.enumerated() {
120 for (n, r) in field.ranges.enumerated() where !r.isEmpty && r.upperBound <= length {
121 guard let range = textRange(r) else { continue }
122 if index == session.active, n == 0 {
123 manager.addRenderingAttribute(.backgroundColor, value: UIColor.systemYellow.withAlphaComponent(0.3), for: range)
124 } else {
125 manager.addRenderingAttribute(.backgroundColor, value: UIColor.systemGray.withAlphaComponent(0.2), for: range)
126 }
127 }
128 }
129 }
130 snippetHighlight = snippetSession?.extent
131 }
132}
133
134extension MobileEditor {
135 func textViewDidChange(_ textView: UITextView) {
136 guard textView === self.textView else { return }
137 updateSnippetMirrors()
138 }
139}
140#endif
Sources/OrgstarMobile/MobileEditor.swift +17 −3 · view
@@ -166,6 +166,10 @@ final class MobileEditor: NSObject, DocumentBuffer {
166 var shrunk = ShrunkColumns() 166 var shrunk = ShrunkColumns()
167 /// A command's edits being applied, which keep shrunk columns narrow. 167 /// A command's edits being applied, which keep shrunk columns narrow.
168 private var commandEditing = false 168 private var commandEditing = false
169 /// The snippet whose fields are being filled in, and the range drawn for it last.
170 var snippetSession: SnippetSession?
171 var snippetHighlight: Range<Int>?
172 var updatingMirrors = false
169 173
170 init( 174 init(
171 document: DocumentState, editable: Bool, options: EditingOptions = .org, theme spec: ThemeSpec = .default, 175 document: DocumentState, editable: Bool, options: EditingOptions = .org, theme spec: ThemeSpec = .default,
@@ -339,6 +343,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
339 setFolds(state) 343 setFolds(state)
340 case .refreshSetup: onRefreshSetup?() 344 case .refreshSetup: onRefreshSetup?()
341 case .timer(let timer): TimerModel.shared.set(timer) 345 case .timer(let timer): TimerModel.shared.set(timer)
346 case .snippet(let session): startSnippet(session)
342 default: break 347 default: break
343 } 348 }
344 } 349 }
@@ -409,7 +414,13 @@ final class MobileEditor: NSObject, DocumentBuffer {
409 } 414 }
410 415
411 func run(_ id: String) { 416 func run(_ id: String) {
417 if let snippet = Snippets.command(id) {
418 _ = perform(snippet)
419 return
420 }
412 switch id { 421 switch id {
422 case "org.snippet.next-field": nextSnippetField()
423 case "org.snippet.previous-field": previousSnippetField()
413 case "org.cycle": 424 case "org.cycle":
414 if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") } 425 if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
415 case "org.cycle-global": cycleGlobal() 426 case "org.cycle-global": cycleGlobal()
@@ -447,8 +458,9 @@ final class MobileEditor: NSObject, DocumentBuffer {
447 static let linkCommands: Set<String> = ["org.link.store", "org.id.store-link", "org.link.insert"] 458 static let linkCommands: Set<String> = ["org.link.store", "org.id.store-link", "org.link.insert"]
448 459
449 func applies(_ id: String, in context: EditContext) -> Bool { 460 func applies(_ id: String, in context: EditContext) -> Bool {
450 if let command = Commands.command(id) { return command.applies(in: context) } 461 if let command = Commands.command(id) ?? Snippets.command(id) { return command.applies(in: context) }
451 switch id { 462 switch id {
463 case "org.snippet.next-field", "org.snippet.previous-field": return snippetSession != nil
452 case "org.cycle": 464 case "org.cycle":
453 return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil 465 return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
454 case _ where id.hasPrefix("org.fold."): return true 466 case _ where id.hasPrefix("org.fold."): return true
@@ -524,6 +536,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
524 } 536 }
525 } 537 }
526 if isearch != nil, isearchKey(chord) { return true } 538 if isearch != nil, isearchKey(chord) { return true }
539 if let handled = snippetKey(chord) { return handled }
527 if modal { return handleModal(chord) } 540 if modal { return handleModal(chord) }
528 // Option alone types characters unless it begins a binding. 541 // Option alone types characters unless it begins a binding.
529 if chord.modifiers == [.meta], dispatcher.pending.isEmpty, 542 if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
@@ -539,7 +552,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
539 fail("\(KeySequence.format(keys)) is undefined") 552 fail("\(KeySequence.format(keys)) is undefined")
540 return true 553 return true
541 case .unbound: 554 case .unbound:
542 return false 555 return snippetTab(chord)
543 case .complete(let keys, let candidates): 556 case .complete(let keys, let candidates):
544 let context = editContext() 557 let context = editContext()
545 let runnable = candidates.first { binding in 558 let runnable = candidates.first { binding in
@@ -547,7 +560,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
547 } 560 }
548 // A sequence runs its command even where it doesn't apply, which says why, as on the Mac. 561 // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
549 let argument = dispatcher.argument != nil 562 let argument = dispatcher.argument != nil
550 guard let binding = runnable ?? (keys.count > 1 || argument ? candidates.first : nil) else { return false } 563 guard let binding = runnable ?? (keys.count > 1 || argument ? candidates.first : nil) else { return keys.count == 1 && !argument && snippetTab(chord) }
551 // A prefix argument (C-u, C-u 3) counts keyboard macros only. 564 // A prefix argument (C-u, C-u 3) counts keyboard macros only.
552 if argument, !binding.command.hasPrefix("macro.") { 565 if argument, !binding.command.hasPrefix("macro.") {
553 fail("\(KeySequence.format(keys)) doesn't take a prefix argument") 566 fail("\(KeySequence.format(keys)) doesn't take a prefix argument")
@@ -619,6 +632,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
619 let old = range.location..<(range.location + range.length - delta) 632 let old = range.location..<(range.location + range.length - delta)
620 let replacement = (textView.textStorage.string as NSString).substring(with: range) 633 let replacement = (textView.textStorage.string as NSString).substring(with: range)
621 let edit = TextEdit(range: old, replacement: replacement) 634 let edit = TextEdit(range: old, replacement: replacement)
635 snippetEdited(edit)
622 let oldTree = document.tree 636 let oldTree = document.tree
623 let oldText = document.text as NSString 637 let oldText = document.text as NSString
624 do { 638 do {
Sources/OrgstarMobile/MobileModel.swift +3 · view
@@ -148,9 +148,12 @@ final class MobileModel {
148 modalKeys = preset.isModal 148 modalKeys = preset.isModal
149 configProblems += loaded.problems.map { "keymap.toml: " + $0 } 149 configProblems += loaded.problems.map { "keymap.toml: " + $0 }
150 configProblems += MacroFile.load().map { "\(NamedMacros.fileName): " + $0 } 150 configProblems += MacroFile.load().map { "\(NamedMacros.fileName): " + $0 }
151 SnippetLibrary.shared.reload(from: UserConfig.file(Snippets.fileName), read: configFolder == nil ? { try? String(contentsOf: $0, encoding: .utf8) } : Self.read)
152 configProblems += SnippetLibrary.shared.problems
151 let settings = OrgPreferences.orgSettings() 153 let settings = OrgPreferences.orgSettings()
152 session.defaults = settings 154 session.defaults = settings
153 session.options = OrgPreferences.options() 155 session.options = OrgPreferences.options()
156 session.options.snippets = SnippetLibrary.shared.snippets
154 workspace?.settings = .with(todoKeywords: settings) 157 workspace?.settings = .with(todoKeywords: settings)
155 if let agenda { 158 if let agenda {
156 agenda.span = OrgPreferences.agendaSpan() 159 agenda.span = OrgPreferences.agendaSpan()
Sources/OrgstarMobile/TemplateScreen.swift added +96 · view
@@ -0,0 +1,96 @@
1#if os(iOS)
2import OrgApp
3import OrgCore
4import SwiftUI
5
6/// A folder New File from Template… creates its file in.
7struct TemplateFolder: Identifiable {
8 let path: String
9 var id: String { path }
10}
11
12/// New File from Template…: a template from `snippets.toml` and a name. The file is created in
13/// the folder as New File creates one, and opens in the editor with the template expanded.
14struct TemplateScreen: View {
15 let folder: String
16 let workspace: WorkspaceModel
17 let created: (String) -> Void
18 @State private var template = ""
19 @State private var name = ""
20 @State private var failure: String?
21 @Environment(\.dismiss) private var dismiss
22
23 var body: some View {
24 let templates = SnippetLibrary.shared.templates
25 NavigationStack {
26 Form {
27 if templates.isEmpty {
28 Text("No templates yet. A snippet in snippets.toml with file = true is one.")
29 .foregroundStyle(.secondary)
30 } else {
31 Picker("Template", selection: $template) {
32 ForEach(templates, id: \.trigger) { Text($0.name).tag($0.trigger) }
33 }
34 Section {
35 TextField("Name", text: $name)
36 .autocorrectionDisabled()
37 .textInputAutocapitalization(.never)
38 } footer: {
39 Text("A name without an extension gets .org.")
40 }
41 }
42 if let failure {
43 Text(failure).foregroundStyle(.red)
44 }
45 }
46 .navigationTitle((folder as NSString).lastPathComponent)
47 .navigationBarTitleDisplayMode(.inline)
48 .toolbar {
49 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
50 ToolbarItem(placement: .confirmationAction) {
51 Button("Create") { create() }
52 .disabled(templates.isEmpty || name.trimmingCharacters(in: .whitespaces).isEmpty)
53 }
54 }
55 .onAppear { if template.isEmpty { template = templates.first?.trigger ?? "" } }
56 }
57 }
58
59 private func create() {
60 guard let chosen = SnippetLibrary.shared.templates.first(where: { $0.trigger == template }) else { return }
61 Task {
62 do {
63 let path = try await SnippetLibrary.shared.createFile(named: name, in: folder, from: chosen, workspace: workspace)
64 dismiss()
65 created(path)
66 } catch {
67 failure = error.localizedDescription
68 }
69 }
70 }
71}
72
73/// The template sheet for `folder`, and the editor the new file opens in.
74private struct NewFromTemplate: ViewModifier {
75 @Binding var folder: TemplateFolder?
76 let workspace: WorkspaceModel
77 let session: DocumentSession
78 @State private var editing: EditorRoute?
79
80 func body(content: Content) -> some View {
81 content
82 .sheet(item: $folder) { folder in
83 TemplateScreen(folder: folder.path, workspace: workspace) { editing = EditorRoute(path: $0, offset: nil) }
84 }
85 .navigationDestination(item: $editing) { route in
86 EditorSplitScreen(path: route.path, offset: nil, workspace: workspace, session: session)
87 }
88 }
89}
90
91extension View {
92 func newFromTemplate(_ folder: Binding<TemplateFolder?>, workspace: WorkspaceModel, session: DocumentSession) -> some View {
93 modifier(NewFromTemplate(folder: folder, workspace: workspace, session: session))
94 }
95}
96#endif
Tests/OrgAppTests/ConfigFolderTests.swift +19 · view
@@ -80,6 +80,25 @@ struct ConfigFolderTests {
80 #expect(try String(contentsOf: second.appendingPathComponent("config.toml"), encoding: .utf8).contains("fill-column = 64")) 80 #expect(try String(contentsOf: second.appendingPathComponent("config.toml"), encoding: .utf8).contains("fill-column = 64"))
81 } 81 }
82 82
83 @Test func readsSnippetsBesideTheFile() throws {
84 let first = try folder()
85 let second = try folder()
86 defer {
87 try? FileManager.default.removeItem(at: first)
88 try? FileManager.default.removeItem(at: second)
89 }
90 try "[[snippet]]\ntrigger = \"d\"\nbody = \"%t\"\n".write(to: first.appendingPathComponent("snippets.toml"), atomically: true, encoding: .utf8)
91 try "[[snippet]]\ntrigger = \"d\n".write(to: second.appendingPathComponent("snippets.toml"), atomically: true, encoding: .utf8)
92 let library = SnippetLibrary()
93 let sync = ConfigSync(url: first.appendingPathComponent("config.toml"), defaults: defaults(), snippets: library)
94 sync.start(watch: false)
95 #expect(library.snippets.map(\.trigger) == ["d"] && sync.problems.isEmpty)
96 // A broken file is reported, and the snippets read before stay.
97 sync.move(to: second.appendingPathComponent("config.toml"))
98 #expect(library.snippets.map(\.trigger) == ["d"])
99 #expect(sync.problems == ["snippets.toml line 2: unclosed string"])
100 }
101
83 @Test func movingBeforeStartDoesNothing() throws { 102 @Test func movingBeforeStartDoesNothing() throws {
84 let first = try folder() 103 let first = try folder()
85 let second = try folder() 104 let second = try folder()
Tests/OrgAppTests/SnippetLibraryTests.swift added +77 · view
@@ -0,0 +1,77 @@
1import Foundation
2import OrgCore
3import Testing
4@testable import OrgApp
5
6@MainActor
7struct SnippetLibraryTests {
8 @Test func aBrokenFileKeepsTheSnippetsReadBefore() {
9 let library = SnippetLibrary()
10 var text: String? = "[[snippet]]\ntrigger = \"a\"\nbody = \"one\"\n[[snippet]]\ntrigger = \"b\"\n"
11 let file = URL(fileURLWithPath: "/nowhere/snippets.toml")
12 library.reload(from: file) { _ in text }
13 #expect(library.snippets.map(\.trigger) == ["a"])
14 #expect(library.problems == ["snippets.toml line 4: a snippet needs trigger and body"])
15 text = "[[snippet]]\ntrigger = \"c\nbody = \"two\"\n"
16 library.reload(from: file) { _ in text }
17 #expect(library.snippets.map(\.trigger) == ["a"])
18 #expect(library.problems == ["snippets.toml line 2: unclosed string"])
19 text = nil
20 library.reload(from: file) { _ in text }
21 #expect(library.snippets.isEmpty && library.problems.isEmpty)
22 }
23
24 @Test func templatesWaitForTheirFile() {
25 let library = SnippetLibrary()
26 let template = Snippet(trigger: "week", body: "#+title: %t\n", file: true)
27 library.expand(template, intoNewFile: "/tmp/notes/../notes/week.org")
28 #expect(library.takeTemplate(for: "/tmp/other.org") == nil)
29 #expect(library.takeTemplate(for: "/tmp/notes/week.org") == template)
30 #expect(library.takeTemplate(for: "/tmp/notes/week.org") == nil)
31 }
32
33 // MARK: - yasnippet
34
35 @Test func readsYasnippetFiles() {
36 let meeting = EmacsImport.yasnippet("# -*- mode: snippet -*-\n# name: Meeting\n# key: meet\n# --\n* Meeting ${1:x}\n$0\n", fileName: "meeting")
37 #expect(meeting == EmacsImport.Yasnippet(key: "meet", name: "Meeting", body: "* Meeting ${1:x}\n$0\n", lisp: nil))
38 // No header: the file name is the key, as yasnippet has it.
39 #expect(EmacsImport.yasnippet("plain $0", fileName: "pl").key == "pl")
40 #expect(EmacsImport.yasnippet("# key: d\n# --\n`(format-time-string \"%F\")`", fileName: "d").lisp != nil)
41 #expect(EmacsImport.yasnippet("# key: d\n# --\n\\`quoted\\`", fileName: "d").lisp == nil)
42 #expect(EmacsImport.yasnippet("# key: u\n# --\n${1:x} ${1:$(upcase yas-text)}", fileName: "u").lisp != nil)
43 #expect(EmacsImport.yasnippet("# key: c\n# type: command\n# --\n(insert \"x\")", fileName: "c").lisp != nil)
44 // The table reads back as the same snippet.
45 let parsed = try? Snippets.parse(EmacsImport.snippetTable(meeting))
46 #expect(parsed?.snippets == [Snippet(trigger: "meet", name: "Meeting", body: "* Meeting ${1:x}\n$0\n")])
47 let quotes = EmacsImport.Yasnippet(key: "q", name: "q", body: "a ''' b\n", lisp: nil)
48 #expect((try? Snippets.parse(EmacsImport.snippetTable(quotes)))?.snippets.first?.body == "a ''' b\n")
49 }
50
51 @Test func importsSnippetsBesideTheConfiguration() async throws {
52 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-snippets-\(UUID().uuidString)")
53 defer { try? FileManager.default.removeItem(at: folder) }
54 let snippets = folder.appendingPathComponent("snippets/org-mode")
55 try FileManager.default.createDirectory(at: snippets, withIntermediateDirectories: true)
56 try "(setq org-tags-column 0)".write(to: folder.appendingPathComponent("config.el"), atomically: true, encoding: .utf8)
57 try "# name: Meeting\n# key: meet\n# --\n* Meeting ${1:x}\n".write(to: snippets.appendingPathComponent("meeting"), atomically: true, encoding: .utf8)
58 try "# key: now\n# --\n`(current-time-string)`".write(to: snippets.appendingPathComponent("now"), atomically: true, encoding: .utf8)
59 try "org-mode".write(to: snippets.appendingPathComponent(".yas-parents"), atomically: true, encoding: .utf8)
60 let result = EmacsImport.scan(EmacsImport.files(in: folder), doomDefaults: [])
61 let found = result.items.filter { if case .snippet = $0.change { true } else { false } }
62 #expect(found.map(\.name) == ["meet"] && found.first?.source == "snippets/org-mode/meeting")
63 #expect(result.snippetsSkipped == 1 && result.unsupported.contains { $0.name == "snippet now" })
64 #expect(Set(result.items.map(\.id) + result.unsupported.map(\.id)).count == result.items.count + result.unsupported.count)
65
66 let out = folder.appendingPathComponent("out")
67 try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)
68 try "[[snippet]]\ntrigger = \"meet\"\nbody = \"mine\"\n".write(to: out.appendingPathComponent("snippets.toml"), atomically: true, encoding: .utf8)
69 let first = await EmacsImport.apply(found, defaults: TestDefaults("orgstar-snippets"), workspace: nil, directory: out)
70 #expect(first == "Nothing new to import.")
71 try FileManager.default.removeItem(at: out.appendingPathComponent("snippets.toml"))
72 let summary = await EmacsImport.apply(found, defaults: TestDefaults("orgstar-snippets"), workspace: nil, directory: out)
73 #expect(summary == "Imported 1 snippet.")
74 let written = try String(contentsOf: out.appendingPathComponent("snippets.toml"), encoding: .utf8)
75 #expect(try Snippets.parse(written).snippets == [Snippet(trigger: "meet", name: "Meeting", body: "* Meeting ${1:x}\n")])
76 }
77}
Tests/OrgCoreTests/SnippetTests.swift added +393 · view
@@ -0,0 +1,393 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct SnippetTests {
6 static let utc: Calendar = {
7 var calendar = Calendar(identifier: .gregorian)
8 calendar.timeZone = TimeZone(identifier: "UTC")!
9 return calendar
10 }()
11 /// Wednesday 2026-11-25 09:30 UTC.
12 static let now = Date(timeIntervalSince1970: 1_795_599_000)
13
14 func capture() -> CaptureContext { CaptureContext(now: Self.now, calendar: Self.utc) }
15
16 func expand(_ body: String, answers: [String] = [], indentation: String = "") throws -> SnippetExpansion {
17 try Snippets.expand(Snippet(trigger: "t", body: body), context: capture(), answers: answers, indentation: indentation).get()
18 }
19
20 func text(_ expansion: SnippetExpansion, _ range: Range<Int>) -> String {
21 (expansion.text as NSString).substring(with: NSRange(range))
22 }
23
24 // MARK: - snippets.toml
25
26 @Test func readsAFile() throws {
27 let (snippets, problems) = try Snippets.parse(#"""
28 # Comments are fine.
29 [[snippet]]
30 trigger = "meet"
31 description = "Meeting notes"
32 body = """
33 * Meeting with ${1:someone} %U
34 - $0
35 """
36
37 [[snippet]]
38 trigger = "day"
39 body = '%<%A>'
40
41 [[snippet]]
42 trigger = "weekly"
43 description = "Weekly review"
44 file = true
45 body = '''
46 #+title: Week of %t
47 '''
48 """#)
49 #expect(problems.isEmpty)
50 #expect(snippets == [
51 Snippet(trigger: "meet", name: "Meeting notes", body: "* Meeting with ${1:someone} %U\n- $0\n"),
52 Snippet(trigger: "day", body: "%<%A>"),
53 Snippet(trigger: "weekly", name: "Weekly review", body: "#+title: Week of %t\n", file: true),
54 ])
55 #expect(snippets[2].commandID == "org.snippet:weekly" && Snippets.trigger(ofCommand: "org.snippet:weekly") == "weekly")
56 }
57
58 @Test func reportsWhereAFileIsWrong() throws {
59 #expect(throws: TOML.ParseError(line: 3, message: "unclosed string")) {
60 try Snippets.parse("[[snippet]]\ntrigger = \"a\"\nbody = \"\"\"\nnever closed\n")
61 }
62 #expect(throws: TOML.ParseError(line: 2, message: "unclosed string")) { try Snippets.parse("[[snippet]]\ntrigger = \"a\n") }
63 let (snippets, problems) = try Snippets.parse("""
64 [[snippet]]
65 trigger = "ok"
66 body = "fine"
67 [[snippet]]
68 body = "no trigger"
69 [[snippet]]
70 trigger = "two words"
71 body = "x"
72 [[snippet]]
73 trigger = "lisp"
74 body = "${1:$(upcase yas-text)}"
75 [[snippet]]
76 trigger = "open"
77 body = "${1:never closed"
78 [[snippet]]
79 trigger = "ok"
80 body = "again"
81 [snippets]
82 """)
83 #expect(snippets.map(\.trigger) == ["ok"])
84 #expect(problems == [
85 "line 4: a snippet needs trigger and body", "line 6: a trigger has no spaces",
86 "line 9: Emacs Lisp in a field isn't supported", "line 12: a ${ isn't closed",
87 "line 15: trigger ok is used twice", "line 18: expected [[snippet]]",
88 ])
89 }
90
91 @Test func multilineStringsFollowTOML() throws {
92 let tables = try TOML.parse("a = \"\"\"\none \\\n two\\tthree\"\"\"\nb = '''x\\n'''\nc = \"\"\"same line\"\"\" # note\n")
93 #expect(tables[0].values["a"] == .string("one two\tthree"))
94 #expect(tables[0].values["b"] == .string("x\\n"))
95 #expect(tables[0].values["c"] == .string("same line"))
96 }
97
98 // MARK: - Bodies
99
100 @Test func fieldsDefaultsAndMirrors() throws {
101 let e = try expand("a ${1:foo} b $1 c ${2:bar} $0 d")
102 #expect(e.text == "a foo b foo c bar d")
103 #expect(e.fields.map(\.number) == [1, 2])
104 #expect(e.fields[0].ranges.map { text(e, $0) } == ["foo", "foo"])
105 #expect(e.fields[0].ranges[0] == 2..<5 && e.fields[0].ranges[1] == 8..<11)
106 #expect(text(e, e.fields[1].ranges[0]) == "bar" && e.fields[1].ranges.count == 1)
107 #expect(e.exit == 18..<18)
108 }
109
110 @Test func theFieldIsTheOccurrenceWithADefault() throws {
111 // As yasnippet: `$1` before `${1:x}` mirrors it.
112 let e = try expand("$1 then ${1:x}")
113 #expect(e.text == "x then x")
114 #expect(e.fields[0].ranges == [7..<8, 0..<1])
115 let empty = try expand("$2 and $2")
116 #expect(empty.text == " and " && empty.fields[0].ranges == [0..<0, 5..<5])
117 }
118
119 @Test func escapesAndExits() throws {
120 #expect(try expand(#"cost \$1 \\ ${1:x\}y} $1"#).text == #"cost $1 \ x}y x}y"#)
121 #expect(try expand("no fields").exit == 9..<9)
122 let selected = try expand("${0:end} $1")
123 #expect(text(selected, selected.exit) == "end")
124 // `%?` of capture is the exit too.
125 #expect(try expand("ab%?cd").exit == 2..<2)
126 // Tabs and blank lines stay as written.
127 #expect(try expand("\n\tx $1\n\n").text == "\n\tx \n\n")
128 }
129
130 @Test func captureEscapesFill() throws {
131 #expect(try expand("%t %U %<%A>").text == "<2026-11-25 Wed> [2026-11-25 Wed 09:30] Wednesday")
132 #expect(try expand("${1:%u} $1").text == "[2026-11-25 Wed] [2026-11-25 Wed]")
133 // An escaped escape stays.
134 #expect(try expand(#"\%t"#).text == "%t")
135 }
136
137 @Test func promptsAreAskedInOrder() throws {
138 let snippet = Snippet(trigger: "p", body: "* %^{Title} $1\n%^{Where|home|home|work} %^t %\\1")
139 let questions = Snippets.questions(snippet, context: capture())
140 #expect(questions.map(\.prompt) == ["Title", "Where", "Date"])
141 #expect(questions[1].defaultValue == "home" && questions[1].choices == ["home", "work"])
142 #expect(Snippets.prompt(questions[2], key: "snippet-2").date == .init(defaultDate: nil))
143 let e = try Snippets.expand(snippet, context: capture(), answers: ["Plan", "", "+1d"]).get()
144 #expect(e.text == "* Plan \nhome <2026-11-26 Thu> Plan")
145 #expect(e.fields[0].ranges == [7..<7])
146 }
147
148 @Test func linesAfterTheFirstTakeTheIndentation() throws {
149 let e = try expand("- ${1:a}\n- $1", indentation: " ")
150 #expect(e.text == "- a\n - a")
151 #expect(e.fields[0].ranges == [2..<3, 8..<9])
152 }
153
154 // MARK: - Triggers
155
156 @Test func triggerBeforeTheCaret() {
157 let snippets = [Snippet(trigger: "date", body: "%t"), Snippet(trigger: "<d", body: "x"), Snippet(trigger: "file", body: "x", file: true)]
158 func found(_ text: String) -> String? {
159 Snippets.trigger(before: text.utf16.count, in: text, snippets: snippets).map { "\($0.snippet.trigger)@\($0.range.lowerBound)" }
160 }
161 #expect(found("today date") == "date@6")
162 #expect(found("(date") == "date@1")
163 #expect(found("x<d") == nil)
164 #expect(found("<d") == "<d@0")
165 #expect(found("update") == nil)
166 #expect(found("date ") == nil)
167 #expect(found("file") == nil)
168 }
169
170 // MARK: - Commands
171
172 func context(_ text: String, caret: Int? = nil, selection: Range<Int>? = nil, snippets: [Snippet], answers: [String: String] = [:]) -> EditContext {
173 var options = EditingOptions.org
174 options.snippets = snippets
175 let caret = caret ?? text.utf16.count
176 return EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [selection ?? caret..<caret],
177 now: Self.now, calendar: Self.utc, answers: answers, options: options)
178 }
179
180 @Test func expandingReplacesTheTriggerAndStartsASession() throws {
181 let snippets = [Snippet(trigger: "todo", body: "TODO ${1:what} by ${2:when}$0")]
182 let ctx = context("* todo", snippets: snippets)
183 #expect(ExpandSnippet().applies(in: ctx))
184 guard case .commit(let result) = ExpandSnippet().run(in: ctx) else { Issue.record("no commit"); return }
185 #expect(result.edits == [TextEdit(range: 2..<6, replacement: "TODO what by when")])
186 #expect(result.selection == [7..<11])
187 guard case .snippet(let session) = result.effects.first else { Issue.record("no session"); return }
188 #expect(session.fields.map(\.ranges) == [[7..<11], [15..<19]] && session.extent == 2..<19)
189 #expect(!ExpandSnippet().applies(in: context("* todo ", snippets: snippets)))
190 #expect(!ExpandSnippet().applies(in: context("* todo", selection: 2..<6, snippets: snippets)))
191 }
192
193 @Test func promptsComeBackAsAnswers() throws {
194 let snippets = [Snippet(trigger: "m", body: "Meet %^{Who}: $0")]
195 guard case .prompt(let prompt) = ExpandSnippet().run(in: context("m", snippets: snippets)) else { Issue.record("no prompt"); return }
196 #expect(prompt.key == "snippet-0" && prompt.message == "Who: ")
197 guard case .commit(let result) = ExpandSnippet().run(in: context("m", snippets: snippets, answers: ["snippet-0": "Ana"])) else {
198 Issue.record("no commit")
199 return
200 }
201 #expect(result.edits.first?.replacement == "Meet Ana: " && result.selection == [10..<10] && result.effects.isEmpty)
202 }
203
204 @Test func insertSnippetChoosesByNameAndWrapsTheSelection() throws {
205 let snippets = [Snippet(trigger: "q", name: "Quote", body: "#+begin_quote\n%i$0\n#+end_quote"), Snippet(trigger: "f", body: "x", file: true)]
206 guard case .prompt(let prompt) = InsertSnippet().run(in: context("hello", selection: 0..<5, snippets: snippets)) else { Issue.record("no prompt"); return }
207 #expect(prompt.choices == ["Quote (q)"])
208 guard case .commit(let result) = InsertSnippet().run(in: context("hello", selection: 0..<5, snippets: snippets, answers: ["snippet": "Quote (q)"])) else {
209 Issue.record("no commit")
210 return
211 }
212 #expect(result.edits == [TextEdit(range: 0..<5, replacement: "#+begin_quote\nhello\n#+end_quote")])
213 #expect(!InsertSnippet().applies(in: context("", snippets: [snippets[1]])))
214 // The named command reaches file templates too.
215 #expect(Snippets.command("org.snippet:f")?.applies(in: context("", snippets: snippets)) == true)
216 #expect(Snippets.command("org.cycle") == nil)
217 }
218
219 // MARK: - Sessions
220
221 /// The buffer and session after typing `typed` over the active field, as the editors do it:
222 /// the edit, then the mirrors.
223 func type(_ typed: String, into text: inout String, _ session: inout SnippetSession?, caret: Int? = nil) {
224 let end = caret ?? text.utf16.count
225 let range = session?.selection ?? (end..<end)
226 let edit = TextEdit(range: range, replacement: typed)
227 text = edit.apply(to: text)
228 if session?.map(edit) == false { session = nil }
229 guard let current = session else { return }
230 for mirror in current.mirrorEdits(in: text).reversed() {
231 text = mirror.apply(to: text)
232 if session?.map(mirror) == false { session = nil }
233 }
234 }
235
236 @Test func tabStopsAsAStateMachine() throws {
237 let e = try expand("a ${1:foo} b $1 c ${2:bar} $0 d")
238 var session = SnippetSession(e, at: 2)
239 var text = "x " + e.text
240 #expect(session?.selection == 4..<7)
241 type("XY", into: &text, &session)
242 #expect(text == "x a XY b XY c bar d")
243 #expect(session?.fields[0].ranges == [4..<6, 9..<11])
244 // Typing at the end of the field goes into it.
245 let end = TextEdit(range: 6..<6, replacement: "Z")
246 text = end.apply(to: text)
247 let mapped = session?.map(end)
248 #expect(mapped == true)
249 for mirror in session!.mirrorEdits(in: text).reversed() {
250 text = mirror.apply(to: text)
251 let kept = session?.map(mirror)
252 #expect(kept == true)
253 }
254 #expect(text == "x a XYZ b XYZ c bar d")
255 let next = session?.next()
256 #expect(next == .field(16..<19))
257 let back = session?.previous(), first = session?.previous()
258 #expect(back == 4..<7 && first == 4..<7)
259 }
260
261 @Test func leavingEndsTheSession() throws {
262 let e = try expand("${1:a} ${2:b}$0!")
263 var session = SnippetSession(e, at: 10)!
264 let second = session.next(), last = session.next()
265 #expect(second == .field(12..<13) && last == .exit(13..<13))
266 #expect(session.contains(10) && session.contains(14) && !session.contains(9) && !session.contains(15))
267 // An edit outside the snippet ends it; one inside moves it.
268 var moved = session
269 let outside = moved.map(TextEdit(range: 0..<1, replacement: ""))
270 let inside = session.map(TextEdit(range: 11..<11, replacement: "--"))
271 #expect(!outside && inside)
272 #expect(session.fields.map(\.ranges) == [[10..<11], [14..<15]] && session.exit == 15..<15)
273 #expect(SnippetSession(try expand("no fields$0"), at: 0) == nil)
274 }
275
276 @Test func mirrorsFollowAnEmptyField() throws {
277 let e = try expand("$1-$1-$1")
278 var session = SnippetSession(e, at: 0)
279 var text = e.text
280 type("ab", into: &text, &session)
281 #expect(text == "ab-ab-ab")
282 type("", into: &text, &session)
283 #expect(text == "--")
284 }
285
286 // MARK: - Completion
287
288 @Test func completionOffersSnippetsWhereOrgOffersNothing() {
289 let snippets = [Snippet(trigger: "meet", name: "Meeting notes", body: "x"), Snippet(trigger: "memo", body: "y"), Snippet(trigger: "mt", body: "z", file: true)]
290 let c = OrgCompletion.at(context("Notes me", snippets: snippets))
291 #expect(c?.kind == .snippet && c?.candidates == ["meet", "memo"] && c?.range == 6..<8)
292 #expect(c?.label("meet") == "meet Meeting notes" && c?.label("memo") == "memo")
293 // Org's own contexts come first.
294 #expect(OrgCompletion.at(context("#+TI", snippets: snippets))?.kind == .keyword)
295 #expect(OrgCompletion.at(context("plain", snippets: snippets)) == nil)
296 #expect(OrgCompletion.at(context("me", snippets: [])) == nil)
297 }
298
299 // MARK: - yasnippet
300
301 /// yasnippet's folder, for comparing expansions with it: `ORGSTAR_YASNIPPET`, else one a
302 /// Doom or package.el install has.
303 static let yasnippet: String? = {
304 if let path = ProcessInfo.processInfo.environment["ORGSTAR_YASNIPPET"] { return path }
305 let home = FileManager.default.homeDirectoryForCurrentUser
306 for base in [".config/emacs/.local/straight", ".emacs.d/.local/straight", ".emacs.d/elpa"] {
307 let folder = home.appendingPathComponent(base)
308 for entry in (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? [] {
309 for candidate in [folder.appendingPathComponent(entry).appendingPathComponent("yasnippet"), folder.appendingPathComponent(entry)]
310 where FileManager.default.fileExists(atPath: candidate.appendingPathComponent("yasnippet.el").path) {
311 return candidate.path
312 }
313 }
314 }
315 return nil
316 }()
317
318 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil && yasnippet != nil
319
320 static let bodies = [
321 "a ${1:foo} b $1 c ${2:bar} $0 d", "${1:x} and $2 then $1$2 end", "no fields $0 here", "plain",
322 "${2:second} ${1:first} $0", #"\$1 \\ ${1:x\}y} $1"#, "${1:a}$1", "line1 ${1:x}\nline2 $1\n$0",
323 ]
324
325 /// After expanding, after typing `XY`, and after each of two `yas-next-field`: the text and
326 /// point (0-based).
327 struct Steps: Codable, Equatable {
328 var text: [String]
329 var point: [Int]
330 }
331
332 func ours(_ body: String) throws -> Steps {
333 let e = try expand(body)
334 var session = SnippetSession(e, at: 0)
335 var text = e.text
336 var steps = Steps(text: [text], point: [session?.selection.lowerBound ?? e.exit.lowerBound])
337 type("XY", into: &text, &session, caret: e.exit.lowerBound)
338 var point = (session?.selection.lowerBound ?? e.exit.lowerBound) + 2
339 steps.text.append(text)
340 steps.point.append(point)
341 for _ in 0..<2 {
342 if var current = session {
343 switch current.next() {
344 case .field(let range):
345 point = range.lowerBound
346 session = current
347 case .exit(let range):
348 point = range.lowerBound
349 session = nil
350 }
351 }
352 steps.point.append(point)
353 }
354 return steps
355 }
356
357 @Test(.enabled(if: oracle)) func matchesYasnippet() throws {
358 func lisp(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }
359 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-yas-\(UUID().uuidString)")
360 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
361 defer { try? FileManager.default.removeItem(at: folder) }
362 let output = folder.appendingPathComponent("out.json")
363 let script = folder.appendingPathComponent("yas.el")
364 try """
365 ;;; -*- lexical-binding: t -*-
366 (add-to-list 'load-path \(lisp(Self.yasnippet!)))
367 (require 'yasnippet)
368 (require 'json)
369 (setq yas-indent-line nil)
370 (let (out)
371 (dolist (body (list \(Self.bodies.map(lisp).joined(separator: " "))))
372 (with-temp-buffer
373 (yas-minor-mode 1)
374 (yas-expand-snippet body)
375 (let ((texts (list (buffer-string))) (points (list (1- (point)))))
376 (insert "XY")
377 (run-hooks 'post-command-hook)
378 (push (buffer-string) texts)
379 (push (1- (point)) points)
380 (dotimes (_ 2)
381 (ignore-errors (yas-next-field))
382 (push (1- (point)) points))
383 (push `((text . ,(vconcat (nreverse texts))) (point . ,(vconcat (nreverse points)))) out))))
384 (with-temp-file \(lisp(output.path)) (insert (json-encode (nreverse out)))))
385 """.write(to: script, atomically: true, encoding: .utf8)
386 _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path])
387 let theirs = try JSONDecoder().decode([Steps].self, from: Data(contentsOf: output))
388 for (body, expected) in zip(Self.bodies, theirs) {
389 let mine = try ours(body)
390 #expect(mine == expected, "\(body): \(mine) against \(expected)")
391 }
392 }
393}
Tests/OrgEditorAppKitTests/SnippetEditorTests.swift added +144 · view
@@ -0,0 +1,144 @@
1import AppKit
2import OrgCore
3import Testing
4@testable import OrgEditorAppKit
5
6/// TAB expands a trigger only where it means nothing else, in each preset; then TAB, S-TAB
7/// and Escape move through the fields and end the snippet.
8@MainActor
9struct SnippetEditorTests {
10 static let snippets = [
11 Snippet(trigger: "date", body: "<2026-11-25 Wed>"),
12 Snippet(trigger: "todo", body: "TODO ${1:what} by ${2:when}$0"),
13 Snippet(trigger: "pair", body: "${1:a}-$1"),
14 ]
15
16 func harness(_ text: String, preset: KeymapPreset = .emacs, caret: Int? = nil) -> Harness {
17 let h = Harness(text)
18 h.editor.keymap = preset.keymap
19 h.editor.modal = preset.isModal
20 var options = h.editor.options
21 options.snippets = Self.snippets
22 h.editor.options = options
23 h.caret(at: caret ?? text.utf16.count)
24 return h
25 }
26
27 func type(_ h: Harness, _ text: String) {
28 h.textView.insertText(text, replacementRange: h.textView.selectedRange())
29 }
30
31 func key(_ h: Harness, _ keys: String) { ModalTests().type(h, keys) }
32
33 func shiftTab(_ h: Harness) {
34 KeyTests().send(h, characters: "\u{19}", ignoring: "\u{19}", code: 48, flags: .shift)
35 }
36
37 @Test(arguments: [KeymapPreset.emacs, .mac]) func tabExpandsATrigger(preset: KeymapPreset) {
38 let h = harness("Due date", preset: preset)
39 key(h, "TAB")
40 #expect(h.string == "Due <2026-11-25 Wed>" && h.editor.snippetSession == nil)
41 // No trigger: TAB is the text system's again.
42 let plain = harness("Due soon", preset: preset)
43 key(plain, "TAB")
44 #expect(plain.string == "Due soon\t")
45 }
46
47 @Test(arguments: [KeymapPreset.emacs, .mac]) func tabStillCyclesAndMovesInTables(preset: KeymapPreset) {
48 let heading = harness("* date\nbody\n", preset: preset, caret: 6)
49 key(heading, "TAB")
50 #expect(heading.string == "* date\nbody\n" && heading.editor.foldState.folds.contains(0))
51 let table = harness("| date | b |\n| c | d |\n", preset: preset, caret: 6)
52 key(table, "TAB")
53 #expect(!table.string.contains("2026") && table.caret > 7)
54 }
55
56 @Test func doomExpandsInInsertStateOnly() {
57 let h = harness("Due date", preset: .doom)
58 key(h, "TAB")
59 #expect(h.string == "Due date")
60 key(h, "A TAB")
61 #expect(h.string == "Due <2026-11-25 Wed>")
62 // A heading demotes in insert state, as Doom's TAB does there.
63 let heading = harness("* date", preset: .doom)
64 key(heading, "A TAB")
65 #expect(heading.string == "** date")
66 }
67
68 @Test func fieldsTakeTypingAndTabMovesOn() {
69 let h = harness("- todo")
70 key(h, "TAB")
71 #expect(h.string == "- TODO what by when")
72 #expect(h.textView.selectedRange() == NSRange(location: 7, length: 4))
73 type(h, "Call")
74 key(h, "TAB")
75 #expect(h.textView.selectedRange() == NSRange(location: 15, length: 4))
76 shiftTab(h)
77 #expect(h.textView.selectedRange() == NSRange(location: 7, length: 4))
78 key(h, "TAB")
79 type(h, "Fri")
80 key(h, "TAB")
81 #expect(h.string == "- TODO Call by Fri" && h.caret == 18 && h.editor.snippetSession == nil)
82 // TAB is TAB again.
83 key(h, "TAB")
84 #expect(h.string == "- TODO Call by Fri\t")
85 }
86
87 @Test func mirrorsFollowTheirField() {
88 let h = harness("pair")
89 key(h, "TAB")
90 type(h, "x")
91 #expect(h.string == "x-x")
92 type(h, "yz")
93 #expect(h.string == "xyz-xyz")
94 h.textView.deleteBackward(nil)
95 #expect(h.string == "xy-xy")
96 }
97
98 @Test func escapeOrLeavingEndsIt() {
99 let h = harness("todo")
100 key(h, "TAB")
101 key(h, "ESC")
102 #expect(h.editor.snippetSession == nil)
103 let moved = harness("text\ntodo")
104 key(moved, "TAB")
105 #expect(moved.editor.snippetSession != nil)
106 moved.caret(at: 0)
107 #expect(moved.editor.snippetSession == nil)
108 }
109
110 @Test func undoingTheExpansionEndsIt() {
111 let h = harness("todo")
112 key(h, "TAB")
113 h.textView.undoManager?.undo()
114 #expect(h.string == "todo" && h.editor.snippetSession == nil)
115 }
116
117 @Test func completionListsAndExpandsSnippets() {
118 let h = harness("Notes da")
119 h.editor.run("editor.complete")
120 #expect(h.string == "Notes <2026-11-25 Wed>")
121 let several = harness("x ")
122 type(several, "p")
123 several.editor.run("editor.complete")
124 #expect(several.string == "x a-a" && several.editor.snippetSession != nil)
125 }
126
127 @Test func aKeyCanExpandOneSnippet() throws {
128 var problems: [String] = []
129 let user = try Keymap(toml: "[[bind]]\nkeys = \"C-c s\"\ncommand = \"org.snippet:date\"\n", problems: &problems, commands: Set(EditorCommands.all.map(\.id)))
130 #expect(problems.isEmpty)
131 let h = harness("On ")
132 h.editor.keymap = .layered([KeymapPreset.emacs.keymap, user])
133 key(h, "C-c s")
134 #expect(h.string == "On <2026-11-25 Wed>")
135 }
136
137 @Test func commandsByName() {
138 let h = harness("")
139 h.editor.run("org.snippet:todo")
140 #expect(h.string == "TODO what by when" && h.editor.snippetSession != nil)
141 h.editor.run("org.snippet.next-field")
142 #expect(h.textView.selectedRange() == NSRange(location: 13, length: 4))
143 }
144}
docs/manual/guide/01-files-and-folders.org +2 · view
@@ -108,6 +108,8 @@ Right-click a file or folder in the sidebar for:
108 108
109Right-click a root's header for New File…, Expand or Collapse, Show in Finder and Remove from Sidebar…. 109Right-click a root's header for New File…, Expand or Collapse, Show in Finder and Remove from Sidebar….
110 110
111File ▸ New File from Template… makes a new file from a template in =snippets.toml=, in a folder and with a name you choose; see [[file:02-the-editor.org][The editor]].
112
111* Opening files 113* Opening files
112 114
113Click a file in the sidebar to open it. Other ways: 115Click a file in the sidebar to open it. Other ways:
docs/manual/guide/02-the-editor.org +51 −1 · view
@@ -273,7 +273,57 @@ What is completed, by position:
273| =:= at the start of a line in a property drawer | property names the entry doesn't have yet | 273| =:= at the start of a line in a property drawer | property names the entry doesn't have yet |
274| =:= at the start of a line elsewhere | drawer names | 274| =:= at the start of a line elsewhere | drawer names |
275 275
276Elsewhere, Complete at Point reports =No match=. Completion is for org files only. 276Where none of these offers anything, the triggers of your snippets that start with the text before the caret are offered, each with its description and marked =snippet=; choosing one expands it (see [[*Snippets][Snippets]]). Elsewhere, Complete at Point reports =No match=. Completion is for org files only.
277
278* Snippets
279
280A snippet is text you insert by typing its trigger and pressing =TAB=, as with yasnippet in Emacs. Snippets are defined in =snippets.toml= in the configuration folder; orgstar ships none. See [[file:13-configuration.org][Configuration]] for the file.
281
282#+BEGIN_SRC toml
283[[snippet]]
284trigger = "meet"
285description = "Meeting notes"
286body = """
287,* Meeting with ${1:someone} %U
288- $0
289"""
290#+END_SRC
291
292** Expanding
293
294Type the trigger and press =TAB=. The trigger is the text before the caret back to a blank, or a shorter part of it that starts after a character other than a letter, digit or =_=: =(meet= expands =meet=. =TAB= expands a trigger only where it has no other meaning:
295
296| Preset | Where =TAB= keeps its own meaning |
297|--------+------------------------------------------------------------------------------------------------------|
298| Emacs | Headings and the first or last line of a drawer or block (=org-cycle=), tables (next field) |
299| Mac | The same as Emacs |
300| Doom | Normal and visual state (=org-cycle=); in insert state, headings (demote), list items (indent) and tables (next field) |
301
302Your own =TAB= bindings in =keymap.toml= come first in the same way. Where =TAB= means something else, expand with Insert Snippet…, the completion list, or a key you bind to =org.snippet.expand= (Expand Snippet).
303
304A snippet that asks questions (=%^{…}= in its body) asks them in the echo area first, one after another; =Escape= cancels and inserts nothing.
305
306** Fields
307
308After expanding, the caret is in the first field, with its default text selected, so typing replaces it. The field has a band behind it, and the other fields and mirrors a fainter grey one.
309
310| Key | While a snippet's fields are filled in |
311|----------+-------------------------------------------------------------------------------|
312| =TAB= | Next field; after the last, the caret goes to =$0= (or the end) and the snippet is done |
313| =S-TAB= | Previous field |
314| =Escape= | The snippet is done; the caret stays. In the Doom preset, insert state ends as well. |
315
316A field used twice (=$1= … =$1=) is mirrored: typing in the field changes every copy. Moving the caret out of the snippet, or an edit outside it, also ends it. Next Snippet Field (=org.snippet.next-field=) and Previous Snippet Field (=org.snippet.previous-field=) are the same as =TAB= and =S-TAB=, for binding to other keys.
317
318** Insert Snippet…
319
320Insert Snippet… (in the command palette) lists the snippets by description and trigger, and expands the one you choose at the caret. With text selected, the snippet replaces it, and =%i= in the body inserts it: a snippet with body =#+begin_quote\n%i$0\n#+end_quote= wraps the selection in a quote block.
321
322Each snippet is also a command, =org.snippet:= and its trigger, such as =org.snippet:meet=, for a key in =keymap.toml=.
323
324** Templates for new files
325
326A snippet with =file = true= in =snippets.toml= is a template for a new file. File ▸ New File from Template… (or the command palette) asks for the template, the folder (that of the shown file to start with) and a name, as New File… does. The file is created empty and opens with the template expanded in it, its prompts asked and its fields ready to fill in.
277 327
278* Electric pairs 328* Electric pairs
279 329
docs/manual/guide/13-configuration.org +90 −3 · view
@@ -22,6 +22,7 @@ The folder holds these files:
22| =capture.toml= | Capture templates | Only by Import from Emacs | 22| =capture.toml= | Capture templates | Only by Import from Emacs |
23| =views.toml= | Saved agenda views | No | 23| =views.toml= | Saved agenda views | No |
24| =macros.toml= | Named keyboard macros | Yes, when you name a macro | 24| =macros.toml= | Named keyboard macros | Yes, when you name a macro |
25| =snippets.toml= | Snippets and templates for new files | Only by Import from Emacs |
25| =default-theme.toml= | The default theme's colors, for reference | Yes, at every launch | 26| =default-theme.toml= | The default theme's colors, for reference | Yes, at every launch |
26 27
27=config.toml= is the source of truth. The Settings window writes each change into it, keeping your comments and the order of lines, and edits you make to the file apply while orgstar runs. If the file doesn't exist at launch, orgstar creates it with every setting at its current value and a comment after each one. A file that is there but can't be read, such as one that isn't UTF-8, is left as it is: the change isn't written and a message says why, as it does when a write fails. Import from Emacs and saving an agenda view treat =capture.toml=, =views.toml= and =keymap.toml= the same way. 28=config.toml= is the source of truth. The Settings window writes each change into it, keeping your comments and the order of lines, and edits you make to the file apply while orgstar runs. If the file doesn't exist at launch, orgstar creates it with every setting at its current value and a comment after each one. A file that is there but can't be read, such as one that isn't UTF-8, is left as it is: the change isn't written and a message says why, as it does when a write fails. Import from Emacs and saving an agenda view treat =capture.toml=, =views.toml= and =keymap.toml= the same way.
@@ -44,7 +45,7 @@ If =config.toml= has a line orgstar can't use, the problem shows in the message
44- =config.toml: org-agenda-start-day must look like "-3d" or "+0d"= 45- =config.toml: org-agenda-start-day must look like "-3d" or "+0d"=
45- =config.toml: theme.light.background must be a color such as "#1f2328"= 46- =config.toml: theme.light.background must be a color such as "#1f2328"=
46 47
47A file that isn't valid TOML is reported with its parse error, and none of it applies. =keymap.toml=, =capture.toml=, =views.toml= and =macros.toml= report their problems the same way when they are read. 48A file that isn't valid TOML is reported with its parse error, and none of it applies. =keymap.toml=, =capture.toml=, =views.toml=, =macros.toml= and =snippets.toml= report their problems the same way when they are read.
48 49
49* The Settings window 50* The Settings window
50 51
@@ -491,6 +492,83 @@ tag-review = "C-c C-q w o r k : r e v i e w RET"
491 492
492A name has letters, digits, =-= and =_=. A line whose keys can't be read, or a table other than =[macros]=, is reported and skipped. 493A name has letters, digits, =-= and =_=. A line whose keys can't be read, or a table other than =[macros]=, is reported and skipped.
493 494
495* snippets.toml
496
497=snippets.toml= holds snippets: text you insert by typing a short trigger and pressing =TAB=, with fields to fill in, as yasnippet's snippets work in Emacs. A snippet with =file = true= is a template for a new file instead. orgstar ships no snippets; without the file there are none. How to use them is in [[file:02-the-editor.org][The editor]].
498
499#+BEGIN_SRC toml
500[[snippet]]
501trigger = "meet"
502description = "Meeting notes"
503body = """
504,* Meeting with ${1:someone} %U
505,** Agenda
506- $0
507,** Actions
508- [ ] $1:
509"""
510
511[[snippet]]
512trigger = "wk"
513description = "Week number"
514body = "Week %<%V>"
515
516[[snippet]]
517trigger = "weekly"
518description = "Weekly review"
519file = true
520body = '''
521,#+title: Week of %t
522,#+filetags: :review:
523
524,* Done
525- $1
526,* Next
527- $0
528'''
529#+END_SRC
530
531| Key | Value |
532|---------------+----------------------------------------------------------------------------------------|
533| =trigger= | What you type before =TAB=; no spaces. Required, and once per file. |
534| =body= | The text. Required. |
535| =description= | The name Insert Snippet…, the completion list and New File from Template… show; the trigger when left out. |
536| =file= | =true= for a template for New File from Template…; its trigger doesn't expand it. |
537
538Bodies are usually multi-line strings: =""" … """= takes escapes such as =\n= and =\t=, and =''' … '''= takes the text exactly as written. A newline right after the opening quotes isn't part of the body. The other TOML files take multi-line strings too.
539
540A body can hold these, as yasnippet writes them:
541
542| Syntax | Meaning |
543|-----------------------+-----------------------------------------------------------------------------------------------|
544| =$1=, =$2=, … | A field, empty. =TAB= visits fields by number, whatever their order in the text. |
545| =${1:default}= | A field with default text, which typing replaces. A default can hold other fields. |
546| =$0=, =${0:text}= | Where the caret goes after the last field; =text= is selected then. Without it, the end of the snippet. |
547| A number used twice | A mirror: it shows what you type in the field. The occurrence with a default is the field; otherwise the first. |
548| =\$=, =\\=, =\`= | A literal =$=, =\= or =`=; in a default, =\}= is a literal =}=. |
549
550And the capture escapes that need no capture (see [[file:08-capture.org][Capture]]):
551
552| Escape | Inserts |
553|-----------------------------------+----------------------------------------------------------------------------------|
554| =%t=, =%T=, =%u=, =%U= | Today's date as an active or inactive timestamp, with the time for =%T= and =%U= |
555| =%<…>= | The date in a =format-time-string= format, such as =%<%Y-%m-%d>= |
556| =%^{Prompt}= | Asks in a prompt first, and inserts the answer |
557| =%^t=, =%^T=, =%^u=, =%^U=, =%^g= | Asks for a date or tags |
558| =%\1=, =%\2=, … | The answer to the first, second, … =%^{…}= prompt |
559| =%i= | The selected text, when Insert Snippet… is run on a selection |
560| =%f=, =%F= | The file's name and path |
561| =%?= | Where the caret goes last, as =$0= |
562| =%(…)= | An Emacs Lisp form, run in orgstar's interpreter |
563
564A prompt takes a default and choices as in capture: =%^{Where}= with =|home|home|work= after the prompt's name offers =home= and =work= and inserts =home= when the answer is empty. Escapes inside a default (=${1:%t}=) are filled in too. =%a=, =%c=, =%k= and the other escapes about a capture insert nothing.
565
566Lines after the first take the indentation of the line the trigger is on.
567
568orgstar reads the file at launch and again when it changes. A file that isn't valid TOML is reported with its line, and the snippets read before stay. A snippet with a problem, such as one without a body, a trigger used twice, a =${= that isn't closed, or Emacs Lisp in a field (=${1:$(upcase yas-text)}=), is reported with the line of its =[[snippet]]= and left out; the others apply.
569
570Import from Emacs reads yasnippet's org-mode snippets into this file; see [[*yasnippet snippets][yasnippet snippets]].
571
494* In-file settings 572* In-file settings
495 573
496Keyword lines in a file set options for that file, as in Emacs. orgstar reads them outside blocks; for =#+STARTUP= only keyword lines count, so a =#+STARTUP= line inside a paragraph or a block changes nothing: not folding, logging or inline images. 574Keyword lines in a file set options for that file, as in Emacs. orgstar reads them outside blocks; for =#+STARTUP= only keyword lines count, so a =#+STARTUP= line inside a paragraph or a block changes nothing: not folding, logging or inline images.
@@ -572,7 +650,7 @@ Import from Emacs reads your Emacs or Doom Emacs configuration and offers to car
5721. Open Settings ▸ General and click Import from Emacs…, or run Import from Emacs… from the command palette (=⇧⌘P=). 6501. Open Settings ▸ General and click Import from Emacs…, or run Import from Emacs… from the command palette (=⇧⌘P=).
5732. 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. 6512. 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.
5743. 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. 6523. 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.
5754. 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. 6534. The sheet lists what it found under Settings, Folders, Capture templates, Key bindings, Structure templates, Agenda views and Snippets, each with the line it came from (=config.el:27=, or =Doom default=). Everything is selected; clear what you don't want.
5765. Click Import. The sheet then summarizes what was imported and any problems. 6545. Click Import. The sheet then summarizes what was imported and any problems.
577 655
578What Import does with each kind of item: 656What Import does with each kind of item:
@@ -582,8 +660,9 @@ What Import does with each kind of item:
582- Capture templates are appended to =capture.toml=, except those whose key is already in the file. 660- Capture templates are appended to =capture.toml=, except those whose key is already in the file.
583- Key bindings are appended to =keymap.toml=, except those already in the file with the same keys, command and state. Running the import again adds no duplicates. 661- Key bindings are appended to =keymap.toml=, except those already in the file with the same keys, command and state. Running the import again adds no duplicates.
584- Agenda views are appended to =views.toml=, except those whose name is already in the file. 662- Agenda views are appended to =views.toml=, except those whose name is already in the file.
663- Snippets are appended to =snippets.toml=, except those whose trigger is already in the file.
585 664
586The 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. 665The 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, snippets with Emacs Lisp, and files it couldn't read. The footer counts variables that aren't about org, which are left alone, and snippets skipped for their Emacs Lisp.
587 666
588A 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. 667A 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.
589 668
@@ -591,6 +670,14 @@ On iOS, Settings ▸ Import from Emacs reads a configuration folder you choose;
591 670
592In the [[file:../install.org][Mac App Store version]], Import from Emacs first opens a picker at the configuration it finds, since the app can read only what you choose. For a Doom configuration, Choose Doom Folder… picks Doom's installation folder, so its org defaults are read; without it the footer says Doom's own org defaults were skipped. On Import, each folder to add opens a picker at that folder, and only the folders you choose there are added. 671In the [[file:../install.org][Mac App Store version]], Import from Emacs first opens a picker at the configuration it finds, since the app can read only what you choose. For a Doom configuration, Choose Doom Folder… picks Doom's installation folder, so its org defaults are read; without it the footer says Doom's own org defaults were skipped. On Import, each folder to add opens a picker at that folder, and only the folders you choose there are added.
593 672
673** yasnippet snippets
674
675When the folder of the configuration read has a =snippets/org-mode/= folder, as =~/.config/doom/snippets/org-mode/= or =~/.emacs.d/snippets/org-mode/= do, its snippets are listed under Snippets. Each file's =# key:= becomes the trigger (the file's name when it has none), =# name:= the description, and the text after =# --= the body.
676
677Snippets with Emacs Lisp aren't imported, and are listed under Not Imported: backquoted forms (=`(format-time-string …)`=), transformations (=$(…)=) and =# type: command=. =# condition:=, =# expand-env:=, =# binding:= and =# group:= are ignored, as are the modes an =.yas-parents= file names. Only the folder beside the configuration is read: other folders in =yas-snippet-dirs=, and Doom's own snippet library, aren't. In the Mac App Store version and on iOS, the folder is read when it is inside the folder you chose.
678
679See [[file:15-alongside-emacs.org][Alongside Emacs]] for how expanding differs from yasnippet.
680
594** Doom Emacs 681** Doom Emacs
595 682
596A configuration counts as Doom when it contains =(doom!=, =(map! = or =(after! =. orgstar then also reads Doom's own org defaults, from the Doom installation in =$EMACSDIR=, =~/.config/emacs= or =~/.emacs.d=: =modules/lang/org/config.el= and =lisp/doom-emacs.el=. Your configuration overrides them. Doom defaults orgstar has no use for are counted in the footer rather than listed. 683A configuration counts as Doom when it contains =(doom!=, =(map! = or =(after! =. orgstar then also reads Doom's own org defaults, from the Doom installation in =$EMACSDIR=, =~/.config/emacs= or =~/.emacs.d=: =modules/lang/org/config.el= and =lisp/doom-emacs.el=. Your configuration overrides them. Doom defaults orgstar has no use for are counted in the footer rather than listed.
docs/manual/guide/14-ios.org +12 −2 · view
@@ -25,7 +25,7 @@ orgstar on iOS works on folders you choose, in iCloud Drive or in another app's
25 25
26orgstar keeps access to the folder across launches. Each folder appears as a section listing its =.org= files by their path inside the folder. To stop using a folder, tap the ⋯ button beside its name, or touch and hold the name, and choose Remove from orgstar…; orgstar asks first. The folder and its files stay where they are. An added folder that is empty also has Delete Folder…, which deletes it from disk too. 26orgstar keeps access to the folder across launches. Each folder appears as a section listing its =.org= files by their path inside the folder. To stop using a folder, tap the ⋯ button beside its name, or touch and hold the name, and choose Remove from orgstar…; orgstar asks first. The folder and its files stay where they are. An added folder that is empty also has Delete Folder…, which deletes it from disk too.
27 27
28Swipe left on a file, or touch and hold it, to delete it. orgstar asks first. A file in iCloud Drive goes to Recently Deleted in the Files app; elsewhere it is removed. New File… and New Folder… under + at the top right make one in the folder shown, or with several added folders, in the one you pick; a file name without an extension gets =.org=. Empty folders are listed too and delete the same way; a folder with anything in it other than hidden files can't be deleted from orgstar. 28Swipe left on a file, or touch and hold it, to delete it. orgstar asks first. A file in iCloud Drive goes to Recently Deleted in the Files app; elsewhere it is removed. New File… and New Folder… under + at the top right make one in the folder shown, or with several added folders, in the one you pick; a file name without an extension gets =.org=. New File from Template… there asks for a template from =snippets.toml= in the configuration folder and a name, then opens the new file in the editor with the template expanded; see [[*Snippets][Snippets]]. Empty folders are listed too and delete the same way; a folder with anything in it other than hidden files can't be deleted from orgstar.
29 29
30Files that iCloud hasn't downloaded to the device yet appear in grey with a cloud icon. orgstar asks iCloud to download them and lists them as files once they arrive; tap one to ask for it at once, and a spinner shows until it arrives. 30Files that iCloud hasn't downloaded to the device yet appear in grey with a cloud icon. orgstar asks iCloud to download them and lists them as files once they arrive; tap one to ask for it at once, and a spinner shows until it arrives.
31 31
@@ -200,6 +200,16 @@ With a hardware keyboard, the editor uses the preset =keymap= sets in the folder
200 200
201See [[file:03-keys.org][Keys and commands]] for the Emacs bindings. 201See [[file:03-keys.org][Keys and commands]] for the Emacs bindings.
202 202
203** Snippets
204
205Snippets come from =snippets.toml= in the configuration folder, the same file as on the Mac, and reload when it changes; problems show in red under the folder in Settings. See [[file:02-the-editor.org][The editor]] and [[file:13-configuration.org][Configuration]].
206
207- Insert Snippet… in Commands lists them and expands the one you choose at the caret, replacing the selection. Questions in the snippet open the question sheet, one after another.
208- With a hardware keyboard, =TAB= after a trigger expands it where =TAB= has no other meaning, as on the Mac, and =TAB=, =S-TAB= and =Escape= move through the fields.
209- On the on-screen keyboard, which has no =TAB=, the first field is selected after expanding, so typing replaces it; tapping elsewhere ends the snippet. The key bar has no snippet buttons yet.
210- Mirrors and the band behind the active field work as on the Mac.
211- New File from Template… is under + in Folders.
212
203* Search 213* Search
204 214
205Search finds: 215Search finds:
@@ -417,7 +427,7 @@ Stop Using This Folder returns every setting to its default.
417Import 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]]): 427Import 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]]):
418 428
4191. Tap Import from Emacs, then Choose Folder…, and choose the folder holding =init.el=, =config.el= or =config.org=. 4291. Tap Import from Emacs, then Choose Folder…, and choose the folder holding =init.el=, =config.el= or =config.org=.
4202. 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. 4302. The screen lists the settings, capture templates, key bindings, structure templates, agenda views and snippets it found, each with the line it came from, all selected. Clear what you don't want.
4213. Tap Import. The screen then summarizes what was imported and any problems. 4313. Tap Import. The screen then summarizes what was imported and any problems.
422 432
423With 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. 433With 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.
docs/manual/guide/15-alongside-emacs.org +13 · view
@@ -210,6 +210,19 @@ The agenda selects the same entries as Org's, but shows them its own way (see [[
210- Today's past deadlines and past scheduled entries are gathered in an Overdue group, oldest first, rather than sorted among today's entries by urgency. 210- Today's past deadlines and past scheduled entries are gathered in an Overdue group, oldest first, rather than sorted among today's entries by urgency.
211- The time grid and the now line are drawn as lines among a day's timed entries, where =org-agenda-time-grid=, =org-agenda-use-time-grid= and =org-agenda-show-current-time-in-grid= put them. orgstar draws the lines itself, so the strings in =org-agenda-time-grid= and =org-agenda-current-time-string= have no equivalent. 211- The time grid and the now line are drawn as lines among a day's timed entries, where =org-agenda-time-grid=, =org-agenda-use-time-grid= and =org-agenda-show-current-time-in-grid= put them. orgstar draws the lines itself, so the strings in =org-agenda-time-grid= and =org-agenda-current-time-string= have no equivalent.
212 212
213** Snippets and yasnippet
214
215orgstar's snippets (see [[file:02-the-editor.org][The editor]]) read yasnippet's field syntax, and Import from Emacs copies your org-mode snippets into =snippets.toml= (see [[file:13-configuration.org][Configuration]]). They are tested against yasnippet's own expansion. Where they differ:
216
217- =TAB= expands a trigger only where it has no other meaning. With yasnippet's minor mode, =TAB= on a heading or in a table expands a trigger before the caret first; in orgstar it cycles or moves to the next field.
218- No Emacs Lisp: backquoted forms, =$(…)= transformations, =# condition:= and =# expand-env:= aren't run. Snippets with the first two aren't imported, and =snippets.toml= refuses =$(…)= in a field. Capture's =%(…)= runs in orgstar's own interpreter instead.
219- The default of a field is selected on entering it; typing replaces it, as yasnippet's first keystroke clears it.
220- Lines after the first take the indentation of the trigger's line, rather than being indented by the mode (=yas-indent-line=).
221- The trigger is the text back to a blank, or a part of it after a character other than a letter, digit or =_=; =yas-key-syntaxes= isn't read.
222- One set of snippets for org files. Snippets for other modes, =.yas-parents=, =# group:=, =# binding:= and =# uuid:= aren't used.
223- A field inside another field's default is skipped by yasnippet once the outer field is typed over; orgstar visits it, empty, where it was.
224- Capture's escapes for dates and prompts (=%t=, =%U=, =%<…>=, =%^{…}=) work in bodies, which yasnippet doesn't have.
225
213** Known differences from Emacs Org 226** Known differences from Emacs Org
214 227
215orgstar refuses some things with a message rather than doing something different from Emacs. These are the ones found in the current version. 228orgstar refuses some things with a message rather than doing something different from Emacs. These are the ones found in the current version.
l10n/Localizable.xcstrings +346 · view
@@ -3411,6 +3411,40 @@
3411 } 3411 }
3412 } 3412 }
3413 }, 3413 },
3414 "Add a folder first.": {
3415 "localizations": {
3416 "de": {
3417 "stringUnit": {
3418 "state": "translated",
3419 "value": "Füge zuerst einen Ordner hinzu."
3420 }
3421 },
3422 "es": {
3423 "stringUnit": {
3424 "state": "translated",
3425 "value": "Añade primero una carpeta."
3426 }
3427 },
3428 "fr": {
3429 "stringUnit": {
3430 "state": "translated",
3431 "value": "Ajoutez d'abord un dossier."
3432 }
3433 },
3434 "ja": {
3435 "stringUnit": {
3436 "state": "translated",
3437 "value": "先にフォルダを追加してください。"
3438 }
3439 },
3440 "pt-BR": {
3441 "stringUnit": {
3442 "state": "translated",
3443 "value": "Adicione uma pasta primeiro."
3444 }
3445 }
3446 }
3447 },
3414 "Add a folder of org files": { 3448 "Add a folder of org files": {
3415 "localizations": { 3449 "localizations": {
3416 "de": { 3450 "de": {
@@ -14568,6 +14602,41 @@
14568 } 14602 }
14569 } 14603 }
14570 }, 14604 },
14605 "Expand Snippet": {
14606 "comment": "Command title",
14607 "localizations": {
14608 "de": {
14609 "stringUnit": {
14610 "state": "translated",
14611 "value": "Textbaustein erweitern"
14612 }
14613 },
14614 "es": {
14615 "stringUnit": {
14616 "state": "translated",
14617 "value": "Expandir fragmento"
14618 }
14619 },
14620 "fr": {
14621 "stringUnit": {
14622 "state": "translated",
14623 "value": "Développer l'extrait"
14624 }
14625 },
14626 "ja": {
14627 "stringUnit": {
14628 "state": "translated",
14629 "value": "スニペットを展開"
14630 }
14631 },
14632 "pt-BR": {
14633 "stringUnit": {
14634 "state": "translated",
14635 "value": "Expandir Trecho"
14636 }
14637 }
14638 }
14639 },
14571 "Expand Table Columns": { 14640 "Expand Table Columns": {
14572 "comment": "Command title", 14641 "comment": "Command title",
14573 "localizations": { 14642 "localizations": {
@@ -19601,6 +19670,41 @@
19601 } 19670 }
19602 } 19671 }
19603 }, 19672 },
19673 "Insert Snippet…": {
19674 "comment": "Command title",
19675 "localizations": {
19676 "de": {
19677 "stringUnit": {
19678 "state": "translated",
19679 "value": "Textbaustein einfügen…"
19680 }
19681 },
19682 "es": {
19683 "stringUnit": {
19684 "state": "translated",
19685 "value": "Insertar fragmento…"
19686 }
19687 },
19688 "fr": {
19689 "stringUnit": {
19690 "state": "translated",
19691 "value": "Insérer un extrait…"
19692 }
19693 },
19694 "ja": {
19695 "stringUnit": {
19696 "state": "translated",
19697 "value": "スニペットを挿入…"
19698 }
19699 },
19700 "pt-BR": {
19701 "stringUnit": {
19702 "state": "translated",
19703 "value": "Inserir Trecho…"
19704 }
19705 }
19706 }
19707 },
19604 "Insert Structure Template": { 19708 "Insert Structure Template": {
19605 "comment": "Command title", 19709 "comment": "Command title",
19606 "localizations": { 19710 "localizations": {
@@ -23392,6 +23496,75 @@
23392 } 23496 }
23393 } 23497 }
23394 }, 23498 },
23499 "New File from Template": {
23500 "localizations": {
23501 "de": {
23502 "stringUnit": {
23503 "state": "translated",
23504 "value": "Neue Datei aus Vorlage"
23505 }
23506 },
23507 "es": {
23508 "stringUnit": {
23509 "state": "translated",
23510 "value": "Nuevo archivo desde plantilla"
23511 }
23512 },
23513 "fr": {
23514 "stringUnit": {
23515 "state": "translated",
23516 "value": "Nouveau fichier depuis un modèle"
23517 }
23518 },
23519 "ja": {
23520 "stringUnit": {
23521 "state": "translated",
23522 "value": "テンプレートから新規ファイル"
23523 }
23524 },
23525 "pt-BR": {
23526 "stringUnit": {
23527 "state": "translated",
23528 "value": "Novo arquivo a partir de modelo"
23529 }
23530 }
23531 }
23532 },
23533 "New File from Template…": {
23534 "comment": "Command title",
23535 "localizations": {
23536 "de": {
23537 "stringUnit": {
23538 "state": "translated",
23539 "value": "Neue Datei aus Vorlage…"
23540 }
23541 },
23542 "es": {
23543 "stringUnit": {
23544 "state": "translated",
23545 "value": "Nuevo archivo desde plantilla…"
23546 }
23547 },
23548 "fr": {
23549 "stringUnit": {
23550 "state": "translated",
23551 "value": "Nouveau fichier depuis un modèle…"
23552 }
23553 },
23554 "ja": {
23555 "stringUnit": {
23556 "state": "translated",
23557 "value": "テンプレートから新規ファイル…"
23558 }
23559 },
23560 "pt-BR": {
23561 "stringUnit": {
23562 "state": "translated",
23563 "value": "Novo Arquivo a Partir de Modelo…"
23564 }
23565 }
23566 }
23567 },
23395 "New File…": { 23568 "New File…": {
23396 "localizations": { 23569 "localizations": {
23397 "de": { 23570 "de": {
@@ -24229,6 +24402,41 @@
24229 } 24402 }
24230 } 24403 }
24231 }, 24404 },
24405 "Next Snippet Field": {
24406 "comment": "Command title",
24407 "localizations": {
24408 "de": {
24409 "stringUnit": {
24410 "state": "translated",
24411 "value": "Nächstes Feld im Textbaustein"
24412 }
24413 },
24414 "es": {
24415 "stringUnit": {
24416 "state": "translated",
24417 "value": "Siguiente campo del fragmento"
24418 }
24419 },
24420 "fr": {
24421 "stringUnit": {
24422 "state": "translated",
24423 "value": "Champ suivant de l'extrait"
24424 }
24425 },
24426 "ja": {
24427 "stringUnit": {
24428 "state": "translated",
24429 "value": "スニペットの次のフィールド"
24430 }
24431 },
24432 "pt-BR": {
24433 "stringUnit": {
24434 "state": "translated",
24435 "value": "Próximo Campo do Trecho"
24436 }
24437 }
24438 }
24439 },
24232 "Next State": { 24440 "Next State": {
24233 "localizations": { 24441 "localizations": {
24234 "de": { 24442 "de": {
@@ -25629,6 +25837,40 @@
25629 } 25837 }
25630 } 25838 }
25631 }, 25839 },
25840 "No templates yet. A snippet in snippets.toml with file = true is one.": {
25841 "localizations": {
25842 "de": {
25843 "stringUnit": {
25844 "state": "translated",
25845 "value": "Noch keine Vorlagen. Ein Textbaustein in snippets.toml mit file = true ist eine."
25846 }
25847 },
25848 "es": {
25849 "stringUnit": {
25850 "state": "translated",
25851 "value": "Aún no hay plantillas. Un fragmento de snippets.toml con file = true es una."
25852 }
25853 },
25854 "fr": {
25855 "stringUnit": {
25856 "state": "translated",
25857 "value": "Aucun modèle pour l'instant. Un extrait de snippets.toml avec file = true en est un."
25858 }
25859 },
25860 "ja": {
25861 "stringUnit": {
25862 "state": "translated",
25863 "value": "テンプレートはまだありません。snippets.toml で file = true を指定したスニペットがテンプレートになります。"
25864 }
25865 },
25866 "pt-BR": {
25867 "stringUnit": {
25868 "state": "translated",
25869 "value": "Ainda não há modelos. Um trecho em snippets.toml com file = true é um modelo."
25870 }
25871 }
25872 }
25873 },
25632 "Node Graph": { 25874 "Node Graph": {
25633 "localizations": { 25875 "localizations": {
25634 "de": { 25876 "de": {
@@ -28955,6 +29197,41 @@
28955 } 29197 }
28956 } 29198 }
28957 }, 29199 },
29200 "Previous Snippet Field": {
29201 "comment": "Command title",
29202 "localizations": {
29203 "de": {
29204 "stringUnit": {
29205 "state": "translated",
29206 "value": "Vorheriges Feld im Textbaustein"
29207 }
29208 },
29209 "es": {
29210 "stringUnit": {
29211 "state": "translated",
29212 "value": "Campo anterior del fragmento"
29213 }
29214 },
29215 "fr": {
29216 "stringUnit": {
29217 "state": "translated",
29218 "value": "Champ précédent de l'extrait"
29219 }
29220 },
29221 "ja": {
29222 "stringUnit": {
29223 "state": "translated",
29224 "value": "スニペットの前のフィールド"
29225 }
29226 },
29227 "pt-BR": {
29228 "stringUnit": {
29229 "state": "translated",
29230 "value": "Campo Anterior do Trecho"
29231 }
29232 }
29233 }
29234 },
28958 "Previous TODO Keyword": { 29235 "Previous TODO Keyword": {
28959 "comment": "Command title", 29236 "comment": "Command title",
28960 "localizations": { 29237 "localizations": {
@@ -36143,6 +36420,40 @@
36143 } 36420 }
36144 } 36421 }
36145 }, 36422 },
36423 "Snippets": {
36424 "localizations": {
36425 "de": {
36426 "stringUnit": {
36427 "state": "translated",
36428 "value": "Textbausteine"
36429 }
36430 },
36431 "es": {
36432 "stringUnit": {
36433 "state": "translated",
36434 "value": "Fragmentos"
36435 }
36436 },
36437 "fr": {
36438 "stringUnit": {
36439 "state": "translated",
36440 "value": "Extraits"
36441 }
36442 },
36443 "ja": {
36444 "stringUnit": {
36445 "state": "translated",
36446 "value": "スニペット"
36447 }
36448 },
36449 "pt-BR": {
36450 "stringUnit": {
36451 "state": "translated",
36452 "value": "Trechos"
36453 }
36454 }
36455 }
36456 },
36146 "Some plans aren't available from the App Store right now.": { 36457 "Some plans aren't available from the App Store right now.": {
36147 "localizations": { 36458 "localizations": {
36148 "de": { 36459 "de": {
@@ -46288,6 +46599,41 @@
46288 } 46599 }
46289 } 46600 }
46290 }, 46601 },
46602 "snippet": {
46603 "comment": "Marks a snippet in the completion list",
46604 "localizations": {
46605 "de": {
46606 "stringUnit": {
46607 "state": "translated",
46608 "value": "Textbaustein"
46609 }
46610 },
46611 "es": {
46612 "stringUnit": {
46613 "state": "translated",
46614 "value": "fragmento"
46615 }
46616 },
46617 "fr": {
46618 "stringUnit": {
46619 "state": "translated",
46620 "value": "extrait"
46621 }
46622 },
46623 "ja": {
46624 "stringUnit": {
46625 "state": "translated",
46626 "value": "スニペット"
46627 }
46628 },
46629 "pt-BR": {
46630 "stringUnit": {
46631 "state": "translated",
46632 "value": "trecho"
46633 }
46634 }
46635 }
46636 },
46291 "sort on a string": { 46637 "sort on a string": {
46292 "localizations": { 46638 "localizations": {
46293 "de": { 46639 "de": {
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form