Commit 9e9d587ae8

9e9d587ae874919cc495edfe46dae92eab2e9619

parent: 9f33aea70f

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-22 12:36 UTC

Compute backlinks off the main actor, when the file, heading or index changes

The link patterns are compiled once instead of for each link.

Closes #188

Layout: unified · split

Sources/OrgApp/WorkspaceModel.swift +7 −3
@@ -19,6 +19,8 @@ public final class WorkspaceModel {
1919 public var lastError: String?
2020 /// Bumped when an indexed file changes on disk, with its path.
2121 public private(set) var changedFile: (path: String, version: Int)?
22 /// Bumped when the index may hold other rows: after a reconcile, or a root's removal.
23 public private(set) var indexVersion = 0
2224
2325 public let index: IndexStore
2426 /// A change (other TODO keywords) reindexes the files it affects.
@@ -279,6 +281,7 @@ public final class WorkspaceModel {
279281 guard let root = roots.first(where: { file.path.hasPrefix($0 + "/") }) else { return nil }
280282 return FileEntry(path: file.path, root: root, kind: file.kind)
281283 }
284 indexVersion += 1
282285 }
283286
284287 /// Reconciles the paths a batch of file events named, or whole roots when events were lost.
@@ -441,11 +444,12 @@ public final class WorkspaceModel {
441444 }
442445
443446 /// Headings with links to `target`, the target heading's own links left out, each with
444 /// the line its link is on as its snippet.
445 public func backlinks(to target: Backlinks.Target, excluding start: Int? = nil, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] {
447 /// the line its link is on as its snippet. Reads every link in the index, so call it off
448 /// the main actor; a cancelled task gets what was found so far.
449 public nonisolated func backlinks(to target: Backlinks.Target, excluding start: Int? = nil, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] {
446450 var seen = Set<HeadingLocation>()
447451 return ((try? index.links(overlay: overlay)) ?? []).compactMap { link in
448 guard !(link.source.path == target.path && link.source.start == start),
452 guard !Task.isCancelled, !(link.source.path == target.path && link.source.start == start),
449453 Backlinks.links(link.target, from: link.source.path, to: target), seen.insert(link.source).inserted else { return nil }
450454 var source = link.source
451455 if let text = try? index.text(of: source, overlay: overlay), let context = Backlinks.context(in: text, link: link.target) {
Sources/OrgCore/Links/Backlinks.swift +7 −3
@@ -19,6 +19,11 @@ public enum Backlinks {
1919 }
2020 }
2121
22 /// A link type and its colon.
23 nonisolated(unsafe) private static let typePrefix = /^[a-zA-Z][-a-zA-Z0-9+]*:/
24 /// A bracket link: what it links to, and its description.
25 nonisolated(unsafe) private static let bracketLink = /\[\[((?:[^\]\\]|\\.)+)\](?:\[([^\]]*)\])?\]/
26
2227 /// Whether `link`, written in the file at `source`, leads to `target`.
2328 public static func links(_ link: String, from source: String, to target: Target, home: String = OrgPaths.home) -> Bool {
2429 let link = Links.unescape(link)
@@ -42,7 +47,7 @@ public enum Backlinks {
4247 let parts = link.components(separatedBy: "::")
4348 path = parts[0]
4449 search = parts.dropFirst().joined(separator: "::")
45 } else if link.firstMatch(of: /^[a-zA-Z][-a-zA-Z0-9+]*:/) != nil {
50 } else if link.firstMatch(of: typePrefix) != nil {
4651 return false
4752 } else {
4853 // Within the file.
@@ -66,13 +71,12 @@ public enum Backlinks {
6671 /// description, else what they link to), and the range of that link in the line. A line
6772 /// longer than `width` keeps the part around the link.
6873 public static func context(in body: String, link: String, width: Int = 160) -> (text: String, link: Range<Int>)? {
69 let pattern = /\[\[((?:[^\]\\]|\\.)+)\](?:\[([^\]]*)\])?\]/
7074 for line in body.split(whereSeparator: \.isNewline) {
7175 guard line.contains("[[" + link + "]") else { continue }
7276 var text = ""
7377 var found: Range<Int>?
7478 var rest = Substring(line)
75 while let match = rest.firstMatch(of: pattern) {
79 while let match = rest.firstMatch(of: bracketLink) {
7680 text += rest[..<match.range.lowerBound]
7781 let shown = match.2.map(String.init) ?? String(match.1)
7882 let start = text.utf16.count
Sources/OrgCore/Links/Links.swift +4 −2
@@ -33,12 +33,14 @@ public enum Links {
3333 pattern: "^(" + types.sorted { $0.count > $1.count }.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|") + "):"
3434 )
3535
36 /// Runs of backslashes before a bracket or the end.
37 private static let escapes = try! NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])")
38
3639 /// `org-link-unescape`: halves each run of backslashes before a bracket or the end.
3740 static func unescape(_ s: String) -> String {
38 let regex = try! NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])")
3941 let ns = s as NSString
4042 var out = s
41 for m in regex.matches(in: s, range: NSRange(location: 0, length: ns.length)).reversed() {
43 for m in escapes.matches(in: s, range: NSRange(location: 0, length: ns.length)).reversed() {
4244 let run = m.range(at: 1)
4345 out = (out as NSString).replacingCharacters(in: run, with: String(repeating: "\\", count: run.length / 2))
4446 }
Sources/Orgstar/BacklinksPane.swift +17 −11
@@ -21,7 +21,8 @@ struct BacklinksPane: View {
2121 private struct Key: Equatable {
2222 var path: String?
2323 var heading: Int?
24 var version: Int
24 var title: String?
25 var index: Int
2526 }
2627
2728 var body: some View {
@@ -32,7 +33,7 @@ struct BacklinksPane: View {
3233 Section("Links to this file") { rows(toFile) }
3334 }
3435 .themedListBackground(theme.color("sidebar-background", in: colorScheme))
35 .task(id: Key(path: session.path, heading: heading?.start, version: session.editVersion)) { refresh() }
36 .task(id: Key(path: session.path, heading: heading?.start, title: heading?.title, index: workspace.indexVersion)) { await refresh() }
3637 }
3738
3839 @ViewBuilder
@@ -56,23 +57,28 @@ struct BacklinksPane: View {
5657 }
5758 }
5859
59 private func refresh() {
60 private func refresh() async {
6061 guard let path = session.path else {
6162 toHeading = []
6263 toFile = []
6364 return
6465 }
6566 let overlay = workspace.overlay(session.openDocuments)
67 let found = await Self.backlinks(in: workspace, path: path, tree: session.document?.tree, heading: heading?.start, overlay: overlay)
68 guard !Task.isCancelled else { return }
69 (toFile, toHeading) = found
70 }
71
72 @concurrent
73 private nonisolated static func backlinks(
74 in workspace: WorkspaceModel, path: String, tree: OrgTree?, heading: Int?, overlay: [String: FileRecord]
75 ) async -> (toFile: [HeadingLocation], toHeading: [HeadingLocation]) {
76 let model = tree.map { DocumentModel(tree: $0) }
6677 // The file's own ID, as an org-roam file node.
67 let fileID = session.document.map { DocumentModel(tree: $0.tree).property("ID", of: nil)?.value }
68 toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: fileID ?? nil), overlay: overlay)
69 guard let heading, let tree = session.document?.tree,
70 let info = DocumentModel(tree: tree).headings.first(where: { $0.headingRange.lowerBound == heading.start }) else {
71 toHeading = []
72 return
73 }
78 let toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: model?.property("ID", of: nil)?.value), overlay: overlay)
79 guard let heading, let info = model?.headings.first(where: { $0.headingRange.lowerBound == heading }) else { return (toFile, []) }
7480 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
7581 let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID)
76 toHeading = workspace.backlinks(to: target, excluding: heading.start, overlay: overlay)
82 return (toFile, workspace.backlinks(to: target, excluding: heading, overlay: overlay))
7783 }
7884}
Sources/OrgstarMobile/BacklinksScreen.swift +15 −6
@@ -28,7 +28,7 @@ struct BacklinksScreen: View {
2828 .navigationBarTitleDisplayMode(.inline)
2929 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } }
3030 }
31 .task { refresh() }
31 .task { await refresh() }
3232 }
3333
3434 @ViewBuilder
@@ -52,15 +52,24 @@ struct BacklinksScreen: View {
5252 }
5353 }
5454
55 private func refresh() {
55 private func refresh() async {
5656 let overlay = workspace.overlay(session.openDocuments)
5757 guard let document = session.openDocuments.first(where: { $0.path == path })?.document else { return }
58 let model = DocumentModel(tree: document.tree)
59 toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: model.property("ID", of: nil)?.value), overlay: overlay)
60 guard let info = model.headings.last(where: { $0.headingRange.lowerBound <= caret }) else { return heading = nil }
58 let found = await Self.backlinks(in: workspace, path: path, tree: document.tree, caret: caret, overlay: overlay)
59 guard !Task.isCancelled else { return }
60 (toFile, heading) = found
61 }
62
63 @concurrent
64 private nonisolated static func backlinks(
65 in workspace: WorkspaceModel, path: String, tree: OrgTree, caret: Int, overlay: [String: FileRecord]
66 ) async -> (toFile: [HeadingLocation], heading: (title: String, links: [HeadingLocation])?) {
67 let model = DocumentModel(tree: tree)
68 let toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: model.property("ID", of: nil)?.value), overlay: overlay)
69 guard let info = model.headings.last(where: { $0.headingRange.lowerBound <= caret }) else { return (toFile, nil) }
6170 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
6271 let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID)
63 heading = (info.title, workspace.backlinks(to: target, excluding: info.headingRange.lowerBound, overlay: overlay))
72 return (toFile, (info.title, workspace.backlinks(to: target, excluding: info.headingRange.lowerBound, overlay: overlay)))
6473 }
6574}
6675#endif
Tests/OrgAppTests/AppTests.swift +2
@@ -149,6 +149,8 @@ struct WorkspaceModelTests {
149149 #expect(model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing", "c.org"])
150150 #expect(model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"])
151151 #expect(model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other", "c.org"])
152 // Off the main actor, as the panes ask.
153 #expect(await Task.detached { model.backlinks(to: sink).map(\.title) }.value == ["Plumbing", "Other", "c.org"])
152154 // Each with the line its link is on, the link as it reads.
153155 #expect(model.backlinks(to: sink).map { $0.snippet?.text } == ["the sink and file:a.org", "file:a.org::#sink https://x.org", "About file:a.org::*Sink and file:a.org."])
154156 #expect(model.backlinks(to: sink).first?.snippet?.matches == [0..<8])
Tests/OrgCoreTests/BacklinkTests.swift +19
@@ -24,6 +24,25 @@ struct BacklinkTests {
2424 #expect(!links("*Fix the sink", from: "/notes/b.org", to: heading))
2525 }
2626
27 /// The patterns are compiled once, not for each link: testing the links takes less time
28 /// than compiling them that often would.
29 @Test func testsManyLinksWithoutCompilingPatterns() throws {
30 let links = (0..<20_000).map { ["id:abc-\($0)", "file:a.org::*Fix the sink", "https://example.org/\($0)", "Fix the sink"][$0 % 4] }
31 let clock = ContinuousClock()
32 let compiling = try clock.measure {
33 for index in links.indices {
34 _ = try NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])")
35 if index % 2 == 0 { _ = try Regex("^[a-zA-Z][-a-zA-Z0-9+]*:") }
36 }
37 }
38 var hits = 0
39 let testing = clock.measure {
40 for link in links where Backlinks.links(link, from: "/notes/b.org", to: heading, home: "/home") { hits += 1 }
41 }
42 #expect(hits == 5_000)
43 #expect(testing < compiling / 2, "\(testing) against \(compiling)")
44 }
45
2746 @Test func followsDenoteLinks() {
2847 let file = Backlinks.Target(path: "/notes/20261119T120000--a-note__kw.org")
2948 let heading = Backlinks.Target(path: file.path, title: "Inside", customID: "in")