CompletionSupplier tokenCompletion()

in hybrid/src/main/java/jetbrains/jetpad/hybrid/TokenCompleter.java [102:172]


  CompletionSupplier tokenCompletion(final Cell tokenCell) {
    final int index = mySync.tokenCells().indexOf(tokenCell);
    return tokenCompletion(new TokenCompletionContext(index), new BaseCompleter() {
      @Override
      public Runnable complete(int selectionIndex, Token... tokens) {
        final int caretPosition;
        String oldText = null;
        SelectionPosition position = LAST;
        if (tokenCell instanceof TextCell) {
          TextCell cell = (TextCell) tokenCell;
          caretPosition = cell.caretPosition().get();
          oldText = cell.text().get();
          if (caretPosition == 0) {
            position = FIRST;
          } else if (caretPosition == cell.text().get().length()) {
            position = LAST;
          } else {
            position = null;
          }
        } else {
          caretPosition = -1;
        }

        CompletionController controller = tokenCell.get(Completion.COMPLETION_CONTROLLER);
        final boolean wasCompletionActive = controller != null && controller.isActive();

        TokenListEditor<?> tokenListEditor = getTokenListEditor();

        if (tokens.length == 0) {
          tokenListEditor.tokens.remove(index);
        } else {
          int sourceIndex = 0;
          int targetIndex = index;
          tokenListEditor.tokens.set(targetIndex++, tokens[sourceIndex++]);
          while (sourceIndex < tokens.length) {
            tokenListEditor.tokens.add(targetIndex++, tokens[sourceIndex++]);
          }
        }

        tokenListEditor.processComments();
        tokenListEditor.updateToPrintedTokens();

        final Cell targetCell =  mySync.tokenCells().get(index + selectionIndex);
        if (!(targetCell instanceof TextCell) || !Objects.equal(((TextCell) targetCell).text().get(), oldText)) {
          if (isComment(targetCell)) {
            position = null;
          } else {
            position = LAST;
          }
        }

        Runnable result;
        if (position == null) {
          result = new Runnable() {
            @Override
            public void run() {
              targetCell.focus();
              ((TextCell) targetCell).caretPosition().set(caretPosition);
            }
          };
        } else {
          result = mySync.tokenOperations().selectOnCreation(index + selectionIndex, position);
        }

        if (wasCompletionActive) {
          result = seq(result, activateCompletion(index + selectionIndex));
        }
        return result;
      }
    });
  }