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

项目:intellij-randomness    文件:DataInsertAction.java   
/**
 * Inserts the string generated by {@link #generateString()} at the caret(s) in the editor.
 *
 * @param event the performed action
 */
@Override
public final void actionPerformed(final AnActionEvent event) {
    final Editor editor = event.getData(CommonDataKeys.EDITOR);
    if (editor == null) {
        return;
    }
    final Project project = event.getData(CommonDataKeys.PROJECT);
    final Document document = editor.getDocument();
    final CaretModel caretModel = editor.getCaretModel();

    final Runnable replaceCaretSelections = () -> caretModel.getAllCarets().forEach(caret -> {
        final int start = caret.getSelectionStart();
        final int end = caret.getSelectionEnd();

        final String string = generateString();
        final int newEnd = start + string.length();

        document.replaceString(start, end, string);
        caret.setSelection(start, newEnd);
    });

    WriteCommandAction.runWriteCommandAction(project, replaceCaretSelections);
}
项目:lua-for-idea    文件:Intention.java   
@Nullable
PsiElement findMatchingElement(PsiFile file,
                               Editor editor) {
  final CaretModel caretModel = editor.getCaretModel();
  final int position = caretModel.getOffset();
  PsiElement element = file.findElementAt(position);
  while (element != null) {
     if (predicate.satisfiedBy(element)) {
      return element;
    } else {
      element = element.getParent();
      if (isStopElement(element)) {
        break;
      }
    }
  }
  return null;
}
项目:intellij-ce-playground    文件:JavadocHelper.java   
/**
 * Tries to navigate caret at the given editor to the target position inserting missing white spaces if necessary.
 * 
 * @param position  target caret position
 * @param editor    target editor
 * @param project   target project
 */
