Sources/OrgCore/Parser/Incremental.swift
419 lines · 20212 bytes
1import Foundation
2
3public struct TextEdit: Sendable, Equatable {
4 /// UTF-16 range in the old text, on unicode scalar boundaries.
5 public let range: Range<Int>
6 public let replacement: String
7
8 public init(range: Range<Int>, replacement: String) {
9 self.range = range
10 self.replacement = replacement
11 }
12
13 /// Works on unicode scalars, so an edit between "\r" and "\n" stays exact.
14 public func apply(to text: String) -> String {
15 let scalars = text.unicodeScalars
16 let start = String.Index(utf16Offset: range.lowerBound, in: text)
17 let end = String.Index(utf16Offset: range.upperBound, in: text)
18 return String(scalars[..<start]) + replacement + String(scalars[end...])
19 }
20}
21
22enum ReparseStrategy: Equatable {
23 /// One element reparsed in place; everything else reused.
24 case element
25 /// A run of elements in one section's body reparsed; everything else reused.
26 case region
27 /// A run of top-level sections reparsed; the sections before and after reused.
28 case sections
29 case full
30}
31
32extension OrgParser {
33 /// The tree for `edit.apply(to: oldText)`, reusing as much of `old` as stays valid. Always
34 /// equal to a full parse of the new text.
35 public static func reparse(_ old: OrgTree, oldText: String, edit: TextEdit, defaults: OrgSettings = .default) -> OrgTree {
36 reparseWithStrategy(old, oldText: oldText, edit: edit, defaults: defaults).tree
37 }
38
39 static func reparseWithStrategy(
40 _ old: OrgTree, oldText: String, edit: TextEdit, defaults: OrgSettings = .default
41 ) -> (tree: OrgTree, strategy: ReparseStrategy) {
42 let newText = edit.apply(to: oldText)
43 let context = ReparseContext(oldText: oldText, newText: newText, edit: edit, alphabetical: defaults.listAllowAlphabetical)
44 if context.touchesSettings() { return (parse(newText, defaults: defaults), .full) }
45 if let tree = context.reparseElement(old) { return (tree, .element) }
46 if let tree = context.reparseRegion(old) { return (tree, .region) }
47 if let tree = context.reparseSections(old) { return (tree, .sections) }
48 return (parse(newText, defaults: defaults), .full)
49 }
50}
51
52private struct ReparseContext {
53 let oldText: String
54 let newText: String
55 let edit: TextEdit
56 /// `org-list-allow-alphabetical`, for classifying lines.
57 let alphabetical: Bool
58 /// Change in UTF-16 length.
59 var delta: Int { edit.replacement.utf16.count - edit.range.count }
60
61 static let settingsKeys: Set<String> = ["TODO", "SEQ_TODO", "TYP_TODO", "PRIORITIES"]
62
63 /// Elements that parse the same in isolation as in place, as long as their lines keep
64 /// their classes.
65 static let leafKinds: Set<SyntaxKind> = [
66 .paragraph, .heading, .tableRow, .planning, .clock, .keyword, .affiliatedKeyword, .horizontalRule,
67 .nodeProperty, .block, .comment, .fixedWidth, .footnoteDefinition,
68 ]
69
70 /// File settings must be read again when an edited line is a settings keyword, or when it
71 /// moves a block or heading boundary in a file that has settings keywords: that can hide or
72 /// expose a keyword inside a block.
73 func touchesSettings() -> Bool {
74 let start = lineStart(oldText, edit.range.lowerBound)
75 let oldLines = classes(slice(oldText, start, lineEnd(oldText, edit.range.upperBound)))
76 let newLines = classes(slice(newText, start, lineEnd(newText, edit.range.lowerBound + edit.replacement.utf16.count)))
77 // Radio targets make links all through the file.
78 if slice(oldText, start, lineEnd(oldText, edit.range.upperBound)).contains("<<<")
79 || slice(newText, start, lineEnd(newText, edit.range.lowerBound + edit.replacement.utf16.count)).contains("<<<")
80 || slice(oldText, start, lineEnd(oldText, edit.range.upperBound)).contains(">>>") { return true }
81 var movesBoundary = false
82 for line in oldLines + newLines {
83 switch line.cls {
84 case .keyword(let key) where Self.settingsKeys.contains(key):
85 return true
86 case .blockBegin, .blockEnd, .dynamicBegin, .dynamicEnd, .latexBegin, .latexEnd, .heading:
87 movesBoundary = true
88 default:
89 break
90 }
91 }
92 return movesBoundary && Self.settingsKeys.contains { newText.range(of: "#+\($0):", options: .caseInsensitive) != nil }
93 }
94
95 // MARK: - Element
96
97 func reparseElement(_ old: OrgTree) -> OrgTree? {
98 guard let leaf = leaf(in: old.root) else { return nil }
99 let start = lineStart(oldText, leaf.range.lowerBound)
100 // An element that starts mid-line (an item's paragraph) follows tokens that would absorb
101 // whitespace typed at its start.
102 guard start == leaf.range.lowerBound || edit.range.lowerBound > leaf.range.lowerBound else { return nil }
103 let oldEnd = leaf.range.upperBound
104 let newEnd = oldEnd + delta
105 let newLength = newText.utf16.count
106 guard newEnd > leaf.range.lowerBound, newEnd <= newLength else { return nil }
107 // The element must still end at a line end.
108 if newEnd < newLength {
109 let utf16 = newText.utf16
110 guard utf16[utf16.index(utf16.startIndex, offsetBy: newEnd - 1)] == 0x0A else { return nil }
111 }
112 let oldClasses = classes(slice(oldText, start, oldEnd))
113 let newClasses = classes(slice(newText, start, newEnd))
114 guard oldClasses.count == newClasses.count,
115 zip(oldClasses, newClasses).allSatisfy({ $0.cls == $1.cls && $0.indent == $1.indent }) else { return nil }
116 let text = String(slice(newText, leaf.range.lowerBound, newEnd))
117 guard let green = Parser.reparseElement(leaf.kind, text: text, settings: old.settings) else { return nil }
118 return OrgTree(green: replacing(leaf, with: green), settings: old.settings)
119 }
120
121 /// The outermost leaf element containing the edit.
122 func leaf(in root: SyntaxNode) -> SyntaxNode? {
123 let range = edit.range
124 var current = root
125 while let child = current.child(containing: range.lowerBound), range.upperBound <= child.range.upperBound {
126 if Self.leafKinds.contains(child.kind) { return child }
127 current = child
128 }
129 return nil
130 }
131
132 /// Copies the path from the root down to `target`, swapping in `green`.
133 func replacing(_ target: SyntaxNode, with green: GreenNode) -> GreenNode {
134 var node = target
135 var replacement = green
136 while let parent = node.parent {
137 var children = parent.green.children
138 let index = children.firstIndex {
139 if case .node(let child) = $0 { return child === node.green }
140 return false
141 }!
142 children[index] = .node(replacement)
143 replacement = GreenNode(kind: parent.kind, children: children)
144 node = parent
145 }
146 return replacement
147 }
148
149 // MARK: - Body region
150
151 /// Reparses a window of the innermost section's own body (the elements between its heading
152 /// lines and its first child section) and splices it into the old section.
153 ///
154 /// The window starts one element before the element holding the line before the edit. It ends at the first
155 /// later element boundary that the reparse reproduces at the same shifted offset. The
156 /// window is parsed one element past that boundary, so every decision about where an element
157 /// ends was made with the following line in view; from a reproduced boundary on, elements
158 /// parse the same as before. Edits that touch heading lines, the first line after a heading
159 /// (where planning lines and property drawers are only recognized), or that add an end
160 /// delimiter (which could pair with a begin line before the window) are left to the
161 /// section strategy.
162 func reparseRegion(_ old: OrgTree) -> OrgTree? {
163 let start = lineStart(oldText, edit.range.lowerBound)
164 let oldLines = classes(slice(oldText, start, lineEnd(oldText, edit.range.upperBound)))
165 let newLines = classes(slice(newText, start, lineEnd(newText, edit.range.lowerBound + edit.replacement.utf16.count)))
166 for line in oldLines + newLines {
167 if case .heading = line.cls { return nil }
168 }
169 for line in newLines {
170 switch line.cls {
171 case .blockEnd, .dynamicEnd, .drawerEnd: return nil
172 default: break
173 }
174 }
175
176 // The innermost section or zeroth section holding the edited lines.
177 let damaged = start..<max(lineEnd(oldText, edit.range.upperBound), start + 1)
178 var container = old.root
179 while let child = container.child(containing: damaged.lowerBound),
180 child.kind == .section || child.kind == .zerothSection,
181 damaged.upperBound <= child.range.upperBound {
182 container = child
183 }
184 guard container.kind == .section || container.kind == .zerothSection else { return nil }
185
186 // Body children with their offsets.
187 var body: [(element: GreenElement, offset: Int)] = []
188 var bodyStart = container.range.lowerBound
189 var bodyEnd = container.range.upperBound
190 var offset = container.range.lowerBound
191 var prefixCount = 0
192 for (index, element) in container.green.children.enumerated() {
193 defer { offset += element.length }
194 if case .node(let node) = element {
195 if [.heading, .planning, .propertyDrawer].contains(node.kind), body.isEmpty {
196 prefixCount = index + 1
197 bodyStart = offset + node.length
198 continue
199 }
200 if node.kind == .section {
201 bodyEnd = offset
202 break
203 }
204 }
205 body.append((element, offset))
206 }
207 // The first body line of a heading section can become a planning line or drawer.
208 let firstEditable = container.kind == .section ? lineEnd(oldText, bodyStart) : bodyStart
209 guard start >= firstEditable, edit.range.upperBound <= bodyEnd, !body.isEmpty else { return nil }
210
211 // Window start: the body element holding the line before the edit, and one more before
212 // it, which could absorb the window's first line if that line changes meaning (a drawer
213 // that loses its end turns into paragraph text).
214 let anchor = max(bodyStart, start - 1)
215 guard var first = body.lastIndex(where: { $0.offset <= anchor }) else { return nil }
216 while first > 0, case .token = body[first].element { first -= 1 }
217 if first > 0 {
218 first -= 1
219 while first > 0, case .token = body[first].element { first -= 1 }
220 }
221 let windowStart = body[first].offset
222
223 var next = body.firstIndex { $0.offset > edit.range.upperBound } ?? body.count
224 var attempts = 0
225 while attempts < 8 {
226 attempts += 1
227 // Parse through one node past the candidate boundary.
228 var verifyEnd = next
229 while verifyEnd < body.count, case .token = body[verifyEnd].element { verifyEnd += 1 }
230 let boundary = next < body.count ? body[next].offset : bodyEnd
231 let oldWindowEnd = verifyEnd < body.count ? body[verifyEnd].offset + body[verifyEnd].element.length : bodyEnd
232 let rows = reusableRows(body[first..<min(verifyEnd + 1, body.count)].map(\.element))
233 guard let window = parseBody(slice(newText, windowStart, oldWindowEnd + delta), settings: old.settings, rows: rows) else { return nil }
234 if window.unmatchedBegin, oldWindowEnd < bodyEnd {
235 next = body.count
236 continue
237 }
238 // The reparsed elements up to the boundary, if the reparse has one there.
239 let target = boundary + delta - windowStart
240 var reparsed: [GreenElement] = []
241 var at = 0
242 for element in window.elements where at < target {
243 reparsed.append(element)
244 at += element.length
245 }
246 guard at == target else {
247 next += 1
248 if next > body.count { return nil }
249 continue
250 }
251 let before = container.green.children[..<(prefixCount + first)]
252 let after = next < body.count ? Array(body[next...].map(\.element)) : []
253 let tail = container.green.children[(prefixCount + body.count)...]
254 let green = GreenNode(kind: container.kind, children: Array(before) + reparsed + after + Array(tail))
255 // A full parse has no zeroth section for empty text.
256 if green.children.isEmpty { return nil }
257 return OrgTree(green: replacing(container, with: green), settings: old.settings)
258 }
259 return nil
260 }
261
262 /// Rows of the tables among `elements`, keyed by their text.
263 func reusableRows(_ elements: [GreenElement]) -> [Substring: GreenNode] {
264 var rows: [Substring: GreenNode] = [:]
265 for case .node(let table) in elements where table.kind == .table {
266 for case .node(let row) in table.children where row.kind == .tableRow {
267 rows[Substring(row.text)] = row
268 }
269 }
270 return rows
271 }
272
273 /// Body elements parsed from `text`, or nil if the text holds a heading.
274 func parseBody(_ text: Substring, settings: OrgSettings, rows: [Substring: GreenNode] = [:]) -> (elements: [GreenElement], unmatchedBegin: Bool)? {
275 var parser = Parser(text: String(text), settings: settings)
276 parser.reusableRows = rows
277 let count = parser.lines.count
278 parser.builder.start(.zerothSection)
279 parser.parseContent(limit: count)
280 guard parser.i == count else { return nil }
281 parser.builder.finish()
282 var unmatched = false
283 for (index, line) in parser.info.enumerated() {
284 switch line.cls {
285 case .blockBegin, .dynamicBegin, .drawerBegin, .latexBegin:
286 if parser.blockEnds[index] == nil { unmatched = true }
287 default:
288 break
289 }
290 }
291 return (parser.builder.build().children, unmatched)
292 }
293
294 // MARK: - Sections
295
296 /// Reparses from the top-level section before the edit up to the first later top-level
297 /// heading that still ends the reparsed run, then reuses the old sections from there.
298 /// Top-level sections parse independently: blocks and drawers never cross a heading.
299 func reparseSections(_ old: OrgTree) -> OrgTree? {
300 let units = old.root.children
301 guard !units.isEmpty else { return nil }
302 let anchor = max(0, lineStart(oldText, edit.range.lowerBound) - 1)
303 guard let startIndex = units.firstIndex(where: { $0.range.contains(anchor) }) else { return nil }
304 let start = units[startIndex].range.lowerBound
305 var endIndex = units.firstIndex { $0.range.lowerBound > edit.range.upperBound } ?? units.count
306 let newLength = newText.utf16.count
307 while true {
308 let newEnd = endIndex < units.count ? units[endIndex].range.lowerBound + delta : newLength
309 var parser = Parser(text: String(slice(newText, start, newEnd)), settings: old.settings)
310 let window = parser.run().green
311 if endIndex == units.count || endsRun(window, next: units[endIndex].green) {
312 let children = units[..<startIndex].map { GreenElement.node($0.green) }
313 + window.children
314 + units[endIndex...].map { GreenElement.node($0.green) }
315 return OrgTree(green: GreenNode(kind: .document, children: children), settings: old.settings)
316 }
317 endIndex += 1
318 }
319 }
320
321 /// Whether the heading of `next` ends the last section of the reparsed window.
322 func endsRun(_ window: GreenNode, next: GreenNode) -> Bool {
323 guard case .node(let last)? = window.children.last, last.kind == .section else { return true }
324 return headingLevel(next) <= headingLevel(last)
325 }
326
327 func headingLevel(_ section: GreenNode) -> Int {
328 for case .node(let heading) in section.children where heading.kind == .heading {
329 for case .token(let token) in heading.children where token.kind == .stars {
330 return token.text.count
331 }
332 }
333 return 0
334 }
335
336 // MARK: - Text helpers
337
338 func classes(_ text: Substring) -> [ClassifiedLine] {
339 splitRawLines(String(text)).map { classifyLine($0.content, alphabetical: alphabetical) }
340 }
341
342 func slice(_ text: String, _ from: Int, _ to: Int) -> Substring {
343 text[String.Index(utf16Offset: from, in: text)..<String.Index(utf16Offset: to, in: text)]
344 }
345
346 /// UTF-16 offset of the start of the line containing `offset`.
347 func lineStart(_ text: String, _ offset: Int) -> Int {
348 let utf16 = text.utf16
349 var index = utf16.index(utf16.startIndex, offsetBy: offset)
350 while index > utf16.startIndex {
351 let before = utf16.index(before: index)
352 if utf16[before] == 0x0A { break }
353 index = before
354 }
355 return utf16.distance(from: utf16.startIndex, to: index)
356 }
357
358 /// UTF-16 offset just past the newline ending the line containing `offset`.
359 func lineEnd(_ text: String, _ offset: Int) -> Int {
360 let utf16 = text.utf16
361 var index = utf16.index(utf16.startIndex, offsetBy: offset)
362 while index < utf16.endIndex {
363 let current = utf16[index]
364 index = utf16.index(after: index)
365 if current == 0x0A { break }
366 }
367 return utf16.distance(from: utf16.startIndex, to: index)
368 }
369}
370
371extension Parser {
372 /// One element of `kind` parsed from exactly `text`, or nil if `text` doesn't parse as a
373 /// single element of that kind.
374 static func reparseElement(_ kind: SyntaxKind, text: String, settings: OrgSettings) -> GreenNode? {
375 var parser = Parser(text: text, settings: settings)
376 let count = parser.lines.count
377 guard count > 0 else { return nil }
378 switch kind {
379 case .paragraph:
380 parser.paragraph(limit: count, floor: nil)
381 case .heading:
382 guard count == 1 else { return nil }
383 parser.headingLine(parser.lines[0])
384 parser.i = 1
385 case .tableRow:
386 guard count == 1 else { return nil }
387 parser.tableRow()
388 case .planning, .clock, .keyword, .affiliatedKeyword, .horizontalRule, .nodeProperty:
389 guard count == 1 else { return nil }
390 parser.single(kind)
391 case .block, .comment, .fixedWidth, .footnoteDefinition:
392 parser.element(limit: count, floor: nil)
393 default:
394 return nil
395 }
396 guard parser.i == count else { return nil }
397 let green = parser.builder.build()
398 return green.kind == kind ? green : nil
399 }
400}
401
402extension TextEdit {
403 /// The one edit between two texts: everything between their common prefix and suffix.
404 public static func between(_ old: String, _ new: String) -> [TextEdit] {
405 let a = Array(old.utf16)
406 let b = Array(new.utf16)
407 var prefix = 0
408 while prefix < a.count, prefix < b.count, a[prefix] == b[prefix] { prefix += 1 }
409 var suffix = 0
410 while suffix < a.count - prefix, suffix < b.count - prefix, a[a.count - 1 - suffix] == b[b.count - 1 - suffix] { suffix += 1 }
411 // Keep the edit on scalar boundaries.
412 while prefix > 0, (prefix < a.count && UTF16.isTrailSurrogate(a[prefix])) || (prefix < b.count && UTF16.isTrailSurrogate(b[prefix])) { prefix -= 1 }
413 while suffix > 0, suffix < a.count, UTF16.isLeadSurrogate(a[a.count - suffix - 1]) { suffix -= 1 }
414 if prefix == a.count, prefix == b.count { return [] }
415 let replacement = String(utf16CodeUnits: Array(b[prefix..<(b.count - suffix)]), count: b.count - suffix - prefix)
416 return [TextEdit(range: prefix..<(a.count - suffix), replacement: replacement)]
417 }
418
419}