类 com.intellij.codeInsight.completion.InsertionContext 源码实例Demo

下面列出了怎么用 com.intellij.codeInsight.completion.InsertionContext 的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: litho   文件: ReplacingConsumerTest.java

@Test
public void insertHandler() {
  testHelper.getPsiClass(
      classes -> {
        PsiClass OneCls = classes.get(0);

        List<String> inserts = new ArrayList<>(1);
        TestCompletionResultSet mutate = new TestCompletionResultSet();
        List<String> namesToReplace = new ArrayList<>();
        namesToReplace.add("One");

        ReplacingConsumer replacingConsumer =
            new ReplacingConsumer(
                namesToReplace, mutate, (context, item) -> inserts.add(item.getLookupString()));

        replacingConsumer.consume(createCompletionResultFor(OneCls));
        mutate.elements.get(0).handleInsert(Mockito.mock(InsertionContext.class));

        assertThat(inserts).hasSize(1);
        assertThat(inserts.get(0)).isEqualTo("One");

        return true;
      },
      "One.java");
}
 

@Override
public void handleInsert(final InsertionContext insertionContext,
    final LookupElement lookupElement) {
  if (shouldUseQuotes(lookupElement)) {
    final boolean hasDoubleQuotes =
        hasStartingOrEndingQuoteOfType(insertionContext, lookupElement, DOUBLE_QUOTE);

    if (hasDoubleQuotes) {
      handleEndingQuote(insertionContext, DOUBLE_QUOTE);
      handleStartingQuote(insertionContext, lookupElement, DOUBLE_QUOTE);
    } else {
      handleEndingQuote(insertionContext, SINGLE_QUOTE);
      handleStartingQuote(insertionContext, lookupElement, SINGLE_QUOTE);
    }
  }
}
 

@Nullable
@RequiredUIAccess
protected PsiElement findNextToken(final InsertionContext context)
{
	final PsiFile file = context.getFile();
	PsiElement element = file.findElementAt(context.getTailOffset());
	if(element instanceof PsiWhiteSpace)
	{
		boolean allowParametersOnNextLine = false;
		if(!allowParametersOnNextLine && element.getText().contains("\n"))
		{
			return null;
		}
		element = file.findElementAt(element.getTextRange().getEndOffset());
	}
	return element;
}
 

@Override
public void handleInsert(final InsertionContext context, final LookupElement lookupElement) {
  if (!nextCharAfterSpacesAndQuotesIsColon(getStringAfterAutoCompletedValue(context))) {
    String existingIndentation = getExistingIndentation(context, lookupElement);
    Suggestion suggestion = (Suggestion) lookupElement.getObject();
    String indentPerLevel = getCodeStyleIntent(context);
    Module module = findModule(context);
    String suggestionWithCaret =
        getSuggestionReplacementWithCaret(module, suggestion, existingIndentation,
            indentPerLevel);
    String suggestionWithoutCaret = suggestionWithCaret.replace(CARET, "");

    PsiElement currentElement = context.getFile().findElementAt(context.getStartOffset());
    assert currentElement != null : "no element at " + context.getStartOffset();

    this.deleteLookupTextAndRetrieveOldValue(context, currentElement);

    insertStringAtCaret(context.getEditor(), suggestionWithoutCaret, false, true,
        getCaretIndex(suggestionWithCaret));
  }
}
 

private void deleteLookupTextAndRetrieveOldValue(InsertionContext context,
    @NotNull PsiElement elementAtCaret) {
  if (elementAtCaret.getNode().getElementType() != YAMLTokenTypes.SCALAR_KEY) {
    deleteLookupPlain(context);
  } else {
    YAMLKeyValue keyValue = PsiTreeUtil.getParentOfType(elementAtCaret, YAMLKeyValue.class);
    assert keyValue != null;
    context.commitDocument();

    // TODO: Whats going on here?
    if (keyValue.getValue() != null) {
      YAMLKeyValue dummyKV =
          YAMLElementGenerator.getInstance(context.getProject()).createYamlKeyValue("foo", "b");
      dummyKV.setValue(keyValue.getValue());
    }

    context.setTailOffset(keyValue.getTextRange().getEndOffset());
    runWriteCommandAction(context.getProject(),
        () -> keyValue.getParentMapping().deleteKeyValue(keyValue));
  }
}
 

public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
    Object object = lookupElement.getObject();

    if (!(object instanceof PhpClass)) {
        return;
    }

    StringBuilder textToInsertBuilder = new StringBuilder();
    PhpClass aClass = (PhpClass)object;
    String fqn = aClass.getNamespaceName();

    if(fqn.startsWith("\\")) {
        fqn = fqn.substring(1);
    }

    textToInsertBuilder.append(fqn);
    context.getDocument().insertString(context.getStartOffset(), textToInsertBuilder);

}
 

