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