@SuppressWarnings("MethodMayBeStatic")
public void navigate(@NotNull LogicalPosition position, @NotNull Editor editor, @NotNull final Project project) {
  final Document document = editor.getDocument();
  final CaretModel caretModel = editor.getCaretModel();
  final int endLineOffset = document.getLineEndOffset(position.line);
  final LogicalPosition endLinePosition = editor.offsetToLogicalPosition(endLineOffset);
  if (endLinePosition.column < position.column && !editor.getSettings().isVirtualSpace() && !editor.isViewer()) {
    final String toInsert = StringUtil.repeat(" ", position.column - endLinePosition.column);
    ApplicationManager.getApplication().runWriteAction(new Runnable() {
      @Override
      public void run() {
        document.insertString(endLineOffset, toInsert);
        PsiDocumentManager.getInstance(project).commitDocument(document);
      }
    });

  }
  caretModel.moveToLogicalPosition(position);
}
项目:intellij-ce-playground    文件:IntroduceParameterObjectHandler.java   
private static PsiMethod getSelectedMethod(Editor editor, PsiFile file, DataContext dataContext) {
  final PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
  PsiMethod selectedMethod = null;
  if (element instanceof PsiMethod) {
    selectedMethod = (PsiMethod)element;
  }
  else if (element instanceof PsiParameter && ((PsiParameter)element).getDeclarationScope() instanceof PsiMethod){
    selectedMethod = (PsiMethod)((PsiParameter)element).getDeclarationScope();
  }
  else {
    final CaretModel caretModel = editor.getCaretModel();
    final int position = caretModel.getOffset();
    final PsiElement elementAt = file.findElementAt(position);
    final PsiMethodCallExpression methodCallExpression =
     PsiTreeUtil.getParentOfType(elementAt, PsiMethodCallExpression.class);
    if (methodCallExpression != null) {
      selectedMethod = methodCallExpression.resolveMethod();
    } else {
      final PsiParameterList parameterList = PsiTreeUtil.getParentOfType(elementAt, PsiParameterList.class);
      if (parameterList != null && parameterList.getParent() instanceof PsiMethod) {
        selectedMethod = (PsiMethod)parameterList.getParent();
      }
    }
  }
  return selectedMethod;
}
项目:intellij-ce-playground    文件:FoldingProcessingOnDocumentModificationTest.java   
public void testUnexpectedClassLevelJavadocExpandingOnClassSignatureChange() throws IOException {
  // Inspired by IDEA-61275

  String text =
    "/**\n" +
    " * This is a test comment\n" +
    " */\n" +
    "public <caret>class Test {\n" +
    "}";
  init(text, TestFileType.JAVA);

  CaretModel caretModel = myEditor.getCaretModel();
  int caretOffset = caretModel.getOffset();

  assertEquals(caretOffset, caretModel.getOffset());

  updateFoldRegions();
  toggleFoldRegionState(getFoldRegion(0), false);
  type('a');
  updateFoldRegions();

  assertEquals(caretOffset + 1, caretModel.getOffset());
  assertEquals(1, myEditor.getFoldingModel().getAllFoldRegions().length);
  FoldRegion foldRegion = getFoldRegion(0);
  assertFalse(foldRegion.isExpanded());
}
项目:intellij-ce-playground    文件:ChangeSignatureGestureTest.java   
public void testAddParamChangeReturnType() {
  doTest(() -> {
    myFixture.type("int param");
    CaretModel model = myFixture.getEditor().getCaretModel();
    PsiElement element = myFixture.getElementAtCaret();
    PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false);
    assertTrue(method != null);
    PsiTypeElement returnTypeElement = method.getReturnTypeElement();
    assertTrue(returnTypeElement != null);
    model.moveToOffset(returnTypeElement.getTextRange().getEndOffset());
    int i = returnTypeElement.getTextLength();
    while (i-- > 0) {
      myFixture.type('\b');
    }
    myFixture.type("boolean");
  }, true, ChangeSignatureDetectorAction.CHANGE_SIGNATURE);
}
项目:intellij-ce-playground    文件:KillToWordStartAction.java   
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
  CaretModel caretModel = editor.getCaretModel();
  int caretOffset = caretModel.getOffset();
  if (caretOffset <= 0) {
    return;
  }

  boolean camel = editor.getSettings().isCamelWords();
  for (int i = caretOffset - 1; i >= 0; i--) {
    if (EditorActionUtil.isWordOrLexemeStart(editor, i, camel)) {
      KillRingUtil.cut(editor, i, caretOffset);
      return;
    }
  }

  KillRingUtil.cut(editor, 0, caretOffset);
}
项目:intellij-ce-playground    文件:PopupFactoryImpl.java   
@Nullable
private static Point getVisibleBestPopupLocation(@NotNull Editor editor) {
  VisualPosition visualPosition = editor.getUserData(ANCHOR_POPUP_POSITION);

  if (visualPosition == null) {
    CaretModel caretModel = editor.getCaretModel();
    if (caretModel.isUpToDate()) {
      visualPosition = caretModel.getVisualPosition();
    }
    else {
      visualPosition = editor.offsetToVisualPosition(caretModel.getOffset());
    }
  }

  Point p = editor.visualPositionToXY(new VisualPosition(visualPosition.line + 1, visualPosition.column));

  final Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
  return visibleArea.contains(p) ? p : null;
}
项目:intellij-ce-playground    文件:PyCommentBreakerEnterProcessor.java   
public boolean doEnter(Editor editor, PsiElement psiElement, boolean isModified) {
  if (isModified) {
    return false;
  }
  final CaretModel caretModel = editor.getCaretModel();
  PsiElement atCaret = psiElement.getContainingFile().findElementAt(caretModel.getOffset());
  if (atCaret instanceof PsiWhiteSpace) {
    atCaret = atCaret.getPrevSibling();
  }
  final PsiElement comment = PsiTreeUtil.getParentOfType(atCaret, PsiComment.class, false);
  if (comment != null) {
    SmartEnterUtil.plainEnter(editor);
    editor.getDocument().insertString(caretModel.getOffset(), "# ");
    caretModel.moveToOffset(caretModel.getOffset() + 2);
    return true;
  }
  return false;
}
项目:intellij-ce-playground    文件:PyStatementMover.java   
private static int getCaretShift(PsiElement startToMove, PsiElement endToMove, CaretModel caretModel, boolean selectionStartAtCaret) {
  int shift;
  if (selectionStartAtCaret) {
    shift = caretModel.getOffset() - startToMove.getTextRange().getStartOffset();
  }
  else {
    shift = caretModel.getOffset();
    if (startToMove != endToMove) {
      shift += startToMove.getTextLength();

      PsiElement tmp = startToMove.getNextSibling();
      while (tmp != endToMove && tmp != null) {
        if (!(tmp instanceof PsiWhiteSpace))
          shift += tmp.getTextLength();
        tmp = tmp.getNextSibling();
      }
    }

    shift -= endToMove.getTextOffset();
  }
  return shift;
}
项目:intellij-ce-playground    文件:PyIntroduceFieldHandler.java   
private static boolean isTestClass(PsiFile file, Editor editor) {
  PsiElement element1 = null;
  final SelectionModel selectionModel = editor.getSelectionModel();
  if (selectionModel.hasSelection()) {
    element1 = file.findElementAt(selectionModel.getSelectionStart());
  }
  else {
    final CaretModel caretModel = editor.getCaretModel();
    final Document document = editor.getDocument();
    int lineNumber = document.getLineNumber(caretModel.getOffset());
    if ((lineNumber >= 0) && (lineNumber < document.getLineCount())) {
      element1 = file.findElementAt(document.getLineStartOffset(lineNumber));
    }
  }
  if (element1 != null) {
    final PyClass clazz = PyUtil.getContainingClassOrSelf(element1);
    if (clazz != null && PythonUnitTestUtil.isTestCaseClass(clazz)) return true;
  }
  return false;
}
项目:intellij-ce-playground    文件:PyClassRefactoringHandler.java   
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
  PsiElement element1 = null;
  PsiElement element2 = null;
  final SelectionModel selectionModel = editor.getSelectionModel();
  if (selectionModel.hasSelection()) {
    element1 = file.findElementAt(selectionModel.getSelectionStart());
    element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1);
  }
  else {
    final CaretModel caretModel = editor.getCaretModel();
    final Document document = editor.getDocument();
    int lineNumber = document.getLineNumber(caretModel.getOffset());
    if ((lineNumber >= 0) && (lineNumber < document.getLineCount())) {
      element1 = file.findElementAt(document.getLineStartOffset(lineNumber));
      element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1);
    }
  }
  if (element1 == null || element2 == null) {
    CommonRefactoringUtil.showErrorHint(project, editor, PyBundle.message("refactoring.introduce.selection.error"), getTitle(),
                                        "members.pull.up");
    return;
  }
  doRefactor(project, element1, element2, editor, file, dataContext);
}
项目:intellij-ce-playground    文件:CreateTypedResourceFileAction.java   
PsiElement[] doCreateAndNavigate(String newName, PsiDirectory directory, String rootTagName, boolean chooseTagName, boolean navigate)
  throws Exception {
  final XmlFile file = AndroidResourceUtil
    .createFileResource(newName, directory, rootTagName, myResourceType.getName(), myValuesResourceFile);

  if (navigate) {
    doNavigate(file);
  }
  if (chooseTagName) {
    XmlDocument document = file.getDocument();
    if (document != null) {
      XmlTag rootTag = document.getRootTag();
      if (rootTag != null) {
        final Project project = file.getProject();
        final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (editor != null) {
          CaretModel caretModel = editor.getCaretModel();
          caretModel.moveToOffset(rootTag.getTextOffset() + 1);
          XmlTagInplaceRenamer.rename(editor, rootTag);
        }
      }
    }
  }
  return new PsiElement[]{file};
}
项目:intellij-ce-playground    文件:UnicodeUnescapeIntention.java   
@Override
public boolean satisfiedBy(PsiElement element, @Nullable Editor editor) {
  if (editor == null) {
    return false;
  }
  final SelectionModel selectionModel = editor.getSelectionModel();
  final Document document = editor.getDocument();
  if (selectionModel.hasSelection()) {
    final int start = selectionModel.getSelectionStart();
    final int end = selectionModel.getSelectionEnd();
    if (start < 0 || end < 0 || start > end) {
      // shouldn't happen but http://ea.jetbrains.com/browser/ea_problems/50192
      return false;
    }
    final String text = document.getCharsSequence().subSequence(start, end).toString();
    return indexOfUnicodeEscape(text, 1) >= 0;
  }
  else {
    final CaretModel caretModel = editor.getCaretModel();
    final int lineNumber = document.getLineNumber(caretModel.getOffset());
    final String line = document.getText(new TextRange(document.getLineStartOffset(lineNumber), document.getLineEndOffset(lineNumber)));
    final int column = caretModel.getLogicalPosition().column;
    final int index = indexOfUnicodeEscape(line, column);
    return index >= 0 && column >= index;
  }
}
项目:idea-multimarkdown    文件:MultiMarkdownPreviewEditor.java   
protected void updateRawHtmlText(final String htmlTxt) {
    final DocumentEx myDocument = myTextViewer.getDocument();

    if (project.isDisposed()) return;

    ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
            if (project.isDisposed()) return;

            CommandProcessor.getInstance().executeCommand(project, new Runnable() {
                @Override
                public void run() {
                    if (project.isDisposed()) return;

                    myDocument.replaceString(0, myDocument.getTextLength(), htmlTxt);
                    final CaretModel caretModel = myTextViewer.getCaretModel();
                    if (caretModel.getOffset() >= myDocument.getTextLength()) {
                        caretModel.moveToOffset(myDocument.getTextLength());
                    }
                }
            }, null, null, UndoConfirmationPolicy.DEFAULT, myDocument);
        }
    });
}
项目:idea-multimarkdown    文件:MultiMarkdownFxPreviewEditor.java   
protected void updateRawHtmlText(final String htmlTxt) {
    final DocumentEx myDocument = myTextViewer.getDocument();

    if (project.isDisposed()) return;

    ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
            if (project.isDisposed()) return;

            CommandProcessor.getInstance().executeCommand(project, new Runnable() {
                @Override
                public void run() {
                    if (project.isDisposed()) return;

                    myDocument.replaceString(0, myDocument.getTextLength(), htmlTxt);
                    final CaretModel caretModel = myTextViewer.getCaretModel();
                    if (caretModel.getOffset() >= myDocument.getTextLength()) {
                        caretModel.moveToOffset(myDocument.getTextLength());
                    }
                }
            }, null, null, UndoConfirmationPolicy.DEFAULT, myDocument);
        }
    });
}
项目:Intellij-Plugin    文件:CustomRenameHandlerTest.java   
@Test
public void testShouldRenameWhenElementIsNotPresentInDataContext() throws Exception {
    CaretModel caretModel = mock(CaretModel.class);
    PsiFile file = mock(PsiFile.class);

    when(dataContext.getData(CommonDataKeys.PSI_ELEMENT.getName())).thenReturn(null);
    when(dataContext.getData(CommonDataKeys.EDITOR.getName())).thenReturn(editor);
    when(editor.getCaretModel()).thenReturn(caretModel);
    when(caretModel.getOffset()).thenReturn(0);
    when(dataContext.getData(CommonDataKeys.PSI_FILE.getName())).thenReturn(file);
    when(file.findElementAt(0)).thenReturn(mock(SpecStepImpl.class));

    boolean isAvailable = new CustomRenameHandler().isAvailableOnDataContext(dataContext);
    assertTrue("Should rename when element is not present in DataContext. Expected: true, Actual: false", isAvailable);

    when(file.findElementAt(0)).thenReturn(mock(ConceptStepImpl.class));
    isAvailable = new CustomRenameHandler().isAvailableOnDataContext(dataContext);
    assertTrue("Should rename when element is not present in DataContext. Expected: true, Actual: false", isAvailable);
}
项目:idea-latex    文件:DialogEditorAction.java   
@NotNull
protected Runnable getDialogAction(@NotNull final T dialog, @NotNull final TextEditor editor) {
    return new Runnable() {
        @Override
        public void run() {
            final Document document = editor.getEditor().getDocument();
            final CaretModel caretModel = editor.getEditor().getCaretModel();
            final String content = getContent(dialog);

            int offset = caretModel.getOffset();

            document.insertString(offset, content);
            caretModel.moveToOffset(offset + content.length());
        }
    };
}
项目:idea-latex    文件:WrapEditorAction.java   
/**
 * Wraps selection.
 *
 * @param editor Current editor.
 */
