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

项目:SmartQQ4IntelliJ    文件:ReviewHandler.java   
@Override
protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
    super.doExecute(editor, caret, dataContext);
    VirtualFile vf = (CommonDataKeys.VIRTUAL_FILE.getData(dataContext));

    if (IMWindowFactory.getDefault() == null) {
        return;
    }
    String path = VFSUtils.getPath(vf);
    if (!TextUtils.isEmpty(path)) {
        String text = editor.getSelectionModel().getSelectedText();
        int line = EditorUtils.getEditorLine(editor);
        ReviewDialog dialog = new ReviewDialog();
        dialog.pack();
        dialog.setLocationRelativeTo(null);
        dialog.setData(path, line, text);
        dialog.setVisible(true);
        dialog.dispose();
    }
}
项目:intellij-ce-playground    文件:LookupActionHandler.java   
@Override
protected void executeInLookup(final LookupImpl lookup, DataContext context, Caret caret) {
  if (!lookup.isCompletion()) {
    myOriginalHandler.execute(lookup.getEditor(), caret, context);
    return;
  }

  if (!lookup.performGuardedChange(new Runnable() {
    @Override
    public void run() {
      lookup.getEditor().getSelectionModel().removeSelection();
    }
  })) {
    return;
  }

  BackspaceHandler.truncatePrefix(context, lookup, myOriginalHandler, lookup.getLookupStart() - 1, caret);
}
项目:MissingInActions    文件:ActionSelectionAdjuster.java   
private void updateLastPastedClipboardCarets(final Transferable transferable, final LinePasteCaretAdjustmentType adjustment, boolean setIfNone) {
    // if we already saved state, it means we might have adjusted caret position for line selections of the clipboard content at the time
    // we need to restore caret column positions to undo adjustments made for clipboard content that no longer applies
    final ClipboardCaretContent lastClipboardData = ClipboardCaretContent.getLastPastedClipboardCarets(myEditor);
    if (lastClipboardData != null) {
        int i = 0;
        for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
            EditorPosition position = myManager.getPositionFactory().fromPosition(caret.getLogicalPosition());
            final EditorPosition atColumn = position.atColumn(lastClipboardData.getCaretColumn(i++));
            if (atColumn != position) {
                caret.moveToLogicalPosition(atColumn);
            }
        }
    }

    if (lastClipboardData != null || setIfNone) {
        final ClipboardCaretContent clipboardData = transferable != null ? ClipboardCaretContent.saveLastPastedCaretsForTransferable(myEditor, transferable, adjustment == LinePasteCaretAdjustmentType.NONE ? null : (caret, isFullLine) -> {
            if (!caret.hasSelection() && isFullLine) {
                caret.moveToOffset(adjustment.getPastePosition(myManager.getPositionFactory().fromPosition(caret.getLogicalPosition())).getOffset());
            }
            return caret.getOffset();
        }) : null;

        ClipboardCaretContent.setLastPastedClipboardCarets(myEditor, clipboardData);
    }
}
项目:MissingInActions    文件:WordHighlightActionBase.java   
@Override
public void actionPerformed(final AnActionEvent e) {
    Editor editor = e.getData(PlatformDataKeys.EDITOR);
    if (editor != null) {
        Document document = editor.getDocument();
        CharSequence chars = document.getCharsSequence();
        Plugin plugin = Plugin.getInstance();

        for (Caret caret : editor.getCaretModel().getAllCarets()) {
            if (caret.hasSelection()) {
                boolean startWord = EditHelpers.isWordStart(chars, caret.getSelectionStart(),false);
                boolean endWord = EditHelpers.isWordEnd(chars, caret.getSelectionEnd(),false);
                if (myIsRemoveWord) {
                    plugin.removeHighlightWord(chars.subSequence(caret.getSelectionStart(), caret.getSelectionEnd()));
                } else {
                    plugin.addHighlightWord(chars.subSequence(caret.getSelectionStart(), caret.getSelectionEnd()), startWord, endWord, null);
                }
            }
        }
    }
}
项目:MissingInActions    文件:CaretSpawningSearchHandler.java   
@Override
protected void updateCarets(final Editor editor, final List<Caret> caretList) {
    LineSelectionManager manager = LineSelectionManager.getInstance(editor);
    if (mySingleMatch) {
        List<Caret> startMatchedCarets = new ArrayList<>();
        for (Caret caret : caretList) {
            for (Caret startCaret : myStartSearchCarets) {
                if (startCaret.getLogicalPosition().line == caret.getLogicalPosition().line) {
                    startMatchedCarets.add(startCaret);
                    break;
                }
            }
        }

        manager.setSearchFoundCaretSpawningHandler(this, myStartCarets, myStartSearchCarets, startMatchedCarets, caretList);
    } else {
        // just regular carets
        manager.clearSearchFoundCarets();
    }
}
项目:MissingInActions    文件:ToggleCaretSelectionAnchorActionHandler.java   
private void perform(Editor editor, LineSelectionManager manager, Caret caret) {
    assert caret != null;

    if (caret.hasSelection()) {
        EditorCaret editorCaret = manager.getEditorCaret(caret);
        if (editorCaret.getSelectionLineCount() > 1) {
            int column = editorCaret.getCaretPosition().column;
            editorCaret.setIsStartAnchorUpdateAnchorColumn(!editorCaret.isStartAnchor());
            if (column != 0 && editorCaret.getCaretPosition().column == 0) {
                editorCaret.restoreColumn(column);
            }
            editorCaret.commit();
        } else {
            // swap start/end
            int startOffset = caret.getSelectionStart();
            int endOffset = caret.getSelectionEnd();
            if (caret.getLeadSelectionOffset() == caret.getSelectionStart()) {
                caret.moveToOffset(startOffset);
            } else {
                caret.moveToOffset(endOffset);
            }
            caret.setSelection(endOffset, startOffset);
        }
    }
}
项目:MissingInActions    文件:ToLineOrCharacterSelectionTypeActionHandler.java   
private void perform(Editor editor, LineSelectionManager manager, Caret caret) {
    assert caret != null;

    EditorCaret editorCaret = manager.getEditorCaret(caret);

    if (editorCaret.hasSelection()) {
        if (editorCaret.isLine()) {
            if (wantCharacter()) {
                editorCaret.toCharSelection()
                        .normalizeCaretPosition()
                        .commit();
            }
        } else if (wantLine()) {
            editorCaret.toLineSelection()
                    .normalizeCaretPosition()
                    .commit();
        }
    }
}
项目:MissingInActions    文件:SwapLastSelectionTextAction.java   
@Override
protected void doExecute(final Editor editor, @Nullable final Caret caret, final DataContext dataContext) {
    LineSelectionManager manager = LineSelectionManager.getInstance(editor);
    RangeMarker previousSelection = manager.getDummyRangeMarker();
    manager.recallLastSelection(0, true, false, true);
    RangeMarker rangeMarker = manager.getDummyRangeMarker();
    boolean handled = false;

    if (rangeMarker != null && previousSelection != null) {
        final Range range1 = new Range(rangeMarker.getStartOffset(), rangeMarker.getEndOffset());
        final Range range2 = new Range(previousSelection.getStartOffset(), previousSelection.getEndOffset());

        handled = EditHelpers.swapRangeText(editor, range1, range2);
    }

    if (!handled && previousSelection != null) {
        manager.pushSelection(true, false, false);
        editor.getSelectionModel().setSelection(previousSelection.getStartOffset(), previousSelection.getEndOffset());
        manager.recallLastSelection(0, true, true, true);
    }
}
项目:intellij-ce-playground    文件:XDebuggerUtilImpl.java   
@NotNull
public static Collection<XSourcePosition> getAllCaretsPositions(@NotNull Project project, DataContext context) {
  Editor editor = getEditor(project, context);
  if (editor == null) {
    return Collections.emptyList();
  }

  VirtualFile file = FileDocumentManager.getInstance().getFile(editor.getDocument());
  List<XSourcePosition> res = new SmartList<XSourcePosition>();
  for (Caret caret : editor.getCaretModel().getAllCarets()) {
    XSourcePositionImpl position = XSourcePositionImpl.createByOffset(file, caret.getOffset());
    if (position != null) {
      res.add(position);
    }
  }
  return res;
}
项目:MissingInActions    文件:NumberActionHandler.java   
private void perform(Editor editor, LineSelectionManager manager, Caret caret) {
    assert caret != null;

    if (caret.hasSelection()) {
        EditorCaret editorCaret = manager.getEditorCaret(caret);
        if (editorCaret.getSelectionLineCount() > 1) {
            int column = editorCaret.getCaretPosition().column;
            editorCaret.setIsStartAnchorUpdateAnchorColumn(!editorCaret.isStartAnchor());
            if (column != 0 && editorCaret.getCaretPosition().column == 0) {
                editorCaret.restoreColumn(column);
            }
            editorCaret.commit();
        } else {
            // swap start/end
            int startOffset = caret.getSelectionStart();
            int endOffset = caret.getSelectionEnd();
            if (caret.getLeadSelectionOffset() == caret.getSelectionStart()) {
                caret.moveToOffset(startOffset);
            } else {
                caret.moveToOffset(endOffset);
            }
            caret.setSelection(endOffset, startOffset);
        }
    }
}
项目:intellij-ce-playground    文件:TextMergeTool.java   
private boolean isSomeChangeSelected(@NotNull ThreeSide side) {
  EditorEx editor = getEditor(side);
  List<Caret> carets = editor.getCaretModel().getAllCarets();
  if (carets.size() != 1) return true;
  Caret caret = carets.get(0);
  if (caret.hasSelection()) return true;

  int line = editor.getDocument().getLineNumber(editor.getExpectedCaretOffset());

  List<TextMergeChange> changes = getAllChanges();
  for (TextMergeChange change : changes) {
    if (!isEnabled(change)) continue;
    int line1 = change.getStartLine(side);
    int line2 = change.getEndLine(side);

    if (DiffUtil.isSelectedByLine(line, line1, line2)) return true;
  }
  return false;
}
项目:intellij-ce-playground    文件:InjectedLanguageUtil.java   
@NotNull
public static Editor getInjectedEditorForInjectedFile(@NotNull Editor hostEditor, @NotNull Caret hostCaret, @Nullable final PsiFile injectedFile) {
  if (injectedFile == null || hostEditor instanceof EditorWindow || hostEditor.isDisposed()) return hostEditor;
  Project project = hostEditor.getProject();
  if (project == null) project = injectedFile.getProject();
  Document document = PsiDocumentManager.getInstance(project).getDocument(injectedFile);
  if (!(document instanceof DocumentWindowImpl)) return hostEditor;
  DocumentWindowImpl documentWindow = (DocumentWindowImpl)document;
  if (hostCaret.hasSelection()) {
    int selstart = hostCaret.getSelectionStart();
    if (selstart != -1) {
      int selend = Math.max(selstart, hostCaret.getSelectionEnd());
      if (!documentWindow.containsRange(selstart, selend)) {
        // selection spreads out the injected editor range
        return hostEditor;
      }
    }
  }
  if (!documentWindow.isValid()) {
    return hostEditor; // since the moment we got hold of injectedFile and this moment call, document may have been dirtied
  }
  return EditorWindowImpl.create(documentWindow, (EditorImpl)hostEditor, injectedFile);
}
项目:intellij-ce-playground    文件:NextPrevWordHandler.java   
@Override
protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  assert caret != null;
  VisualPosition currentPosition = caret.getVisualPosition();
  if (caret.isAtBidiRunBoundary() && (myNext ^ currentPosition.leansRight)) {
    int selectionStartOffset = caret.getLeadSelectionOffset();
    VisualPosition selectionStartPosition = caret.getLeadSelectionPosition();
    caret.moveToVisualPosition(currentPosition.leanRight(!currentPosition.leansRight));
    if (myWithSelection) {
      caret.setSelection(selectionStartPosition, selectionStartOffset, caret.getVisualPosition(), caret.getOffset());
    }
  }
  else {
    if (myNext ^ caret.isAtRtlLocation()) {
      EditorActionUtil.moveCaretToNextWord(editor, myWithSelection, myInDifferentHumpsMode ^ editor.getSettings().isCamelWords());
    }
    else {
      EditorActionUtil.moveCaretToPreviousWord(editor, myWithSelection, myInDifferentHumpsMode ^ editor.getSettings().isCamelWords());
    }
  }
}
项目:intellij-ce-playground    文件:MultiCaretCodeInsightAction.java   
private static void iterateOverCarets(@NotNull final Project project,
                               @NotNull final Editor hostEditor,
                               @NotNull final MultiCaretCodeInsightActionHandler handler) {
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  final PsiFile psiFile = documentManager.getCachedPsiFile(hostEditor.getDocument());
  documentManager.commitAllDocuments();

  hostEditor.getCaretModel().runForEachCaret(new CaretAction() {
    @Override
    public void perform(Caret caret) {
      Editor editor = hostEditor;
      if (psiFile != null) {
        Caret injectedCaret = InjectedLanguageUtil.getCaretForInjectedLanguageNoCommit(caret, psiFile);
        if (injectedCaret != null) {
          caret = injectedCaret;
          editor = caret.getEditor();
        }
      }
      final PsiFile file = PsiUtilBase.getPsiFileInEditor(caret, project);
      if (file != null) {
        handler.invoke(project, editor, caret, file);
      }
    }
  });
}
项目:intellij-ce-playground    文件:DuplicateLinesAction.java   
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
  if (editor.getSelectionModel().hasSelection()) {
    int selStart = editor.getSelectionModel().getSelectionStart();
    int selEnd = editor.getSelectionModel().getSelectionEnd();
    if (selEnd > selStart && DocumentUtil.isAtLineStart(selEnd, editor.getDocument())) {
      selEnd--;
    }
    VisualPosition rangeStart = editor.offsetToVisualPosition(Math.min(selStart, selEnd));
    VisualPosition rangeEnd = editor.offsetToVisualPosition(Math.max(selStart, selEnd));
    final Couple<Integer> copiedRange =
      DuplicateAction.duplicateLinesRange(editor, editor.getDocument(), rangeStart, rangeEnd);
    if (copiedRange != null) {
      editor.getSelectionModel().setSelection(copiedRange.first, copiedRange.second);
    }
  }
  else {
    VisualPosition caretPos = editor.getCaretModel().getVisualPosition();
    DuplicateAction.duplicateLinesRange(editor, editor.getDocument(), caretPos, caretPos);
  }
}
项目:intellij-ce-playground    文件:BaseFoldingHandler.java   
/**
 * Returns fold regions inside selection, or all regions in editor, if selection doesn't exist or doesn't contain fold regions.
 */
