Java Code Examples for com.intellij.openapi.editor.EditorModificationUtil#insertStringAtCaret()

The following examples show how to use com.intellij.openapi.editor.EditorModificationUtil#insertStringAtCaret() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonInsertFieldHandler.java    From intellij-swagger with MIT License 6 votes vote down vote up
@Override
public void handleInsert(
    final InsertionContext insertionContext, final LookupElement lookupElement) {
  handleStartingQuote(insertionContext, lookupElement);
  handleEndingQuote(insertionContext);

  if (!StringUtils.nextCharAfterSpacesAndQuotesIsColon(
      getStringAfterAutoCompletedValue(insertionContext))) {
    final String suffixWithCaret =
        field.getJsonPlaceholderSuffix(getIndentation(insertionContext, lookupElement));
    final String suffixWithoutCaret = suffixWithCaret.replace(CARET, "");
    EditorModificationUtil.insertStringAtCaret(
        insertionContext.getEditor(),
        withOptionalComma(suffixWithoutCaret, insertionContext),
        false,
        true,
        getCaretIndex(suffixWithCaret));
  }
}
 
Example 2
Source File: JsxNameCompletionProvider.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
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);
}
 
Example 3
Source File: FunctionDeclarationBracesBodyHandler.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
@Override
public Result charTyped(char c, Project project, @NotNull Editor editor, @NotNull PsiFile editedFile) {
    if ((editedFile.getLanguage() instanceof XQueryLanguage) && (c == '{' || c == '}')) {
        PsiDocumentManager.getInstance(project).commitAllDocuments();
        PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
        if (file == null) return Result.CONTINUE;
        FileViewProvider provider = file.getViewProvider();
        final int offset = editor.getCaretModel().getOffset();
        PsiElement element = provider.findElementAt(offset - 1, XQueryLanguage.class);
        if (element == null) return Result.CONTINUE;
        if (!(element.getLanguage() instanceof XQueryLanguage)) return Result.CONTINUE;
        ASTNode prevLeaf = element.getNode();
        if (prevLeaf == null) return Result.CONTINUE;
        final String prevLeafText = prevLeaf.getText();

        if (isInFunctionBodyAfterInsertionOfMatchingRightBrace(element, prevLeafText)) {
            if (c == '{') {
                editor.getDocument().insertString(offset + 1, ";");
            } else {
                EditorModificationUtil.insertStringAtCaret(editor, ";", false);
            }
        }

    }

    return Result.CONTINUE;
}
 
Example 4
Source File: JsxAttributeCompletionProvider.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
private static void insertTagAttributeHandler(@NotNull InsertionContext context) {
    context.setAddCompletionChar(false);

    Editor editor = context.getEditor();
    EditorModificationUtil.insertStringAtCaret(editor, "=()");
    editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() - 1);
}
 
Example 5
Source File: PostfixInsertHandler.java    From bamboo-soy with Apache License 2.0 5 votes vote down vote up
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());
  }
}
 
Example 6
Source File: FilterInsertHandler.java    From intellij-latte with MIT License 5 votes vote down vote up
public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	if (element != null && element.getLanguage() == LatteLanguage.INSTANCE) {
		PsiElement parent = element.getParent();

		LatteFilterSettings filter = null;
		if (parent instanceof LatteMacroModifier) {
			String modifierName = ((LatteMacroModifier) parent).getModifierName();
			filter = LatteConfiguration.getInstance(element.getProject()).getFilter(modifierName);
		}

		Editor editor = context.getEditor();
		if (filter != null && filter.getModifierInsert() != null && filter.getModifierInsert().length() > 0) {
			CaretModel caretModel = editor.getCaretModel();
			String text = editor.getDocument().getText();

			int offset = caretModel.getOffset();

			int lastBraceOffset = text.indexOf(":", offset);
			int endOfLineOffset = text.indexOf("\n", offset);

			if (endOfLineOffset == -1) {
				endOfLineOffset = text.length();
			}
			if (lastBraceOffset == -1 || lastBraceOffset > endOfLineOffset) {
				EditorModificationUtil.insertStringAtCaret(editor, filter.getModifierInsert());
				caretModel.moveToOffset(offset + 1);
			}
		}
		PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
	}
}
 
