Future _completionHelper()

in lib/editing/editor_codemirror.dart [79:148]


  Future<HintResults> _completionHelper(
      CodeMirror editor, CodeCompleter completer, HintsOptions? options) {
    final ed = _CodeMirrorEditor._fromExisting(this, editor);

    return completer
        .complete(ed, onlyShowFixes: ed._lookingForQuickFix)
        .then((CompletionResult result) {
      final doc = editor.doc;
      final from = doc.posFromIndex(result.replaceOffset);
      final to = doc.posFromIndex(result.replaceOffset + result.replaceLength);
      final stringToReplace = doc.getValue()!.substring(
          result.replaceOffset, result.replaceOffset + result.replaceLength);

      var hints = result.completions.map((completion) {
        return HintResult(
          completion.value,
          displayText: completion.displayString,
          className: completion.type,
          hintApplier: (CodeMirror editor, HintResult hint, pos.Position? from,
              pos.Position? to) {
            doc.replaceRange(hint.text!, from!, to);

            if (completion.type == 'type-quick_fix') {
              for (final edit in completion.quickFixes) {
                ed.document.applyEdit(edit);
              }
            }

            if (completion.absoluteCursorPosition != null) {
              doc.setCursor(
                  doc.posFromIndex(completion.absoluteCursorPosition!));
            } else if (completion.cursorOffset != null) {
              final diff = hint.text!.length - completion.cursorOffset!;
              doc.setCursor(pos.Position(
                  editor.getCursor().line, editor.getCursor().ch! - diff));
            }
          },
          hintRenderer: (html.Element element, HintResult hint) {
            final escapeHtml = HtmlEscape().convert as String Function(String?);
            if (completion.type != 'type-quick_fix') {
              element.innerHtml = escapeHtml(completion.displayString)
                  .replaceFirst(escapeHtml(stringToReplace),
                      '<em>${escapeHtml(stringToReplace)}</em>');
            } else {
              element.innerHtml = escapeHtml(completion.displayString);
            }
          },
        );
      }).toList();

      if (hints.isEmpty && ed._lookingForQuickFix) {
        hints = [
          HintResult(stringToReplace,
              displayText: 'No fixes available',
              className: 'type-no_suggestions')
        ];
      } else if (hints.isEmpty &&
          (ed.completionActive ||
              (!ed.completionActive && !ed.completionAutoInvoked))) {
        // Only show 'no suggestions' if the completion was explicitly invoked
        // or if the popup was already active.
        hints = [
          HintResult(stringToReplace,
              displayText: 'No suggestions', className: 'type-no_suggestions')
        ];
      }

      return HintResults.fromHints(hints, from, to);
    });
  }