Sources/OrgCore/Completion/IndexCompletion.swift
cmc Completion from the index: id links by title, property values, Denote notes
30fb15c9bc 15 hours ago134 lines · 6088 bytes
1import Foundation
2
3/// A heading or file a link completes to: from the buffer, or from the index for other files.
4public struct CompletionItem: Sendable, Hashable {
5 public var title: String
6 /// Its `ID`, or a Denote note's identifier; nil when the heading has none yet.
7 public var id: String?
8 public var path: String
9 /// Where its heading starts; 0 for a file.
10 public var start: Int
11 /// A heading, not a file.
12 public var heading: Bool
13
14 public init(title: String, id: String?, path: String, start: Int, heading: Bool) {
15 self.title = title
16 self.id = id
17 self.path = path
18 self.start = start
19 self.heading = heading
20 }
21}
22
23/// What a completion asks the index, off the main thread, after the buffer's candidates show.
24public enum CompletionQuery: Sendable, Hashable {
25 /// Headings and files in every folder, for `[[id:`.
26 case linkTargets
27 /// Denote's notes, for `[[denote:`.
28 case denoteNotes
29 /// Values used for a property, and its `_ALL` values.
30 case propertyValues(String)
31 /// Words starting with the abbreviation.
32 case words(String)
33}
34
35/// What the index answers.
36public struct CompletionResult: Sendable, Equatable {
37 public var items: [CompletionItem] = []
38 public var strings: [String] = []
39
40 public init(items: [CompletionItem] = [], strings: [String] = []) {
41 self.items = items
42 self.strings = strings
43 }
44}
45
46extension OrgCompletion {
47 /// `completion` with what the index answered for its query added to the buffer's
48 /// candidates, matching what's typed.
49 public static func filled(_ completion: Completion, with result: CompletionResult, fuzzy: Bool) -> Completion {
50 var filled = completion
51 switch completion.kind {
52 case .idLink, .denoteLink:
53 let items = completion.targets + result.items
54 filled.setItems(items, fuzzy: fuzzy)
55 case .propertyValue:
56 filled.pool = completion.pool + result.strings
57 filled.candidates = matching(filled.pool, completion.typed, fuzzy: fuzzy, ignoringCase: true, sorted: false)
58 case .word:
59 filled = Dabbrev.adding(result.strings, to: completion)
60 default:
61 break
62 }
63 filled.query = nil
64 return filled
65 }
66
67 /// `[[id:` and `[[denote:`: the link type, what's typed after it, and the whole link
68 /// typed so far, through `]]` after the caret.
69 static func linkTarget(_ context: EditContext, lineStart: Int, toHere: String) -> (type: String, typed: Range<Int>, link: Range<Int>)? {
70 guard let match = toHere.firstMatch(of: /\[\[(id|denote):([^\[\]]*)$/) else { return nil }
71 let ns = context.text as NSString
72 let caret = lineStart + (toHere as NSString).length
73 let linkStart = lineStart + toHere.utf16.distance(from: toHere.utf16.startIndex, to: match.range.lowerBound)
74 let typedStart = caret - String(match.2).utf16.count
75 var end = caret
76 if end + 2 <= ns.length, ns.substring(with: NSRange(location: end, length: 2)) == "]]" { end += 2 }
77 return (String(match.1), typedStart..<caret, linkStart..<end)
78 }
79
80 /// The open file's headings and its own ID, for `[[id:`.
81 static func bufferTargets(_ context: EditContext) -> [CompletionItem] {
82 let path = context.options.filePath ?? ""
83 let model = DocumentModel(tree: context.tree)
84 let file = model.property("ID", of: nil).map { id in
85 let title = context.text.firstMatch(of: /(?im)^[ \t]*#\+title:[ \t]*(.*?)[ \t]*$/).map { String($0.1) }
86 return CompletionItem(title: title ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension, id: id.value,
87 path: path, start: 0, heading: false)
88 }
89 return (file.map { [$0] } ?? []) + model.headings.map { CompletionItem(title: $0.title, id: $0.id, path: path, start: $0.headingRange.lowerBound, heading: true) }
90 }
91
92 /// Property values in the buffer: those `org-property-get-allowed-values` gives at the
93 /// caret, then those headings give `name`.
94 static func bufferValues(_ name: String, _ context: EditContext) -> [String] {
95 let model = DocumentModel(tree: context.tree)
96 let allowed = PropertyValues.allowed(name, at: context.caret, text: context.text, tree: context.tree)?.values.filter { !$0.isEmpty } ?? []
97 let key = name.uppercased()
98 return allowed + (model.fileProperties + model.headings.flatMap(\.properties)).filter { $0.key.uppercased() == key && !$0.value.isEmpty }.map(\.value)
99 }
100}
101
102extension Completion {
103 /// Candidates for link items: titles, with the file's name where titles repeat.
104 mutating func setItems(_ all: [CompletionItem], fuzzy: Bool) {
105 var counts: [String: Int] = [:]
106 for item in all { counts[item.title, default: 0] += 1 }
107 var labels: [String: CompletionItem] = [:]
108 var order: [String] = []
109 for item in all {
110 var label = counts[item.title, default: 0] > 1 ? "\(item.title) (\((item.path as NSString).lastPathComponent))" : item.title
111 var n = 2
112 while labels[label] != nil {
113 label = "\(item.title) (\((item.path as NSString).lastPathComponent) \(n))"
114 n += 1
115 }
116 labels[label] = item
117 order.append(label)
118 }
119 pool = order
120 candidates = OrgCompletion.matching(order, typed, fuzzy: fuzzy, ignoringCase: true)
121 items = candidates.compactMap { labels[$0] }
122 targets = all
123 }
124
125 /// The item behind a candidate of a link completion.
126 public func item(_ candidate: String) -> CompletionItem? {
127 candidates.firstIndex(of: candidate).flatMap { items.indices.contains($0) ? items[$0] : nil }
128 }
129
130 /// The link a link completion inserts for `item`, given its ID.
131 public func link(_ item: CompletionItem, id: String) -> String {
132 Links.makeString((kind == .denoteLink ? "denote:" : "id:") + id, item.title)
133 }
134}