com.intellij.openapi.editor.Caret Java Examples

The following examples show how to use com.intellij.openapi.editor.Caret. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FocusModeModel.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void applyFocusMode(@Nonnull Caret caret) {
  // Focus mode should not be applied when idea is used as rd server (for example, centaur mode).
  if (ApplicationManager.getApplication().isHeadlessEnvironment() && !ApplicationManager.getApplication().isUnitTestMode()) return;

  RangeMarkerEx[] startRange = new RangeMarkerEx[1];
  RangeMarkerEx[] endRange = new RangeMarkerEx[1];
  myFocusMarkerTree.processContaining(caret.getSelectionStart(), startMarker -> {
    if (startRange[0] == null || startRange[0].getStartOffset() < startMarker.getStartOffset()) {
      startRange[0] = startMarker;
    }
    return true;
  });
  myFocusMarkerTree.processContaining(caret.getSelectionEnd(), endMarker -> {
    if (endRange[0] == null || endRange[0].getEndOffset() > endMarker.getEndOffset()) {
      endRange[0] = endMarker;
    }
    return true;
  });

  clearFocusMode();
  if (startRange[0] != null && endRange[0] != null) {
    applyFocusMode(enlargeFocusRangeIfNeeded(new TextRange(startRange[0].getStartOffset(), endRange[0].getEndOffset())));
  }
}
 
Example #2
Source File: DeleteInColumnModeHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  if (editor.isColumnMode() && caret == null && editor.getCaretModel().getCaretCount() > 1) {
    EditorUIUtil.hideCursorInEditor(editor);
    CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
    CopyPasteManager.getInstance().stopKillRings();

    editor.getCaretModel().runForEachCaret(c -> {
      int offset = c.getOffset();
      int lineEndOffset = DocumentUtil.getLineEndOffset(offset, editor.getDocument());
      if (offset < lineEndOffset) myOriginalHandler.execute(editor, c, dataContext);
    });
  }
  else {
    myOriginalHandler.execute(editor, caret, dataContext);
  }
}
 
Example #3
Source File: ConvertIndentsActionBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(final Editor editor, @Nullable Caret caret, DataContext dataContext) {
  final SelectionModel selectionModel = editor.getSelectionModel();
  int changedLines = 0;
  if (selectionModel.hasSelection()) {
    changedLines = performAction(editor, new TextRange(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()));
  }
  else {
    changedLines += performAction(editor, new TextRange(0, editor.getDocument().getTextLength()));
  }
  if (changedLines == 0) {
    HintManager.getInstance().showInformationHint(editor, "All lines already have requested indentation");
  }
  else {
    HintManager.getInstance().showInformationHint(editor, "Changed indentation in " + changedLines + (changedLines == 1 ? " line" : " lines"));
  }
}
 
Example #4
Source File: CsvHighlightUsagesHandler.java    From intellij-csv-validator with Apache License 2.0 6 votes vote down vote up
@Override
public List<PsiElement> getTargets() {
    if (!this.myEditor.getSelectionModel().hasSelection()) {
        return Collections.emptyList();
    }

    Caret primaryCaret = this.myEditor.getCaretModel().getPrimaryCaret();
    PsiElement myFocusedElement = this.myFile.getViewProvider().findElementAt(primaryCaret.getOffset());
    if (myFocusedElement == null) {
        myFocusedElement = this.myFile.getLastChild();
    }
    myFocusedElement = CsvHelper.getParentFieldElement(myFocusedElement);

    if (myFocusedElement == null) {
        return Collections.emptyList();
    }

    return Collections.singletonList(myFocusedElement);
}
 
Example #5
Source File: DeleteToWordEndAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
  CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
  CopyPasteManager.getInstance().stopKillRings();

  int lineNumber = editor.getCaretModel().getLogicalPosition().line;
  if (editor.isColumnMode() && editor.getCaretModel().supportsMultipleCarets()
      && editor.getCaretModel().getOffset() == editor.getDocument().getLineEndOffset(lineNumber)) {
    return;
  }

  boolean camelMode = editor.getSettings().isCamelWords();
  if (myNegateCamelMode) {
    camelMode = !camelMode;
  }
  deleteToWordEnd(editor, camelMode);
}
 
