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 {
19 public var lastError: String? 19 public var lastError: String?
20 /// Bumped when an indexed file changes on disk, with its path. 20 /// Bumped when an indexed file changes on disk, with its path.
21 public private(set) var changedFile: (path: String, version: Int)? 21 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
22 24
23 public let index: IndexStore 25 public let index: IndexStore
24 /// A change (other TODO keywords) reindexes the files it affects. 26 /// A change (other TODO keywords) reindexes the files it affects.
@@ -279,6 +281,7 @@ public final class WorkspaceModel {
279 guard let root = roots.first(where: { file.path.hasPrefix($0 + "/") }) else { return nil } 281 guard let root = roots.first(where: { file.path.hasPrefix($0 + "/") }) else { return nil }
280 return FileEntry(path: file.path, root: root, kind: file.kind) 282 return FileEntry(path: file.path, root: root, kind: file.kind)
281 } 283 }
284 indexVersion += 1
282 } 285 }
283 286
284 /// Reconciles the paths a batch of file events named, or whole roots when events were lost. 287 /// Reconciles the paths a batch of file events named, or whole roots when events were lost.
@@ -441,11 +444,12 @@ public final class WorkspaceModel {
441 } 444 }
442 445
443 /// Headings with links to `target`, the target heading's own links left out, each with 446 /// 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. 447 /// the line its link is on as its snippet. Reads every link in the index, so call it off
445 public func backlinks(to target: Backlinks.Target, excluding start: Int? = nil, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] { 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] {
446 var seen = Set<HeadingLocation>() 450 var seen = Set<HeadingLocation>()
447 return ((try? index.links(overlay: overlay)) ?? []).compactMap { link in 451 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),
449 Backlinks.links(link.target, from: link.source.path, to: target), seen.insert(link.source).inserted else { return nil } 453 Backlinks.links(link.target, from: link.source.path, to: target), seen.insert(link.source).inserted else { return nil }
450 var source = link.source 454 var source = link.source
451 if let text = try? index.text(of: source, overlay: overlay), let context = Backlinks.context(in: text, link: link.target) { 455 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 {
19 } 19 }
20 } 20 }
21 21
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
22 /// Whether `link`, written in the file at `source`, leads to `target`. 27 /// Whether `link`, written in the file at `source`, leads to `target`.
23 public static func links(_ link: String, from source: String, to target: Target, home: String = OrgPaths.home) -> Bool { 28 public static func links(_ link: String, from source: String, to target: Target, home: String = OrgPaths.home) -> Bool {
24 let link = Links.unescape(link) 29 let link = Links.unescape(link)
@@ -42,7 +47,7 @@ public enum Backlinks {
42 let parts = link.components(separatedBy: "::") 47 let parts = link.components(separatedBy: "::")
43 path = parts[0] 48 path = parts[0]
44 search = parts.dropFirst().joined(separator: "::") 49 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 {
46 return false 51 return false
47 } else { 52 } else {
48 // Within the file. 53 // Within the file.
@@ -66,13 +71,12 @@ public enum Backlinks {
66 /// description, else what they link to), and the range of that link in the line. A line 71 /// description, else what they link to), and the range of that link in the line. A line
67 /// longer than `width` keeps the part around the link. 72 /// longer than `width` keeps the part around the link.
68 public static func context(in body: String, link: String, width: Int = 160) -> (text: String, link: Range<Int>)? { 73 public static func context(in body: String, link: String, width: Int = 160) -> (text: String, link: Range<Int>)? {
69 let pattern = /\[\[((?:[^\]\\]|\\.)+)\](?:\[([^\]]*)\])?\]/
70 for line in body.split(whereSeparator: \.isNewline) { 74 for line in body.split(whereSeparator: \.isNewline) {
71 guard line.contains("[[" + link + "]") else { continue } 75 guard line.contains("[[" + link + "]") else { continue }
72 var text = "" 76 var text = ""
73 var found: Range<Int>? 77 var found: Range<Int>?
74 var rest = Substring(line) 78 var rest = Substring(line)
75 while let match = rest.firstMatch(of: pattern) { 79 while let match = rest.firstMatch(of: bracketLink) {
76 text += rest[..<match.range.lowerBound] 80 text += rest[..<match.range.lowerBound]
77 let shown = match.2.map(String.init) ?? String(match.1) 81 let shown = match.2.map(String.init) ?? String(match.1)
78 let start = text.utf16.count 82 let start = text.utf16.count
Sources/OrgCore/Links/Links.swift +4 −2
@@ -33,12 +33,14 @@ public enum Links {
33 pattern: "^(" + types.sorted { $0.count > $1.count }.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|") + "):" 33 pattern: "^(" + types.sorted { $0.count > $1.count }.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|") + "):"
34 ) 34 )
35 35
36 /// Runs of backslashes before a bracket or the end.
37 private static let escapes = try! NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])")
38
36 /// `org-link-unescape`: halves each run of backslashes before a bracket or the end. 39 /// `org-link-unescape`: halves each run of backslashes before a bracket or the end.
37 static func unescape(_ s: String) -> String { 40 static func unescape(_ s: String) -> String {
38 let regex = try! NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])")
39 let ns = s as NSString 41 let ns = s as NSString
40 var out = s 42 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() {
42 let run = m.range(at: 1) 44 let run = m.range(at: 1)
43 out = (out as NSString).replacingCharacters(in: run, with: String(repeating: "\\", count: run.length / 2)) 45 out = (out as NSString).replacingCharacters(in: run, with: String(repeating: "\\", count: run.length / 2))
44 } 46 }
Sources/Orgstar/BacklinksPane.swift +17 −11
@@ -21,7 +21,8 @@ struct BacklinksPane: View {
21 private struct Key: Equatable { 21 private struct Key: Equatable {
22 var path: String? 22 var path: String?
23 var heading: Int? 23 var heading: Int?
24 var version: Int 24 var title: String?
25 var index: Int
25 } 26 }
26 27
27 var body: some View { 28 var body: some View {
@@ -32,7 +33,7 @@ struct BacklinksPane: View {
32 Section("Links to this file") { rows(toFile) } 33 Section("Links to this file") { rows(toFile) }
33 } 34 }
34 .themedListBackground(theme.color("sidebar-background", in: colorScheme)) 35 .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() }
36 } 37 }
37 38
38 @ViewBuilder 39 @ViewBuilder
@@ -56,23 +57,28 @@ struct BacklinksPane: View {
56 } 57 }
57 } 58 }
58 59
59 private func refresh() { 60 private func refresh() async {
60 guard let path = session.path else { 61 guard let path = session.path else {
61 toHeading = [] 62 toHeading = []
62 toFile = [] 63 toFile = []
63 return 64 return
64 } 65 }
65 let overlay = workspace.overlay(session.openDocuments) 66 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) }
66 // The file's own ID, as an org-roam file node. 77 // 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 } 78 let toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: model?.property("ID", of: nil)?.value), overlay: overlay)
68 toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: fileID ?? nil), overlay: overlay) 79 guard let heading, let info = model?.headings.first(where: { $0.headingRange.lowerBound == heading }) else { return (toFile, []) }
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 }
74 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value 80 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
75 let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID) 81 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))
77 } 83 }
78} 84}
Sources/OrgstarMobile/BacklinksScreen.swift +15 −6
@@ -28,7 +28,7 @@ struct BacklinksScreen: View {
28 .navigationBarTitleDisplayMode(.inline) 28 .navigationBarTitleDisplayMode(.inline)
29 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } } 29 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } }
30 } 30 }
31 .task { refresh() } 31 .task { await refresh() }
32 } 32 }
33 33
34 @ViewBuilder 34 @ViewBuilder
@@ -52,15 +52,24 @@ struct BacklinksScreen: View {
52 } 52 }
53 } 53 }
54 54
55 private func refresh() { 55 private func refresh() async {
56 let overlay = workspace.overlay(session.openDocuments) 56 let overlay = workspace.overlay(session.openDocuments)
57 guard let document = session.openDocuments.first(where: { $0.path == path })?.document else { return } 57 guard let document = session.openDocuments.first(where: { $0.path == path })?.document else { return }
58 let model = DocumentModel(tree: document.tree) 58 let found = await Self.backlinks(in: workspace, path: path, tree: document.tree, caret: caret, overlay: overlay)
59 toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: model.property("ID", of: nil)?.value), overlay: overlay) 59 guard !Task.isCancelled else { return }
60 guard let info = model.headings.last(where: { $0.headingRange.lowerBound <= caret }) else { return heading = nil } 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) }
61 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value 70 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
62 let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID) 71 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)))
64 } 73 }
65} 74}
66#endif 75#endif
Tests/OrgAppTests/AppTests.swift +2
@@ -149,6 +149,8 @@ struct WorkspaceModelTests {
149 #expect(model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing", "c.org"]) 149 #expect(model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing", "c.org"])
150 #expect(model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"]) 150 #expect(model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"])
151 #expect(model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other", "c.org"]) 151 #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"])
152 // Each with the line its link is on, the link as it reads. 154 // Each with the line its link is on, the link as it reads.
153 #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."]) 155 #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."])
154 #expect(model.backlinks(to: sink).first?.snippet?.matches == [0..<8]) 156 #expect(model.backlinks(to: sink).first?.snippet?.matches == [0..<8])
Tests/OrgCoreTests/BacklinkTests.swift +19
@@ -24,6 +24,25 @@ struct BacklinkTests {
24 #expect(!links("*Fix the sink", from: "/notes/b.org", to: heading)) 24 #expect(!links("*Fix the sink", from: "/notes/b.org", to: heading))
25 } 25 }
26 26
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
27 @Test func followsDenoteLinks() { 46 @Test func followsDenoteLinks() {
28 let file = Backlinks.Target(path: "/notes/20261119T120000--a-note__kw.org") 47 let file = Backlinks.Target(path: "/notes/20261119T120000--a-note__kw.org")
29 let heading = Backlinks.Target(path: file.path, title: "Inside", customID: "in") 48 let heading = Backlinks.Target(path: file.path, title: "Inside", customID: "in")