private PsiElement findElementBeforeNameFragment(InsertionContext context) {
    final PsiFile file = context.getFile();
    PsiElement element = file.findElementAt(context.getStartOffset() - 1);
    element = getElementInFrontOfWhitespace(file, element);
    if (element instanceof LeafPsiElement
            && ((LeafPsiElement) element).getElementType() == XQueryTypes.COLON) {
        PsiElement elementBeforeColon = file.findElementAt(context.getStartOffset() - 2);
        if (elementBeforeColon != null) {
            element = elementBeforeColon;
            PsiElement beforeElementBeforeColon = file.findElementAt(elementBeforeColon.getTextRange().getStartOffset() - 1);
            if (beforeElementBeforeColon != null) {
                element = getElementInFrontOfWhitespace(file, beforeElementBeforeColon);
            }
        }
    }
    return element;
}
 

private void handleStartingQuote(
    final InsertionContext insertionContext,
    final LookupElement lookupElement,
    final char quoteType) {
  final int caretOffset = insertionContext.getEditor().getCaretModel().getOffset();
  final int startOfLookupStringOffset = caretOffset - lookupElement.getLookupString().length();

  final boolean hasStartingQuote =
      hasStartingQuote(insertionContext, quoteType, startOfLookupStringOffset);

  if (!hasStartingQuote) {
    insertionContext
        .getDocument()
        .insertString(startOfLookupStringOffset, String.valueOf(quoteType));
  }
}
 

/**
 * Rough insertion of load statement somewhere near top of file, preferentially near other load
 * statements.
 *
 * <p>Doesn't try to combine with existing load statements with the same package (we've already
 * checked whether the symbol is already available).
 *
 * <p>TODO(brendandouglas): use buildozer instead.
 */
private static void insertLoadStatement(
    InsertionContext context, BuildFile file, String packageLocation, String symbol) {
  EventLoggingService.getInstance()
      .logEvent(
          CommonMacroCompletionContributor.class,
          "completed",
          ImmutableMap.of(symbol, packageLocation));

  String text = String.format("load(\"%s\", \"%s\")\n", packageLocation, symbol);

  Document doc = context.getEditor().getDocument();
  PsiElement anchor = findAnchorElement(file);
  int lineNumber = anchor == null ? 0 : doc.getLineNumber(anchor.getTextRange().getStartOffset());
  int offset = doc.getLineStartOffset(lineNumber);
  doc.insertString(offset, text);
}
 

public void handleInsert(InsertionContext context, LookupElement item) {
    final Editor editor = context.getEditor();
    final Project project = editor.getProject();
    if (project != null) {

        final JSGraphQLEndpointImportDeclaration[] imports = PsiTreeUtil.getChildrenOfType(context.getFile(), JSGraphQLEndpointImportDeclaration.class);

        int insertionOffset = 0;
        if(imports != null && imports.length > 0) {
            JSGraphQLEndpointImportDeclaration lastImport = imports[imports.length - 1];
            insertionOffset = lastImport.getTextRange().getEndOffset();
        }

        final String name = JSGraphQLEndpointImportUtil.getImportName(project, fileToImport);
        String importDeclaration = "import \"" + name + "\"\n";
        if(insertionOffset > 0) {
            importDeclaration = "\n" + importDeclaration;
        }
        editor.getDocument().insertString(insertionOffset, importDeclaration);
    }
}
 

public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	Editor editor = context.getEditor();
	if (context.getCompletionChar() == '(') {
		context.setAddCompletionChar(false);
	}

	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	if (element != null && element.getNode().getElementType() == LatteTypes.T_PHP_IDENTIFIER) {
		boolean notInUse = PhpUseImpl.getUseList(element) == null;

		if (notInUse) {
			if (!LatteUtil.isStringAtCaret(editor, "(")) {
				this.insertParenthesesCodeStyleAware(editor);
			} else if (LatteUtil.isStringAtCaret(editor, "()")) {
				editor.getCaretModel().moveCaretRelatively(2, 0, false, false, true);
			} else {
				editor.getCaretModel().moveCaretRelatively(1, 0, false, false, true);
				showParameterInfo(editor);
			}
		}
	}
}
 

