Java 类com.intellij.openapi.editor.EditorModificationUtil 实例源码

项目:intellij-ce-playground    文件:SmartPsiElementPointersTest.java   
public void testUpdateAfterInsertingIdenticalText() {
  PsiJavaFile file = (PsiJavaFile)configureByText(StdFileTypes.JAVA, "class Foo {\n" +
                                                                     "    void m() {\n" +
                                                                     "    }\n" +
                                                                     "<caret>}\n");
  PsiMethod method = file.getClasses()[0].getMethods()[0];
  TextRange originalRange = method.getTextRange();
  SmartPsiElementPointer pointer = createPointer(method);

  EditorModificationUtil.insertStringAtCaret(myEditor, "    void m() {\n" +
                                                       "    }\n");
  PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.getDocument());
  PsiElement element = pointer.getElement();
  assertNotNull(element);
  TextRange newRange = element.getTextRange();
  assertEquals(originalRange, newRange);
}
项目:intellij-ce-playground    文件:CutAction.java   
@Override
public void executeWriteAction(final Editor editor, DataContext dataContext) {
  if(!editor.getSelectionModel().hasSelection(true)) {
    if (Registry.is(CopyAction.SKIP_COPY_AND_CUT_FOR_EMPTY_SELECTION_KEY)) {
      return;
    }
    editor.getCaretModel().runForEachCaret(new CaretAction() {
      @Override
      public void perform(Caret caret) {
        editor.getSelectionModel().selectLineAtCaret();
      }
    });
  }
  editor.getSelectionModel().copySelectionToClipboard();
  EditorModificationUtil.deleteSelectedTextForAllCarets(editor);
}
项目:intellij-ce-playground    文件:DeleteToWordEndAction.java   
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
  CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
  CopyPasteManager.getInstance().stopKillRings();

  boolean camelMode = editor.getSettings().isCamelWords();
  if (myNegateCamelMode) {
    camelMode = !camelMode;
  }

  if (editor.getSelectionModel().hasSelection()) {
    EditorModificationUtil.deleteSelectedText(editor);
    return;
  }

  deleteToWordEnd(editor, camelMode);
}
项目:intellij-ce-playground    文件:AddSpaceInsertHandler.java   
public void handleInsert(InsertionContext context, LookupElement item) {
  Editor editor = context.getEditor();
  if (context.getCompletionChar() == ' ') return;
  Project project = editor.getProject();
  if (project != null) {
    if (!isCharAtSpace(editor)) {
      EditorModificationUtil.insertStringAtCaret(editor, " ");
      PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    }
    else {
      editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() + 1);
    }
    if (myTriggerAutoPopup) {
      AutoPopupController.getInstance(project).autoPopupMemberLookup(editor, null);
    }
  }
}
项目:intellij-ce-playground    文件:BackspaceHandler.java   
public static void deleteToTargetPosition(@NotNull Editor editor, @NotNull LogicalPosition pos) {
  LogicalPosition logicalPosition = editor.getCaretModel().getLogicalPosition();
  if (logicalPosition.line != pos.line) {
    LOGGER.error("Unexpected caret position: " + logicalPosition + ", target indent position: " + pos);
    return;
  }
  if (pos.column < logicalPosition.column) {
    int targetOffset = editor.logicalPositionToOffset(pos);
    int offset = editor.getCaretModel().getOffset();
    editor.getSelectionModel().setSelection(targetOffset, offset);
    EditorModificationUtil.deleteSelectedText(editor);
  }
  else if (pos.column > logicalPosition.column) {
    EditorModificationUtil.insertStringAtCaret(editor, StringUtil.repeatSymbol(' ', pos.column - logicalPosition.column));
  }
}
项目:intellij-ce-playground    文件:PasteReferenceProvider.java   
private static void insert(final String fqn, final PsiElement element, final Editor editor, final QualifiedNameProvider provider) {
  final Project project = editor.getProject();
  if (project == null) return;

  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  documentManager.commitDocument(editor.getDocument());

  final PsiFile file = documentManager.getPsiFile(editor.getDocument());
  if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

  CommandProcessor.getInstance().executeCommand(project, new Runnable() {
    @Override
    public void run() {
      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          Document document = editor.getDocument();
          documentManager.doPostponedOperationsAndUnblockDocument(document);
          documentManager.commitDocument(document);
          EditorModificationUtil.deleteSelectedText(editor);
          provider.insertQualifiedName(fqn, element, editor, project);
        }
      });
    }
  }, IdeBundle.message("command.pasting.reference"), null);
}
项目:epigraph    文件:AddRetroAction.java   
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
  if (element.getNode().getElementType() == TokenType.WHITE_SPACE) element = PsiTreeUtil.prevVisibleLeaf(element);

  SchemaValueTypeRef valueTypeRef = PsiTreeUtil.getParentOfType(element, SchemaValueTypeRef.class);
  if (valueTypeRef != null) {
    int endOffset = valueTypeRef.getNode().getTextRange().getEndOffset();
    editor.getCaretModel().moveToOffset(endOffset);
    EditorModificationUtil.insertStringAtCaret(editor, " default ");

    ApplicationManager.getApplication().invokeLater(() -> {
      AnActionEvent event = AnActionEvent.createFromDataContext("AddDefaultAction",
          new Presentation(), ((EditorEx) editor).getDataContext());

      new CodeCompletionAction().actionPerformed(event);
    });
  }
}
项目:tools-idea    文件:PasteFromX11Action.java   
@Override
public void executeWriteAction(Editor editor, DataContext dataContext) {
  final Clipboard clip = editor.getComponent().getToolkit().getSystemSelection();
  if (clip != null) {
    Transferable res = null;
    try {
      res = clip.getContents(null);
    }
    catch (Exception e) {
      if (!ApplicationManager.getApplication().isHeadlessEnvironment()) {
        LOG.info(e);
        Messages.showErrorDialog(editor.getProject(), "Cannot paste from X11 clipboard: " + e.getLocalizedMessage(), "Cannot Paste");
        return;
      }
    }
    editor.putUserData(EditorEx.LAST_PASTED_REGION, EditorModificationUtil.pasteFromTransferrable(res, editor));
  }
}
项目:tools-idea    文件:PasteReferenceProvider.java   
private static void insert(final String fqn, final PsiElement element, final Editor editor, final QualifiedNameProvider provider) {
  final Project project = editor.getProject();
  if (project == null) return;

  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  documentManager.commitDocument(editor.getDocument());

  final PsiFile file = documentManager.getPsiFile(editor.getDocument());
  if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

  CommandProcessor.getInstance().executeCommand(project, new Runnable() {
    @Override
    public void run() {
      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          Document document = editor.getDocument();
          documentManager.doPostponedOperationsAndUnblockDocument(document);
          documentManager.commitDocument(document);
          EditorModificationUtil.deleteSelectedText(editor);
          provider.insertQualifiedName(fqn, element, editor, project);
        }
      });
    }
  }, IdeBundle.message("command.pasting.reference"), null);
}
项目:intellij-xquery    文件:XQueryXmlGtTypedHandler.java   
@Override
public Result beforeCharTyped(final char c, final Project project, final Editor editor, final PsiFile editedFile, final FileType fileType) {
    if ((editedFile.getLanguage() instanceof XQueryLanguage) && c == '>') {
        PsiDocumentManager.getInstance(project).commitAllDocuments();
        PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
        if (file == null) return Result.CONTINUE;
        final int offset = editor.getCaretModel().getOffset();
        FileViewProvider provider = file.getViewProvider();
        PsiElement element = provider.findElementAt(offset, XQueryLanguage.class);

        if (element != null && element.getNode() != null && (
                element.getNode().getElementType() == XQueryTypes.XMLTAGEND ||
                        element.getNode().getElementType() == XQueryTypes.XMLEMPTYELEMENTEND)) {
            EditorModificationUtil.moveCaretRelatively(editor, 1);
            editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
            return Result.STOP;
        }
    }
    return Result.CONTINUE;
}
项目:emacsIDEAs    文件:CutAfterJumpCommand.java   
@Override
public void afterJump() {
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (inSameEditor()) {
                selectJumpArea();

                _se.getSelectionModel().copySelectionToClipboard();
                EditorModificationUtil.deleteSelectedText(_se);
                _se.getSelectionModel().removeSelection();
            }
        }
    };

    AppUtil.runWriteAction(runnable, _se);
}
项目:consulo    文件:CutAction.java   
@RequiredWriteAction
@Override
public void executeWriteAction(final Editor editor, DataContext dataContext) {
  if(!editor.getSelectionModel().hasSelection(true)) {
    if (Registry.is(CopyAction.SKIP_COPY_AND_CUT_FOR_EMPTY_SELECTION_KEY)) {
      return;
    }
    editor.getCaretModel().runForEachCaret(new CaretAction() {
      @Override
      public void perform(Caret caret) {
        editor.getSelectionModel().selectLineAtCaret();
      }
    });
  }
  editor.getSelectionModel().copySelectionToClipboard();
  EditorModificationUtil.deleteSelectedTextForAllCarets(editor);
}
项目:consulo    文件:AddSpaceInsertHandler.java   
public void handleInsert(InsertionContext context, LookupElement item) {
  Editor editor = context.getEditor();
  char completionChar = context.getCompletionChar();
  if (completionChar == ' ' || StringUtil.containsChar(myIgnoreOnChars, completionChar)) return;
  Project project = editor.getProject();
  if (project != null) {
    if (!isCharAtSpace(editor)) {
      EditorModificationUtil.insertStringAtCaret(editor, " ");
      PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    }
    else if (shouldOverwriteExistingSpace(editor)) {
      editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() + 1);
    }
    if (myTriggerAutoPopup) {
      AutoPopupController.getInstance(project).autoPopupMemberLookup(editor, null);
    }
  }
}
项目:consulo    文件:CompletionAutoPopupHandler.java   
@Override
public Result checkAutoPopup(char charTyped, final Project project, final Editor editor, final PsiFile file) {
  LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(editor);

  if (LOG.isDebugEnabled()) {
    LOG.debug("checkAutoPopup: character=" + charTyped + ";");
    LOG.debug("phase=" + CompletionServiceImpl.getCompletionPhase());
    LOG.debug("lookup=" + lookup);
    LOG.debug("currentCompletion=" + CompletionServiceImpl.getCompletionService().getCurrentCompletion());
  }

  if (lookup != null) {
    if (editor.getSelectionModel().hasSelection()) {
      lookup.performGuardedChange(() -> EditorModificationUtil.deleteSelectedText(editor));
    }
    return Result.STOP;
  }

  if (Character.isLetter(charTyped) || charTyped == '_') {
    AutoPopupController.getInstance(project).scheduleAutoPopup(editor);
    return Result.STOP;
  }

  return Result.CONTINUE;
}
项目:consulo    文件:TemplateLineStartEndHandler.java   
@Override
protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  if (templateState != null && !templateState.isFinished()) {
    final TextRange range = templateState.getCurrentVariableRange();
    final int caretOffset = editor.getCaretModel().getOffset();
    if (range != null && shouldStayInsideVariable(range, caretOffset)) {
      int selectionOffset = editor.getSelectionModel().getLeadSelectionOffset();
      int offsetToMove = myIsHomeHandler ? range.getStartOffset() : range.getEndOffset();
      LogicalPosition logicalPosition = editor.offsetToLogicalPosition(offsetToMove).leanForward(myIsHomeHandler);
      editor.getCaretModel().moveToLogicalPosition(logicalPosition);
      EditorModificationUtil.scrollToCaret(editor);
      if (myWithSelection) {
        editor.getSelectionModel().setSelection(selectionOffset, offsetToMove);
      }
      else {
        editor.getSelectionModel().removeSelection();
      }
      return;
    }
  }
  myOriginalHandler.execute(editor, caret, dataContext);
}
项目:consulo    文件:PasteReferenceProvider.java   
private static void insert(final String fqn, final PsiElement element, final Editor editor, final QualifiedNameProvider provider) {
  final Project project = editor.getProject();
  if (project == null) return;

  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  documentManager.commitDocument(editor.getDocument());

  final PsiFile file = documentManager.getPsiFile(editor.getDocument());
  if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

  CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
    Document document = editor.getDocument();
    documentManager.doPostponedOperationsAndUnblockDocument(document);
    documentManager.commitDocument(document);
    EditorModificationUtil.deleteSelectedText(editor);
    provider.insertQualifiedName(fqn, element, editor, project);
  }), IdeBundle.message("command.pasting.reference"), null);
}
项目:consulo-java    文件:CommentBreakerEnterProcessor.java   
@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);
        if(comment.getTokenType() == JavaTokenType.END_OF_LINE_COMMENT)
        {
            EditorModificationUtil.insertStringAtCaret(editor, "// ");
        }
        return true;
    }
    return false;
}
项目:consulo-java    文件:JavaTypedHandler.java   
private static boolean handleSemicolon(Editor editor, FileType fileType)
{
    if(fileType != JavaFileType.INSTANCE)
    {
        return false;
    }
    int offset = editor.getCaretModel().getOffset();
    if(offset == editor.getDocument().getTextLength())
    {
        return false;
    }

    char charAt = editor.getDocument().getCharsSequence().charAt(offset);
    if(charAt != ';')
    {
        return false;
    }

    EditorModificationUtil.moveCaretRelatively(editor, 1);
    return true;
}
项目:TS-IJ    文件:TSCaseCorrectingInsertHandler.java   
@Override
public void handleInsert(InsertionContext context1, LookupElement item) {
    Editor editor = context1.getEditor();

    //If they typed the element we should replace the thing they're typing with the correct case
    // Even though Torque is case-insensitive it looks bad if we don't
    PsiElement editing = context1.getFile().findElementAt(context1.getStartOffset());
    if (editing != null) {
        //Delete the element they were typing (note to only go to their carat position)
        editor.getDocument().deleteString(editing.getTextOffset(), editor.getCaretModel().getCurrentCaret().getOffset());
        //And insert the correctly cased version
        EditorModificationUtil.insertStringAtCaret(editor, item.getLookupString(), true);
    }
}
项目: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());
  }
}
项目:intellij-postfix-templates    文件:CustomPostfixTemplateProvider.java   
@Override
public void preExpand(@NotNull final PsiFile file, @NotNull final Editor editor) {
    ApplicationManager.getApplication().assertIsDispatchThread();

    if (isSemicolonNeeded(file, editor)) {
        ApplicationManager.getApplication().runWriteAction(() -> CommandProcessor.getInstance().runUndoTransparentAction(
            () -> {
                EditorModificationUtil.insertStringAtCaret(editor, ";", false, false);
                PsiDocumentManager.getInstance(file.getProject()).commitDocument(editor.getDocument());
            }));
    }
}
项目:intellij-swagger    文件:JsonInsertValueHandler.java   
private void handleEndingQuote(final InsertionContext insertionContext) {
    final int caretOffset = insertionContext.getEditor().getCaretModel().getOffset();
    final CharSequence chars = insertionContext.getDocument().getCharsSequence();

    final boolean hasEndingQuote = CharArrayUtil.regionMatches(chars, caretOffset, "\"");
    if (!hasEndingQuote) {
        insertionContext.getDocument().insertString(caretOffset, "\"");
        EditorModificationUtil.moveCaretRelatively(insertionContext.getEditor(), 1);
    }
}
项目:intellij-swagger    文件:JsonInsertFieldHandler.java   
@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));
    }
}
项目:intellij-swagger    文件:JsonInsertFieldHandler.java   
private void handleEndingQuote(final InsertionContext insertionContext) {
    final int caretOffset = insertionContext.getEditor().getCaretModel().getOffset();
    final CharSequence chars = insertionContext.getDocument().getCharsSequence();

    final boolean hasEndingQuote = CharArrayUtil.regionMatches(chars, caretOffset, "\"");
    if (!hasEndingQuote) {
        insertionContext.getDocument().insertString(caretOffset, "\"");
    }
    EditorModificationUtil.moveCaretRelatively(insertionContext.getEditor(), 1);
}
项目:intellij-swagger    文件:YamlInsertFieldHandler.java   
@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));
    }
}
项目:intellij-kubernetes    文件:KubernetesYamlCompletionContributor.java   
/**
 * Create a {@link LookupElementBuilder} for completing the text of a key. Do not use when completing a value.
 *
 * @param completionObject the object to pass to {@link LookupElementBuilder#create(Object)}.
 * @param addLayerOfNesting whether a newline and indent should be added when accepting the completed value - this is used when inserting the value will introduce a level of nesting (i.e. for an
 * object or array type).
 * @return the created {@code LookupElementBuilder}.
 */