protected List<FoldRegion> getFoldRegionsForSelection(@NotNull Editor editor, @Nullable Caret caret) {
  FoldRegion[] allRegions = editor.getFoldingModel().getAllFoldRegions();
  if (caret == null) {
    caret = editor.getCaretModel().getPrimaryCaret();
  }
  if (caret.hasSelection()) {
    List<FoldRegion> result = new ArrayList<FoldRegion>();
    for (FoldRegion region : allRegions) {
      if (region.getStartOffset() >= caret.getSelectionStart() && region.getEndOffset() <= caret.getSelectionEnd()) {
        result.add(region);
      }
    }
    if (!result.isEmpty()) {
      return result;
    }
  }
  return Arrays.asList(allRegions);
}
项目:intellij-ce-playground    文件:CopyAction.java   
@Override
public void execute(final Editor editor, DataContext dataContext) {
  if (!editor.getSelectionModel().hasSelection(true)) {
    if (Registry.is(SKIP_COPY_AND_CUT_FOR_EMPTY_SELECTION_KEY)) {
      return;
    }
    editor.getCaretModel().runForEachCaret(new CaretAction() {
      @Override
      public void perform(Caret caret) {
        editor.getSelectionModel().selectLineAtCaret();
        EditorActionUtil.moveCaretToLineStartIgnoringSoftWraps(editor);
      }
    });
  }
  editor.getSelectionModel().copySelectionToClipboard();
}
项目:intellij-ce-playground    文件:CodeBlockEndAction.java   
@Override
public void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  Project project = CommonDataKeys.PROJECT.getData(dataContext);
  if (project != null) {
    CodeBlockUtil.moveCaretToCodeBlockEnd(project, editor, false);
  }
}
项目:intellij-ce-playground    文件:NextVariableAction.java   
@Override
public void executeWriteAction(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  assert templateState != null;
  CommandProcessor.getInstance().setCurrentCommandName(CodeInsightBundle.message("template.next.variable.command"));
  templateState.nextTab();
}
项目:MissingInActions    文件:ActionSelectionAdjuster.java   
private void forAllCarets(@NotNull AnActionEvent event, CaretBeforeAction runnable, @NotNull CaretAfterAction afterAction) {
    final ActionContext context = new ActionContext();

    for (Caret caret1 : myEditor.getCaretModel().getAllCarets()) {
        runnable.run(caret1, context);
    }

    myAfterActions.addAfterAction(event, () -> {
        for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
            afterAction.run(caret, context.get(caret));
        }
    });
}
项目:MissingInActions    文件:ActionSelectionAdjuster.java   
private void forAllEditorCarets(@NotNull ActionContext context, @NotNull EditorCaretBeforeAction runnable) {
    int index = 0;
    for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
        EditorCaret editorCaret = myManager.getEditorCaret(caret);
        CaretSnapshot snapshot = new CaretSnapshot(editorCaret, index++);

        if (runnable.run(editorCaret, snapshot)) {
            context.add(editorCaret, snapshot);
        }
    }
}
项目:MissingInActions    文件:ActionSelectionAdjuster.java   
private void forAllEditorCarets(@NotNull AnActionEvent event, @NotNull EditorCaretBeforeAction runnable, @NotNull EditorCaretAfterAction afterAction) {
    final ActionContext context = new ActionContext();
    forAllEditorCarets(context, runnable);

    myAfterActions.addAfterAction(event, () -> {
        for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
            afterAction.run(myManager.getEditorCaret(caret), context.get(caret));
        }
    });
}
项目:intellij-ce-playground    文件:TextEditorPsiDataProvider.java   
private static Language getLanguageAtCurrentPositionInEditor(Caret caret, final PsiFile psiFile) {
  int caretOffset = caret.getOffset();
  int mostProbablyCorrectLanguageOffset = caretOffset == caret.getSelectionStart() ||
                                          caretOffset == caret.getSelectionEnd()
                                          ? caret.getSelectionStart()
                                          : caretOffset;
  if (caret.hasSelection()) {
    return getLanguageAtOffset(psiFile, mostProbablyCorrectLanguageOffset, caret.getSelectionEnd());
  }

  return PsiUtilCore.getLanguageAtOffset(psiFile, mostProbablyCorrectLanguageOffset);
}
项目:intellij-ce-playground    文件:PrevNextParameterHandler.java   
@Override
protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  int offset = caret != null ? caret.getOffset() : editor.getCaretModel().getOffset();
  PsiElement exprList = getExpressionList(editor, offset, dataContext);
  if (exprList != null) {
    int listOffset = exprList.getTextRange().getStartOffset();
    ParameterInfoController.prevOrNextParameter(editor, listOffset, myIsNextParameterHandler);
  }
}
项目:intellij-ce-playground    文件:EndHandler.java   
@Override
public void doExecute(Editor editor, Caret caret, DataContext dataContext){
  LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(editor);
  if (lookup == null || !lookup.isFocused()) {
    myOriginalHandler.execute(editor, caret, dataContext);
    return;
  }

  lookup.markSelectionTouched();
  ScrollingUtil.moveEnd(lookup.getList());
  lookup.refreshUi(false, true);
}
项目:intellij-ce-playground    文件:ScratchFileActions.java   
@Nullable
static Language getLanguageFromCaret(@NotNull Project project,
                                     @Nullable Editor editor,
                                     @Nullable PsiFile psiFile) {
  if (editor == null || psiFile == null) return null;
  Caret caret = editor.getCaretModel().getPrimaryCaret();
  int offset = caret.getOffset();
  PsiElement element = InjectedLanguageManager.getInstance(project).findInjectedElementAt(psiFile, offset);
  PsiFile file = element != null ? element.getContainingFile() : psiFile;
  return file.getLanguage();
}
项目:intellij-ce-playground    文件:GoToEditPointAction.java   
public Forward() {
  super(new EditorActionHandler(true) {
    @Override
    protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
      EmmetEditPointUtil.moveForward(editor, getFile(dataContext));
    }
  });
}
项目:intellij-ce-playground    文件:InvokeTemplateAction.java   
public void perform() {
  final Document document = myEditor.getDocument();
  final VirtualFile file = FileDocumentManager.getInstance().getFile(document);
  if (file != null) {
    ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(file);
  }

  CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
    public void run() {
      myEditor.getCaretModel().runForEachCaret(new CaretAction() {
        public void perform(Caret caret) {
          // adjust the selection so that it starts with a non-whitespace character (to make sure that the template is inserted
          // at a meaningful position rather than at indent 0)
          if (myEditor.getSelectionModel().hasSelection() && myTemplate.isToReformat()) {
            int offset = myEditor.getSelectionModel().getSelectionStart();
            int selectionEnd = myEditor.getSelectionModel().getSelectionEnd();
            int lineEnd = document.getLineEndOffset(document.getLineNumber(offset));
            while (offset < lineEnd && offset < selectionEnd &&
                   (document.getCharsSequence().charAt(offset) == ' ' || document.getCharsSequence().charAt(offset) == '\t')) {
              offset++;
            }
            // avoid extra line break after $SELECTION$ in case when selection ends with a complete line
            if (selectionEnd == document.getLineStartOffset(document.getLineNumber(selectionEnd))) {
              selectionEnd--;
            }
            if (offset < lineEnd && offset < selectionEnd) {  // found non-WS character in first line of selection
              myEditor.getSelectionModel().setSelection(offset, selectionEnd);
            }
          }
          String selectionString = myEditor.getSelectionModel().getSelectedText();
          TemplateManager.getInstance(myProject).startTemplate(myEditor, selectionString, myTemplate);
        }
      });
    }
  }, "Wrap with template", "Wrap with template " + myTemplate.getKey());
}
项目:intellij-ce-playground    文件:EnterHandler.java   
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
  final Project project = editor.getProject();
  if (project != null && TemplateManager.getInstance(project).startTemplate(editor, TemplateSettings.ENTER_CHAR)) {
    return;
  }

  if (myOriginalHandler != null) {
    myOriginalHandler.execute(editor, caret, dataContext);
  }
}
项目:intellij-ce-playground    文件:InjectedLanguageUtil.java   
/**
 * Invocation of this method on uncommitted <code>file</code> can lead to unexpected results, including throwing an exception!
 */
