Sources/OrgstarMobile/MobileEditor+Completion.swift

30fb15c9bc849ec1e8371b73bd02d071a4b4eb2a
orgstar/Sources/OrgstarMobile/MobileEditor+Completion.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form