Sources/OrgApp/CompletionSources.swift
cmc Completion from the index: id links by title, property values, Denote notes
30fb15c9bc 7 hours ago45 lines · 2561 bytes
1import Foundation
2import OrgCore
3import OrgIndex
4
5/// What completion takes from the index and the other files, for both apps' editors.
6public enum CompletionSources {
7 /// Answers `query` from `index`, leaving out `path`, whose buffer gives its own. Reads the
8 /// index, so it runs off the main actor; a failed read answers nothing.
9 @concurrent
10 public nonisolated static func answer(_ query: CompletionQuery, index: IndexStore, excluding path: String?) async -> CompletionResult {
11 switch query {
12 case .linkTargets:
13 return CompletionResult(items: (try? index.linkTargets(excluding: path)) ?? [])
14 case .denoteNotes:
15 let notes = ((try? index.denoteNodes()) ?? []).filter { $0.location.path != path }
16 return CompletionResult(items: notes.map { CompletionItem(title: $0.title, id: $0.id, path: $0.location.path, start: 0, heading: false) })
17 case .propertyValues(let name):
18 guard let values = try? index.propertyValues(name, excluding: path) else { return CompletionResult() }
19 return CompletionResult(strings: values.allowed + values.used)
20 case .words(let prefix):
21 return CompletionResult(strings: (try? index.words(prefix, excluding: path)) ?? [])
22 }
23 }
24
25 /// `org-id-get-create` on a heading in another file, through its buffer when it's open:
26 /// the new ID, or nil when the heading isn't where the index put it.
27 @MainActor
28 public static func createID(_ item: CompletionItem, session: DocumentSession, newID: String = UUID().uuidString.lowercased()) -> String? {
29 guard item.heading, let text = session.text(of: item.path) else { return nil }
30 let ns = text as NSString
31 guard item.start < ns.length else { return nil }
32 var end = 0
33 ns.getLineStart(nil, end: nil, contentsEnd: &end, for: NSRange(location: item.start, length: 0))
34 let line = ns.substring(with: NSRange(location: item.start, length: end - item.start))
35 guard line.hasPrefix("*"), line.contains(item.title) else { return nil }
36 guard case .commit = session.perform(CreateID(newID: { newID }), path: item.path, at: item.start, expect: (item.start, line)) else { return nil }
37 return newID
38 }
39
40 /// The text of the open buffers other than `path`, for word completion.
41 @MainActor
42 public static func otherBuffers(_ session: DocumentSession, excluding path: String?) -> [String] {
43 session.openPaths.filter { $0 != path }.compactMap { session.text(of: $0) }
44 }
45}