public static Editor getEditorForInjectedLanguageNoCommit(@Nullable Editor editor, @Nullable Caret caret, @Nullable PsiFile file) {
  if (editor == null || file == null || editor instanceof EditorWindow || caret == null) return editor;

  PsiFile injectedFile = findInjectedPsiNoCommit(file, caret.getOffset());
  return getInjectedEditorForInjectedFile(editor, caret, injectedFile);
}
项目:intellij-ce-playground    文件:GoToEditPointAction.java   
public Backward() {
  super(new EditorActionHandler(true) {
    @Override
    protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
      EmmetEditPointUtil.moveBackward(editor, getFile(dataContext));
    }
  });
}
项目:MissingInActions    文件:PatternSearchCaretHandler.java   
protected boolean perform(@NotNull LineSelectionManager manager, @NotNull Caret caret, @NotNull Range range, @NotNull ArrayList<CaretState> createCarets) {
    Editor editor = caret.getEditor();
    final BasedSequence chars = BasedSequenceImpl.of(editor.getDocument().getCharsSequence());
    boolean keepCaret = !isMoveFirstMatch();

    T matcher = prepareMatcher(manager, caret, range, chars);
    if (matcher != null) {
        // forward search withing range in document
        CaretMatch lastMatch = null;
        while (true) {
            CaretMatch match = nextMatch(matcher, chars, range, lastMatch);
            if (match == null) break;

            // found it, create or move caret here
            if (!keepCaret) {
                keepCaret = true;
                if (isMoveFirstMatch()) {
                    caret.moveToOffset(match.caretOffset);
                    caret.setSelection(match.selectionStart, match.selectionEnd);
                }
            } else {
                // create a new position if caret moved
                LogicalPosition offset = editor.offsetToLogicalPosition(match.caretOffset);
                LogicalPosition startOffset = editor.offsetToLogicalPosition(match.selectionStart);
                LogicalPosition endOffset = editor.offsetToLogicalPosition(match.selectionEnd);
                CaretState caretState = new CaretState(offset, startOffset, endOffset);
                createCarets.add(caretState);
            }

            if (isSingleMatch() || match.caretOffset + match.matchLength >= chars.length()) break;
            lastMatch = match;
        }
    }

    return keepCaret || isSingleMatch();
}
项目:MissingInActions    文件:StraightenCaretsAction.java   
@Override
public void actionPerformed(AnActionEvent e) {
    final EditorEx editor = getEditor(e);
    final CaretModel caretModel = editor.getCaretModel();
    final DocumentEx doc = editor.getDocument();

    if (caretModel.getCaretCount() > 1 && !editor.getSelectionModel().hasSelection()) {
        // move all carets to column of primary
        int column = caretModel.getPrimaryCaret().getLogicalPosition().column;
        for (Caret caret : caretModel.getAllCarets()) {
            caret.moveToLogicalPosition(new LogicalPosition(doc.getLineNumber(caret.getOffset()), column));
        }
    }
}
项目:MissingInActions    文件:ToLineOrCharacterSelectionTypeActionHandler.java   
@Override
public void doExecute(final Editor editor, final @Nullable Caret caret, final DataContext dataContext) {
    final LineSelectionManager manager = LineSelectionManager.getInstance(editor);
    manager.guard(() -> {
        if (!editor.getCaretModel().supportsMultipleCarets()) {
            perform(editor, manager, caret);
        } else {
            if (caret == null) {
                editor.getCaretModel().runForEachCaret(caret1 -> perform(editor, manager, caret1));
            } else {
                perform(editor, manager, caret);
            }
        }
    });
}
项目:MissingInActions    文件:AbstractNextOrPrevWordHandler.java   
@Override
protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
    assert caret != null;

    boolean withSelection = isWithSelection();
    boolean isNext = isNext();
    boolean differentHumpsMode = isInDifferentHumpsMode();
    int boundaryFlags = getBoundaryFlags();

    if (EditHelpers.isPasswordEditor(editor)) {
        int selectionStartOffset = caret.getLeadSelectionOffset();
        caret.moveToOffset(isNext ? editor.getDocument().getTextLength() : 0);
        if (withSelection) caret.setSelection(selectionStartOffset, caret.getOffset());
    } else {
        VisualPosition currentPosition = caret.getVisualPosition();
        if (caret.isAtBidiRunBoundary() && (isNext ^ currentPosition.leansRight)) {
            int selectionStartOffset = caret.getLeadSelectionOffset();
            VisualPosition selectionStartPosition = caret.getLeadSelectionPosition();
            caret.moveToVisualPosition(currentPosition.leanRight(!currentPosition.leansRight));
            if (withSelection) {
                caret.setSelection(selectionStartPosition, selectionStartOffset, caret.getVisualPosition(), caret.getOffset());
            }
        } else {
            if (isNext ^ caret.isAtRtlLocation()) {
                EditHelpers.moveCaretToNextWordStartOrEnd(editor, withSelection, differentHumpsMode ^ editor.getSettings().isCamelWords(), boundaryFlags);
            } else {
                EditHelpers.moveCaretToPreviousWordStartOrEnd(editor, withSelection, differentHumpsMode ^ editor.getSettings().isCamelWords(), boundaryFlags);
            }
        }
    }
}
项目:intellij-ce-playground    文件:CommentByBlockCommentAction.java   
@Override
protected boolean isValidFor(@NotNull Project project, @NotNull Editor editor, @NotNull Caret caret, @NotNull final PsiFile file) {
  final FileType fileType = file.getFileType();
  if (fileType instanceof AbstractFileType) {
    return ((AbstractFileType)fileType).getCommenter() != null;
  }

  Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(file.getLanguage());
  if (commenter == null) commenter = LanguageCommenters.INSTANCE.forLanguage(file.getViewProvider().getBaseLanguage());
  if (commenter == null) return false;
  return commenter.getBlockCommentPrefix() != null && commenter.getBlockCommentSuffix() != null;
}
项目:intellij-ce-playground    文件:TextEditorPsiDataProvider.java   
private Language[] computeLanguages(@NotNull Editor editor, @NotNull Caret caret) {
  LinkedHashSet<Language> set = new LinkedHashSet<Language>(4);
  Language injectedLanguage = (Language)getData(injectedId(LANGUAGE.getName()), editor, caret);
  addIfNotNull(injectedLanguage, set);
  Language language = (Language)getData(LANGUAGE.getName(), editor, caret);
  addIfNotNull(language, set);
  PsiFile psiFile = (PsiFile)getData(PSI_FILE.getName(), editor, caret);
  if (psiFile != null) {
    addIfNotNull(psiFile.getViewProvider().getBaseLanguage(), set);
  }
  return set.toArray(new Language[set.size()]);
}
项目:intellij-ce-playground    文件:CollapseRegionAction.java   
public CollapseRegionAction() {
  super(new BaseFoldingHandler() {
    @Override
    public void doExecute(final Editor editor, @Nullable Caret caret, DataContext dataContext) {
      CodeFoldingManager foldingManager = CodeFoldingManager.getInstance(editor.getProject());
      foldingManager.updateFoldRegions(editor);

      final int line = editor.getCaretModel().getLogicalPosition().line;

      Runnable processor = new Runnable() {
        @Override
        public void run() {
          FoldRegion region = FoldingUtil.findFoldRegionStartingAtLine(editor, line);
          if (region != null && region.isExpanded()){
            region.setExpanded(false);
          }
          else {
            int offset = editor.getCaretModel().getOffset();
            FoldRegion[] regions = FoldingUtil.getFoldRegionsAtOffset(editor, offset);
            for (FoldRegion region1 : regions) {
              if (region1.isExpanded()) {
                region1.setExpanded(false);
                break;
              }
            }
          }
        }
      };
      editor.getFoldingModel().runBatchFoldingOperation(processor);
    }
  });
}
项目:intellij-ce-playground    文件:ForwardParagraphAction.java   
@Override
protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  assert  caret != null;

  Document document = editor.getDocument();
  int currentLine = caret.getLogicalPosition().line;
  int lineCount = document.getLineCount();

  if (isLineEmpty(document, currentLine)) {
    while (++currentLine < lineCount) {
      if (!isLineEmpty(document, currentLine)) {
        break;
      }
    }
  }

  int targetOffset = document.getTextLength();
  while (++currentLine < lineCount) {
    if (isLineEmpty(document, currentLine)) {
      targetOffset = document.getLineStartOffset(currentLine);
      break;
    }
  }

  caret.removeSelection();
  caret.moveToOffset(targetOffset);
  EditorModificationUtil.scrollToCaret(editor);
}
项目:intellij-ce-playground    文件:UnselectPreviousOccurrenceAction.java   
@Override
public void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  if (editor.getCaretModel().getCaretCount() > 1) {
    editor.getCaretModel().removeCaret(editor.getCaretModel().getPrimaryCaret());
  }
  else {
    editor.getSelectionModel().removeSelection();
  }
  getAndResetNotFoundStatus(editor);
  editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}