private void wrap(@NotNull TextEditor editor) {
    final Document document = editor.getEditor().getDocument();
    final SelectionModel selectionModel = editor.getEditor().getSelectionModel();
    final CaretModel caretModel = editor.getEditor().getCaretModel();

    final int start = selectionModel.getSelectionStart();
    final int end = selectionModel.getSelectionEnd();
    final String text = StringUtil.notNullize(selectionModel.getSelectedText());

    String newText = getLeftText() + text + getRightText();
    int newStart = start + getLeftText().length();
    int newEnd = StringUtil.isEmpty(text) ? newStart : end + getLeftText().length();

    document.replaceString(start, end, newText);
    selectionModel.setSelection(newStart, newEnd);
    caretModel.moveToOffset(newEnd);
}
项目:idea-latex    文件:WrapEditorAction.java   
/**
 * Unwraps selection.
 *
 * @param editor  Current editor.
 * @param matched Matched PSI element.
 */
private void unwrap(@NotNull final TextEditor editor, @NotNull final PsiElement matched) {
    final Document document = editor.getEditor().getDocument();
    final SelectionModel selectionModel = editor.getEditor().getSelectionModel();
    final CaretModel caretModel = editor.getEditor().getCaretModel();

    final int start = matched.getTextRange().getStartOffset();
    final int end = matched.getTextRange().getEndOffset();
    final String text = StringUtil.notNullize(matched.getText());

    String newText = StringUtil.trimEnd(StringUtil.trimStart(text, getLeftText()), getRightText());
    int newStart = selectionModel.getSelectionStart() - getLeftText().length();
    int newEnd = selectionModel.getSelectionEnd() - getLeftText().length();

    document.replaceString(start, end, newText);

    selectionModel.setSelection(newStart, newEnd);
    caretModel.moveToOffset(newEnd);
}
项目:tools-idea    文件:FoldingProcessingOnDocumentModificationTest.java   
public void testUnexpectedClassLevelJavadocExpandingOnClassSignatureChange() throws IOException {
  // Inspired by IDEA-61275

  String text =
    "/**\n" +
    " * This is a test comment\n" +
    " */\n" +
    "public <caret>class Test {\n" +
    "}";
  init(text, TestFileType.JAVA);

  CaretModel caretModel = myEditor.getCaretModel();
  int caretOffset = caretModel.getOffset();

  assertEquals(caretOffset, caretModel.getOffset());

  updateFoldRegions();
  toggleFoldRegionState(getFoldRegion(0), false);
  type('a');
  updateFoldRegions();

  assertEquals(caretOffset + 1, caretModel.getOffset());
  assertEquals(1, myEditor.getFoldingModel().getAllFoldRegions().length);
  FoldRegion foldRegion = getFoldRegion(0);
  assertFalse(foldRegion.isExpanded());
}
项目:tools-idea    文件:ChangeSignatureGestureTest.java   
public void testAddParamChangeReturnType() {
  doTest(new Runnable() {
    @Override
    public void run() {
      myFixture.type("int param");
      CaretModel model = myFixture.getEditor().getCaretModel();
      PsiElement element = myFixture.getElementAtCaret();
      PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false);
      assertTrue(method != null);
      PsiTypeElement returnTypeElement = method.getReturnTypeElement();
      assertTrue(returnTypeElement != null);
      model.moveToOffset(returnTypeElement.getTextRange().getEndOffset());
      int i = returnTypeElement.getTextLength();
      while (i-- > 0) {
        myFixture.type('\b');
      }
      myFixture.type("boolean");
    }
  }, true, ChangeSignatureDetectorAction.CHANGE_SIGNATURE);
}
项目:tools-idea    文件:KillToWordStartAction.java   
@Override
public void executeWriteAction(Editor editor, DataContext dataContext) {
  CaretModel caretModel = editor.getCaretModel();
  int caretOffset = caretModel.getOffset();
  Document document = editor.getDocument();
  if (caretOffset <= 0) {
    return;
  }

  CharSequence text = document.getCharsSequence();
  boolean camel = editor.getSettings().isCamelWords();
  for (int i = caretOffset - 1; i >= 0; i--) {
    if (EditorActionUtil.isWordStart(text, i, camel)) {
      KillRingUtil.cut(editor, i, caretOffset);
      return;
    }
  }

  KillRingUtil.cut(editor, 0, caretOffset);
}
项目:tools-idea    文件:SwapSelectionBoundariesAction.java   
@Override
public void execute(Editor editor, DataContext dataContext) {
  if (!(editor instanceof EditorEx)) {
    return;
  }
  final SelectionModel selectionModel = editor.getSelectionModel();
  if (!selectionModel.hasSelection()) {
    return;
  }

  EditorEx editorEx = (EditorEx)editor;
  final int start = selectionModel.getSelectionStart();
  final int end = selectionModel.getSelectionEnd();
  final CaretModel caretModel = editor.getCaretModel();
  boolean moveToEnd = caretModel.getOffset() == start;
  editorEx.setStickySelection(false);
  editorEx.setStickySelection(true);
  if (moveToEnd) {
    caretModel.moveToOffset(end);
  }
  else {
    caretModel.moveToOffset(start);
  }
}
项目:tools-idea    文件:PopupFactoryImpl.java   
@Nullable
private static Point getVisibleBestPopupLocation(@NotNull Editor editor) {
  VisualPosition visualPosition = editor.getUserData(ANCHOR_POPUP_POSITION);

  if (visualPosition == null) {
    CaretModel caretModel = editor.getCaretModel();
    if (caretModel.isUpToDate()) {
      visualPosition = caretModel.getVisualPosition();
    }
    else {
      visualPosition = editor.offsetToVisualPosition(caretModel.getOffset());
    }
  }

  Point p = editor.visualPositionToXY(new VisualPosition(visualPosition.line + 1, visualPosition.column));

  final Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
  return visibleArea.contains(p) ? p : null;
}
项目:tools-idea    文件:ExpandToNormalAnnotationIntention.java   
@Override
protected void processIntention(@NotNull PsiElement element) throws IncorrectOperationException {
  final PsiNameValuePair attribute = (PsiNameValuePair)element;
  final int textOffset = attribute.getTextOffset();
  final Project project = attribute.getProject();
  final String text = buildReplacementText(attribute);
  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
  final PsiAnnotation newAnnotation = factory.createAnnotationFromText("@A(" + text +" )", attribute);
  attribute.replace(newAnnotation.getParameterList().getAttributes()[0]);
  final FileEditorManager editorManager = FileEditorManager.getInstance(project);
  final Editor editor = editorManager.getSelectedTextEditor();
  if (editor == null) {
    return;
  }
  final CaretModel caretModel = editor.getCaretModel();
  caretModel.moveToOffset(textOffset + text.length() - 1);
}
项目:nosql4idea    文件:OperatorCompletionAction.java   
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
    final Document document = editor.getDocument();
    CaretModel caretModel = editor.getCaretModel();
    final int offset = caretModel.getOffset();
    new PopupChooserBuilder(QUERY_OPERATOR_LIST)
            .setMovable(false)
            .setCancelKeyEnabled(true)
            .setItemChoosenCallback(new Runnable() {
                public void run() {
                    final String selectedQueryOperator = (String) QUERY_OPERATOR_LIST.getSelectedValue();
                    if (selectedQueryOperator == null) return;

                    new WriteCommandAction(project, MONGO_OPERATOR_COMPLETION) {
                        @Override
                        protected void run(@NotNull Result result) throws Throwable {
                            document.insertString(offset, selectedQueryOperator);
                        }
                    }.execute();
                }
            })
            .createPopup()
            .showInBestPositionFor(editor);
}
项目:consulo-lua    文件:Intention.java   
@Nullable
PsiElement findMatchingElement(PsiFile file,
                               Editor editor) {
  final CaretModel caretModel = editor.getCaretModel();
  final int position = caretModel.getOffset();
  PsiElement element = file.findElementAt(position);
  while (element != null) {
    if (predicate.satisfiedBy(element)) {
      return element;
    } else {
      element = element.getParent();
      if (isStopElement(element)) {
        break;
      }
    }
  }
  return null;
}
项目:intellij-plugin-v4    文件:InputPanel.java   
public void highlightAndOfferHint(Editor editor, int offset,
                                  Interval sourceInterval,
                                  JBColor color,
                                  EffectType effectType, String hintText) {
    CaretModel caretModel = editor.getCaretModel();
    final TextAttributes attr = new TextAttributes();
    attr.setForegroundColor(color);
    attr.setEffectColor(color);
    attr.setEffectType(effectType);
    MarkupModel markupModel = editor.getMarkupModel();
    markupModel.addRangeHighlighter(
        sourceInterval.a,
        sourceInterval.b,
        InputPanel.TOKEN_INFO_LAYER, // layer
        attr,
        HighlighterTargetArea.EXACT_RANGE
                                   );

    if ( hintText.contains("<") ) {
        hintText = hintText.replaceAll("<", "&lt;");
    }

    // HINT
    caretModel.moveToOffset(offset); // info tooltip only shows at cursor :(
    HintManager.getInstance().showInformationHint(editor, hintText);
}
项目:consulo    文件:KillToWordStartAction.java   
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, DataContext dataContext) {
  CaretModel caretModel = editor.getCaretModel();
  int caretOffset = caretModel.getOffset();
  Document document = editor.getDocument();
  if (caretOffset <= 0) {
    return;
  }

  CharSequence text = document.getCharsSequence();
  boolean camel = editor.getSettings().isCamelWords();
  for (int i = caretOffset - 1; i >= 0; i--) {
    if (EditorActionUtil.isWordStart(text, i, camel)) {
      KillRingUtil.cut(editor, i, caretOffset);
      return;
    }
  }

  KillRingUtil.cut(editor, 0, caretOffset);
}
项目:consulo    文件:SwapSelectionBoundariesAction.java   
@Override
public void execute(Editor editor, DataContext dataContext) {
  if (!(editor instanceof EditorEx)) {
    return;
  }
  final SelectionModel selectionModel = editor.getSelectionModel();
  if (!selectionModel.hasSelection()) {
    return;
  }

  EditorEx editorEx = (EditorEx)editor;
  final int start = selectionModel.getSelectionStart();
  final int end = selectionModel.getSelectionEnd();
  final CaretModel caretModel = editor.getCaretModel();
  boolean moveToEnd = caretModel.getOffset() == start;
  editorEx.setStickySelection(false);
  editorEx.setStickySelection(true);
  if (moveToEnd) {
    caretModel.moveToOffset(end);
  }
  else {
    caretModel.moveToOffset(start);
  }
}
项目:consulo    文件:PopupFactoryImpl.java   
@Nullable
private static Point getVisibleBestPopupLocation(@Nonnull Editor editor) {
  VisualPosition visualPosition = editor.getUserData(ANCHOR_POPUP_POSITION);

  if (visualPosition == null) {
    CaretModel caretModel = editor.getCaretModel();
    if (caretModel.isUpToDate()) {
      visualPosition = caretModel.getVisualPosition();
    }
    else {
      visualPosition = editor.offsetToVisualPosition(caretModel.getOffset());
    }
  }

  final int lineHeight = editor.getLineHeight();
  Point p = editor.visualPositionToXY(visualPosition);
  p.y += lineHeight;

  final Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
  return !visibleArea.contains(p) && !visibleArea.contains(p.x, p.y - lineHeight)
         ? null : p;
}
项目:consulo-google-guice    文件:Intention.java   
@Nullable
public PsiElement findMatchingElement(PsiFile file, Editor editor)
{
    final CaretModel caretModel = editor.getCaretModel();
    final int position = caretModel.getOffset();
    PsiElement element = file.findElementAt(position);
    while(element != null)
    {
        if(predicate.satisfiedBy(element))
        {
            return element;
        }
        else
        {
            element = element.getParent();
        }
    }
    return null;
}
项目:Intellij-Dust    文件:DustTypedHandler.java   
/**
 * When appropriate, automatically reduce the indentation for else tags "{:else}"
 */