Example #6
Source File: PreviewView.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void applyEditorSelectionToTree(Caret caret) {
  final List<FlutterOutline> selectedOutlines = new ArrayList<>();

  // Try to find outlines covered by the selection.
  addOutlinesCoveredByRange(selectedOutlines, caret.getSelectionStart(), caret.getSelectionEnd(), currentOutline);

  // If no covered outlines, try to find the outline under the caret.
  if (selectedOutlines.isEmpty()) {
    final FlutterOutline outline = getOutlineOffsetConverter().findOutlineAtOffset(currentOutline, caret.getOffset());
    if (outline != null) {
      selectedOutlines.add(outline);
    }
  }

  activeOutlines.setValue(selectedOutlines);

  applyOutlinesSelectionToTree(selectedOutlines);

  // TODO(jacobr): refactor the previewArea to listen on the stream of
  // selected outlines instead.
  if (previewArea != null) {
    previewArea.select(selectedOutlines, currentEditor);
  }
}
 
Example #7
Source File: PreviewView.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void applyEditorSelectionToTree(Caret caret) {
  final List<FlutterOutline> selectedOutlines = new ArrayList<>();

  // Try to find outlines covered by the selection.
  addOutlinesCoveredByRange(selectedOutlines, caret.getSelectionStart(), caret.getSelectionEnd(), currentOutline);

  // If no covered outlines, try to find the outline under the caret.
  if (selectedOutlines.isEmpty()) {
    final FlutterOutline outline = getOutlineOffsetConverter().findOutlineAtOffset(currentOutline, caret.getOffset());
    if (outline != null) {
      selectedOutlines.add(outline);
    }
  }

  activeOutlines.setValue(selectedOutlines);

  applyOutlinesSelectionToTree(selectedOutlines);

  // TODO(jacobr): refactor the previewArea to listen on the stream of
  // selected outlines instead.
  if (previewArea != null) {
    previewArea.select(selectedOutlines, currentEditor);
  }
}
 
Example #8
Source File: BaseFoldingHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * 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(@Nonnull 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<>();
    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);
}
 
Example #9
Source File: PasteImageHandler.java    From pasteimages with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void doExecute(@NotNull final Editor editor, Caret caret, final DataContext dataContext) {
    if (editor instanceof EditorEx) {
        VirtualFile virtualFile = ((EditorEx) editor).getVirtualFile();
        if (virtualFile != null) {
            FileType fileType = virtualFile.getFileType();
            if ("Markdown".equals(fileType.getName())) {
                Image imageFromClipboard = ImageUtils.getImageFromClipboard();
                if (imageFromClipboard != null) {
                    assert caret == null : "Invocation of 'paste' operation for specific caret is not supported";
                    PasteImageFromClipboard action = new PasteImageFromClipboard();
                    AnActionEvent event = createAnEvent(action, dataContext);
                    action.actionPerformed(event);
                    return;
                }
            }
        }
    }

    if (myOriginalHandler != null) {
        myOriginalHandler.execute(editor, null, dataContext);
    }
}
 
Example #10
Source File: PsiUtilBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static PsiFile getPsiFileInEditor(@Nonnull Caret caret, @Nonnull final Project project) {
  Editor editor = caret.getEditor();
  final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  if (file == null) return null;

  PsiUtilCore.ensureValid(file);

  final Language language = getLanguageInEditor(caret, project);
  if (language == null) return file;

  if (language == file.getLanguage()) return file;

  int caretOffset = caret.getOffset();
  int mostProbablyCorrectLanguageOffset = caretOffset == caret.getSelectionEnd() ? caret.getSelectionStart() : caretOffset;
  return getPsiFileAtOffset(file, mostProbablyCorrectLanguageOffset);
}
 
Example #11
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Invocation of this method on uncommitted {@code file} can lead to unexpected results, including throwing an exception!
 */