Example 7
Source File: TemplateExpressionLookupElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean handleCompletionChar(InsertionContext context) {
  if (context.getCompletionChar() == '.') {
    EditorModificationUtil.insertStringAtCaret(context.getEditor(), ".");
    AutoPopupController.getInstance(context.getProject()).autoPopupMemberLookup(context.getEditor(), null);
    return false;
  }
  return true;
}
 
Example 8
Source File: YamlInsertFieldHandler.java    From intellij-swagger with MIT License 5 votes vote down vote up
@Override
public void handleInsert(final InsertionContext context, final LookupElement item) {
  if (!StringUtils.nextCharAfterSpacesAndQuotesIsColon(
      getStringAfterAutoCompletedValue(context))) {
    final String suffixWithCaret = field.getYamlPlaceholderSuffix(getIndentation(context, item));
    final String suffixWithoutCaret = suffixWithCaret.replace(CARET, "");
    EditorModificationUtil.insertStringAtCaret(
        context.getEditor(), suffixWithoutCaret, false, true, getCaretIndex(suffixWithCaret));
  }
}
 
Example 9
Source File: JSGraphQLEndpointImportInsertHandler.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
public void handleInsert(InsertionContext context, LookupElement item) {
  final Editor editor = context.getEditor();
  final Project project = editor.getProject();
  if (project != null) {
    EditorModificationUtil.insertStringAtCaret(editor, " \"\"");
    PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() - 1);
    if (myTriggerAutoPopup) {
      AutoPopupController.getInstance(project).autoPopupMemberLookup(editor, null);
    }
  }
}
 
Example 10
Source File: JustOneSpace.java    From emacsIDEAs with Apache License 2.0 5 votes vote down vote up
private void makeOneSpaceBetween(final int begin, final int end) {
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            _editor.getSelectionModel().setSelection(begin, end);
            EditorModificationUtil.deleteSelectedText(_editor);
            EditorModificationUtil.insertStringAtCaret(_editor, " ");
        }
    };
    AppUtil.runWriteAction(runnable, _editor);
}
 
Example 11
Source File: EnterInStringLiteralHandler.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@Override
public Result preprocessEnter(@NotNull PsiFile file, @NotNull Editor editor, @NotNull Ref<Integer> caretOffset, @NotNull Ref<Integer> caretAdvance, @NotNull DataContext dataContext, @Nullable EditorActionHandler originalHandler) {
    if (!(file instanceof BashFile)) {
        return Result.Continue;
    }


    int offset = caretOffset.get();

    // don't wrap at EOL or EOF
    CharSequence content = editor.getDocument().getCharsSequence();
    if (offset >= content.length() || content.charAt(offset) == '\n') {
        return Result.Continue;
    }

    if (PsiDocumentManager.getInstance(file.getProject()).isUncommited(editor.getDocument())) {
        // return early if PSI is not up-to-date to avoid blocking the editor
        // this might result in line-continuations not being inserted while editing
        return Result.Continue;
    }

    PsiElement psi = file.findElementAt(offset);
    if (psi == null || psi.getNode() == null) {
        return Result.Continue;
    }

    boolean isUserTyping = !Boolean.TRUE.equals(DataManager.getInstance().loadFromDataContext(dataContext, AutoHardWrapHandler.AUTO_WRAP_LINE_IN_PROGRESS_KEY));
    if (isUserTyping && !isInString(psi)) {
        return Result.Continue;
    }

    if (offset >= psi.getTextOffset() && psi.getNode().getElementType() != BashTokenTypes.LINE_FEED) {
        EditorModificationUtil.insertStringAtCaret(editor, "\\\n");
        return Result.Stop;
    }

    return Result.Continue;
}
 