private static LookupElementBuilder createKeyLookupElement(@NotNull final Object completionObject, final boolean addLayerOfNesting) {
    return LookupElementBuilder.create(completionObject).withInsertHandler((insertionContext, lookupElement) -> {
        // If the caret is at the end of the line, add in the property colon when completing
        if (insertionContext.getCompletionChar() != ':' && insertionContext.getCompletionChar() != ' ') {
            final Editor editor = insertionContext.getEditor();
            final int offset = editor.getCaretModel().getOffset();
            final int lineNumber = editor.getDocument().getLineNumber(offset);
            final int lineEndOffset = editor.getDocument().getLineEndOffset(lineNumber);
            if (lineEndOffset == offset) {
                final String autocompleteString;
                if (addLayerOfNesting) {
                    // Copy the indentation characters present on this line, and add one additional level of indentation
                    final int lineStartOffset = editor.getDocument().getLineStartOffset(lineNumber);
                    final String lineContent = editor.getDocument().getText().substring(lineStartOffset, lineEndOffset);
                    final int offsetOfContent = lineContent.length() - StringUtil.trimLeading(lineContent).length();
                    final String indentToLine = lineContent.substring(0, offsetOfContent);
                    final CodeStyleSettings currentSettings = CodeStyleSettingsManager.getSettings(insertionContext.getProject());
                    final CommonCodeStyleSettings.IndentOptions indentOptions = currentSettings.getIndentOptions(insertionContext.getFile().getFileType());
                    final String additionalIndent = indentOptions.USE_TAB_CHARACTER ? "\t" : StringUtil.repeatSymbol(' ', indentOptions.INDENT_SIZE);
                    autocompleteString = ":\n" + indentToLine + additionalIndent;
                } else {
                    autocompleteString = ": ";
                }
                EditorModificationUtil.insertStringAtCaret(editor, autocompleteString);
            }
        }
    });
}
项目:camel-idea-plugin    文件:CamelSmartCompletionEndpointOptions.java   
/**
 * We need special logic to determine when it should insert "=" at the end of the options
 */
