Sources/OrgstarMobile/MobileEditor+Completion.swift
285 lines · 13234 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import UIKit
5
6/// The completion list under the caret, as on the Mac: keys on a hardware keyboard pick a
7/// row, and a tap inserts one.
8final class CompletionListView: UIView {
9 static let rows = 8
10 private(set) var list: CompletionList
11 private let stack = UIStackView()
12 var onChoose: ((String) -> Void)?
13
14 init(_ completion: Completion, selection: Int?) {
15 list = CompletionList(completion, selection: selection)
16 super.init(frame: .zero)
17 backgroundColor = .secondarySystemBackground
18 layer.borderColor = UIColor.separator.cgColor
19 layer.borderWidth = 1
20 layer.cornerRadius = 6
21 layer.shadowOpacity = 0.15
22 layer.shadowRadius = 6
23 stack.axis = .vertical
24 stack.alignment = .fill
25 addSubview(stack)
26 accessibilityIdentifier = "completion"
27 }
28
29 required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
30
31 var completion: Completion { list.completion }
32
33 func update(_ completion: Completion) { list.update(completion) }
34
35 func key(_ chord: KeyChord) -> CompletionList.Action { list.key(chord) }
36
37 /// Lays the rows out under `caret`, or above it when there isn't room below, kept inside
38 /// `bounds`: the part of the text view not under the keyboard and the key bar.
39 func show(under caret: CGRect, within bounds: CGRect, font: UIFont) {
40 stack.arrangedSubviews.forEach { $0.removeFromSuperview() }
41 var width: CGFloat = 80
42 for index in list.visible(rows: Self.rows) {
43 let candidate = completion.candidates[index]
44 let label = UILabel()
45 label.text = " " + completion.label(candidate) + (completion.kind == .snippet ? " " + String(localized: "snippet", comment: "Marks a snippet in the completion list") : "") + " "
46 label.font = font
47 label.lineBreakMode = .byTruncatingTail
48 label.isUserInteractionEnabled = true
49 label.backgroundColor = index == list.selection ? .tintColor : .clear
50 label.textColor = index == list.selection ? .white : .label
51 label.tag = index
52 label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapped(_:))))
53 label.heightAnchor.constraint(equalToConstant: max(28, font.lineHeight + 6)).isActive = true
54 stack.addArrangedSubview(label)
55 width = max(width, label.intrinsicContentSize.width)
56 }
57 width = min(width, bounds.width - 16)
58 let height = stack.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
59 let x = min(max(bounds.minX + 8, caret.minX), bounds.maxX - width - 8)
60 let below = caret.maxY + 2
61 let y = below + height <= bounds.maxY || caret.minY - 2 - height < bounds.minY ? below : caret.minY - 2 - height
62 frame = CGRect(x: x, y: y, width: width, height: height)
63 stack.frame = CGRect(origin: .zero, size: frame.size)
64 }
65
66 @objc private func tapped(_ gesture: UITapGestureRecognizer) {
67 guard let index = gesture.view?.tag, completion.candidates.indices.contains(index) else { return }
68 onChoose?(completion.candidates[index])
69 }
70}
71
72extension MobileEditor {
73 /// Org files complete Org's positions; other files only words.
74 var completesOrg: Bool { fileName.map(DocumentSession.isOrgPath) ?? true }
75
76 /// `completion-at-point`: one candidate is inserted, several are listed.
77 func completeAtPoint() {
78 guard completesOrg, let completion = OrgCompletion.at(editContext()), !completion.candidates.isEmpty || completion.query != nil else {
79 closeCompletion()
80 onMessage?("No match")
81 return
82 }
83 if completion.query == nil, completion.candidates.count == 1 {
84 closeCompletion()
85 insertCompletion(completion, completion.candidates[0])
86 return
87 }
88 openCompletion(completion)
89 }
90
91 /// Words in a list, the first chosen, or with `last` the last.
92 func completeWord(last: Bool) {
93 guard let completion = Dabbrev.completion(editContext(), others: otherBuffers()) else {
94 closeCompletion()
95 return fail("No possible abbreviation preceding point")
96 }
97 if completion.candidates.isEmpty, completionSource == nil { return fail("No dynamic expansion for `\(completion.typed)' found") }
98 openCompletion(completion, select: last ? completion.candidates.count - 1 : 0)
99 }
100
101 func openCompletion(_ completion: Completion, select: Int? = nil) {
102 completionFetched = nil
103 if !completion.candidates.isEmpty { showCompletion(completion, select: select) }
104 guard let query = completion.query, let source = completionSource else {
105 if completion.candidates.isEmpty { closeCompletion() }
106 return
107 }
108 let start = completion.range.lowerBound, kind = completion.kind
109 completionTask?.cancel()
110 completionTask = Task { [weak self] in
111 let result = await source(query)
112 guard !Task.isCancelled, let self else { return }
113 self.completionFetched = (kind, start, result)
114 self.fetchedCompletion(kind: kind, start: start, select: select)
115 }
116 }
117
118 private func fetchedCompletion(kind: Completion.Kind, start: Int, select: Int?) {
119 guard textView.selectedRange.length == 0 else { return }
120 let open = completionList?.completion
121 guard open == nil || (open?.kind == kind && open?.range.lowerBound == start) else { return }
122 guard let current = CompletionFlow.current(editContext(), open: nil, words: kind == .word, others: otherBuffers, fetched: completionFetched),
123 current.kind == kind, current.range.lowerBound == start, !current.candidates.isEmpty else { return }
124 showCompletion(current, select: open == nil ? select.map { $0 < 0 || $0 >= current.candidates.count ? current.candidates.count - 1 : $0 } : nil)
125 }
126
127 func showCompletion(_ completion: Completion, select: Int? = nil) {
128 let view: CompletionListView
129 if let open = completionList {
130 open.update(completion)
131 view = open
132 } else {
133 view = CompletionListView(completion, selection: select)
134 view.onChoose = { [weak self, weak view] candidate in
135 guard let self, let view else { return }
136 let completion = view.completion
137 self.closeCompletion()
138 self.insertCompletion(completion, candidate)
139 }
140 completionList = view
141 textView.addSubview(view)
142 }
143 guard let position = textView.position(from: textView.beginningOfDocument, offset: completion.range.lowerBound) else { return }
144 let caret = textView.caretRect(for: position)
145 let insets = textView.adjustedContentInset
146 let visible = CGRect(x: textView.contentOffset.x, y: textView.contentOffset.y + insets.top,
147 width: textView.bounds.width, height: textView.bounds.height - insets.top - insets.bottom)
148 view.show(under: caret, within: visible, font: theme.font)
149 }
150
151 func closeCompletion() {
152 completionTimer?.invalidate()
153 completionTimer = nil
154 completionTask?.cancel()
155 completionList?.removeFromSuperview()
156 completionList = nil
157 }
158
159 /// After typing: the open list follows the text; otherwise, as the settings say, a list
160 /// opens after a pause once enough is typed.
161 func textTyped() {
162 completionTimer?.invalidate()
163 completionTimer = nil
164 if completionList != nil { return refreshCompletion() }
165 guard let delay = CompletionAuto.delay(options.completion, modal: modal, insertState: vim.mode == .insert, isOrg: completesOrg) else { return }
166 completionTimer = Timer.scheduledTimer(withTimeInterval: delay, repeats: false) { [weak self] _ in
167 MainActor.assumeIsolated { self?.autoComplete() }
168 }
169 }
170
171 func autoComplete() {
172 guard completionList == nil, textView.selectedRange.length == 0, textView.markedTextRange == nil else { return }
173 let context = editContext()
174 var completion = completesOrg ? OrgCompletion.at(context) : nil
175 if options.completion.words, completion.map({ $0.candidates.isEmpty && $0.query == nil }) ?? true {
176 completion = Dabbrev.completion(context, others: otherBuffers())
177 }
178 guard CompletionAuto.opens(completion, options.completion), let completion else { return }
179 openCompletion(completion)
180 }
181
182 func refreshCompletion() {
183 guard let open = completionList else { return }
184 guard textView.selectedRange.length == 0,
185 let completion = CompletionFlow.current(editContext(), open: open.completion, words: false, others: otherBuffers, fetched: completionFetched),
186 completion.range.lowerBound == open.completion.range.lowerBound, !completion.candidates.isEmpty else {
187 closeCompletion()
188 return
189 }
190 showCompletion(completion)
191 }
192
193 func insertCompletion(_ completion: Completion, _ candidate: String) {
194 defer {
195 completionTimer?.invalidate()
196 completionTimer = nil
197 }
198 if completion.kind == .snippet {
199 textView.selectedRange = NSRange(location: completion.range.lowerBound, length: completion.range.count)
200 _ = perform(ExpandNamedSnippet(trigger: candidate))
201 return
202 }
203 if completion.kind == .idLink || completion.kind == .denoteLink { return insertLink(completion, candidate) }
204 let (text, caret) = completion.insertion(candidate)
205 applyEdits([TextEdit(range: completion.range, replacement: text)])
206 textView.selectedRange = NSRange(location: completion.range.lowerBound + caret, length: 0)
207 }
208
209 /// A link to the chosen heading or note, with an ID given to a heading without one.
210 func insertLink(_ completion: Completion, _ candidate: String) {
211 guard let item = completion.item(candidate) else { return }
212 var created: [TextEdit] = []
213 var id = item.id
214 if id == nil, completion.kind == .idLink {
215 if item.path == (options.filePath ?? "") {
216 let newID = UUID().uuidString.lowercased()
217 if let edits = CompletionFlow.createID(item, in: editContext(), newID: newID) {
218 applyEdits(edits)
219 created = edits
220 id = newID
221 }
222 } else {
223 id = createID?(item)
224 }
225 }
226 guard let id else { return fail("Can't give \(item.title) an ID") }
227 let edit = CompletionFlow.linkEdit(completion, item, id: id, after: created)
228 applyEdits([edit])
229 textView.selectedRange = NSRange(location: edit.range.lowerBound + edit.replacement.utf16.count, length: 0)
230 }
231
232 /// `dabbrev-expand`, repeated right after for the next expansion.
233 func dabbrevExpand() {
234 closeCompletion()
235 let caret = textView.selectedRange.location
236 let repeated = dabbrevRevision == document.revision && dabbrev?.end == caret
237 if !repeated {
238 guard let expansion = DabbrevExpansion(editContext(), others: otherBuffers()) else { return fail("No possible abbreviation preceding point") }
239 dabbrev = expansion
240 if let source = completionSource {
241 let abbrev = expansion.abbrev, start = expansion.start
242 completionTask = Task { [weak self] in
243 let result = await source(.words(abbrev))
244 guard !Task.isCancelled, let self, self.dabbrev?.start == start else { return }
245 self.dabbrev?.add(result.strings)
246 }
247 }
248 }
249 guard var expansion = dabbrev else { return }
250 let (edit, exhausted) = expansion.advance()
251 dabbrev = expansion
252 if (document.text as NSString).substring(with: NSRange(edit.range)) != edit.replacement { applyEdits([edit]) }
253 textView.selectedRange = NSRange(location: expansion.end, length: 0)
254 dabbrevRevision = document.revision
255 if exhausted { fail(expansion.failure) }
256 }
257
258 /// Keys while the list is open; nil lets the key through.
259 func completionKey(_ chord: KeyChord) -> Bool? {
260 guard let open = completionList else { return nil }
261 let completion = open.completion
262 switch open.key(chord) {
263 case .shown:
264 showCompletion(open.completion)
265 return true
266 case .insert(let candidate):
267 closeCompletion()
268 insertCompletion(completion, candidate)
269 return true
270 case .common(let common):
271 insertCompletion(completion, common)
272 refreshCompletion()
273 return true
274 case .close:
275 closeCompletion()
276 return true
277 case .closeAndPass:
278 closeCompletion()
279 return nil
280 case .pass:
281 return nil
282 }
283 }
284}
285#endif