Speed up parsing and opening files !461
12 files changed, +90 −39
Layout: unified · split
Sources/OrgCore/Parser/Lines.swift +23 −9
| @@ -84,7 +84,9 @@ func classifyLine(_ line: Substring, alphabetical: Bool = false) -> ClassifiedLi | ||
| 84 | 84 | let inlineTaskLevel = 15 |
| 85 | 85 | |
| 86 | 86 | private 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 | 91 | // As org's `org-outline-regexp`: stars and then a space. A lone `*`, or stars before a tab, |
| 90 | 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 | 102 | let lower = trimmed.lowercased() |
| 101 | 103 | if lower.hasPrefix("#+begin_") { |
| 102 | 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 | 122 | let begin = rest.hasPrefix("\\begin{") |
| 121 | 123 | let after = rest.dropFirst(begin ? 7 : 5) |
| 122 | 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 | 144 | if rest.first == "|" { return .tableRow } |
| 143 | 145 | if rest.first == "+", trimmed.wholeMatch(of: /\+(?:-+\+)+/) != nil { return .tableElRule } |
| 144 | if columnZero, rest.hasPrefix("%%(") { return .diarySexp } | |
| 145 | if trimmed.count >= 5, trimmed.allSatisfy({ $0 == "-" }) { return .horizontalRule } | |
| 146 | if columnZero, first == UInt8(ascii: "%"), rest.hasPrefix("%%(") { return .diarySexp } | |
| 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 | 150 | close > rest.index(rest.startIndex, offsetBy: 4) { |
| 149 | 151 | return .footnoteDefinition |
| 150 | 152 | } |
| 151 | 153 | |
| 152 | if rest.hasPrefix("CLOCK:") { return .clock } | |
| 153 | if rest.hasPrefix("SCHEDULED:") || rest.hasPrefix("DEADLINE:") || rest.hasPrefix("CLOSED:") { return .planning } | |
| 154 | if first == UInt8(ascii: "C"), rest.hasPrefix("CLOCK:") { return .clock } | |
| 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 | 157 | if isListBullet(rest, indented: !columnZero, alphabetical: alphabetical) { return .listItem } |
| 155 | 158 | return .plain |
| 156 | 159 | } |
| @@ -175,6 +178,17 @@ private func isListBullet(_ rest: Substring, indented: Bool, alphabetical: Bool) | ||
| 175 | 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. | |
| 183 | func 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 | ||
| 178 | 192 | extension Substring { |
| 179 | 193 | var trimmingTrailingWhitespace: Substring { |
| 180 | 194 | var s = self |
Sources/OrgCore/Parser/Parser.swift +11 −6
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | public enum OrgParser { |
| 2 | 2 | public static func parse(_ text: String, defaults: OrgSettings = .default) -> OrgTree { |
| 3 | 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 | 331 | if rest.hasPrefix("|-") { |
| 331 | 332 | builder.token(.text, rest) |
| 332 | 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 | 336 | var cellStart = rest.startIndex |
| 334 | var index = rest.startIndex | |
| 335 | while index < rest.endIndex { | |
| 336 | if rest[index] == "|" { | |
| 337 | let bytes = rest.utf8 | |
| 338 | var index = bytes.startIndex | |
| 339 | while index < bytes.endIndex { | |
| 340 | if bytes[index] == UInt8(ascii: "|"), rest[index] == "|" { | |
| 337 | 341 | if index > rest.startIndex { tableCell(rest[cellStart..<index]) } |
| 338 | 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 | 347 | if cellStart < rest.endIndex { tableCell(rest[cellStart...]) } |
| 344 | 348 | } |
| @@ -451,6 +455,7 @@ struct Parser { | ||
| 451 | 455 | /// A description item's tag and separator: the text before the last ` ::` on the line |
| 452 | 456 | /// that ends it or has blanks after it, and that blank with the `::`. |
| 453 | 457 | static func descriptionTag(_ s: Substring) -> (tag: Substring, separator: Substring)? { |
| 458 | guard containsBytes(s.utf8, UInt8(ascii: ":"), count: 2) else { return nil } | |
| 454 | 459 | let line = s.prefix { $0 != "\n" && $0 != "\r" } |
| 455 | 460 | var k = line.endIndex |
| 456 | 461 | while k > line.startIndex { |
Sources/OrgCore/Parser/Settings.swift +1 −1
| @@ -140,7 +140,7 @@ enum SettingsScanner { | ||
| 140 | 140 | } |
| 141 | 141 | let sequences = types + todos + seqs |
| 142 | 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 | 144 | for m in String(line.content).matches(of: /<<<([^<>\n\r \t](?:[^<>\n\r]*[^<>\n\r \t])?)>>>/) where !radio.contains(String(m.1)) { |
| 145 | 145 | radio.append(String(m.1)) |
| 146 | 146 | } |
Sources/OrgCore/Syntax/SyntaxNode.swift +15 −2
| @@ -120,15 +120,24 @@ public struct SyntaxToken: Sendable, Equatable { | ||
| 120 | 120 | public struct OrgTree: Sendable { |
| 121 | 121 | public let green: GreenNode |
| 122 | 122 | public let settings: OrgSettings |
| 123 | private let textCache = TextCache() | |
| 123 | private let textCache: TextCache | |
| 124 | 124 | |
| 125 | 125 | public init(green: GreenNode, settings: OrgSettings) { |
| 126 | 126 | self.green = green |
| 127 | 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 | 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 | 141 | public var text: String { textCache.text(of: green) } |
| 133 | 142 | } |
| 134 | 143 | |
| @@ -137,6 +146,10 @@ private final class TextCache: @unchecked Sendable { | ||
| 137 | 146 | private let lock = NSLock() |
| 138 | 147 | private var text: String? |
| 139 | 148 | |
| 149 | init(_ text: String? = nil) { | |
| 150 | self.text = text | |
| 151 | } | |
| 152 | ||
| 140 | 153 | func text(of green: GreenNode) -> String { |
| 141 | 154 | lock.withLock { |
| 142 | 155 | if let text { return text } |
Sources/OrgCore/Syntax/Wrappers.swift +6 −1
| @@ -45,8 +45,13 @@ public enum Wrappers { | ||
| 45 | 45 | public static func all(_ tree: OrgTree) -> [Wrapper] { |
| 46 | 46 | var result: [Wrapper] = [] |
| 47 | 47 | let text = tree.text as NSString |
| 48 | // Nodes are made only for drawers, blocks and containers, not for every paragraph. | |
| 48 | 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 | 55 | if let wrapper = wrapper(child, in: text) { result.append(wrapper) } |
| 51 | 56 | if containers.contains(child.kind) { walk(child) } |
| 52 | 57 | } |
Sources/OrgEditorAppKit/LineIndex.swift +6 −4
| @@ -14,13 +14,15 @@ final class LineIndex { | ||
| 14 | 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 | 18 | private func appendStarts(in text: NSString, from: Int, to end: Int) { |
| 19 | var buffer = [unichar](repeating: 0, count: 4096) | |
| 18 | 20 | var location = from |
| 19 | 21 | while location < end { |
| 20 | let found = text.range(of: "\n", options: .literal, range: NSRange(location: location, length: end - location)) | |
| 21 | guard found.location != NSNotFound else { break } | |
| 22 | starts.append(found.location + 1) | |
| 23 | location = found.location + 1 | |
| 22 | let count = min(buffer.count, end - location) | |
| 23 | text.getCharacters(&buffer, range: NSRange(location: location, length: count)) | |
| 24 | for i in 0..<count where buffer[i] == 10 { starts.append(location + i + 1) } | |
| 25 | location += count | |
| 24 | 26 | } |
| 25 | 27 | } |
| 26 | 28 | |
Sources/OrgEditorAppKit/OrgEditor+Folding.swift +4 −3
| @@ -15,8 +15,9 @@ extension OrgEditor { | ||
| 15 | 15 | setFolds(state, wrappers: nil) |
| 16 | 16 | } |
| 17 | 17 | |
| 18 | /// `wrappers`, when given, holds every folded drawer and block. | |
| 19 | func setFolds(_ state: FoldState, wrappers: [Wrapper]?) { | |
| 18 | /// `wrappers`, when given, holds every folded drawer and block. `layout` is false when | |
| 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 | 21 | sparseHidden = nil |
| 21 | 22 | view.folds = state.folds |
| 22 | 23 | view.bodyFolds = state.bodyFolds |
| @@ -27,7 +28,7 @@ extension OrgEditor { | ||
| 27 | 28 | : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) }) |
| 28 | 29 | wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a } |
| 29 | 30 | view.wrapperFolds = Set(wrapperHidden.keys) |
| 30 | updateHiddenAndLayout() | |
| 31 | if layout { updateHiddenAndLayout() } else { updateHidden() } | |
| 31 | 32 | redrawViews() |
| 32 | 33 | caretsOutOfHiddenText() |
| 33 | 34 | } |
Sources/OrgEditorAppKit/OrgEditor.swift +3 −2
| @@ -125,10 +125,11 @@ public final class OrgEditor: NSObject { | ||
| 125 | 125 | // Files open at their start, as in Emacs; replacing the storage leaves it at the end. |
| 126 | 126 | textView.setSelectedRange(NSRange(location: 0, length: 0)) |
| 127 | 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 | 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 | 133 | truncatesLines = options.startupTruncated |
| 133 | 134 | } |
| 134 | 135 | |
Sources/OrgPresentation/Presentation.swift +9 −5
| @@ -223,20 +223,24 @@ public enum Presentation { | ||
| 223 | 223 | |
| 224 | 224 | private static func computeShadedBlocks(_ tree: OrgTree) -> [Range<Int>] { |
| 225 | 225 | var ranges: [Range<Int>] = [] |
| 226 | func walk(_ node: SyntaxNode) { | |
| 227 | for child in node.children { | |
| 226 | // Over green nodes, so no node object is made for each paragraph. | |
| 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 | 232 | switch child.kind { |
| 229 | 233 | case .block, .dynamicBlock, .fixedWidth: |
| 230 | 234 | // Without the blank lines org counts as part of the element. |
| 231 | 235 | let text = child.text |
| 232 | 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 | 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 | 244 | return ranges |
| 241 | 245 | } |
| 242 | 246 | |
Tests/OrgCoreTests/ParserElementTests.swift +6
| @@ -52,6 +52,12 @@ struct ParserElementTests { | ||
| 52 | 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 | 61 | @Test func footnoteDefinition() { |
| 56 | 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] { | ||
| 12 | 12 | struct ParserSectionTests { |
| 13 | 13 | @Test func emptyDocument() { |
| 14 | 14 | let tree = OrgParser.parse("") |
| 15 | #expect(tree.text == "") | |
| 15 | #expect(tree.root.text == "") | |
| 16 | 16 | #expect(nodeKinds("") == [.document]) |
| 17 | 17 | } |
| 18 | 18 | |
| @@ -63,11 +63,11 @@ struct ParserSectionTests { | ||
| 63 | 63 | } |
| 64 | 64 | |
| 65 | 65 | @Test func headingWithoutNewlineAtEnd() { |
| 66 | #expect(OrgParser.parse("* a").text == "* a") | |
| 66 | #expect(OrgParser.parse("* a").root.text == "* a") | |
| 67 | 67 | } |
| 68 | 68 | |
| 69 | 69 | @Test(arguments: ["* a\n", "*\n", "* TODO\n", "text\r\n* a\r\n** b\r\n", "\n\n* a\n\n"]) |
| 70 | 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 | 50 | for n in 0..<2_000 { |
| 51 | 51 | let text = randomDocument(&rng) |
| 52 | 52 | let tree = OrgParser.parse(text) |
| 53 | #expect(tree.text == text, "document \(n)") | |
| 53 | #expect(tree.root.text == text, "document \(n)") | |
| 54 | 54 | #expect(checkLengths(tree.root), "document \(n)") |
| 55 | 55 | _ = DocumentModel(tree: tree) |
| 56 | 56 | } |
| @@ -66,7 +66,7 @@ struct RoundTripTests { | ||
| 66 | 66 | func encodingFixturesRoundTrip(bytes: [UInt8]) { |
| 67 | 67 | let source = SourceText(bytes: bytes) |
| 68 | 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 | 72 | /// Private corpus: `ORGSTAR_CORPUS=/path/to/org swift test --filter corpus`. |
| @@ -81,7 +81,7 @@ struct RoundTripTests { | ||
| 81 | 81 | let bytes = try [UInt8](Data(contentsOf: file)) |
| 82 | 82 | let source = SourceText(bytes: bytes) |
| 83 | 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 | 85 | _ = DocumentModel(tree: tree) |
| 86 | 86 | } |
| 87 | 87 | } |