Sources/OrgApp/CompletionSources.swift
49 lines · 2922 bytes
4 symbols in this file
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 case .citationKeys(let files):
23 // With `org-cite-global-bibliography` as it is now, not as the buffer was parsed.
24 let global = OrgPreferences.citeGlobalBibliography().map { OrgPaths.expandingTilde($0) }
25 return CompletionResult(entries: BibliographyCache.shared.entries(files + global.filter { !files.contains($0) }))
26 }
27 }
28
29 /// `org-id-get-create` on a heading in another file, through its buffer when it's open:
30 /// the new ID, or nil when the heading isn't where the index put it.
31 @MainActor
32 public static func createID(_ item: CompletionItem, session: DocumentSession, newID: String = UUID().uuidString.lowercased()) -> String? {
33 guard item.heading, let text = session.text(of: item.path) else { return nil }
34 let ns = text as NSString
35 guard item.start < ns.length else { return nil }
36 var end = 0
37 ns.getLineStart(nil, end: nil, contentsEnd: &end, for: NSRange(location: item.start, length: 0))
38 let line = ns.substring(with: NSRange(location: item.start, length: end - item.start))
39 guard line.hasPrefix("*"), line.contains(item.title) else { return nil }
40 guard case .commit = session.perform(CreateID(newID: { newID }), path: item.path, at: item.start, expect: (item.start, line)) else { return nil }
41 return newID
42 }
43
44 /// The text of the open buffers other than `path`, for word completion.
45 @MainActor
46 public static func otherBuffers(_ session: DocumentSession, excluding path: String?) -> [String] {
47 session.openPaths.filter { $0 != path }.compactMap { session.text(of: $0) }
48 }
49}