private void adjustFormatting(Project project, int offset, Editor editor, PsiFile file, FileViewProvider provider) {
  PsiElement elementAtCaret = provider.findElementAt(offset - 1, DustLanguage.class);
  PsiElement elseParent = PsiTreeUtil.findFirstParent(elementAtCaret, true, new Condition<PsiElement>() {
    @Override
    public boolean value(PsiElement element) {
      return element != null
          && (element instanceof DustElseTag);
    }
  });

  // run the formatter if the user just completed typing a SIMPLE_INVERSE or a CLOSE_BLOCK_STACHE
  if (elseParent != null) {
    // grab the current caret position (AutoIndentLinesHandler is about to mess with it)
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    CaretModel caretModel = editor.getCaretModel();
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    codeStyleManager.adjustLineIndent(file, editor.getDocument().getLineStartOffset(caretModel.getLogicalPosition().line));
  }
}
项目:consulo-java    文件:ExpandToNormalAnnotationIntention.java   
@Override
protected void processIntention(@NotNull PsiElement element) throws IncorrectOperationException {
  final PsiNameValuePair attribute = (PsiNameValuePair)element;
  final int textOffset = attribute.getTextOffset();
  final Project project = attribute.getProject();
  final String text = buildReplacementText(attribute);
  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
  final PsiAnnotation newAnnotation = factory.createAnnotationFromText("@A(" + text +" )", attribute);
  attribute.replace(newAnnotation.getParameterList().getAttributes()[0]);
  final FileEditorManager editorManager = FileEditorManager.getInstance(project);
  final Editor editor = editorManager.getSelectedTextEditor();
  if (editor == null) {
    return;
  }
  final CaretModel caretModel = editor.getCaretModel();
  caretModel.moveToOffset(textOffset + text.length() - 1);
}
项目:consulo-java    文件:ChangeSignatureGestureTest.java   
public void testAddParamChangeReturnType()
{
    doTest(() ->
    {
        myFixture.type("int param");
        PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
        CaretModel model = myFixture.getEditor().getCaretModel();
        PsiElement element = myFixture.getElementAtCaret();
        PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false);
        assertTrue(method != null);
        PsiTypeElement returnTypeElement = method.getReturnTypeElement();
        assertTrue(returnTypeElement != null);
        model.moveToOffset(returnTypeElement.getTextRange().getEndOffset());
        int i = returnTypeElement.getTextLength();
        while(i-- > 0)
        {
            myFixture.type('\b');
        }
        myFixture.type("boolean");
    });
}
项目:consulo-java    文件:FoldingProcessingOnDocumentModificationTest.java   
public void testUnexpectedClassLevelJavadocExpandingOnClassSignatureChange() throws IOException
{
    // Inspired by IDEA-61275

    String text = "/**\n" + " * This is a test comment\n" + " */\n" + "public <caret>class Test {\n" + "}";
    init(text, TestFileType.JAVA);

    CaretModel caretModel = myEditor.getCaretModel();
    int caretOffset = caretModel.getOffset();

    assertEquals(caretOffset, caretModel.getOffset());

    updateFoldRegions();
    toggleFoldRegionState(getFoldRegion(0), false);
    type('a');
    updateFoldRegions();

    assertEquals(caretOffset + 1, caretModel.getOffset());
    assertEquals(1, myEditor.getFoldingModel().getAllFoldRegions().length);
    FoldRegion foldRegion = getFoldRegion(0);
    assertFalse(foldRegion.isExpanded());
}
项目:laravel-insight    文件:ScopeCompletionContributor.java   
@Override
public void handleInsert(final InsertionContext context) {
    if (element.getParent() instanceof FieldReference) {
        final Editor     editor     = context.getEditor();
        final CaretModel caretModel = editor.getCaretModel();
        final Document   document   = editor.getDocument();

        document.insertString(caretModel.getOffset(), "()");
        caretModel.moveCaretRelatively(1, 0, false, false, false);
    }
}
项目:json2java4idea    文件:SettingsPanel.java   
public void setPreviewText(@Nonnull String text) {
    final CommandProcessor processor = CommandProcessor.getInstance();
    processor.executeCommand(null, () -> {
        final Application application = ApplicationManager.getApplication();
        application.runWriteAction(() -> {
            previewDocument.replaceString(INITIAL_OFFSET, previewDocument.getTextLength(), text);

            final int textLength = previewDocument.getTextLength();
            final CaretModel caret = previewEditor.getCaretModel();
            if (caret.getOffset() >= textLength) {
                caret.moveToOffset(textLength);
            }
        });
    }, null, null);
}
项目:json2java4idea    文件:NewClassDialog.java   
public void setJson(@NotNull String json) {
    final CommandProcessor processor = CommandProcessor.getInstance();
    processor.executeCommand(project, () -> {
        final Application application = ApplicationManager.getApplication();
        application.runWriteAction(() -> {
            jsonDocument.replaceString(INITIAL_OFFSET, jsonDocument.getTextLength(), json);

            final int textLength = jsonDocument.getTextLength();
            final CaretModel caret = jsonEditor.getCaretModel();
            if (caret.getOffset() >= textLength) {
                caret.moveToOffset(textLength);
            }
        });
    }, null, null);
}