Sources/OrgEditorAppKit/CompletionPopup.swift

5ab870e0abd4140b7b83076712bf63910aaa4ec0
orgstar/Sources/OrgEditorAppKit/CompletionPopup.swift

274 lines · 13024 bytes

  1#if os(macOS)
  2import AppKit
  3import OrgCore
  4
  5/// The candidate list under the caret, as corfu shows it: at most 16 rows, nothing selected
  6/// until C-n or an arrow picks one.
  7@MainActor
  8final class CompletionPopup {
  9    static let rows = 16
 10    let window: NSPanel
 11    private let stack = NSStackView()
 12    private(set) var list: CompletionList
 13
 14    var completion: Completion { list.completion }
 15    var selected: String? { list.selected }
 16
 17    init(_ completion: Completion, selection: Int? = nil) {
 18        list = CompletionList(completion, selection: selection)
 19        window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 200, height: 20), styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: true)
 20        window.identifier = NSUserInterfaceItemIdentifier("completion")
 21        window.hasShadow = true
 22        window.backgroundColor = .controlBackgroundColor
 23        window.isReleasedWhenClosed = false
 24        stack.orientation = .vertical
 25        stack.alignment = .leading
 26        stack.spacing = 0
 27        stack.edgeInsets = NSEdgeInsets(top: 2, left: 0, bottom: 2, right: 0)
 28        window.contentView = stack
 29        window.contentView?.wantsLayer = true
 30        window.contentView?.layer?.borderColor = NSColor.separatorColor.cgColor
 31        window.contentView?.layer?.borderWidth = 1
 32    }
 33
 34    func update(_ completion: Completion) { list.update(completion) }
 35
 36    func move(_ delta: Int) { list.move(delta) }
 37
 38    func key(_ chord: KeyChord) -> CompletionList.Action { list.key(chord) }
 39
 40    /// Lays the rows out and puts the list under `caret`, a rectangle in screen coordinates.
 41    func show(under caret: NSRect, in parent: NSWindow?, font: NSFont) {
 42        stack.arrangedSubviews.forEach { $0.removeFromSuperview() }
 43        let candidates = completion.candidates
 44        var width: CGFloat = 80
 45        for index in list.visible(rows: Self.rows) {
 46            let candidate = candidates[index]
 47            let label = NSTextField(labelWithString: " " + completion.label(candidate) + (completion.kind == .snippet ? "  " + String(localized: "snippet", comment: "Marks a snippet in the completion list") : "") + " ")
 48            label.font = font
 49            label.drawsBackground = index == list.selection
 50            label.backgroundColor = .selectedContentBackgroundColor
 51            label.textColor = index == list.selection ? .alternateSelectedControlTextColor : .labelColor
 52            label.lineBreakMode = .byTruncatingTail
 53            stack.addArrangedSubview(label)
 54            width = max(width, label.intrinsicContentSize.width)
 55        }
 56        width = min(width, 120 * font.maximumAdvancement.width)
 57        for label in stack.arrangedSubviews { label.widthAnchor.constraint(equalToConstant: width).isActive = true }
 58        let height = stack.fittingSize.height
 59        window.setContentSize(NSSize(width: width, height: height))
 60        window.setFrameTopLeftPoint(NSPoint(x: caret.minX, y: caret.minY - 2))
 61        if window.parent == nil { parent?.addChildWindow(window, ordered: .above) }
 62        window.orderFront(nil)
 63    }
 64
 65    func close() {
 66        window.parent?.removeChildWindow(window)
 67        window.orderOut(nil)
 68    }
 69}
 70
 71extension OrgEditor {
 72    /// `completion-at-point`: one candidate is inserted, several are listed. Candidates from
 73    /// the index join the list when it answers.
 74    func completeAtPoint() {
 75        guard let completion = OrgCompletion.at(context()), !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 from the buffers and the index in a list, the first chosen, or with `last` the
 89    /// last (Doom's C-n and C-p in insert state).
 90    func completeWord(last: Bool) {
 91        guard let completion = Dabbrev.completion(context(), others: otherBuffers()) else {
 92            closeCompletion()
 93            return fail("No possible abbreviation preceding point")
 94        }
 95        if completion.candidates.isEmpty, completionSource == nil { return fail("No dynamic expansion for `\(completion.typed)' found") }
 96        openCompletion(completion, select: last ? completion.candidates.count - 1 : 0)
 97    }
 98
 99    /// Shows `completion` when it has candidates, and asks the index for more.
100    func openCompletion(_ completion: Completion, select: Int? = nil) {
101        completionFetched = nil
102        if !completion.candidates.isEmpty { showCompletion(completion, select: select) }
103        guard let query = completion.query, let source = completionSource else {
104            if completion.candidates.isEmpty { closeCompletion() }
105            return
106        }
107        let start = completion.range.lowerBound, kind = completion.kind
108        completionTask?.cancel()
109        completionTask = Task { [weak self] in
110            let result = await source(query)
111            guard !Task.isCancelled, let self else { return }
112            self.completionFetched = (kind, start, result)
113            self.fetchedCompletion(kind: kind, start: start, select: select)
114        }
115    }
116
117    /// The index answered: the list shows what it adds, or opens with it.
118    private func fetchedCompletion(kind: Completion.Kind, start: Int, select: Int?) {
119        guard textView.selectedRange().length == 0 else { return }
120        let open = completionPopup?.completion
121        guard open == nil || (open?.kind == kind && open?.range.lowerBound == start) else { return }
122        let words = kind == .word
123        guard let current = CompletionFlow.current(context(), open: nil, words: words, others: otherBuffers, fetched: completionFetched),
124              current.kind == kind, current.range.lowerBound == start, !current.candidates.isEmpty else { return }
125        showCompletion(current, select: open == nil ? select.map { $0 < 0 || $0 >= current.candidates.count ? current.candidates.count - 1 : $0 } : nil)
126    }
127
128    func showCompletion(_ completion: Completion, select: Int? = nil) {
129        if let popup = completionPopup { popup.update(completion) } else { completionPopup = CompletionPopup(completion, selection: select) }
130        let screen = textView.firstRect(forCharacterRange: NSRange(location: completion.range.lowerBound, length: 0), actualRange: nil)
131        completionPopup?.show(under: screen, in: textView.window, font: theme.font)
132    }
133
134    func closeCompletion() {
135        completionTimer?.cancel()
136        completionTask?.cancel()
137        completionPopup?.close()
138        completionPopup = nil
139    }
140
141    /// After typing: the open list follows the text; otherwise, as the completion settings
142    /// say, a list opens after a pause once enough is typed (corfu-auto).
143    func textTyped() {
144        completionTimer?.cancel()
145        if completionPopup != nil {
146            refreshCompletion()
147            return
148        }
149        guard let delay = CompletionAuto.delay(options.completion, modal: modal, insertState: vim.mode == .insert, isOrg: isOrg) else { return }
150        let work = DispatchWorkItem { [weak self] in self?.autoComplete() }
151        completionTimer = work
152        DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: work)
153    }
154
155    func autoComplete() {
156        guard completionPopup == nil, textView.selectedRange().length == 0 else { return }
157        let context = context()
158        var completion = isOrg ? OrgCompletion.at(context) : nil
159        if options.completion.words, completion.map({ $0.candidates.isEmpty && $0.query == nil }) ?? true {
160            completion = Dabbrev.completion(context, others: otherBuffers())
161        }
162        guard CompletionAuto.opens(completion, options.completion), let completion else { return }
163        openCompletion(completion)
164    }
165
166    func refreshCompletion() {
167        guard let popup = completionPopup else { return }
168        guard textView.selectedRange().length == 0,
169              let completion = CompletionFlow.current(context(), open: popup.completion, words: false, others: otherBuffers, fetched: completionFetched),
170              completion.range.lowerBound == popup.completion.range.lowerBound, !completion.candidates.isEmpty else {
171            closeCompletion()
172            return
173        }
174        showCompletion(completion)
175    }
176
177    func insertCompletion(_ completion: Completion, _ candidate: String) {
178        defer { completionTimer?.cancel() }
179        if completion.kind == .snippet { return expandCompleted(completion, candidate) }
180        if completion.kind == .idLink || completion.kind == .denoteLink { return insertLink(completion, candidate) }
181        let (text, caret) = completion.insertion(candidate)
182        let range = NSRange(location: completion.range.lowerBound, length: completion.range.count)
183        guard textView.shouldChangeText(in: range, replacementString: text) else { return }
184        textView.textStorage?.replaceCharacters(in: range, with: text)
185        textView.didChangeText()
186        setCaret(completion.range.lowerBound + caret)
187    }
188
189    /// A link to the chosen heading or note, its title the description. A heading without an
190    /// ID gets one first, here or in its file, as `org-id-get-create` would.
191    func insertLink(_ completion: Completion, _ candidate: String) {
192        guard let item = completion.item(candidate) else { return }
193        var created: [TextEdit] = []
194        var id = item.id
195        if id == nil, completion.kind == .idLink {
196            if item.path == (options.filePath ?? "") {
197                let newID = UUID().uuidString.lowercased()
198                if let edits = CompletionFlow.createID(item, in: context(), newID: newID) {
199                    applyEdits(edits)
200                    created = edits
201                    id = newID
202                }
203            } else {
204                id = createID?(item)
205            }
206        }
207        guard let id else { return fail("Can't give \(item.title) an ID") }
208        let edit = CompletionFlow.linkEdit(completion, item, id: id, after: created)
209        let range = NSRange(edit.range)
210        guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { return }
211        textView.textStorage?.replaceCharacters(in: range, with: edit.replacement)
212        textView.didChangeText()
213        setCaret(edit.range.lowerBound + edit.replacement.utf16.count)
214    }
215
216    /// `dabbrev-expand`: the word before the caret completed from the buffers, then the
217    /// index; again right after, the next expansion in its place.
218    func dabbrevExpand() {
219        closeCompletion()
220        let caret = textView.selectedRange().location
221        let repeated = lastCommand?.id == "editor.dabbrev-expand" && lastCommand?.revision == document.revision && dabbrev?.end == caret
222        if !repeated {
223            guard let expansion = DabbrevExpansion(context(), others: otherBuffers()) else { return fail("No possible abbreviation preceding point") }
224            dabbrev = expansion
225            if let source = completionSource {
226                let abbrev = expansion.abbrev, start = expansion.start
227                completionTask = Task { [weak self] in
228                    let result = await source(.words(abbrev))
229                    guard !Task.isCancelled, let self, self.dabbrev?.start == start else { return }
230                    self.dabbrev?.add(result.strings)
231                }
232            }
233        }
234        guard var expansion = dabbrev else { return }
235        let (edit, exhausted) = expansion.advance()
236        dabbrev = expansion
237        let range = NSRange(edit.range)
238        if (document.text as NSString).substring(with: range) != edit.replacement, textView.shouldChangeText(in: range, replacementString: edit.replacement) {
239            textView.textStorage?.replaceCharacters(in: range, with: edit.replacement)
240            textView.didChangeText()
241        }
242        setCaret(expansion.end)
243        completionTimer?.cancel()
244        if exhausted { fail(expansion.failure) }
245    }
246
247    /// Keys while the list is open. Nil lets the key through.
248    func completionKey(_ chord: KeyChord) -> Bool? {
249        guard let popup = completionPopup else { return nil }
250        let completion = popup.completion
251        switch popup.key(chord) {
252        case .shown:
253            showCompletion(popup.completion)
254            return true
255        case .insert(let candidate):
256            closeCompletion()
257            insertCompletion(completion, candidate)
258            return true
259        case .common(let common):
260            insertCompletion(completion, common)
261            refreshCompletion()
262            return true
263        case .close:
264            closeCompletion()
265            return true
266        case .closeAndPass:
267            closeCompletion()
268            return nil
269        case .pass:
270            return nil
271        }
272    }
273}
274#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