Sources/OrgCore/Compute/BabelResults.swift
554 lines · 26739 bytes
1import Foundation
2
3extension Babel {
4 // MARK: - Finishing
5
6 /// What the run produced, as Babel holds it before inserting.
7 enum Value: Equatable {
8 case none
9 case string(String)
10 /// Rows of cells; nil rows are rules.
11 case table([[String]?])
12 }
13
14 /// The edit that writes the run's result under the block, or why it can't.
15 public static func finish(_ job: BabelJob, output: BabelOutput, text: String, settings: OrgSettings = .default) -> Result<[TextEdit], Failure> {
16 let ns = text as NSString
17 var blockRange = job.block
18 if blockRange.upperBound > ns.length || ns.substring(with: NSRange(blockRange)) != job.blockText {
19 let found = ns.range(of: job.blockText)
20 guard found.location != NSNotFound,
21 ns.range(of: job.blockText, range: NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))).location == NSNotFound else {
22 return .failure(.message("The block changed while it ran; the result wasn't written."))
23 }
24 blockRange = found.location..<NSMaxRange(found)
25 }
26 let value = Self.value(job.finish, output)
27 if job.finish.params.contains("silent") || job.finish.params.contains("none") || job.finish.params.contains("discard") { return .success([]) }
28 let buffer = EmacsBuffer(text, point: 0, settings: settings)
29 if job.finish.inline {
30 do {
31 try insertInlineResult(value, job.finish, at: blockRange, buffer: buffer)
32 } catch let error as Failure {
33 return .failure(error)
34 } catch {
35 return .failure(.message("\(error)"))
36 }
37 return .success(TextEdit.between(text, buffer.text as String))
38 }
39 insertResult(value, job.finish, block: blockRange, buffer: buffer)
40 return .success(TextEdit.between(text, buffer.text as String))
41 }
42
43 /// The language's result handling: `org-babel-result-cond` and the table import.
44 static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
45 let value = reassemble(rawValue(finish, output), finish)
46 switch (finish.kind, value) {
47 case (.calc, .string(let s)), (.sqlite, .string(let s)):
48 // `org-babel-execute-src-block` makes a table of a value that isn't a list.
49 if !finish.params.contains("output"), finish.params.contains("vector") || finish.params.contains("table") { return .table([[s]]) }
50 return value
51 default:
52 return value
53 }
54 }
55
56 static func rawValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
57 let params = finish.params
58 if params.contains("file") {
59 // `org-babel-result-to-file`: a link to `:file`, or to the result as a path.
60 let path = finish.file ?? rawResult(finish, output)
61 var link = "[[file:" + path + "]"
62 if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" }
63 return .string(link + "]")
64 }
65 let scalar = resultCondScalar(params)
66 switch finish.kind {
67 case .calc:
68 guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
69 return .string(output.stdout)
70 }
71 if let rows = object["rows"] as? [[String]] { return .table(rows) }
72 return .string(object["value"] as? String ?? "")
73 case .sqlite(let csv, let headers):
74 return sqliteValue(output.stdout, csv: csv, headers: headers, scalar: scalar)
75 case .shell(let valueIsExitStatus):
76 var results = output.stdout
77 if valueIsExitStatus {
78 results = results.split(separator: "\n", omittingEmptySubsequences: true).last.map(String.init) ?? ""
79 }
80 if scalar { return .string(results) }
81 return importTable(results)
82 case .generic:
83 return .string(output.stdout)
84 case .python:
85 let raw = finish.output ? output.stdout : (output.resultFile ?? "")
86 if scalar { return .string(raw) }
87 return pythonValue(raw)
88 case .emacsLisp:
89 guard let data = output.stdout.data(using: .utf8),
90 let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return .string(output.stdout) }
91 if scalar {
92 return .string((params.contains("scalar") || params.contains("verbatim") ? object["S"] : object["s"]) as? String ?? "")
93 }
94 if object["string"] as? Bool == true { return .string(object["s"] as? String ?? "") }
95 if let rows = object["rows"] as? [Any] {
96 return .table(rows.map { $0 as? String == "hline" ? nil : ($0 as? [String] ?? []) })
97 }
98 let printed = object["S"] as? String ?? ""
99 return printed == "nil" ? .none : .string(printed)
100 case .compiled:
101 return compiledValue(finish, output, scalar: scalar)
102 case .script(let js, _):
103 let raw = rawResult(finish, output)
104 if scalar { return .string(raw) }
105 // `org-babel-ruby-table-or-string`, its nils rules.
106 return js ? jsValue(raw) : pythonValue(raw, none: "nil", braces: true)
107 }
108 }
109
110 /// The result as the program left it, before tables are read.
111 static func rawResult(_ finish: BabelJob.Finish, _ output: BabelOutput) -> String {
112 switch finish.kind {
113 case .python: return finish.output ? output.stdout : (output.resultFile ?? "")
114 case .emacsLisp:
115 guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return output.stdout }
116 return object["s"] as? String ?? ""
117 case .shell(let valueIsExitStatus):
118 return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout
119 case .generic: return output.stdout
120 case .calc:
121 guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return output.stdout }
122 return object["value"] as? String ?? ""
123 case .sqlite: return output.stdout
124 case .compiled: return compiledResult(finish, output)
125 case .script(let js, let session): return finish.output || (js && !session) ? output.stdout : (output.resultFile ?? "")
126 }
127 }
128
129 /// With `:results file` and `:file`, what to write there, relative to the run's folder;
130 /// nil when there's nothing to write or the program wrote it.
131 public static func fileResult(_ job: BabelJob, output: BabelOutput) -> (path: String, contents: String)? {
132 guard job.finish.params.contains("file"), let file = job.finish.file, !job.finish.writesFile else { return nil }
133 return (file, rawResult(job.finish, output))
134 }
135
136 /// `org-babel-import-elisp-from-file`.
137 static func importTable(_ results: String) -> Value {
138 guard !results.isEmpty else { return .none }
139 var lines = results.components(separatedBy: "\n")
140 if lines.last == "" { lines.removeLast() }
141 let nonEmpty = lines.filter { !$0.isEmpty }
142 let rows: [[String]]
143 if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains("\t") }) {
144 rows = lines.map { $0.components(separatedBy: "\t") }
145 } else if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains(",") }) {
146 rows = lines.map(csvFields)
147 } else if lines.count == 1 {
148 rows = [[lines[0]]]
149 } else {
150 rows = lines.map { line in
151 let trimmed = line.drop { $0 == " " }
152 return trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init).isEmpty
153 ? [""] : trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init)
154 }
155 }
156 let cells = rows.map { row in row.map { field -> String in
157 let trimmed = field.trimmingCharacters(in: .whitespaces)
158 switch cell(trimmed) {
159 case .number(let n): return n
160 case .text(let t): return t
161 }
162 } }
163 if cells.count == 1, cells[0].count == 1 { return .string(cells[0][0]) }
164 return .table(cells)
165 }
166
167 static func csvFields(_ line: String) -> [String] {
168 var fields: [String] = []
169 var current = ""
170 var quoted = false
171 for c in line {
172 if c == "\"" {
173 quoted.toggle()
174 } else if c == ",", !quoted {
175 fields.append(current.trimmingCharacters(in: .whitespaces))
176 current = ""
177 } else {
178 current.append(c)
179 }
180 }
181 fields.append(current.trimmingCharacters(in: .whitespaces))
182 return fields
183 }
184
185 /// `org-babel-python-table-or-string`; with `none` "null" and `braces`,
186 /// `org-babel-java-table-or-string`, which reads `{…}` as a list too.
187 static func pythonValue(_ raw: String, none: String = "None", braces: Bool = false) -> Value {
188 guard let first = raw.first, let last = raw.last, raw.count >= 2,
189 (first == "[" && last == "]") || (first == "(" && last == ")") || (braces && first == "{" && last == "}") else {
190 if raw.isEmpty { return .string("") }
191 if raw.count > 2, (raw.hasPrefix("'") && raw.hasSuffix("'")) || (raw.hasPrefix("\"") && raw.hasSuffix("\"")) {
192 return .string(String(raw.dropFirst().dropLast()))
193 }
194 if let n = number(raw) { return .string(n) }
195 return .string(raw)
196 }
197 var parser = PythonLiteral(Array(raw))
198 parser.braces = braces
199 guard let parsed = parser.parse(), parser.atEnd, case .list(let items) = parsed else { return .string(raw) }
200 func text(_ v: PythonLiteral.Node) -> String {
201 switch v {
202 case .atom(let s): return s
203 case .string(let s): return s
204 case .list(let xs): return "(" + xs.map(text).joined(separator: " ") + ")"
205 }
206 }
207 if items.allSatisfy({ if case .list = $0 { return true }; if case .atom(none) = $0 { return true }; return false }) {
208 return .table(items.map { item -> [String]? in
209 if case .list(let cells) = item { return cells.map(text) }
210 return nil
211 })
212 }
213 return .table([items.map { if case .atom(none) = $0 { return "hline" }; return text($0) }])
214 }
215
216 struct PythonLiteral {
217 indirect enum Node: Equatable {
218 case atom(String)
219 case string(String)
220 case list([Node])
221 }
222
223 let chars: [Character]
224 var i = 0
225 /// `{…}` is a list, as `org-babel-script-escape` reads it.
226 var braces = false
227 init(_ chars: [Character]) { self.chars = chars }
228 var atEnd: Bool { mutating get { skip(); return i == chars.count } }
229
230 mutating func skip() { while i < chars.count, chars[i] == " " || chars[i] == "\n" { i += 1 } }
231
232 mutating func parse() -> Node? {
233 skip()
234 guard i < chars.count else { return nil }
235 let c = chars[i]
236 if c == "[" || c == "(" || (braces && c == "{") {
237 let close: Character = c == "[" ? "]" : c == "{" ? "}" : ")"
238 i += 1
239 var items: [Node] = []
240 skip()
241 if i < chars.count, chars[i] == close {
242 i += 1
243 return .list(items)
244 }
245 while true {
246 guard let item = parse() else { return nil }
247 items.append(item)
248 skip()
249 guard i < chars.count else { return nil }
250 if chars[i] == "," {
251 i += 1
252 skip()
253 if i < chars.count, chars[i] == close {
254 i += 1
255 return .list(items)
256 }
257 continue
258 }
259 if chars[i] == close {
260 i += 1
261 return .list(items)
262 }
263 return nil
264 }
265 }
266 if c == "'" || c == "\"" {
267 i += 1
268 var s = ""
269 while i < chars.count, chars[i] != c {
270 if chars[i] == "\\", i + 1 < chars.count {
271 i += 1
272 switch chars[i] {
273 case "n": s.append("\n")
274 case "t": s.append("\t")
275 default: s.append(chars[i])
276 }
277 } else {
278 s.append(chars[i])
279 }
280 i += 1
281 }
282 guard i < chars.count else { return nil }
283 i += 1
284 return .string(s)
285 }
286 var s = ""
287 while i < chars.count, !",)] \n".contains(chars[i]), !(braces && chars[i] == "}") {
288 s.append(chars[i])
289 i += 1
290 }
291 guard !s.isEmpty else { return nil }
292 return .atom(number(s) ?? s)
293 }
294 }
295
296 // MARK: - Inserting
297
298 static let resultKeyword = "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:"
299
300 /// `org-babel-where-is-src-block-result` with `insert`: the line of the block's results
301 /// keyword, added when there is none.
302 /// The `#+RESULTS` line of a block's results (`org-babel-where-is-src-block-result`):
303 /// the one naming `name`, or for an unnamed block an empty one right after it.
304 static func existingResults(name: String?, block: Range<Int>, text ns: NSString) -> Int? {
305 if let name {
306 let pattern = "(?im)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$"
307 let regex = try! NSRegularExpression(pattern: pattern)
308 return regex.firstMatch(in: ns as String, range: NSRange(location: 0, length: ns.length))?.range.location
309 }
310 // The element after the block, past blank lines.
311 var location = block.upperBound
312 while location < ns.length {
313 let line = ns.lineRange(for: NSRange(location: location, length: 0))
314 let content = ns.substring(with: line)
315 if content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
316 location = NSMaxRange(line)
317 continue
318 }
319 if content.range(of: "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*\\n?$", options: .regularExpression) != nil {
320 return line.location
321 }
322 break
323 }
324 return nil
325 }
326
327 /// The hash in the `#+RESULTS[…]:` line at `line` (`org-babel-result-regexp`).
328 static func resultsHash(at line: Int, text ns: NSString) -> String? {
329 let content = ns.substring(with: ns.lineRange(for: NSRange(location: line, length: 0)))
330 return content.firstMatch(of: #/(?i)^[ \t]*#\+results\[(?:\(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\) )?([0-9a-f]+)\]:/#).map { String($0.1) }
331 }
332
333 static func resultsLine(_ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) -> Int {
334 if let line = existingResults(name: finish.name, block: block, text: buffer.text) {
335 // `org-babel--clear-results-maybe`: a different hash clears the results and
336 // rewrites the keyword.
337 if let hash = finish.hash, resultsHash(at: line, text: buffer.text) != hash {
338 buffer.point = line
339 let indent = String(buffer.substring(line, buffer.lineEnd(line)).prefix { $0 == " " || $0 == "\t" })
340 buffer.forwardLine(1)
341 let contents = buffer.point
342 buffer.deleteRegion(contents, max(contents, resultEnd(buffer)))
343 buffer.deleteRegion(line, contents)
344 buffer.point = line
345 buffer.insert(indent + "#+RESULTS[\(hash)]:" + (finish.name.map { " " + $0 } ?? "") + "\n")
346 if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil {
347 buffer.saveExcursion { buffer.insert("\n") }
348 }
349 }
350 return line
351 }
352 // A new keyword after the block.
353 buffer.point = min(block.upperBound, buffer.length)
354 buffer.skipBackward([32, 9, 10, 13])
355 buffer.forwardLine(1)
356 if !buffer.bolp { buffer.insert("\n") }
357 let indent = buffer.saveExcursion { () -> String in
358 buffer.point = block.lowerBound
359 let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point))
360 return String(line.prefix { $0 == " " || $0 == "\t" })
361 }
362 buffer.insert("\n")
363 let keywordLine = buffer.point
364 buffer.insert(indent + "#+RESULTS" + (finish.hash.map { "[\($0)]" } ?? "") + ":" + (finish.name.map { " " + $0 } ?? "") + "\n")
365 if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil {
366 buffer.saveExcursion { buffer.insert("\n") }
367 }
368 return keywordLine
369 }
370
371 /// `org-babel-result-end` with point at the start of the result.
372 static func resultEnd(_ buffer: EmacsBuffer) -> Int {
373 let start = buffer.point
374 let line = buffer.substring(buffer.lineStart(start), buffer.lineEnd(start))
375 if line.trimmingCharacters(in: .whitespaces).isEmpty { return start }
376 if line.range(of: "^[ \\t]*\\[\\[[^\\]]+\\](\\[[^\\]]*\\])?\\][ \\t]*$", options: .regularExpression) != nil {
377 return min(buffer.length, buffer.lineEnd(start) + 1)
378 }
379 let tree = OrgParser.parse(buffer.text as String)
380 var node = tree.root
381 var found: SyntaxNode?
382 while let child = node.child(containing: start) {
383 if child.range.lowerBound == start || (buffer.lineStart(child.range.lowerBound) == start) {
384 if [.fixedWidth, .table, .plainList, .drawer, .block, .dynamicBlock, .latexFragment].contains(child.kind) {
385 found = child
386 break
387 }
388 }
389 node = child
390 }
391 guard let element = found else { return start }
392 var end = element.range.upperBound
393 while end > start, let c = buffer.character(at: end - 1), c == 32 || c == 9 || c == 10 || c == 13 { end -= 1 }
394 return min(buffer.length, buffer.lineEnd(end) + 1)
395 }
396
397 /// `org-babel-insert-result` for a src block.
398 /// An inline block's result, after it: ` {{{results(=value=)}}}`, replacing one already
399 /// there; raw results go in as they are.
400 static func insertInlineResult(_ value: Value, _ finish: BabelJob.Finish, at object: Range<Int>, buffer: EmacsBuffer) throws {
401 var string: String
402 switch value {
403 case .none: string = ""
404 case .string(let s): string = s
405 case .table(let rows):
406 let cells = rows.compactMap { $0 }
407 guard cells.count == 1, cells[0].count == 1 else { throw Failure.message("Inline source block results can't be tables or lists") }
408 string = cells[0][0]
409 }
410 buffer.point = object.upperBound
411 if let existing = buffer.lookingAt("[ \\t]*\\{\\{\\{results\\(.*?\\)\\}\\}\\}") {
412 buffer.deleteRegion(existing[0]!.lowerBound, existing[0]!.upperBound)
413 }
414 if finish.params.contains("raw") {
415 buffer.insert(" " + string)
416 return
417 }
418 if string.hasSuffix("\n") { string.removeLast() }
419 guard !string.contains("\n") else { throw Failure.message("Inline source block results must be one line") }
420 buffer.insert(" {{{results(=" + string + "=)}}}")
421 }
422
423 static func insertResult(_ value: Value, _ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) {
424 let params = finish.params
425 let keyword = resultsLine(finish, block: block, buffer: buffer)
426 buffer.point = keyword
427 let indent = buffer.substring(buffer.lineStart(keyword), buffer.lineEnd(keyword)).prefix { $0 == " " || $0 == "\t" }.count
428 buffer.forwardLine(1)
429 if buffer.point == buffer.lineEnd(keyword) { buffer.insert("\n") }
430 var beg = buffer.point
431 if params.contains("replace") {
432 buffer.deleteRegion(beg, resultEnd(buffer))
433 buffer.point = beg
434 } else if params.contains("append") {
435 buffer.point = resultEnd(buffer)
436 beg = buffer.point
437 }
438 var tabulated = false
439 // A list made from a string is examplified, as a string result is.
440 var listed = false
441 switch value {
442 case .none:
443 break
444 case .string(var s) where params.contains("list"):
445 if s.last != "\n" { s += "\n" }
446 let items = s.split(separator: "\n", omittingEmptySubsequences: true)
447 buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
448 case .table(let rows) where params.contains("list") && finish.kind.isSQLite:
449 // ob-sqlite's value is always rows: each an item, its first cell the text and the
450 // others lines under it.
451 listed = true
452 var items = rows.map { row in
453 guard let row else { return "- hline\n" }
454 return "- " + (row.first ?? "") + "\n" + row.dropFirst().map { " " + $0 + "\n" }.joined()
455 }.joined()
456 while let last = items.unicodeScalars.last, " \r\t\n".unicodeScalars.contains(last) { items.unicodeScalars.removeLast() }
457 buffer.insert(items + "\n")
458 case .table(let rows) where params.contains("list"):
459 listed = true
460 let items = rows.count == 1 ? (rows[0] ?? []) : rows.compactMap { $0?.joined(separator: " ") }
461 buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
462 case .table(let rows):
463 tabulated = true
464 let lines = rows.map { row in row.map { "| " + $0.map { " " + $0 + " " }.joined(separator: "|").dropFirst() + " |" } ?? "|-" }
465 let start = buffer.point
466 buffer.insert(lines.joined(separator: "\n") + "\n")
467 buffer.point = start
468 buffer.tableAlign()
469 buffer.point = buffer.tableEnd()
470 case .string(var s):
471 // `org-string-nw-p`: a blank result gets no newline.
472 if s.unicodeScalars.contains(where: { !" \r\t\n".unicodeScalars.contains($0) }), s.unicodeScalars.last != "\n" { s += "\n" }
473 buffer.insert(s)
474 }
475 let end = buffer.marker(buffer.point, advances: true)
476 defer { buffer.release(end) }
477 func wrap(_ open: String, _ close: String, escape: Bool) {
478 buffer.point = end.position
479 buffer.insert(close + "\n")
480 buffer.point = beg
481 buffer.insert(open + "\n")
482 if escape { escapeCode(buffer, from: buffer.point, to: end.position - close.utf16.count - 1) }
483 }
484 if let wrapValue = finish.wrap {
485 let full = wrapValue.isEmpty ? "results" : wrapValue
486 let type = String(full.split(separator: " ").first ?? "results")
487 if type.lowercased() != "nil", type.lowercased() != "no" {
488 wrap("#+begin_" + full, "#+end_" + type, escape: !["example", "src", "export"].contains(type.lowercased()) ? false : true)
489 }
490 } else if params.contains("html") {
491 wrap("#+begin_export html", "#+end_export", escape: true)
492 } else if params.contains("latex") {
493 wrap("#+begin_export latex", "#+end_export", escape: true)
494 } else if params.contains("org") {
495 wrap("#+begin_src org", "#+end_src", escape: true)
496 } else if params.contains("code") {
497 wrap("#+begin_src \(finish.language.isEmpty ? "none" : finish.language)", "#+end_src", escape: true)
498 } else if params.contains("raw") || params.contains("file") {
499 // As inserted.
500 } else if params.contains("drawer") {
501 wrap(":results:", ":end:", escape: false)
502 } else if !tabulated, !(params.contains("list") && listed) {
503 examplify(buffer, beg, end.position)
504 }
505 if indent > 0, !(tabulated && params.contains("append")) {
506 buffer.point = beg
507 while buffer.point < end.position {
508 if !buffer.eolp { buffer.insert(String(repeating: " ", count: indent)) }
509 if buffer.forwardLine(1) != 0 { break }
510 }
511 }
512 }
513
514 /// `org-escape-code-in-region`.
515 static func escapeCode(_ buffer: EmacsBuffer, from start: Int, to end: Int) {
516 buffer.point = start
517 let stop = buffer.marker(end)
518 defer { buffer.release(stop) }
519 while buffer.point < stop.position {
520 let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
521 if let m = line.firstMatch(of: /^[ \t]*(,*(\*|#\+))/) {
522 buffer.point += line[..<m.1.startIndex].utf16.count
523 buffer.insert(",")
524 }
525 if buffer.forwardLine(1) != 0 { break }
526 }
527 }
528
529 /// `org-babel-examplify-region`: fewer than ten lines get `: `, more an example block.
530 static func examplify(_ buffer: EmacsBuffer, _ beg: Int, _ end: Int) {
531 let text = buffer.substring(beg, end)
532 var size = text.components(separatedBy: "\n").count - (text.utf16.last == 10 ? 1 : 0)
533 if text.isEmpty { size = 0 }
534 guard size > 0 else { return }
535 if size < 10 {
536 buffer.point = beg
537 for _ in 0..<size {
538 buffer.point = buffer.lineStart(buffer.point)
539 buffer.insert(": ")
540 buffer.forwardLine(1)
541 }
542 return
543 }
544 let endMarker = buffer.marker(end)
545 defer { buffer.release(endMarker) }
546 buffer.point = beg
547 buffer.insert("#+begin_example\n")
548 escapeCode(buffer, from: buffer.point, to: endMarker.position)
549 buffer.point = endMarker.position
550 if !buffer.bolp { buffer.insert("\n") }
551 buffer.insert("#+end_example")
552 if !buffer.eolp { buffer.insert("\n") }
553 }
554}