Commit 1463e5877b

1463e5877b72143aaef62fe7ffcd24f9394e3c75

parent: 2f17964617

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-22 18:33 UTC

Speed up parsing and opening files

Parsing tests bytes before searching by Character: radio targets
(slower since 6c7e17c), description item tags (since 0cc0e6b), line
classes and table pipes. A parsed tree keeps the parsed text instead
of rebuilding it.

Opening: startup folds skip layout invalidation before the first
layout; Wrappers.all and shadedBlocks make no node per paragraph; the
line index reads the text in blocks; spelling marks are cleared only
when spell checking was on.

Closes #228

Layout: unified · split

Sources/OrgCore/Parser/Lines.swift +23 −9
@@ -84,7 +84,9 @@ func classifyLine(_ line: Substring, alphabetical: Bool = false) -> ClassifiedLi
84let inlineTaskLevel = 15 84let inlineTaskLevel = 15
85 85
86private func lineClass(_ rest: Substring, columnZero: Bool, alphabetical: Bool) -> LineClass { 86private func lineClass(_ rest: Substring, columnZero: Bool, alphabetical: Bool) -> LineClass {
87 let trimmed = rest.trimmingTrailingWhitespace 87 lazy var trimmed = rest.trimmingTrailingWhitespace
88 // Every test below needs a particular first character; the first byte rules most out.
89 let first = rest.utf8.first
88 90
89 // As org's `org-outline-regexp`: stars and then a space. A lone `*`, or stars before a tab, 91 // As org's `org-outline-regexp`: stars and then a space. A lone `*`, or stars before a tab,
90 // is not a heading. 92 // is not a heading.
@@ -96,7 +98,7 @@ private func lineClass(_ rest: Substring, columnZero: Bool, alphabetical: Bool)
96 } 98 }
97 } 99 }
98 100
99 if rest.hasPrefix("#+") { 101 if first == UInt8(ascii: "#"), rest.hasPrefix("#+") {
100 let lower = trimmed.lowercased() 102 let lower = trimmed.lowercased()
101 if lower.hasPrefix("#+begin_") { 103 if lower.hasPrefix("#+begin_") {
102 let name = lower.dropFirst(8).prefix { !$0.isWhitespace } 104 let name = lower.dropFirst(8).prefix { !$0.isWhitespace }
@@ -114,9 +116,9 @@ private func lineClass(_ rest: Substring, columnZero: Bool, alphabetical: Bool)
114 } 116 }
115 } 117 }
116 118
117 if trimmed == "#" || rest.hasPrefix("# ") || rest.hasPrefix("#\t") { return .comment } 119 if first == UInt8(ascii: "#"), trimmed == "#" || rest.hasPrefix("# ") || rest.hasPrefix("#\t") { return .comment }
118 120
119 if rest.hasPrefix("\\begin{") || rest.hasPrefix("\\end{") { 121 if first == UInt8(ascii: "\\"), rest.hasPrefix("\\begin{") || rest.hasPrefix("\\end{") {
120 let begin = rest.hasPrefix("\\begin{") 122 let begin = rest.hasPrefix("\\begin{")
121 let after = rest.dropFirst(begin ? 7 : 5) 123 let after = rest.dropFirst(begin ? 7 : 5)
122 let name = after.prefix { $0.isLetter || $0.isNumber || $0 == "*" } 124 let name = after.prefix { $0.isLetter || $0.isNumber || $0 == "*" }
@@ -141,16 +143,17 @@ private func lineClass(_ rest: Substring, columnZero: Bool, alphabetical: Bool)
141 143
142 if rest.first == "|" { return .tableRow } 144 if rest.first == "|" { return .tableRow }
143 if rest.first == "+", trimmed.wholeMatch(of: /\+(?:-+\+)+/) != nil { return .tableElRule } 145 if rest.first == "+", trimmed.wholeMatch(of: /\+(?:-+\+)+/) != nil { return .tableElRule }
144 if columnZero, rest.hasPrefix("%%(") { return .diarySexp } 146 if columnZero, first == UInt8(ascii: "%"), rest.hasPrefix("%%(") { return .diarySexp }
145 if trimmed.count >= 5, trimmed.allSatisfy({ $0 == "-" }) { return .horizontalRule } 147 if rest.first == "-", trimmed.count >= 5, trimmed.allSatisfy({ $0 == "-" }) { return .horizontalRule }
146 148
147 if columnZero, rest.hasPrefix("[fn:"), let close = rest.firstIndex(of: "]"), 149 if columnZero, first == UInt8(ascii: "["), rest.hasPrefix("[fn:"), let close = rest.firstIndex(of: "]"),
148 close > rest.index(rest.startIndex, offsetBy: 4) { 150 close > rest.index(rest.startIndex, offsetBy: 4) {
149 return .footnoteDefinition 151 return .footnoteDefinition
150 } 152 }
151 153
152 if rest.hasPrefix("CLOCK:") { return .clock } 154 if first == UInt8(ascii: "C"), rest.hasPrefix("CLOCK:") { return .clock }
153 if rest.hasPrefix("SCHEDULED:") || rest.hasPrefix("DEADLINE:") || rest.hasPrefix("CLOSED:") { return .planning } 155 if first == UInt8(ascii: "S") || first == UInt8(ascii: "D") || first == UInt8(ascii: "C"),
156 rest.hasPrefix("SCHEDULED:") || rest.hasPrefix("DEADLINE:") || rest.hasPrefix("CLOSED:") { return .planning }
154 if isListBullet(rest, indented: !columnZero, alphabetical: alphabetical) { return .listItem } 157 if isListBullet(rest, indented: !columnZero, alphabetical: alphabetical) { return .listItem }
155 return .plain 158 return .plain
156} 159}
@@ -175,6 +178,17 @@ private func isListBullet(_ rest: Substring, indented: Bool, alphabetical: Bool)
175 return afterBullet.isEmpty || afterBullet.first == " " || afterBullet.first == "\t" 178 return afterBullet.isEmpty || afterBullet.first == " " || afterBullet.first == "\t"
176} 179}
177 180
181/// Whether `bytes` holds a run of `count` copies of `byte`. A cheap test before a search by
182/// Character.
183func containsBytes(_ bytes: Substring.UTF8View, _ byte: UInt8, count: Int) -> Bool {
184 var run = 0
185 for b in bytes {
186 run = b == byte ? run + 1 : 0
187 if run == count { return true }
188 }
189 return false
190}
191
178extension Substring { 192extension Substring {
179 var trimmingTrailingWhitespace: Substring { 193 var trimmingTrailingWhitespace: Substring {
180 var s = self 194 var s = self
Sources/OrgCore/Parser/Parser.swift +11 −6
@@ -1,7 +1,8 @@
1public enum OrgParser { 1public enum OrgParser {
2 public static func parse(_ text: String, defaults: OrgSettings = .default) -> OrgTree { 2 public static func parse(_ text: String, defaults: OrgSettings = .default) -> OrgTree {
3 var parser = Parser(text: text, defaults: defaults) 3 var parser = Parser(text: text, defaults: defaults)
4 return parser.run() 4 let tree = parser.run()
5 return OrgTree(green: tree.green, settings: tree.settings, text: text)
5 } 6 }
6} 7}
7 8
@@ -330,15 +331,18 @@ struct Parser {
330 if rest.hasPrefix("|-") { 331 if rest.hasPrefix("|-") {
331 builder.token(.text, rest) 332 builder.token(.text, rest)
332 } else { 333 } else {
334 // Pipes are found by byte; one counts only where the Character there is a lone `|`,
335 // as a walk by Character would find it.
333 var cellStart = rest.startIndex 336 var cellStart = rest.startIndex
334 var index = rest.startIndex 337 let bytes = rest.utf8
335 while index < rest.endIndex { 338 var index = bytes.startIndex
336 if rest[index] == "|" { 339 while index < bytes.endIndex {
340 if bytes[index] == UInt8(ascii: "|"), rest[index] == "|" {
337 if index > rest.startIndex { tableCell(rest[cellStart..<index]) } 341 if index > rest.startIndex { tableCell(rest[cellStart..<index]) }
338 builder.token(.marker, "|") 342 builder.token(.marker, "|")
339 cellStart = rest.index(after: index) 343 cellStart = bytes.index(after: index)
340 } 344 }
341 index = rest.index(after: index) 345 index = bytes.index(after: index)
342 } 346 }
343 if cellStart < rest.endIndex { tableCell(rest[cellStart...]) } 347 if cellStart < rest.endIndex { tableCell(rest[cellStart...]) }
344 } 348 }
@@ -451,6 +455,7 @@ struct Parser {
451 /// A description item's tag and separator: the text before the last ` ::` on the line 455 /// A description item's tag and separator: the text before the last ` ::` on the line
452 /// that ends it or has blanks after it, and that blank with the `::`. 456 /// that ends it or has blanks after it, and that blank with the `::`.
453 static func descriptionTag(_ s: Substring) -> (tag: Substring, separator: Substring)? { 457 static func descriptionTag(_ s: Substring) -> (tag: Substring, separator: Substring)? {
458 guard containsBytes(s.utf8, UInt8(ascii: ":"), count: 2) else { return nil }
454 let line = s.prefix { $0 != "\n" && $0 != "\r" } 459 let line = s.prefix { $0 != "\n" && $0 != "\r" }
455 var k = line.endIndex 460 var k = line.endIndex
456 while k > line.startIndex { 461 while k > line.startIndex {
Sources/OrgCore/Parser/Settings.swift +1 −1
@@ -140,7 +140,7 @@ enum SettingsScanner {
140 } 140 }
141 let sequences = types + todos + seqs 141 let sequences = types + todos + seqs
142 var radio: [String] = [] 142 var radio: [String] = []
143 for line in lines where line.content.utf8.contains(UInt8(ascii: "<")) && line.content.contains("<<<") { 143 for line in lines where containsBytes(line.content.utf8, UInt8(ascii: "<"), count: 3) {
144 for m in String(line.content).matches(of: /<<<([^<>\n\r \t](?:[^<>\n\r]*[^<>\n\r \t])?)>>>/) where !radio.contains(String(m.1)) { 144 for m in String(line.content).matches(of: /<<<([^<>\n\r \t](?:[^<>\n\r]*[^<>\n\r \t])?)>>>/) where !radio.contains(String(m.1)) {
145 radio.append(String(m.1)) 145 radio.append(String(m.1))
146 } 146 }
Sources/OrgCore/Syntax/SyntaxNode.swift +15 −2
@@ -120,15 +120,24 @@ public struct SyntaxToken: Sendable, Equatable {
120public struct OrgTree: Sendable { 120public struct OrgTree: Sendable {
121 public let green: GreenNode 121 public let green: GreenNode
122 public let settings: OrgSettings 122 public let settings: OrgSettings
123 private let textCache = TextCache() 123 private let textCache: TextCache
124 124
125 public init(green: GreenNode, settings: OrgSettings) { 125 public init(green: GreenNode, settings: OrgSettings) {
126 self.green = green 126 self.green = green
127 self.settings = settings 127 self.settings = settings
128 textCache = TextCache()
129 }
130
131 /// A tree parsed from `text`, which its tokens spell out exactly.
132 init(green: GreenNode, settings: OrgSettings, text: String) {
133 self.green = green
134 self.settings = settings
135 textCache = TextCache(text)
128 } 136 }
129 137
130 public var root: SyntaxNode { SyntaxNode(green: green, offset: 0, parent: nil) } 138 public var root: SyntaxNode { SyntaxNode(green: green, offset: 0, parent: nil) }
131 /// Built from the tree on first use, then kept: views read it once per heading. 139 /// The text the tree was parsed from, or for a tree made another way, built from it on
140 /// first use and kept: views read it once per heading.
132 public var text: String { textCache.text(of: green) } 141 public var text: String { textCache.text(of: green) }
133} 142}
134 143
@@ -137,6 +146,10 @@ private final class TextCache: @unchecked Sendable {
137 private let lock = NSLock() 146 private let lock = NSLock()
138 private var text: String? 147 private var text: String?
139 148
149 init(_ text: String? = nil) {
150 self.text = text
151 }
152
140 func text(of green: GreenNode) -> String { 153 func text(of green: GreenNode) -> String {
141 lock.withLock { 154 lock.withLock {
142 if let text { return text } 155 if let text { return text }
Sources/OrgCore/Syntax/Wrappers.swift +6 −1
@@ -45,8 +45,13 @@ public enum Wrappers {
45 public static func all(_ tree: OrgTree) -> [Wrapper] { 45 public static func all(_ tree: OrgTree) -> [Wrapper] {
46 var result: [Wrapper] = [] 46 var result: [Wrapper] = []
47 let text = tree.text as NSString 47 let text = tree.text as NSString
48 // Nodes are made only for drawers, blocks and containers, not for every paragraph.
48 func walk(_ node: SyntaxNode) { 49 func walk(_ node: SyntaxNode) {
49 for child in node.children { 50 var at = node.offset
51 for element in node.green.children {
52 defer { at += element.length }
53 guard case .node(let green) = element, kind(green.kind) != nil || containers.contains(green.kind) else { continue }
54 let child = SyntaxNode(green: green, offset: at, parent: node)
50 if let wrapper = wrapper(child, in: text) { result.append(wrapper) } 55 if let wrapper = wrapper(child, in: text) { result.append(wrapper) }
51 if containers.contains(child.kind) { walk(child) } 56 if containers.contains(child.kind) { walk(child) }
52 } 57 }
Sources/OrgEditorAppKit/LineIndex.swift +6 −4
@@ -14,13 +14,15 @@ final class LineIndex {
14 appendStarts(in: text, from: 0, to: text.length) 14 appendStarts(in: text, from: 0, to: text.length)
15 } 15 }
16 16
17 /// Reads the text in blocks: a search per line costs more than reading every character.
17 private func appendStarts(in text: NSString, from: Int, to end: Int) { 18 private func appendStarts(in text: NSString, from: Int, to end: Int) {
19 var buffer = [unichar](repeating: 0, count: 4096)
18 var location = from 20 var location = from
19 while location < end { 21 while location < end {
20 let found = text.range(of: "\n", options: .literal, range: NSRange(location: location, length: end - location)) 22 let count = min(buffer.count, end - location)
21 guard found.location != NSNotFound else { break } 23 text.getCharacters(&buffer, range: NSRange(location: location, length: count))
22 starts.append(found.location + 1) 24 for i in 0..<count where buffer[i] == 10 { starts.append(location + i + 1) }
23 location = found.location + 1 25 location += count
24 } 26 }
25 } 27 }
26 28
Sources/OrgEditorAppKit/OrgEditor+Folding.swift +4 −3
@@ -15,8 +15,9 @@ extension OrgEditor {
15 setFolds(state, wrappers: nil) 15 setFolds(state, wrappers: nil)
16 } 16 }
17 17
18 /// `wrappers`, when given, holds every folded drawer and block. 18 /// `wrappers`, when given, holds every folded drawer and block. `layout` is false when
19 func setFolds(_ state: FoldState, wrappers: [Wrapper]?) { 19 /// nothing has been laid out since the text loaded, so there is no layout to invalidate.
20 func setFolds(_ state: FoldState, wrappers: [Wrapper]?, layout: Bool = true) {
20 sparseHidden = nil 21 sparseHidden = nil
21 view.folds = state.folds 22 view.folds = state.folds
22 view.bodyFolds = state.bodyFolds 23 view.bodyFolds = state.bodyFolds
@@ -27,7 +28,7 @@ extension OrgEditor {
27 : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) }) 28 : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) })
28 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a } 29 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
29 view.wrapperFolds = Set(wrapperHidden.keys) 30 view.wrapperFolds = Set(wrapperHidden.keys)
30 updateHiddenAndLayout() 31 if layout { updateHiddenAndLayout() } else { updateHidden() }
31 redrawViews() 32 redrawViews()
32 caretsOutOfHiddenText() 33 caretsOutOfHiddenText()
33 } 34 }
Sources/OrgEditorAppKit/OrgEditor.swift +3 −2
@@ -125,10 +125,11 @@ public final class OrgEditor: NSObject {
125 // Files open at their start, as in Emacs; replacing the storage leaves it at the end. 125 // Files open at their start, as in Emacs; replacing the storage leaves it at the end.
126 textView.setSelectedRange(NSRange(location: 0, length: 0)) 126 textView.setSelectedRange(NSRange(location: 0, length: 0))
127 if let startup { 127 if let startup {
128 if startup.folds != FoldState() { setFolds(startup.folds, wrappers: startup.wrappers) } 128 if startup.folds != FoldState() { setFolds(startup.folds, wrappers: startup.wrappers, layout: false) }
129 if startup.alignTables { _ = perform(AlignAllTables()) } 129 if startup.alignTables { _ = perform(AlignAllTables()) }
130 } 130 }
131 spellChecking = options.spellCheck 131 // Turning it off clears spelling marks from the whole text; a new view has none.
132 if spellChecking != options.spellCheck { spellChecking = options.spellCheck }
132 truncatesLines = options.startupTruncated 133 truncatesLines = options.startupTruncated
133 } 134 }
134 135
Sources/OrgPresentation/Presentation.swift +9 −5
@@ -223,20 +223,24 @@ public enum Presentation {
223 223
224 private static func computeShadedBlocks(_ tree: OrgTree) -> [Range<Int>] { 224 private static func computeShadedBlocks(_ tree: OrgTree) -> [Range<Int>] {
225 var ranges: [Range<Int>] = [] 225 var ranges: [Range<Int>] = []
226 func walk(_ node: SyntaxNode) { 226 // Over green nodes, so no node object is made for each paragraph.
227 for child in node.children { 227 func walk(_ node: GreenNode, at offset: Int) {
228 var at = offset
229 for element in node.children {
230 defer { at += element.length }
231 guard case .node(let child) = element else { continue }
228 switch child.kind { 232 switch child.kind {
229 case .block, .dynamicBlock, .fixedWidth: 233 case .block, .dynamicBlock, .fixedWidth:
230 // Without the blank lines org counts as part of the element. 234 // Without the blank lines org counts as part of the element.
231 let text = child.text 235 let text = child.text
232 let trimmed = text.utf16.count - String(text.reversed().prefix { $0.isWhitespace }).utf16.count 236 let trimmed = text.utf16.count - String(text.reversed().prefix { $0.isWhitespace }).utf16.count
233 ranges.append(child.range.lowerBound..<(child.range.lowerBound + trimmed)) 237 ranges.append(at..<(at + trimmed))
234 case .paragraph, .table, .heading, .planning, .propertyDrawer, .drawer, .keyword, .comment: continue 238 case .paragraph, .table, .heading, .planning, .propertyDrawer, .drawer, .keyword, .comment: continue
235 default: walk(child) 239 default: walk(child, at: at)
236 } 240 }
237 } 241 }
238 } 242 }
239 walk(tree.root) 243 walk(tree.green, at: 0)
240 return ranges 244 return ranges
241 } 245 }
242 246
Tests/OrgCoreTests/ParserElementTests.swift +6
@@ -52,6 +52,12 @@ struct ParserElementTests {
52 #expect(table.children.map(\.kind) == [.tableRow, .tableRow, .tableRow, .tableFormula, .tableFormula]) 52 #expect(table.children.map(\.kind) == [.tableRow, .tableRow, .tableRow, .tableFormula, .tableFormula])
53 } 53 }
54 54
55 @Test func pipeWithACombiningMarkIsCellText() {
56 let row = OrgParser.parse("| a |\u{301} b | ü |\n").root.children[0].children[0].children[0]
57 #expect(row.tokens.filter { $0.kind == .marker }.count == 3)
58 #expect(row.children.filter { $0.kind == .tableCell }.map(\.text) == [" a |\u{301} b ", " ü "])
59 }
60
55 @Test func footnoteDefinition() { 61 @Test func footnoteDefinition() {
56 #expect(childKinds("[fn:1] note\ncontinued\n\nafter\n") == [.footnoteDefinition, .paragraph]) 62 #expect(childKinds("[fn:1] note\ncontinued\n\nafter\n") == [.footnoteDefinition, .paragraph])
57 } 63 }
Tests/OrgCoreTests/ParserSectionTests.swift +3 −3
@@ -12,7 +12,7 @@ func tokens(of kind: SyntaxKind, in text: String) -> [SyntaxToken] {
12struct ParserSectionTests { 12struct ParserSectionTests {
13 @Test func emptyDocument() { 13 @Test func emptyDocument() {
14 let tree = OrgParser.parse("") 14 let tree = OrgParser.parse("")
15 #expect(tree.text == "") 15 #expect(tree.root.text == "")
16 #expect(nodeKinds("") == [.document]) 16 #expect(nodeKinds("") == [.document])
17 } 17 }
18 18
@@ -63,11 +63,11 @@ struct ParserSectionTests {
63 } 63 }
64 64
65 @Test func headingWithoutNewlineAtEnd() { 65 @Test func headingWithoutNewlineAtEnd() {
66 #expect(OrgParser.parse("* a").text == "* a") 66 #expect(OrgParser.parse("* a").root.text == "* a")
67 } 67 }
68 68
69 @Test(arguments: ["* a\n", "*\n", "* TODO\n", "text\r\n* a\r\n** b\r\n", "\n\n* a\n\n"]) 69 @Test(arguments: ["* a\n", "*\n", "* TODO\n", "text\r\n* a\r\n** b\r\n", "\n\n* a\n\n"])
70 func roundTrip(text: String) { 70 func roundTrip(text: String) {
71 #expect(OrgParser.parse(text).text == text) 71 #expect(OrgParser.parse(text).root.text == text)
72 } 72 }
73} 73}
Tests/OrgCoreTests/RoundTripTests.swift +3 −3
@@ -50,7 +50,7 @@ struct RoundTripTests {
50 for n in 0..<2_000 { 50 for n in 0..<2_000 {
51 let text = randomDocument(&rng) 51 let text = randomDocument(&rng)
52 let tree = OrgParser.parse(text) 52 let tree = OrgParser.parse(text)
53 #expect(tree.text == text, "document \(n)") 53 #expect(tree.root.text == text, "document \(n)")
54 #expect(checkLengths(tree.root), "document \(n)") 54 #expect(checkLengths(tree.root), "document \(n)")
55 _ = DocumentModel(tree: tree) 55 _ = DocumentModel(tree: tree)
56 } 56 }
@@ -66,7 +66,7 @@ struct RoundTripTests {
66 func encodingFixturesRoundTrip(bytes: [UInt8]) { 66 func encodingFixturesRoundTrip(bytes: [UInt8]) {
67 let source = SourceText(bytes: bytes) 67 let source = SourceText(bytes: bytes)
68 let tree = OrgParser.parse(source.text) 68 let tree = OrgParser.parse(source.text)
69 #expect(source.encode(tree.text) == bytes) 69 #expect(source.encode(tree.root.text) == bytes)
70 } 70 }
71 71
72 /// Private corpus: `ORGSTAR_CORPUS=/path/to/org swift test --filter corpus`. 72 /// Private corpus: `ORGSTAR_CORPUS=/path/to/org swift test --filter corpus`.
@@ -81,7 +81,7 @@ struct RoundTripTests {
81 let bytes = try [UInt8](Data(contentsOf: file)) 81 let bytes = try [UInt8](Data(contentsOf: file))
82 let source = SourceText(bytes: bytes) 82 let source = SourceText(bytes: bytes)
83 let tree = OrgParser.parse(source.text) 83 let tree = OrgParser.parse(source.text)
84 #expect(source.encode(tree.text) == bytes, "\(file.path)") 84 #expect(source.encode(tree.root.text) == bytes, "\(file.path)")
85 _ = DocumentModel(tree: tree) 85 _ = DocumentModel(tree: tree)
86 } 86 }
87 } 87 }