public static Caret getCaretForInjectedLanguageNoCommit(@Nullable Caret caret, @Nullable PsiFile file) {
  if (caret == null || file == null || caret instanceof InjectedCaret) return caret;

  PsiFile injectedFile = findInjectedPsiNoCommit(file, caret.getOffset());
  Editor injectedEditor = getInjectedEditorForInjectedFile(caret.getEditor(), injectedFile);
  if (!(injectedEditor instanceof EditorWindow)) {
    return caret;
  }
  for (Caret injectedCaret : injectedEditor.getCaretModel().getAllCarets()) {
    if (((InjectedCaret)injectedCaret).getDelegate() == caret) {
      return injectedCaret;
    }
  }
  return null;
}
 
Example #12
Source File: CompletionInitializationUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static CompletionInitializationContextImpl runContributorsBeforeCompletion(Editor editor, PsiFile psiFile, int invocationCount, @Nonnull Caret caret, CompletionType completionType) {
  final Ref<CompletionContributor> current = Ref.create(null);
  CompletionInitializationContextImpl context = new CompletionInitializationContextImpl(editor, caret, psiFile, completionType, invocationCount) {
    CompletionContributor dummyIdentifierChanger;

    @Override
    public void setDummyIdentifier(@Nonnull String dummyIdentifier) {
      super.setDummyIdentifier(dummyIdentifier);

      if (dummyIdentifierChanger != null) {
        LOG.error("Changing the dummy identifier twice, already changed by " + dummyIdentifierChanger);
      }
      dummyIdentifierChanger = current.get();
    }
  };
  Project project = psiFile.getProject();
  for (final CompletionContributor contributor : CompletionContributor.forLanguageHonorDumbness(context.getPositionLanguage(), project)) {
    current.set(contributor);
    contributor.beforeCompletion(context);
    CompletionAssertions.checkEditorValid(editor);
    assert !PsiDocumentManager.getInstance(project).isUncommited(editor.getDocument()) : "Contributor " + contributor + " left the document uncommitted";
  }
  return context;
}
 
Example #13
Source File: EditorActionHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Executes the action in the context of given caret. If the caret is {@code null}, and the handler is a 'per-caret' handler,
 * it's executed for all carets.
 *
 * @param editor      the editor in which the action is invoked.
 * @param dataContext the data context for the action.
 */
public final void execute(@Nonnull Editor editor, @Nullable final Caret contextCaret, final DataContext dataContext) {
  Editor hostEditor = dataContext == null ? null : dataContext.getData(CommonDataKeys.HOST_EDITOR);
  if (hostEditor == null) {
    hostEditor = editor;
  }
  if (contextCaret == null && runForAllCarets()) {
    hostEditor.getCaretModel().runForEachCaret(caret -> {
      if (myWorksInInjected) ensureInjectionUpToDate(caret);
      doIfEnabled(caret, dataContext, (caret1, dc) -> doExecute(caret1.getEditor(), caret1, dc));
    });
  }
  else {
    if (contextCaret == null) {
      if (myWorksInInjected) ensureInjectionUpToDate(hostEditor.getCaretModel().getCurrentCaret());
      doIfEnabled(hostEditor.getCaretModel().getCurrentCaret(), dataContext, (caret, dc) -> doExecute(caret.getEditor(), null, dc));
    }
    else {
      doExecute(editor, contextCaret, dataContext);
    }
  }
}
 
Example #14
Source File: AbstractStringManipAction.java    From StringManipulation with Apache License 2.0 6 votes vote down vote up
protected void executeMyWriteActionPerCaret(Editor editor, Caret caret, Map<String, Object> actionContext, DataContext dataContext, T additionalParam) {
final SelectionModel selectionModel = editor.getSelectionModel();
String selectedText = selectionModel.getSelectedText();

if (selectedText == null) {
	selectSomethingUnderCaret(editor, dataContext, selectionModel);
	selectedText = selectionModel.getSelectedText();

	if (selectedText == null) {
		return;
	}
}

String s = transformSelection(editor, actionContext, dataContext, selectedText, additionalParam);
s = s.replace("\r\n", "\n");
s = s.replace("\r", "\n");
      editor.getDocument().replaceString(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd(), s);
  }
 