@NotNull
private static LookupElementBuilder addInsertHandler(final Editor editor, final LookupElementBuilder builder, String suffix) {
    return builder.withInsertHandler((context, item) -> {
        // enforce using replace select char as we want to replace any existing option
        if (context.getCompletionChar() == Lookup.NORMAL_SELECT_CHAR) {
            int endSelectOffBy = 0;
            if (context.getFile() instanceof PropertiesFileImpl) {
                //if it's a property file the PsiElement does not start and end with an quot
                endSelectOffBy = 1;
            }
            final char text = context.getDocument().getCharsSequence().charAt(context.getSelectionEndOffset() - endSelectOffBy);
            if (text != '=') {
                EditorModificationUtil.insertStringAtCaret(editor, "=");
            }
        } else if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
            // we still want to keep the suffix because they are other options
            String value = suffix;
            int pos = value.indexOf("&");
            if (pos > -1) {
                // strip out first part of suffix until next option
                value = value.substring(pos);
            }
            EditorModificationUtil.insertStringAtCaret(editor, "=" + value);
            // and move cursor back again
            int offset = -1 * value.length();
            EditorModificationUtil.moveCaretRelatively(editor, offset);
        }

    });
}
项目:intellij-ce-playground    文件:CreateFromUsageUtils.java   
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);
      }
      newEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    }
  }
}
项目:intellij-ce-playground    文件:CommentBreakerEnterProcessor.java   
@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);
    if (comment.getTokenType() == JavaTokenType.END_OF_LINE_COMMENT) {
      EditorModificationUtil.insertStringAtCaret(editor, "// ");
    }
    return true;
  }
  return false;
}
项目:intellij-ce-playground    文件:JavaTypedHandler.java   
private static boolean handleSemicolon(Editor editor, FileType fileType) {
  if (fileType != StdFileTypes.JAVA) return false;
  int offset = editor.getCaretModel().getOffset();
  if (offset == editor.getDocument().getTextLength()) return false;

  char charAt = editor.getDocument().getCharsSequence().charAt(offset);
  if (charAt != ';') return false;

  EditorModificationUtil.moveCaretRelatively(editor, 1);
  return true;
}
项目:intellij-ce-playground    文件:CompletionAutoPopupHandler.java   
@Override
public Result checkAutoPopup(char charTyped, final Project project, final Editor editor, final PsiFile file) {
  LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(editor);

  if (LOG.isDebugEnabled()) {
    LOG.debug("checkAutoPopup: character=" + charTyped + ";");
    LOG.debug("phase=" + CompletionServiceImpl.getCompletionPhase());
    LOG.debug("lookup=" + lookup);
    LOG.debug("currentCompletion=" + CompletionServiceImpl.getCompletionService().getCurrentCompletion());
  }

  if (lookup != null) {
    if (editor.getSelectionModel().hasSelection()) {
      lookup.performGuardedChange(new Runnable() {
        @Override
        public void run() {
          EditorModificationUtil.deleteSelectedText(editor);
        }
      });
    }
    return Result.STOP;
  }

  if (Character.isLetter(charTyped) || charTyped == '_') {
    AutoPopupController.getInstance(project).scheduleAutoPopup(editor);
    return Result.STOP;
  }

  return Result.CONTINUE;
}
项目:intellij-ce-playground    文件:TemplateExpressionLookupElement.java   
@Override
public void handleInsert(final InsertionContext context) {
  LookupElement item = getDelegate();
  Project project = context.getProject();
  Editor editor = context.getEditor();

  PsiDocumentManager.getInstance(project).commitAllDocuments();

  TextRange range = myState.getCurrentVariableRange();
  final TemplateLookupSelectionHandler handler = item.getUserData(TemplateLookupSelectionHandler.KEY_IN_LOOKUP_ITEM);
  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();
}
项目:intellij-ce-playground    文件:PydevConsoleExecuteActionHandler.java   
private void indentEditor(final Editor editor, final int indentSize) {
  new WriteCommandAction(getProject()) {
    @Override
    protected void run(@NotNull Result result) throws Throwable {
      EditorModificationUtil.insertStringAtCaret(editor, IndentHelperImpl.fillIndent(getProject(), PythonFileType.INSTANCE, indentSize));
    }
  }.execute();
}
项目:intellij-ce-playground    文件:GroovyEnterHandler.java   
private static void insertLineFeedInString(Editor editor,
                                           DataContext dataContext,
                                           EditorActionHandler originalHandler,
                                           boolean isInsertIndent) {
  if (isInsertIndent) {
    originalHandler.execute(editor, dataContext);
  }
  else {
    EditorModificationUtil.insertStringAtCaret(editor, "\n");
  }
}
项目:js-graphql-intellij-plugin    文件:JSGraphQLEndpointImportInsertHandler.java   
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);
    }
  }
}
项目:intellij-ocaml    文件:OCamlBackspaceHandler.java   
public boolean charDeleted(final char c, @NotNull final PsiFile file, @NotNull final Editor editor) {
    if (myTargetPosition != null) {
        final int offset = editor.getCaretModel().getOffset();
        editor.getSelectionModel().setSelection(offset - editor.getCaretModel().getVisualPosition().column + myTargetPosition.column, offset);
        EditorModificationUtil.deleteSelectedText(editor);
        editor.getCaretModel().moveToLogicalPosition(myTargetPosition);
        myTargetPosition = null;
        return true;
    }
    return false;
}
项目:tools-idea    文件:CreateFromUsageUtils.java   
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);
      }
      newEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    }
  }
}
项目:tools-idea    文件:CommentBreakerEnterProcessor.java   
@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);
    if (comment.getTokenType() == JavaTokenType.END_OF_LINE_COMMENT) {
      EditorModificationUtil.insertStringAtCaret(editor, "// ");
    }
    return true;
  }
  return false;
}
项目:tools-idea    文件:CutAction.java   
@Override
public void executeWriteAction(Editor editor, DataContext dataContext) {
  if(!editor.getSelectionModel().hasSelection()) {
    if (Registry.is(CopyAction.SKIP_COPY_AND_CUT_FOR_EMPTY_SELECTION_KEY)) {
      return;
    }
    editor.getSelectionModel().selectLineAtCaret();
  }
  editor.getSelectionModel().copySelectionToClipboard();
  EditorModificationUtil.deleteSelectedText(editor);
}
项目:tools-idea    文件:PasteAction.java   
@Override
public void executeWriteAction(Editor editor, DataContext dataContext) {
  Producer<Transferable> producer = (Producer<Transferable>)dataContext.getData(TRANSFERABLE_PROVIDER);

  if (editor.isColumnMode() || editor.getSelectionModel().hasBlockSelection()) {
    EditorModificationUtil.pasteTransferableAsBlock(editor, producer == null ? null : producer.produce());
  }
  else {
    editor.putUserData(EditorEx.LAST_PASTED_REGION,
                       producer == null ? EditorModificationUtil.pasteFromClipboard(editor) :
                       EditorModificationUtil.pasteFromTransferrable(producer.produce(), editor));
  }
}