public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	// for removing first `\` (because class completion is triggered if prev element is `\` and PHP completion adding `\` before)
	super.handleInsert(context, lookupElement);

	PsiElement prev = context.getFile().findElementAt(context.getStartOffset() - 1);
	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	String prevText = prev != null ? prev.getText() : null;
	String text = element != null ? element.getText() : null;
	if (prevText == null || text == null || (prevText.startsWith("\\") && !text.startsWith("\\"))) {
		return;
	}
	LattePhpClassUsage classUsage = element.getParent() instanceof LattePhpClassUsage ? (LattePhpClassUsage) element.getParent() : null;
	String[] className = (classUsage != null ? classUsage.getClassName() : "").split("\\\\");

	if ((prevText.length() > 0 || className.length > 1) && element.getNode().getElementType() == LatteTypes.T_PHP_NAMESPACE_RESOLUTION) {
		Editor editor = context.getEditor();
		CaretModel caretModel = editor.getCaretModel();
		int offset = caretModel.getOffset();
		caretModel.moveToOffset(element.getTextOffset());
		editor.getSelectionModel().setSelection(element.getTextOffset(), element.getTextOffset() + 1);
		EditorModificationUtil.deleteSelectedText(editor);
		caretModel.moveToOffset(offset - 1);
		PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
	}
}
 

public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	if (element != null && element.getLanguage() == LatteLanguage.INSTANCE && element.getNode().getElementType() == LatteTypes.T_HTML_TAG_NATTR_NAME) {
		Editor editor = context.getEditor();
		CaretModel caretModel = editor.getCaretModel();
		int offset = caretModel.getOffset();
		if (LatteUtil.isStringAtCaret(editor, "=")) {
			caretModel.moveToOffset(offset + 2);
			return;
		}

		String attrName = LatteUtil.normalizeNAttrNameModifier(element.getText());
		LatteTagSettings macro = LatteConfiguration.getInstance(element.getProject()).getTag(attrName);
		if (macro != null && !macro.hasParameters()) {
			return;
		}

		editor.getDocument().insertString(offset, "=\"\"");
		caretModel.moveToOffset(offset + 2);

		PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
	}
}
 
源代码14 项目: intellij-haxe   文件: HaxeLookupElement.java

@Override
public void handleInsert(InsertionContext context) {
  HaxeBaseMemberModel memberModel = HaxeBaseMemberModel.fromPsi(myComponentName);
  boolean hasParams = false;
  boolean isMethod = false;
  if (memberModel != null) {
    if (memberModel instanceof HaxeMethodModel) {
      isMethod = true;
      HaxeMethodModel methodModel = (HaxeMethodModel)memberModel;
      hasParams = !methodModel.getParametersWithContext(this.context).isEmpty();
    }
  }

  if (isMethod) {
    final LookupElement[] allItems = context.getElements();
    final boolean overloadsMatter = allItems.length == 1 && getUserData(FORCE_SHOW_SIGNATURE_ATTR) == null;
    JavaCompletionUtil.insertParentheses(context, this, overloadsMatter, hasParams);
  }
}
 
源代码15 项目: litho   文件: MethodChainLookupElement.java

@Override
public void handleInsert(InsertionContext context) {
  context.setAddCompletionChar(false);
  handleInsertInternal(
      context.getEditor(),
      context.getDocument(),
      context.getStartOffset(),
      context.getTailOffset(),
      context.getProject());
  final Map<String, String> data = new HashMap<>();
  data.put(EventLogger.KEY_TYPE, "required_builder");
  data.put(EventLogger.KEY_TARGET, EventLogger.VALUE_COMPLETION_TARGET_CALL);
  LithoLoggerProvider.getEventLogger().log(EventLogger.EVENT_COMPLETION, data);
}
 
源代码16 项目: consulo-csharp   文件: LtGtInsertHandler.java

@Nullable
protected com.intellij.psi.PsiElement findNextToken(final InsertionContext context)
{
	final PsiFile file = context.getFile();
	PsiElement element = file.findElementAt(context.getTailOffset());
	if(element instanceof PsiWhiteSpace)
	{
		if(!myAllowParametersOnNextLine && element.getText().contains("\n"))
		{
			return null;
		}
		element = file.findElementAt(element.getTextRange().getEndOffset());
	}
	return element;
}
 

@Override
public void handleInsert(InsertionContext context, LookupElement item)
{
	if(myTailType.isApplicable(context))
	{
		myTailType.processTail(context.getEditor(), context.getTailOffset());
	}
}
 

@NotNull
public static String getCodeStyleIntent(InsertionContext insertionContext) {
  final CodeStyleSettings currentSettings =
      CodeStyleSettingsManager.getSettings(insertionContext.getProject());
  final CommonCodeStyleSettings.IndentOptions indentOptions =
      currentSettings.getIndentOptions(insertionContext.getFile().getFileType());
  return indentOptions.USE_TAB_CHARACTER ?
      "\t" :
      StringUtil.repeatSymbol(' ', indentOptions.INDENT_SIZE);
}
 

