Sources/OrgCore/Completion/IndexCompletion.swift
150 lines · 6929 bytes
10 symbols in this file
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 /// The keys of these bibliography files, for `@` in a citation.
34 case citationKeys([String])
35}
36
37/// What the index answers.
38public struct CompletionResult: Sendable, Equatable {
39 public var items: [CompletionItem] = []
40 public var strings: [String] = []
41 /// Text shown after each string, by string.
42 public var annotations: [String: String] = [:]
43
44 public init(items: [CompletionItem] = [], strings: [String] = [], annotations: [String: String] = [:]) {
45 self.items = items
46 self.strings = strings
47 self.annotations = annotations
48 }
49
50 /// The keys of bibliography entries, each with its authors, year and title.
51 public init(entries: [BibEntry]) {
52 self.init(strings: entries.map(\.key), annotations: Dictionary(entries.map { entry in
53 (entry.key, [entry.authors, entry.year, entry.title].compactMap { $0 }.joined(separator: " "))
54 }) { a, _ in a })
55 }
56}
57
58extension OrgCompletion {
59 /// `completion` with what the index answered for its query added to the buffer's
60 /// candidates, matching what's typed.
61 public static func filled(_ completion: Completion, with result: CompletionResult, fuzzy: Bool) -> Completion {
62 var filled = completion
63 switch completion.kind {
64 case .idLink, .denoteLink:
65 let items = completion.targets + result.items
66 filled.setItems(items, fuzzy: fuzzy)
67 case .propertyValue:
68 filled.pool = completion.pool + result.strings
69 filled.candidates = matching(filled.pool, completion.typed, fuzzy: fuzzy, ignoringCase: true, sorted: false)
70 case .word:
71 filled = Dabbrev.adding(result.strings, to: completion)
72 case .citationKey:
73 filled.pool = result.strings
74 filled.annotations = result.annotations
75 filled.candidates = matching(result.strings, completion.typed, fuzzy: fuzzy)
76 default:
77 break
78 }
79 filled.query = nil
80 return filled
81 }
82
83 /// `[[id:` and `[[denote:`: the link type, what's typed after it, and the whole link
84 /// typed so far, through `]]` after the caret.
85 static func linkTarget(_ context: EditContext, lineStart: Int, toHere: String) -> (type: String, typed: Range<Int>, link: Range<Int>)? {
86 guard let match = toHere.firstMatch(of: /\[\[(id|denote):([^\[\]]*)$/) else { return nil }
87 let ns = context.text as NSString
88 let caret = lineStart + (toHere as NSString).length
89 let linkStart = lineStart + toHere.utf16.distance(from: toHere.utf16.startIndex, to: match.range.lowerBound)
90 let typedStart = caret - String(match.2).utf16.count
91 var end = caret
92 if end + 2 <= ns.length, ns.substring(with: NSRange(location: end, length: 2)) == "]]" { end += 2 }
93 return (String(match.1), typedStart..<caret, linkStart..<end)
94 }
95
96 /// The open file's headings and its own ID, for `[[id:`.
97 static func bufferTargets(_ context: EditContext) -> [CompletionItem] {
98 let path = context.options.filePath ?? ""
99 let model = DocumentModel(tree: context.tree)
100 let file = model.property("ID", of: nil).map { id in
101 let title = context.text.firstMatch(of: /(?im)^[ \t]*#\+title:[ \t]*(.*?)[ \t]*$/).map { String($0.1) }
102 return CompletionItem(title: title ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension, id: id.value,
103 path: path, start: 0, heading: false)
104 }
105 return (file.map { [$0] } ?? []) + model.headings.map { CompletionItem(title: $0.title, id: $0.id, path: path, start: $0.headingRange.lowerBound, heading: true) }
106 }
107
108 /// Property values in the buffer: those `org-property-get-allowed-values` gives at the
109 /// caret, then those headings give `name`.
110 static func bufferValues(_ name: String, _ context: EditContext) -> [String] {
111 let model = DocumentModel(tree: context.tree)
112 let allowed = PropertyValues.allowed(name, at: context.caret, text: context.text, tree: context.tree)?.values.filter { !$0.isEmpty } ?? []
113 let key = name.uppercased()
114 return allowed + (model.fileProperties + model.headings.flatMap(\.properties)).filter { $0.key.uppercased() == key && !$0.value.isEmpty }.map(\.value)
115 }
116}
117
118extension Completion {
119 /// Candidates for link items: titles, with the file's name where titles repeat.
120 mutating func setItems(_ all: [CompletionItem], fuzzy: Bool) {
121 var counts: [String: Int] = [:]
122 for item in all { counts[item.title, default: 0] += 1 }
123 var labels: [String: CompletionItem] = [:]
124 var order: [String] = []
125 for item in all {
126 var label = counts[item.title, default: 0] > 1 ? "\(item.title) (\((item.path as NSString).lastPathComponent))" : item.title
127 var n = 2
128 while labels[label] != nil {
129 label = "\(item.title) (\((item.path as NSString).lastPathComponent) \(n))"
130 n += 1
131 }
132 labels[label] = item
133 order.append(label)
134 }
135 pool = order
136 candidates = OrgCompletion.matching(order, typed, fuzzy: fuzzy, ignoringCase: true)
137 items = candidates.compactMap { labels[$0] }
138 targets = all
139 }
140
141 /// The item behind a candidate of a link completion.
142 public func item(_ candidate: String) -> CompletionItem? {
143 candidates.firstIndex(of: candidate).flatMap { items.indices.contains($0) ? items[$0] : nil }
144 }
145
146 /// The link a link completion inserts for `item`, given its ID.
147 public func link(_ item: CompletionItem, id: String) -> String {
148 Links.makeString((kind == .denoteLink ? "denote:" : "id:") + id, item.title)
149 }
150}