Example 12
Source File: XQueryXmlSlashTypedHandler.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
private void closeEmptyTag(@NotNull Editor editor) {
    EditorModificationUtil.insertStringAtCaret(editor, ">", false);
}
 
Example 13
Source File: HaxeQualifiedNameProvider.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
@Override
public void insertQualifiedName(String fqn, PsiElement element, Editor editor, Project project) {
  EditorModificationUtil.insertStringAtCaret(editor, fqn);
}
 
Example 14
Source File: XQueryXmlSlashTypedHandler.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
private void finishClosingTag(@NotNull Editor editor, XQueryXmlTagName tagName) {
    String prefix = tagName.getXmlTagNamespace() != null ? tagName.getXmlTagNamespace().getName() + ":" : "";
    String name = prefix + tagName.getXmlTagLocalName().getText();
    EditorModificationUtil.insertStringAtCaret(editor, name + ">", false);
}
 
Example 15
Source File: MacroInsertHandler.java    From intellij-latte with MIT License 4 votes vote down vote up
public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	if (element != null && element.getLanguage() == LatteLanguage.INSTANCE) {
		PsiElement parent = element.getParent();

		String spacesBefore = "";
		boolean resolvePairMacro = false;
		boolean lastError = parent.getLastChild().getNode().getElementType() == TokenType.ERROR_ELEMENT;
		String macroName = null;
		LatteTagSettings macro = null;
		if (lastError && element.getNode().getElementType() == LatteTypes.T_MACRO_NAME) {
			macroName = element.getText();
			macro = LatteConfiguration.getInstance(element.getProject()).getTag(macroName);

		} else if (parent instanceof LatteMacroTag) {
			macroName = ((LatteMacroTag) parent).getMacroName();
			macro = LatteConfiguration.getInstance(element.getProject()).getTag(macroName);
		}

		boolean isCloseTag = parent instanceof LatteMacroCloseTag;
		if (!isCloseTag && macro != null && macro.getType() == LatteTagSettings.Type.PAIR) {
			resolvePairMacro = true;
		}

		if (macroName != null) {
			if (resolvePairMacro && macro.isMultiLine()) {
				spacesBefore += LatteUtil.getSpacesBeforeCaret(context.getEditor());
			}

			Editor editor = context.getEditor();
			CaretModel caretModel = editor.getCaretModel();
			String text = editor.getDocument().getText();

			int spaceInserted = 0;
			int offset = caretModel.getOffset();

			if (macro != null && !isCloseTag && macro.hasParameters() && !LatteUtil.isStringAtCaret(editor, " ")) {
				EditorModificationUtil.insertStringAtCaret(editor, " ");
				spaceInserted = 1;
			}

			int lastBraceOffset = text.indexOf("}", offset);
			int endOfLineOffset = text.indexOf("\n", offset);

			if (endOfLineOffset == -1) {
				endOfLineOffset = text.length();
			}
			if (lastBraceOffset == -1 || lastBraceOffset > endOfLineOffset) {
				caretModel.moveToOffset(endOfLineOffset + spaceInserted);
				EditorModificationUtil.insertStringAtCaret(editor, "}");
				lastBraceOffset = endOfLineOffset;
				endOfLineOffset++;
			}

			if (resolvePairMacro) {
				String endTag = "";
				if (macro.isMultiLine()) {
					endTag += "\n\n" + spacesBefore;
				}
				endTag += "{/" + macroName + "}";

				int endTagOffset = text.indexOf(endTag, offset);
				if (endTagOffset == -1 || endTagOffset > endOfLineOffset) {
					caretModel.moveToOffset(lastBraceOffset + spaceInserted + 1);
					EditorModificationUtil.insertStringAtCaret(editor, endTag);
				}
			}

			caretModel.moveToOffset(offset + 1);
			PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
		}
	}
}
 