Example #15
Source File: SortLinesBySubSelectionAction.java    From StringManipulation with Apache License 2.0 6 votes vote down vote up
public void filterCarets(Editor editor, List<CaretState> caretsAndSelections) {
	int previousLineNumber = -1;
	Iterator<CaretState> iterator = caretsAndSelections.iterator();
	while (iterator.hasNext()) {
		CaretState caretsAndSelection = iterator.next();
		LogicalPosition caretPosition = caretsAndSelection.getCaretPosition();
		int lineNumber = editor.getDocument().getLineNumber(
				editor.logicalPositionToOffset(caretPosition));
		if (lineNumber == previousLineNumber) {
			Caret caret = getCaretAt(editor, caretsAndSelection.getCaretPosition());
			editor.getCaretModel().removeCaret(caret);
			iterator.remove();
		}
		previousLineNumber = lineNumber;
	}
}
 
Example #16
Source File: TextMergeViewer.java    From consulo with Apache License 2.0 6 votes vote down vote up
private boolean isSomeChangeSelected(@Nonnull 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;
}
 
Example #17
Source File: BackspaceHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void doExecute(@Nonnull final Editor editor, Caret caret, final DataContext dataContext) {
  LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(editor);
  if (lookup == null) {
    myOriginalHandler.execute(editor, caret, dataContext);
    return;
  }

  int hideOffset = lookup.getLookupStart();
  int originalStart = lookup.getLookupOriginalStart();
  if (originalStart >= 0 && originalStart <= hideOffset) {
    hideOffset = originalStart - 1;
  }

  truncatePrefix(dataContext, lookup, myOriginalHandler, hideOffset, caret);
}
 
Example #18
Source File: MyEditorWriteActionHandler.java    From dummytext-plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected final void doExecute(@NotNull final Editor editor, @Nullable final Caret caret, final DataContext dataContext) {
    MyApplicationComponent.setAction(actionClass);

    final Pair<Boolean, T> additionalParameter = beforeWriteAction(editor, dataContext);
    if (!additionalParameter.first) {
        return;
    }

    final Runnable runnable = () -> executeWriteAction(editor, caret, dataContext, additionalParameter.second);
    new EditorWriteActionHandler(false) {
        @Override
        public void executeWriteAction(Editor editor1, @Nullable Caret caret1, DataContext dataContext1) {
            runnable.run();
        }
    }.doExecute(editor, caret, dataContext);
}
 
Example #19
Source File: CompletionInitializationUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
static CompletionInitializationContextImpl createCompletionInitializationContext(@Nonnull Project project,
                                                                                 @Nonnull Editor editor,
                                                                                 @Nonnull Caret caret,
                                                                                 int invocationCount,
                                                                                 CompletionType completionType) {
  return WriteAction.compute(() -> {
    EditorUtil.fillVirtualSpaceUntilCaret(editor);
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    CompletionAssertions.checkEditorValid(editor);

    final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(caret, project);
    assert psiFile != null : "no PSI file: " + FileDocumentManager.getInstance().getFile(editor.getDocument());
    psiFile.putUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING, Boolean.TRUE);
    CompletionAssertions.assertCommitSuccessful(editor, psiFile);

    return runContributorsBeforeCompletion(editor, psiFile, invocationCount, caret, completionType);
  });
}
 
Example #20
Source File: PreviousVariableAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  assert templateState != null;
  CommandProcessor.getInstance().setCurrentCommandName(CodeInsightBundle.message("template.previous.variable.command"));
  templateState.previousTab();
}
 
Example #21
Source File: UnselectPreviousOccurrenceAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #22
Source File: EditorActionHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the action in the context of given caret. Subclasses should override this method.
 *
 * @param editor      the editor in which the action is invoked.
 * @param caret       the caret for which the action is performed at the moment, or {@code null} if it's a 'one-off' action executed
 *                    without current context
 * @param dataContext the data context for the action.
 */