@Override
public void handleInsert(InsertionContext context, LookupElement lookupElement) {

    if(!(lookupElement instanceof ClassConstantLookupElementInterface) || !(lookupElement.getObject() instanceof PhpClass)) {
        return;
    }

    PhpReferenceInsertHandler.getInstance().handleInsert(context, lookupElement);
    PhpInsertHandlerUtil.insertStringAtCaret(context.getEditor(), "::class");
}
 

@Override
public void handleInsert(InsertionContext context, LookupElement item)
{
	if(context.getCompletionChar() == myEnterChar)
	{
		context.setAddCompletionChar(false);
		myTailType.processTail(context.getEditor(), context.getTailOffset());
	}
}
 

@Override
public void handleInsert(InsertionContext context) {

    if(this.insertHandler != null) {
        this.insertHandler.handleInsert(context, this);
        return;
    }

    super.handleInsert(context);
}
 

private static void insertTagNameHandler(@NotNull Project project, @NotNull InsertionContext context, @NotNull String tagName) {
    char completionChar = context.getCompletionChar();
    if (completionChar == ' ') {
        context.setAddCompletionChar(false);
    }

    Editor editor = context.getEditor();
    EditorModificationUtil.insertStringAtCaret(editor, " ></" + tagName + ">");
    editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() - 4 - tagName.length());

    AutoPopupController.getInstance(project).autoPopupMemberLookup(editor, null);
}
 

private static void insertExpression(@NotNull InsertionContext insertionContext, @NotNull LookupElement element) {
    PsiElement psiElement = element.getPsiElement();
    if (psiElement instanceof PsiLet) {
        PsiLet let = (PsiLet) psiElement;
        if (let.isFunction()) {
            insertionContext.setAddCompletionChar(false);
            Editor editor = insertionContext.getEditor();
            EditorModificationUtil.insertStringAtCaret(editor, "()");
            editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() - 1);
        }
    }
}
 

private static void insertTagAttributeHandler(@NotNull InsertionContext context) {
    context.setAddCompletionChar(false);

    Editor editor = context.getEditor();
    EditorModificationUtil.insertStringAtCaret(editor, "=()");
    editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() - 1);
}
 

public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {

        // check this:
        // {{ form_javasc|() }}
        // {{ form_javasc| }}
        if(PhpInsertHandlerUtil.isStringAtCaret(context.getEditor(), "(")) {
            return;
        }

        String addText = "()";
        PhpInsertHandlerUtil.insertStringAtCaret(context.getEditor(), addText);

        context.getEditor().getCaretModel().moveCaretRelatively(-1, 0, false, false, true);

    }
 

@Override
public void handleInsert(InsertionContext context) {

    if(insertHandler != null) {
        insertHandler.handleInsert(context, this);
        super.handleInsert(context);
        return;
    }

    if(assetFile.getAssetPosition().equals(AssetEnum.Position.Bundle)) {
        ResourceFileInsertHandler.getInstance().handleInsert(context, this);
    }

    super.handleInsert(context);
}
 

public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {

        // reuse core class + namespace insertHandler
        PhpReferenceInsertHandler.getInstance().handleInsert(context, lookupElement);

        // phpstorm8: remove leading backslash on PhpReferenceInsertHandler
        String backslash = context.getDocument().getText(new TextRange(context.getStartOffset(), context.getStartOffset() + 1));
        if("\\".equals(backslash)) {
            context.getDocument().deleteString(context.getStartOffset(), context.getStartOffset() + 1);
        }

    }
 

public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {

        PsiElement psiElement = lookupElement.getPsiElement();
        if (psiElement instanceof Method && needParameter((Method) psiElement)) {
            if (PhpInsertHandlerUtil.isStringAtCaret(context.getEditor(), "(")) {
                return;
            }

            String addText = "()";
            PhpInsertHandlerUtil.insertStringAtCaret(context.getEditor(), addText);

            context.getEditor().getCaretModel().moveCaretRelatively(-1, 0, false, false, true);
        }
    }
 

@Override
public void handleInsert(InsertionContext context) {
    if(twigExtension.getTwigExtensionType() == TwigExtensionParser.TwigExtensionType.SIMPLE_FUNCTION) {
        TwigExtensionInsertHandler.getInstance().handleInsert(context, this, twigExtension);
    }

    super.handleInsert(context);
}
 
源代码30 项目: bamboo-soy   文件: PostfixInsertHandler.java

public void handleInsert(InsertionContext context, LookupElement item) {
  Editor editor = context.getEditor();
  Project project = editor.getProject();

  if (project != null) {
    EditorModificationUtil.insertStringAtCaret(
        editor, closingTagBeforeCaret + closingTagAfterCaret);
    PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    EditorModificationUtil.moveCaretRelatively(editor, -closingTagAfterCaret.length());
  }
}