// SPDX-License-Identifier: GPL-3.0-or-later import AppKit /// AppKit supplies the native completion list and keyboard behavior. Suggestions /// never provisionally rewrite source: only a final, still-valid choice is an /// editor operation, preserving the normal document Undo manager. class CMOCCompletionTextView: NSTextView, SourceFindEditor { weak var sourceFind: SourceFind? var completionProvider: ((String, Int) -> [CMOCCompletion.Candidate])? var completionStatus: ((String) -> Void)? var parameterHintAction: (() -> Void)? var assistanceFocusLost: (() -> Void)? private var completionSource: String? private var completionRange = NSRange(location: NSNotFound, length: 0) private var completionOffset = 0 private var completionCandidates: [CMOCCompletion.Candidate] = [] @discardableResult func prepareCompletion() -> Bool { invalidateCompletion() guard isEditable else { completionStatus?("Completion is available in editable C sources."); return false } guard !hasMarkedText() else { completionStatus?("Finish the current text composition before completing an identifier."); return false } guard selectedRange().length == 0 else { completionStatus?("Place the insertion point inside or after an identifier to complete it."); return false } guard let completionProvider else { completionStatus?("Source completion is not ready for this editor."); return false } let source = string, offset = selectedRange().location let candidates = completionProvider(source, offset) guard let first = candidates.first, first.replacementRange.location != NSNotFound, NSMaxRange(first.replacementRange) <= (source as NSString).length else { completionStatus?("No completion candidates here. Suggestions use the project’s source index.") return false } completionSource = source; completionRange = first.replacementRange; completionOffset = offset completionCandidates = candidates.filter { $0.replacementRange == first.replacementRange } let uncertain = completionCandidates.contains { $0.conditional } completionStatus?("\(completionCandidates.count) source-based suggestions" + (uncertain ? " · Some candidates depend on build settings or scope." : ".")) return true } func invalidateCompletion() { completionSource = nil; completionRange = NSRange(location: NSNotFound, length: 0) completionCandidates = [] } override func complete(_ sender: Any?) { guard prepareCompletion() else { return } super.complete(sender) } override var rangeForUserCompletion: NSRange { completionSource == string ? completionRange : NSRange(location: NSNotFound, length: 0) } override func completions(forPartialWordRange charRange: NSRange, indexOfSelectedItem index: UnsafeMutablePointer?) -> [String]? { guard isEditable, completionSource == string, charRange == completionRange else { return [] } index?.pointee = -1 return completionCandidates.map(\.insertion) } override func insertCompletion(_ word: String, forPartialWordRange charRange: NSRange, movement: Int, isFinal flag: Bool) { // The native list asks to preview candidates as the selection moves. // Keeping these out of the document also keeps them out of draft recovery. guard flag else { return } defer { invalidateCompletion() } guard movement != NSTextMovement.cancel.rawValue, isEditable, !hasMarkedText(), completionSource == string, selectedRange() == NSRange(location: completionOffset, length: 0), charRange == completionRange, completionCandidates.contains(where: { $0.insertion == word }), completionRange.location != NSNotFound, NSMaxRange(completionRange) <= (string as NSString).length else { return } breakUndoCoalescing() insertText(word, replacementRange: completionRange) breakUndoCoalescing() undoManager?.setActionName("Complete Identifier") } override func cancelOperation(_ sender: Any?) { invalidateCompletion() if sourceFind?.cancel(from: self) != true { _ = nextResponder?.tryToPerform(#selector(NSResponder.cancelOperation(_:)), with: sender) } } override func resignFirstResponder() -> Bool { let resigned = super.resignFirstResponder() if resigned { invalidateCompletion(); assistanceFocusLost?() } return resigned } override func performKeyEquivalent(with event: NSEvent) -> Bool { let modifiers = event.modifierFlags.intersection([.command, .control, .option, .shift]) if event.keyCode == 49, modifiers == [.control] { complete(nil); return true } if event.keyCode == 49, modifiers == [.control, .shift] { parameterHintAction?(); return true } return super.performKeyEquivalent(with: event) } }