Sources/OrgCore/Commands/BlockCommands.swift
283 lines · 13535 bytes
1import Foundation
2
3// Blocks (Org 9.8.7): `org-insert-structure-template` (C-c C-,) with
4// `org-structure-template-alist`, and `org-edit-special` (C-c ') on src, example and export
5// blocks with Doom's `org-src-preserve-indentation` t: the block's lines as they are, commas
6// that protect `*` and `#+` lines taken off while editing and put back after.
7
8/// An entry of `org-structure-template-alist`: a key and the block type it inserts.
9public struct StructureTemplate: Sendable, Equatable, Codable {
10 public var key: String
11 public var type: String
12
13 public init(key: String, type: String) {
14 self.key = key
15 self.type = type
16 }
17
18 /// Org's default `org-structure-template-alist`.
19 public static let defaults: [StructureTemplate] = [
20 .init(key: "a", type: "export ascii"), .init(key: "c", type: "center"), .init(key: "C", type: "comment"),
21 .init(key: "e", type: "example"), .init(key: "E", type: "export"), .init(key: "h", type: "export html"),
22 .init(key: "l", type: "export latex"), .init(key: "q", type: "quote"), .init(key: "s", type: "src"),
23 .init(key: "v", type: "verse"),
24 ]
25
26 /// The defaults with `extra` over them: an entry with a default's key takes its place, the
27 /// others follow.
28 public static func merged(_ extra: [StructureTemplate]) -> [StructureTemplate] {
29 defaults.map { entry in extra.first { $0.key == entry.key } ?? entry } + extra.filter { entry in !defaults.contains { $0.key == entry.key } }
30 }
31}
32
33/// C-c C-,: `org-insert-structure-template`. Asks for a block type by key (Tab to type one),
34/// then inserts an empty block, or wraps the selection. Keys of more than one letter take two
35/// strokes, as `org--insert-structure-template-mks` makes them: the first letter, then the
36/// second (Tab for the one-letter key).
37public struct InsertStructureTemplate: OrgCommand {
38 public init() {}
39 public var id: String { "org.structure-template" }
40 public var title: String { "Insert Structure Template" }
41 public func applies(in context: EditContext) -> Bool { true }
42
43 /// The templates under each first letter, in the order the letters first appear.
44 static func groups(_ templates: [StructureTemplate]) -> [(letter: Character, templates: [StructureTemplate])] {
45 var groups: [(letter: Character, templates: [StructureTemplate])] = []
46 for template in templates {
47 guard let letter = template.key.first else { continue }
48 if let index = groups.firstIndex(where: { $0.letter == letter }) {
49 groups[index].templates.append(template)
50 } else {
51 groups.append((letter, [template]))
52 }
53 }
54 return groups
55 }
56
57 /// `org--insert-structure-template-unique-keys`: the second stroke of each key, Tab for a
58 /// one-letter key; nil when keys can't be told apart.
59 static func secondKeys(_ templates: [StructureTemplate]) -> [Character]? {
60 var used: [String: Int] = [:]
61 for (index, template) in templates.enumerated().sorted(by: { ($0.element.key.count, $0.offset) < ($1.element.key.count, $1.offset) }) {
62 let key = Array(template.key)
63 let candidate: String? = switch key.count {
64 case 1: String(key) + "\t"
65 case 2: String(key)
66 default: key.dropFirst().map { String(key[0]) + String($0) }.first { used[$0] == nil }
67 }
68 guard let candidate, used[candidate] == nil else { return nil }
69 used[candidate] = index
70 }
71 let byIndex = Dictionary(uniqueKeysWithValues: used.map { ($1, $0) })
72 return templates.indices.map { Array(byIndex[$0]!)[1] }
73 }
74
75 public func run(in context: EditContext) -> CommandStep {
76 let templates = context.options.structureTemplates ?? StructureTemplate.defaults
77 let groups = Self.groups(templates)
78 guard let key = context.answers["template"] else {
79 let items = groups.map { group -> FastSelection.Item in
80 let names = group.templates.map(\.type)
81 let name = names.count == 1 ? names[0] : names.prefix(3).joined(separator: ", ") + (names.count > 3 ? ", ..." : "")
82 return FastSelection.Item.option(key: group.letter, name: name)
83 } + [.option(key: "\t", name: "other (Tab)")]
84 return .prompt(Prompt(key: "template", message: "Insert block: [key] or Tab to type one", fast: FastSelection(items: items, multiple: false)))
85 }
86 let type: String
87 if key == "\t" {
88 guard let typed = context.answers["type"] else { return .prompt(Prompt(key: "type", message: "Structure type:")) }
89 guard !typed.isEmpty else { return .failed("Empty structure type") }
90 type = typed
91 } else {
92 guard let group = groups.first(where: { String($0.letter) == key }) else { return .failed("Quit") }
93 if group.templates.count == 1 {
94 type = group.templates[0].type
95 } else {
96 guard let seconds = Self.secondKeys(group.templates) else {
97 return .failed("Could not make unique key for `\(group.templates.last!.key)'")
98 }
99 guard let second = context.answers["template2"] else {
100 let items = zip(seconds, group.templates).map { FastSelection.Item.option(key: $0, name: $1.type) }
101 return .prompt(Prompt(key: "template2", message: "Insert block: [key]", fast: FastSelection(items: items, multiple: false)))
102 }
103 guard let index = seconds.firstIndex(where: { String($0) == second }) else { return .failed("Quit") }
104 type = group.templates[index].type
105 }
106 }
107 let region = context.selection.first.flatMap { $0.isEmpty ? nil : $0 }
108 return commitBuffer(context) { buffer in
109 try buffer.insertStructureTemplate(type, region: region)
110 }
111 }
112}
113
114extension EmacsBuffer {
115 func insertStructureTemplate(_ type: String, region: Range<Int>?) throws {
116 let name = String(type.split(separator: " ").first ?? "")
117 let extended = type.range(of: "^(src|export)$", options: [.regularExpression, .caseInsensitive]) != nil
118 let verbatim = type.range(of: "^(example|export|src|comment)", options: [.regularExpression, .caseInsensitive]) != nil
119 let upcase = name == name.uppercased()
120 let regionEnd = region.map { marker($0.upperBound) }
121 defer { regionEnd.map(release) }
122 if let region { point = region.lowerBound }
123 let column = currentIndentation
124 let atIndentation = saveExcursion { () -> Bool in
125 skipBackward([32, 9])
126 return bolp
127 }
128 if atIndentation { point = lineStart(point) } else { insert("\n") }
129 saveExcursion {
130 indentTo(column)
131 insert("#+\(upcase ? "BEGIN" : "begin")_\(type)\(extended ? " " : "")\n")
132 if let regionEnd {
133 if verbatim { escapeCode(from: point, to: regionEnd.position) }
134 point = regionEnd.position
135 // Without the blank lines at the region's end.
136 skipBackward([32, 13, 9, 10])
137 if !eolp {
138 insert("\n")
139 forwardLine(-1)
140 }
141 point = lineEnd(point)
142 }
143 if !bolp { insert("\n") }
144 indentTo(column)
145 insert("#+\(upcase ? "END" : "end")_\(name)")
146 if let blank = lookingAt("[ \\t]*$"), let whole = blank[0] {
147 deleteRegion(whole.lowerBound, whole.upperBound)
148 } else {
149 insert("\n")
150 }
151 if eobp, !bolp { insert("\n") }
152 }
153 if extended {
154 point = lineEnd(point)
155 } else {
156 forwardLine(1)
157 skipForward([32, 9])
158 }
159 }
160
161 /// `org-escape-code-in-region`: a comma before lines that would read as headings or
162 /// keywords.
163 func escapeCode(from start: Int, to end: Int) {
164 let limit = marker(end)
165 defer { release(limit) }
166 point = start
167 while point < limit.position, let match = searchForward("^[ \\t]*(,*(?:\\*|#\\+))", bound: limit.position, caseInsensitive: false) {
168 point = match[1]!.lowerBound
169 insert(",")
170 point = lineEnd(point)
171 }
172 }
173}
174
175/// A block's text, as `org-edit-special` hands it to an editing buffer.
176public struct BlockEdit: Sendable, Equatable {
177 /// The lines between the opening and closing lines.
178 public let range: Range<Int>
179 /// Those lines as they were, to check nothing changed them meanwhile.
180 public let original: String
181 /// What to edit: the lines with their protecting commas taken off.
182 public let content: String
183 /// The src block's language, for highlighting.
184 public let language: String?
185 /// `src`, `example` or `export`; `formulas` or `field` for a table's.
186 public let kind: String
187 /// A table field's point and coordinate (`@2$3`).
188 public var point: Int?
189 public var coordinate: String?
190
191 /// What the editor is editing, for its title.
192 public var title: String {
193 switch kind {
194 case Self.formulasKind: "Editing table formulas"
195 case Self.fieldKind: "Editing field \(coordinate ?? "")"
196 default: "Editing \(language.map { "\($0) " } ?? "")\(kind) block"
197 }
198 }
199
200 /// `org-unescape-code-in-string`.
201 public static func unescape(_ s: String) -> String {
202 s.replacingOccurrences(of: "(?m)^([ \\t]*),(,*(?:\\*|#\\+))", with: "$1$2", options: .regularExpression)
203 }
204
205 /// `org-escape-code-in-string`.
206 public static func escape(_ s: String) -> String {
207 s.replacingOccurrences(of: "(?m)^([ \\t]*)(,*(?:\\*|#\\+))", with: "$1,$2", options: .regularExpression)
208 }
209
210 /// The block's lines for edited `content`: escaped again, ending in a newline.
211 public func lines(for content: String) -> String {
212 guard !content.isEmpty else { return "" }
213 let escaped = Self.escape(content)
214 return escaped.hasSuffix("\n") ? escaped : escaped + "\n"
215 }
216
217 /// The src, example or export block whose lines hold `offset`, opening and closing
218 /// lines included.
219 public static func at(_ offset: Int, text: String, tree: OrgTree) -> BlockEdit? {
220 var node = tree.root
221 var found: SyntaxNode?
222 while let child = node.child(containing: offset) {
223 if child.kind == .block { found = child }
224 node = child
225 }
226 guard let block = found else { return nil }
227 let ns = text as NSString
228 let first = ns.lineRange(for: NSRange(location: block.range.lowerBound, length: 0))
229 let opening = ns.substring(with: first)
230 guard let header = opening.firstMatch(of: /(?i)^[ \t]*#\+begin_(src|example|export)(?:[ \t]+([^ \t\n]+))?/) else { return nil }
231 guard let wrapper = Wrappers.starting(at: block.range.lowerBound, in: tree) else { return nil }
232 let start = NSMaxRange(first)
233 let end = wrapper.closeLine
234 guard start <= end else { return nil }
235 let original = ns.substring(with: NSRange(location: start, length: end - start))
236 let kind = header.1.lowercased()
237 return BlockEdit(range: start..<end, original: original, content: unescape(original),
238 language: kind == "src" ? header.2.map(String.init) : nil, kind: kind)
239 }
240}
241
242/// C-c ': `org-edit-special` on a src, example or export block: the app edits its text apart,
243/// then `ReplaceBlockLines` puts it back.
244public struct EditSpecial: OrgCommand {
245 public init() {}
246 public var id: String { "org.edit-special" }
247 public var title: String { "Edit Block" }
248 public func applies(in context: EditContext) -> Bool { edit(context) != nil }
249
250 private func edit(_ context: EditContext) -> BlockEdit? {
251 BlockEdit.at(context.caret, text: context.text, tree: context.tree) ?? BlockEdit.formulas(at: context.caret, text: context.text)
252 }
253
254 public func run(in context: EditContext) -> CommandStep {
255 guard let edit = edit(context) else {
256 return .failed("No special environment to edit here")
257 }
258 return .external(.editBlock(edit))
259 }
260}
261
262/// Writes an edited block back, unless its lines changed meanwhile.
263public struct ReplaceBlockLines: OrgCommand {
264 public let edit: BlockEdit
265 public let content: String
266 public init(edit: BlockEdit, content: String) {
267 self.edit = edit
268 self.content = content
269 }
270 public var id: String { "internal.replace-block" }
271 public var title: String { "Replace Block" }
272 public func applies(in context: EditContext) -> Bool { true }
273 public func run(in context: EditContext) -> CommandStep {
274 let ns = context.text as NSString
275 guard edit.range.upperBound <= ns.length, ns.substring(with: NSRange(edit.range)) == edit.original else {
276 return .failed("The block changed while you edited it; its edit wasn't saved.")
277 }
278 if edit.kind == BlockEdit.formulasKind { return edit.installFormulas(content, in: context) }
279 if edit.kind == BlockEdit.fieldKind { return edit.installField(content, in: context) }
280 let lines = edit.lines(for: content)
281 return .commit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: edit.range, replacement: lines)]))
282 }
283}