Sources/OrgCore/Completion/CompletionList.swift
162 lines · 8047 bytes
1import Foundation
2
3/// How the completion list behaves, from `config.toml`, with the preset's choices resolved.
4public struct CompletionOptions: Sendable, Equatable, Codable {
5 /// The list opens by itself after typing (`corfu-auto`).
6 public var auto = false
7 /// The pause after typing before it opens, in seconds (`corfu-auto-delay`).
8 public var delay = 0.4
9 /// Characters typed before it opens (`corfu-auto-prefix`).
10 public var prefix = 2
11 /// Candidates match when the typed characters appear in order, best first, as the
12 /// palette matches; otherwise they start with what's typed.
13 public var fuzzy = false
14 /// Words from the buffers and the index fill the list that opens by itself where Org
15 /// offers nothing.
16 public var words = false
17
18 public init(auto: Bool = false, delay: Double = 0.4, prefix: Int = 2, fuzzy: Bool = false, words: Bool = false) {
19 self.auto = auto
20 self.delay = delay
21 self.prefix = prefix
22 self.fuzzy = fuzzy
23 self.words = words
24 }
25}
26
27/// When the list opens by itself.
28public enum CompletionAuto {
29 /// The pause after a change before the list opens, or nil when it doesn't: the setting is
30 /// off, Vim keys are outside insert state, or the file isn't org and words aren't offered.
31 public static func delay(_ options: CompletionOptions, modal: Bool, insertState: Bool, isOrg: Bool) -> Double? {
32 guard options.auto, !modal || insertState, isOrg || options.words else { return nil }
33 return max(0, options.delay)
34 }
35
36 /// Whether `completion`, found after the pause, opens the list: enough typed, and
37 /// something to show now or from the index.
38 public static func opens(_ completion: Completion?, _ options: CompletionOptions) -> Bool {
39 guard let completion, completion.range.count >= max(1, options.prefix) else { return false }
40 return !completion.candidates.isEmpty || completion.query != nil
41 }
42}
43
44/// The open list, as corfu keeps it: the completion shown and the chosen row, nil while the
45/// typed text stands (`corfu-preselect` prompt).
46public struct CompletionList: Sendable, Equatable {
47 public private(set) var completion: Completion
48 public private(set) var selection: Int?
49
50 public init(_ completion: Completion, selection: Int? = nil) {
51 self.completion = completion
52 self.selection = selection.flatMap { completion.candidates.indices.contains($0) ? $0 : nil }
53 }
54
55 /// New candidates; the chosen one stays chosen if it is still there.
56 public mutating func update(_ completion: Completion) {
57 if completion.candidates != self.completion.candidates { selection = selected.flatMap { completion.candidates.firstIndex(of: $0) } }
58 self.completion = completion
59 }
60
61 /// corfu-cycle: past either end the choice wraps through the typed text.
62 public mutating func move(_ delta: Int) {
63 let count = completion.candidates.count
64 guard count > 0 else { return }
65 if let s = selection {
66 let next = s + delta
67 selection = next < 0 || next >= count ? nil : next
68 } else {
69 selection = delta > 0 ? 0 : count - 1
70 }
71 }
72
73 public var selected: String? { selection.map { completion.candidates[$0] } }
74
75 /// The rows shown when at most `rows` fit: those around the choice.
76 public func visible(rows: Int) -> Range<Int> {
77 let count = completion.candidates.count
78 let first = max(0, min((selection ?? 0) - rows + 1, count - rows))
79 return first..<min(count, first + rows)
80 }
81
82 public enum Action: Equatable {
83 /// The choice moved, or the key did nothing more; show the list again.
84 case shown
85 /// Insert this candidate and close the list.
86 case insert(String)
87 /// Insert the part the candidates share, keeping the list open.
88 case common(String)
89 /// Close the list.
90 case close
91 /// Close the list and let the key do what it otherwise does.
92 case closeAndPass
93 /// Not the list's key.
94 case pass
95 }
96
97 /// What a key does while the list is open.
98 public mutating func key(_ chord: KeyChord) -> Action {
99 switch chord {
100 case KeyChord("n", .control), KeyChord("<down>"), KeyChord("j", .control):
101 move(1)
102 return .shown
103 case KeyChord("p", .control), KeyChord("<up>"), KeyChord("k", .control):
104 move(-1)
105 return .shown
106 case KeyChord("TAB"):
107 // corfu-complete: the choice, else the candidates' common start.
108 let candidates = completion.candidates
109 if let selected { return .insert(selected) }
110 if candidates.count == 1 { return .insert(candidates[0]) }
111 guard let first = candidates.first, ![.template, .snippet, .idLink, .denoteLink].contains(completion.kind) else { return .shown }
112 let common = candidates.dropFirst().reduce(first) { $0.commonPrefix(with: $1) }
113 if common.utf16.count > completion.range.count, common.lowercased().hasPrefix(completion.typed.lowercased()) { return .common(common) }
114 return .shown
115 case KeyChord("RET"):
116 return selected.map { .insert($0) } ?? .closeAndPass
117 case KeyChord("ESC"):
118 return .closeAndPass
119 case KeyChord("g", .control):
120 return .close
121 default:
122 return .pass
123 }
124 }
125}
126
127/// The steps both editors take with a list: finding the completion at the caret again as
128/// typing goes on, and inserting a link.
129public enum CompletionFlow {
130 /// The index's answer for the completion of `kind` starting at `start`.
131 public typealias Fetched = (kind: Completion.Kind, start: Int, result: CompletionResult)
132
133 /// The completion at the caret for a list showing `open`, or for a new list of words
134 /// (`words`) or of what Org offers. Words narrow what was found when the list opened;
135 /// the rest are found again, with the index's answer added when it was for this place.
136 public static func current(_ context: EditContext, open: Completion?, words: Bool, others: () -> [String], fetched: Fetched?) -> Completion? {
137 if let open, open.kind == .word {
138 guard let range = Dabbrev.abbreviation(in: context.text, caret: context.caret), range.lowerBound == open.range.lowerBound else { return nil }
139 return Dabbrev.narrowed(open, to: range, in: context.text)
140 }
141 guard let found = words ? Dabbrev.completion(context, others: others()) : OrgCompletion.at(context) else { return nil }
142 if let fetched, fetched.kind == found.kind, fetched.start == found.range.lowerBound, found.query != nil {
143 return OrgCompletion.filled(found, with: fetched.result, fuzzy: context.options.completion.fuzzy)
144 }
145 return found
146 }
147
148 /// `org-id-get-create` on `item`'s heading in this buffer: the edits giving it `newID`.
149 public static func createID(_ item: CompletionItem, in context: EditContext, newID: String) -> [TextEdit]? {
150 let at = EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: [item.start..<item.start], options: context.options)
151 guard case .commit(let result) = CreateID(newID: { newID }).run(in: at) else { return nil }
152 return result.edits
153 }
154
155 /// The edit putting the link to `item`, with `id`, in place of the link typed, after
156 /// `earlier` edits (an ID given in this buffer) moved the text.
157 public static func linkEdit(_ completion: Completion, _ item: CompletionItem, id: String, after earlier: [TextEdit] = []) -> TextEdit {
158 let range = completion.link ?? completion.range
159 let shift = earlier.filter { $0.range.upperBound <= range.lowerBound }.reduce(0) { $0 + $1.replacement.utf16.count - $1.range.count }
160 return TextEdit(range: (range.lowerBound + shift)..<(range.upperBound + shift), replacement: completion.link(item, id: id))
161 }
162}