protected void doExecute(@Nonnull Editor editor, @Nullable Caret caret, DataContext dataContext) {
  if (inExecution) {
    return;
  }
  try {
    inExecution = true;
    //noinspection deprecation
    execute(editor, dataContext);
  }
  finally {
    inExecution = false;
  }
}
 
Example #23
Source File: EditorActionHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Implementations can override this method to define whether handler is enabled for a specific caret in a given editor.
 */
protected boolean isEnabledForCaret(@Nonnull Editor editor, @Nonnull Caret caret, DataContext dataContext) {
  if (inCheck) {
    return true;
  }
  inCheck = true;
  try {
    //noinspection deprecation
    return isEnabled(editor, dataContext);
  }
  finally {
    inCheck = false;
  }
}
 
Example #24
Source File: PasteAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
  TextRange range = null;
  if (myTransferable != null) {
    TextRange[] ranges = EditorCopyPasteHelper.getInstance().pasteTransferable(editor, myTransferable);
    if (ranges != null && ranges.length == 1) {
      range = ranges[0];
    }
  }
  editor.putUserData(EditorEx.LAST_PASTED_REGION, range);
}
 
Example #25
Source File: EditorActionHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
static boolean ensureInjectionUpToDate(@Nonnull Caret hostCaret) {
  Editor editor = hostCaret.getEditor();
  Project project = editor.getProject();
  if (project != null && InjectedLanguageManager.getInstance(project).mightHaveInjectedFragmentAtOffset(editor.getDocument(), hostCaret.getOffset())) {
    PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    return true;
  }
  return false;
}
 
Example #26
Source File: EditorActionHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void doIfEnabled(@Nonnull Caret hostCaret, @Nullable DataContext context, @Nonnull CaretTask task) {
  DataContext caretContext = context == null ? null : new CaretSpecificDataContext(context, hostCaret);
  Editor editor = hostCaret.getEditor();
  if (myWorksInInjected && caretContext != null) {
    DataContext injectedCaretContext = AnActionEvent.getInjectedDataContext(caretContext);
    Caret injectedCaret = injectedCaretContext.getData(CommonDataKeys.CARET);
    if (injectedCaret != null && injectedCaret != hostCaret && isEnabledForCaret(injectedCaret.getEditor(), injectedCaret, injectedCaretContext)) {
      task.perform(injectedCaret, injectedCaretContext);
      return;
    }
  }
  if (isEnabledForCaret(editor, hostCaret, caretContext)) {
    task.perform(hostCaret, caretContext);
  }
}
 
Example #27
Source File: SimpleDiffViewer.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected boolean isSomeChangeSelected(@Nonnull Side side) {
  if (myDiffChanges.isEmpty()) return false;

  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());

  for (SimpleDiffChange change : myDiffChanges) {
    if (change.isSelectedByLine(line, side)) return true;
  }
  return false;
}
 
Example #28
Source File: StartNewLineAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
  CopyPasteManager.getInstance().stopKillRings();
  if (editor.getDocument().getLineCount() != 0) {
    editor.getSelectionModel().removeSelection();
    LogicalPosition caretPosition = editor.getCaretModel().getLogicalPosition();
    int lineEndOffset = editor.getDocument().getLineEndOffset(caretPosition.line);
    editor.getCaretModel().moveToOffset(lineEndOffset);
  }

  getEnterHandler().execute(editor, caret, dataContext);
}
 
Example #29
Source File: RollbackLineStatusAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected static boolean isSomeChangeSelected(@Nonnull Editor editor, @Nonnull LineStatusTracker tracker) {
  List<Caret> carets = editor.getCaretModel().getAllCarets();
  if (carets.size() != 1) return true;
  Caret caret = carets.get(0);
  if (caret.hasSelection()) return true;
  if (caret.getOffset() == editor.getDocument().getTextLength() &&
      tracker.getRangeForLine(editor.getDocument().getLineCount()) != null) {
    return true;
  }
  return tracker.getRangeForLine(caret.getLogicalPosition().line) != null;
}
 
Example #30
Source File: InvokeTemplateAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
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() {
    @Override
    public void run() {
      myEditor.getCaretModel().runForEachCaret(new CaretAction() {
        @Override
        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());
}