akvelon / flutter-code-editor

Flutter Code Editor is a multi-platform code editor supporting syntax highlighting, code blocks folding, autocompletion, read-only code blocks, hiding specific code blocks, themes, and more.

Home Page:https://akvelon.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Please provide an autocomplete callback based on custom triggers

sma opened this issue · comments

I'd like to provide code completion after the user enters >>. Currently, there seems to be no easy way to achieve this. There's a hardcoded AutoCompleter in CodeController which is asked for suggestions by the controller, but it knows only the language Mode and extracts keywords and isn't context sensitive. I think, I need an API that accepts a callback asking me for suggestions based on one or multiple triggers.

I tried to subclass CodeController like shown below, but I consider this a workaround (which doesn't support to incrementally narrow down the selection yet):

class MyCodeController extends CodeController {
  MyCodeController({
    super.text,
    super.language,
    super.analyzer,
    super.namedSectionParser,
    super.readOnlySectionNames,
    super.visibleSectionNames,
    super.analysisResult,
    super.patternMap,
    super.stringMap,
    super.params,
    super.modifiers,
  });

  @override
  Future<void> generateSuggestions() async {
    if (!value.selection.isCollapsed) {
      popupController.hide();
      return;
    }
    final start = value.selection.start;
    if (start >= 3 && value.text.startsWith('>> ', start - 3)) {
      popupController.show(
        const [
          'Kirche',
          'Friedhof',
        ],
      );
    } else {
      popupController.hide();
    }
  }

  @override
  void insertSelectedWord() {
    final previousSelection = selection;
    final selectedWord = popupController.getSelectedWord();
    final startPosition = previousSelection.start; // changed to not search for a word

    final replacedText = text.replaceRange(
      startPosition,
      selection.baseOffset,
      selectedWord,
    );

    final adjustedSelection = previousSelection.copyWith(
      baseOffset: startPosition + selectedWord.length,
      extentOffset: startPosition + selectedWord.length,
    );

    value = TextEditingValue(
      text: replacedText,
      selection: adjustedSelection,
    );

    popupController.hide();
  }
}

I'm using version 0.2.15.