List of usage examples for com.intellij.openapi.editor EditorModificationUtil insertStringAtCaret
public static void insertStringAtCaret(Editor editor, @NotNull String s)
From source file:com.goide.completion.GoKeywordCompletionProvider.java
License:Apache License
@Nullable public static InsertHandler<LookupElement> createTemplateBasedInsertHandler(@Nonnull String templateId) { return (context, item) -> { Template template = TemplateSettings.getInstance().getTemplateById(templateId); Editor editor = context.getEditor(); if (template != null) { editor.getDocument().deleteString(context.getStartOffset(), context.getTailOffset()); TemplateManager.getInstance(context.getProject()).startTemplate(editor, template); } else {/*w w w . j a v a 2 s . c om*/ int currentOffset = editor.getCaretModel().getOffset(); CharSequence documentText = editor.getDocument().getImmutableCharSequence(); if (documentText.length() <= currentOffset || documentText.charAt(currentOffset) != ' ') { EditorModificationUtil.insertStringAtCaret(editor, " "); } else { EditorModificationUtil.moveCaretRelatively(editor, 1); } } }; }
From source file:com.google.bamboo.soy.insight.completion.PostfixInsertHandler.java
License:Apache License
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()); }//ww w . jav a2 s . co m }
From source file:com.intellij.codeInsight.completion.LambdaCompletionProvider.java
License:Apache License
@Override protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) { if (!PsiUtil.isLanguageLevel8OrHigher(parameters.getOriginalFile())) return;/*from w ww. j a va2 s . co m*/ final ExpectedTypeInfo[] expectedTypes = JavaSmartCompletionContributor.getExpectedTypes(parameters); for (ExpectedTypeInfo expectedType : expectedTypes) { final PsiType defaultType = expectedType.getDefaultType(); if (LambdaHighlightingUtil.checkInterfaceFunctional(defaultType) == null) { final PsiMethod method = LambdaUtil.getFunctionalInterfaceMethod(defaultType); if (method != null) { final PsiParameter[] params = method.getParameterList().getParameters(); final String paramsString = "(" + StringUtil.join(params, new Function<PsiParameter, String>() { @Override public String fun(PsiParameter parameter) { return parameter.getName(); } }, ",") + ")"; final LookupElementBuilder builder = LookupElementBuilder.create(paramsString) .withPresentableText(paramsString + " -> {}") .withInsertHandler(new InsertHandler<LookupElement>() { @Override public void handleInsert(InsertionContext context, LookupElement item) { final Editor editor = context.getEditor(); EditorModificationUtil.insertStringAtCaret(editor, " -> "); } }); result.addElement(builder.withAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE)); } } } }
From source file:com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.java
License:Apache License
public static void setupEditor(PsiMethod method, final Editor newEditor) { PsiCodeBlock body = method.getBody(); if (body != null) { PsiElement l = PsiTreeUtil.skipSiblingsForward(body.getLBrace(), PsiWhiteSpace.class); PsiElement r = PsiTreeUtil.skipSiblingsBackward(body.getRBrace(), PsiWhiteSpace.class); if (l != null && r != null) { int start = l.getTextRange().getStartOffset(); int end = r.getTextRange().getEndOffset(); newEditor.getCaretModel().moveToOffset(Math.max(start, end)); if (end < start) { newEditor.getCaretModel().moveToOffset(end + 1); CodeStyleManager styleManager = CodeStyleManager.getInstance(method.getProject()); PsiFile containingFile = method.getContainingFile(); final String lineIndent = styleManager.getLineIndent(containingFile, Math.min(start, end)); PsiDocumentManager manager = PsiDocumentManager.getInstance(method.getProject()); manager.doPostponedOperationsAndUnblockDocument(manager.getDocument(containingFile)); EditorModificationUtil.insertStringAtCaret(newEditor, lineIndent); EditorModificationUtil.insertStringAtCaret(newEditor, "\n", false, false); } else { //correct position caret for groovy and java methods final PsiGenerationInfo<PsiMethod> info = OverrideImplementUtil.createGenerationInfo(method); info.positionCaret(newEditor, true); }//from w w w. j a v a2 s . c o m newEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } } }
From source file:com.intellij.codeInsight.editorActions.EndHandler.java
License:Apache License
@Override public void execute(final Editor editor, DataContext dataContext) { CodeInsightSettings settings = CodeInsightSettings.getInstance(); if (!settings.SMART_END_ACTION) { if (myOriginalHandler != null) { myOriginalHandler.execute(editor, dataContext); }// w w w. ja v a 2s.c om return; } final Project project = CommonDataKeys.PROJECT .getData(DataManager.getInstance().getDataContext(editor.getComponent())); if (project == null) { if (myOriginalHandler != null) { myOriginalHandler.execute(editor, dataContext); } return; } final Document document = editor.getDocument(); final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document); if (file == null) { if (myOriginalHandler != null) { myOriginalHandler.execute(editor, dataContext); } return; } final EditorNavigationDelegate[] extensions = EditorNavigationDelegate.EP_NAME.getExtensions(); if (extensions != null) { for (EditorNavigationDelegate delegate : extensions) { if (delegate.navigateToLineEnd(editor, dataContext) == EditorNavigationDelegate.Result.STOP) { return; } } } final CaretModel caretModel = editor.getCaretModel(); final int caretOffset = caretModel.getOffset(); CharSequence chars = editor.getDocument().getCharsSequence(); int length = editor.getDocument().getTextLength(); if (caretOffset < length) { final int offset1 = CharArrayUtil.shiftBackward(chars, caretOffset - 1, " \t"); if (offset1 < 0 || chars.charAt(offset1) == '\n' || chars.charAt(offset1) == '\r') { int offset2 = CharArrayUtil.shiftForward(chars, offset1 + 1, " \t"); boolean isEmptyLine = offset2 >= length || chars.charAt(offset2) == '\n' || chars.charAt(offset2) == '\r'; if (isEmptyLine) { // There is a possible case that indent string is not calculated for particular document (that is true at least for plain text // documents). Hence, we check that and don't finish processing in case we have such a situation. AtomicBoolean is used // here just as a boolean value holder due to requirement to declare variable used from inner class as final. final AtomicBoolean stopProcessing = new AtomicBoolean(true); PsiDocumentManager.getInstance(project).commitAllDocuments(); ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { CodeStyleManager styleManager = CodeStyleManager.getInstance(project); final String lineIndent = styleManager.getLineIndent(file, caretOffset); if (lineIndent != null) { int col = calcColumnNumber(lineIndent, editor.getSettings().getTabSize(project)); int line = caretModel.getVisualPosition().line; caretModel.moveToVisualPosition(new VisualPosition(line, col)); if (caretModel.getLogicalPosition().column != col) { if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) { return; } editor.getSelectionModel().removeSelection(); EditorModificationUtil.insertStringAtCaret(editor, lineIndent); } } else { stopProcessing.set(false); } editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().removeSelection(); } private int calcColumnNumber(final String lineIndent, final int tabSize) { int result = 0; for (char c : lineIndent.toCharArray()) { if (c == ' ') result++; if (c == '\t') result += tabSize; } return result; } }); if (stopProcessing.get()) { return; } } } } if (myOriginalHandler != null) { myOriginalHandler.execute(editor, dataContext); } }
From source file:com.intellij.codeInsight.editorActions.enter.BaseIndentEnterHandler.java
License:Apache License
@Override public Result preprocessEnter(@NotNull final PsiFile file, @NotNull final Editor editor, @NotNull final Ref<Integer> caretOffset, @NotNull final Ref<Integer> caretAdvance, @NotNull final DataContext dataContext, final EditorActionHandler originalHandler) { final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) { return Result.Continue; }//from ww w . j a v a2s . c o m if (!file.getViewProvider().getLanguages().contains(myLanguage)) { return Result.Continue; } if (editor.isViewer()) { return Result.Continue; } final Document document = editor.getDocument(); if (!document.isWritable()) { return Result.Continue; } PsiDocumentManager.getInstance(project).commitDocument(document); int caret = editor.getCaretModel().getOffset(); if (caret <= 0) { return Result.Continue; } 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 (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; } }
From source file:com.intellij.codeInsight.editorActions.smartEnter.CommentBreakerEnterProcessor.java
License:Apache License
@Override public boolean doEnter(Editor editor, PsiElement psiElement, boolean isModified) { if (isModified) return false; final PsiElement atCaret = psiElement.getContainingFile().findElementAt(editor.getCaretModel().getOffset()); final PsiComment comment = PsiTreeUtil.getParentOfType(atCaret, PsiComment.class, false); if (comment != null) { plainEnter(editor);/*from w w w. j ava 2 s . c o m*/ if (comment.getTokenType() == JavaTokenType.END_OF_LINE_COMMENT) { EditorModificationUtil.insertStringAtCaret(editor, "// "); } return true; } return false; }
From source file:com.intellij.codeInsight.editorActions.XmlSlashTypedHandler.java
License:Apache License
public Result charTyped(final char c, final Project project, final Editor editor, final PsiFile editedFile) { if ((editedFile.getLanguage() instanceof XMLLanguage || editedFile.getViewProvider().getBaseLanguage() instanceof XMLLanguage) && c == '/') { PsiDocumentManager.getInstance(project).commitAllDocuments(); PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); FileViewProvider provider = file.getViewProvider(); final int offset = editor.getCaretModel().getOffset(); PsiElement element = provider.findElementAt(offset - 1, XMLLanguage.class); if (element == null) return Result.CONTINUE; if (!(element.getLanguage() instanceof XMLLanguage)) return Result.CONTINUE; ASTNode prevLeaf = element.getNode(); final String prevLeafText = prevLeaf != null ? prevLeaf.getText() : null; if (prevLeaf != null && !"/".equals(prevLeafText)) { if (!"/".equals(prevLeafText.trim())) return Result.CONTINUE; }/* w w w. j ava 2s .c o m*/ while ((prevLeaf = TreeUtil.prevLeaf(prevLeaf)) != null && prevLeaf.getElementType() == XmlTokenType.XML_WHITE_SPACE) ; if (prevLeaf instanceof OuterLanguageElement) { element = file.getViewProvider().findElementAt(offset - 1, file.getLanguage()); prevLeaf = element.getNode(); while ((prevLeaf = TreeUtil.prevLeaf(prevLeaf)) != null && prevLeaf.getElementType() == XmlTokenType.XML_WHITE_SPACE) ; } if (prevLeaf == null) return Result.CONTINUE; XmlTag tag = PsiTreeUtil.getParentOfType(prevLeaf.getPsi(), XmlTag.class); if (tag == null) { // prevLeaf maybe in one tree and element in another PsiElement element2 = provider.findElementAt(prevLeaf.getStartOffset(), XMLLanguage.class); tag = PsiTreeUtil.getParentOfType(element2, XmlTag.class); if (tag == null) return Result.CONTINUE; } final XmlToken startToken = XmlUtil.getTokenOfType(tag, XmlTokenType.XML_START_TAG_START); if (startToken == null || !startToken.getText().equals("<")) return Result.CONTINUE; if (XmlUtil.getTokenOfType(tag, XmlTokenType.XML_TAG_END) != null) return Result.CONTINUE; if (XmlUtil.getTokenOfType(tag, XmlTokenType.XML_EMPTY_ELEMENT_END) != null) return Result.CONTINUE; if (PsiTreeUtil.getParentOfType(element, XmlAttributeValue.class) != null) return Result.CONTINUE; EditorModificationUtil.insertStringAtCaret(editor, ">"); return Result.STOP; } return Result.CONTINUE; }
From source file:com.intellij.codeInsight.template.impl.TemplateExpressionLookupElement.java
License:Apache License
@Override public void handleInsert(final InsertionContext context) { LookupElement item = getDelegate();//from w ww .j ava2 s .c o m Project project = context.getProject(); Editor editor = context.getEditor(); PsiDocumentManager.getInstance(project).commitAllDocuments(); TextRange range = myState.getCurrentVariableRange(); final TemplateLookupSelectionHandler handler = item instanceof LookupItem ? ((LookupItem<?>) item).getAttribute(TemplateLookupSelectionHandler.KEY_IN_LOOKUP_ITEM) : null; if (handler != null && range != null) { handler.itemSelected(item, context.getFile(), context.getDocument(), range.getStartOffset(), range.getEndOffset()); } else { super.handleInsert(context); } if (context.getCompletionChar() == '.') { EditorModificationUtil.insertStringAtCaret(editor, "."); AutoPopupController.getInstance(project).autoPopupMemberLookup(editor, null); return; } if (!myState.isFinished()) { myState.calcResults(true); } myState.nextTab(); }
From source file:com.intellij.codeInsight.template.impl.TemplateState.java
License:Apache License
private void insertSingleItem(List<TemplateExpressionLookupElement> lookupItems) { TemplateExpressionLookupElement first = lookupItems.get(0); EditorModificationUtil.insertStringAtCaret(myEditor, first.getLookupString()); first.handleTemplateInsert(lookupItems, Lookup.AUTO_INSERT_SELECT_CHAR); }