Example 16
Source File: BaseIndentEnterHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public Result preprocessEnter(
        @Nonnull final PsiFile file,
        @Nonnull final Editor editor,
        @Nonnull final Ref<Integer> caretOffset,
        @Nonnull final Ref<Integer> caretAdvance,
        @Nonnull final DataContext dataContext,
        final EditorActionHandler originalHandler)
{
  Result res = shouldSkipWithResult(file, editor, dataContext);
  if (res != null) {
    return res;
  }

  final Document document = editor.getDocument();
  int caret = editor.getCaretModel().getOffset();
  final int lineNumber = document.getLineNumber(caret);

  final int lineStartOffset = document.getLineStartOffset(lineNumber);
  final int previousLineStartOffset = lineNumber > 0 ? document.getLineStartOffset(lineNumber - 1) : lineStartOffset;
  final EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter();
  final HighlighterIterator iterator = highlighter.createIterator(caret - 1);
  final IElementType type = getNonWhitespaceElementType(iterator, lineStartOffset, previousLineStartOffset);

  final CharSequence editorCharSequence = document.getCharsSequence();
  final CharSequence lineIndent =
          editorCharSequence.subSequence(lineStartOffset, EditorActionUtil.findFirstNonSpaceOffsetOnTheLine(document, lineNumber));

  // Enter in line comment
  if (type == myLineCommentType) {
    final String restString = editorCharSequence.subSequence(caret, document.getLineEndOffset(lineNumber)).toString();
    if (!StringUtil.isEmptyOrSpaces(restString)) {
      final String linePrefix = lineIndent + myLineCommentPrefix;
      EditorModificationUtil.insertStringAtCaret(editor, "\n" + linePrefix);
      editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(lineNumber + 1, linePrefix.length()));
      return Result.Stop;
    }
    else if (iterator.getStart() < lineStartOffset) {
      EditorModificationUtil.insertStringAtCaret(editor, "\n" + lineIndent);
      return Result.Stop;
    }
  }

  if (!myWorksWithFormatter && LanguageFormatting.INSTANCE.forLanguage(myLanguage) != null) {
    return Result.Continue;
  }
  else {
    if (myIndentTokens.contains(type)) {
      final String newIndent = getNewIndent(file, document, lineIndent);
      EditorModificationUtil.insertStringAtCaret(editor, "\n" + newIndent);
      return Result.Stop;
    }

    EditorModificationUtil.insertStringAtCaret(editor, "\n" + lineIndent);
    editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(lineNumber + 1, calcLogicalLength(editor, lineIndent)));
    return Result.Stop;
  }
}
 
Example 17
Source File: EnterHandler.java    From bamboo-soy with Apache License 2.0 4 votes vote down vote up
private static void insertText(PsiFile file, Editor editor, String text, int numChar) {
  EditorModificationUtil.insertStringAtCaret(editor, text, false, numChar);
  PsiDocumentManager.getInstance(file.getProject()).commitDocument(editor.getDocument());
}
 
Example 18
Source File: FluidTypedHandler.java    From idea-php-typo3-plugin with MIT License 4 votes vote down vote up
private static void typeInStringAndMoveCaret(Editor editor, String str, int caretShift) {
    EditorModificationUtil.insertStringAtCaret(editor, str, true, caretShift);
}
 
Example 19
Source File: YamlTagCompletionProvider.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
@Override
public void handleInsert(InsertionContext context, @NotNull LookupElement lookupElement) {
    EditorModificationUtil.insertStringAtCaret(context.getEditor(), " ", false, 1);
}
 
Example 20
Source File: PsiDocumentUtils.java    From markdown-image-kit with MIT License 2 votes vote down vote up
/**
 * 将字符串插入到光标位置
 *
 * @param marks  the marks
 * @param editor the editor
 */
public static void insertDocument(String marks, Editor editor){
    Runnable r = () -> EditorModificationUtil.insertStringAtCaret(editor, marks);
    WriteCommandAction.runWriteCommandAction(editor.getProject(), r);
}