Java Code Examples for com.intellij.openapi.editor.Caret#hasSelection()

The following examples show how to use com.intellij.openapi.editor.Caret#hasSelection() . 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: 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 2
Source File: DeleteSelectionHandler.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 (caret == null ? editor.getSelectionModel().hasSelection(true) : caret.hasSelection()) {
    EditorUIUtil.hideCursorInEditor(editor);
    CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
    CopyPasteManager.getInstance().stopKillRings();
    CaretAction action = c -> EditorModificationUtil.deleteSelectedText(editor);
    if (caret == null) {
      editor.getCaretModel().runForEachCaret(action);
    }
    else {
      action.perform(caret);
    }
  }
  else {
    myOriginalHandler.execute(editor, caret, dataContext);
  }
}
 
Example 3
Source File: PsiUtilBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static Language getLanguageInEditor(@Nonnull Caret caret, @Nonnull final Project project) {
  Editor editor = caret.getEditor();
  PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  if (file == null) return null;

  int caretOffset = caret.getOffset();
  int mostProbablyCorrectLanguageOffset = caretOffset == caret.getSelectionEnd() ? caret.getSelectionStart() : caretOffset;
  PsiElement elt = getElementAtOffset(file, mostProbablyCorrectLanguageOffset);
  Language lang = findLanguageFromElement(elt);

  if (caret.hasSelection()) {
    final Language rangeLanguage = evaluateLanguageInRange(caret.getSelectionStart(), caret.getSelectionEnd(), file);
    if (rangeLanguage == null) return file.getLanguage();

    lang = rangeLanguage;
  }

  return narrowLanguage(lang, file.getLanguage());
}
 
Example 4
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 5
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static Editor getInjectedEditorForInjectedFile(@Nonnull Editor hostEditor, @Nonnull 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, (DesktopEditorImpl)hostEditor, injectedFile);
}
 
Example 6
Source File: DelimitedListAction.java    From StringManipulation with Apache License 2.0 5 votes vote down vote up
protected String getSelectedText(Caret caret) {
	final String originalText;
	if (caret.hasSelection()) {
		originalText = caret.getSelectedText() + "";//avoid null value
	} else {
		originalText = "";
	}
	return originalText;
}
 
Example 7
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 8
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 9
Source File: TextEditorPsiDataProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 10
Source File: SelectAllOccurrencesAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void doExecute(Editor editor, @Nullable Caret c, DataContext dataContext) {
  Caret caret = c == null ? editor.getCaretModel().getPrimaryCaret() : c;

  if (!caret.hasSelection()) {
    TextRange wordSelectionRange = getSelectionRange(editor, caret);
    if (wordSelectionRange != null) {
      setSelection(editor, caret, wordSelectionRange);
    }
  }

  String selectedText = caret.getSelectedText();
  Project project = editor.getProject();
  if (project == null || selectedText == null) {
    return;
  }

  int caretShiftFromSelectionStart = caret.getOffset() - caret.getSelectionStart();
  FindManager findManager = FindManager.getInstance(project);

  FindModel model = new FindModel();
  model.setStringToFind(selectedText);
  model.setCaseSensitive(true);
  model.setWholeWordsOnly(true);

  int searchStartOffset = 0;
  FindResult findResult = findManager.findString(editor.getDocument().getCharsSequence(), searchStartOffset, model);
  while (findResult.isStringFound()) {
    int newCaretOffset = caretShiftFromSelectionStart + findResult.getStartOffset();
    EditorActionUtil.makePositionVisible(editor, newCaretOffset);
    Caret newCaret = editor.getCaretModel().addCaret(editor.offsetToVisualPosition(newCaretOffset));
    if (newCaret != null) {
      setSelection(editor, newCaret, findResult);
    }
    findResult = findManager.findString(editor.getDocument().getCharsSequence(), findResult.getEndOffset(), model);
  }
  editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
 
Example 11
Source File: QueryAction.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
    Analytics.event("query", getQueryExecutionAction(e));

    Project project = getEventProject(e);
    Editor editor = e.getData(CommonDataKeys.EDITOR_EVEN_IF_INACTIVE);
    PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);

    if (isNull(project)) {
        Notifier.error(QUERY_EXECUTION_ERROR_TITLE, NO_PROJECT_PRESENT_MESSAGE);
        return;
    }
    if (isNull(editor)) {
        Notifier.error(QUERY_EXECUTION_ERROR_TITLE, NO_EDITOR_PRESENT_MESSAGE);
        return;
    }

    String query = null;
    String analyticsEvent;
    Map<String, Object> parameters = Collections.emptyMap();
    if (preSetQuery == null) {
        Caret caret = editor.getCaretModel().getPrimaryCaret();
        analyticsEvent = caret.hasSelection() ? CONTENT_FROM_SELECT_ACTION : CONTENT_FROM_CARET_ACTION;

        if (caret.hasSelection()) {
            query = caret.getSelectedText();
        } else if (nonNull(psiFile)) {
            String languageId = psiFile.getLanguage().getID();
            if (isSupported(languageId)) {
                PsiElement cypherStatement = getCypherStatementAtOffset(psiFile, caret.getOffset());
                if (nonNull(cypherStatement)) {
                    query = cypherStatement.getText();
                    parameters = getParametersFromQuery(cypherStatement, project, editor);
                }
            }
        }
    } else {
        analyticsEvent = CONTENT_FROM_LINE_MARKER_ACTION;
        query = preSetQuery.getText();
        parameters = getParametersFromQuery(preSetQuery, project, editor);
    }

    Analytics.event("query-content", analyticsEvent);

    if (isNull(query)) {
        Notifier.error(QUERY_EXECUTION_ERROR_TITLE, NO_QUERY_SELECTED_MESSAGE);
        return;
    }

    actionPerformed(e, project, editor, query, parameters);
}
 
Example 12
Source File: ActionPerformer.java    From dummytext-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * @param   event    ActionSystem event
 */
void write(final AnActionEvent event) {
    Editor editor = event.getData(PlatformDataKeys.EDITOR);

    if (editor != null) {
        final Document document = editor.getDocument();

        CaretModel caretModel = editor.getCaretModel();

        for (Caret caret : caretModel.getAllCarets()) {
            boolean hasSelection = caret.hasSelection();
            String selectedText  = caret.getSelectedText();

            String trailingCharacter    = TextualHelper.getTrailingPunctuationMark(selectedText);
            String leadingCharacters    = TextualHelper.getLeadingPreservation(selectedText);

            int amountLines     = 1;
            // applies only when replacing a single-lined selection, can be rounded up
            Integer amountWords = null;

            // Generated dummy text will replace the current selected text
            if (hasSelection && selectedText != null ) {
                int selectionLength = selectedText.length();
                if (selectionLength > 0) {
                    amountLines = TextualHelper.countLines(selectedText);
                    if (amountLines == 1) {
                        amountWords = TextualHelper.getWordCount(selectedText);
                    }
                }
            }

            // Generate and insert / replace selection with dummy text
            String dummyText  = generateText(amountLines, amountWords, leadingCharacters, trailingCharacter, selectedText).toString();

            Integer dummyTextLength = dummyText.length();
            Integer offsetStart;

            if (hasSelection) {
                // Move caret to end of selection
                offsetStart = caret.getSelectionStart();
                int offsetEnd = caret.getSelectionEnd();

                document.replaceString(offsetStart, offsetEnd, dummyText);
                caret.setSelection(offsetStart, offsetStart + dummyTextLength);
            } else {
                // Move caret to end of inserted text
                offsetStart  = caretModel.getOffset();
                dummyText   = dummyText.trim();
                document.insertString(offsetStart, dummyText);
            }
        }

    }
}
 
Example 13
Source File: CutLineActionHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  if (caret == null) {
    caret = editor.getCaretModel().getCurrentCaret();
  }
  if (!myIgnoreSelection && caret.hasSelection()) {
    delete(editor, caret, caret.getSelectionStart(), caret.getSelectionEnd());
    return;
  }

  final Document doc = editor.getDocument();
  int caretOffset = caret.getOffset();
  if ((myToLineStart && (caretOffset == 0)) || (!myToLineStart && (caretOffset >= doc.getTextLength()))) {
    return;
  }
  final int lineNumber = doc.getLineNumber(caretOffset);
  int lineEndOffset = doc.getLineEndOffset(lineNumber);
  int lineStartOffset = doc.getLineStartOffset(lineNumber);

  if (editor.isColumnMode() && editor.getCaretModel().supportsMultipleCarets()
      && caretOffset == (myToLineStart ? lineStartOffset : lineEndOffset)) {
    return;
  }

  int start;
  int end;
  if (myToLineStart) {
    start = lineStartOffset;
    end = caretOffset;
  }
  else {
    if (caretOffset >= lineEndOffset) {
      start = lineEndOffset;
      end = lineEndOffset + 1;
    }
    else {
      start = caretOffset;
      end = lineEndOffset;
      if (lineEndOffset < doc.getTextLength() && CharArrayUtil.isEmptyOrSpaces(doc.getCharsSequence(), caretOffset, lineEndOffset)) {
        end++;
      }
    }
  }

  delete(editor, caret, start, end);
}
 
Example 14
Source File: CompletionInitializationContext.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static int calcSelectionEnd(Caret caret) {
  return caret.hasSelection() ? caret.getSelectionEnd() : caret.getOffset();
}
 
Example 15
Source File: CompletionInitializationContext.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static int calcStartOffset(Caret caret) {
  return caret.hasSelection() ? caret.getSelectionStart() : caret.getOffset();
}
 
Example 16
Source File: SelectNextOccurrenceAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void doExecute(Editor editor, @Nullable Caret c, DataContext dataContext) {
  Caret caret = c == null ? editor.getCaretModel().getPrimaryCaret() : c;
  TextRange wordSelectionRange = getSelectionRange(editor, caret);
  boolean notFoundPreviously = getAndResetNotFoundStatus(editor);
  boolean wholeWordSearch = isWholeWordSearch(editor);
  if (caret.hasSelection()) {
    Project project = editor.getProject();
    String selectedText = caret.getSelectedText();
    if (project == null || selectedText == null) {
      return;
    }
    FindManager findManager = FindManager.getInstance(project);

    FindModel model = new FindModel();
    model.setStringToFind(selectedText);
    model.setCaseSensitive(true);
    model.setWholeWordsOnly(wholeWordSearch);

    int searchStartOffset = notFoundPreviously ? 0 : caret.getSelectionEnd();
    FindResult findResult = findManager.findString(editor.getDocument().getCharsSequence(), searchStartOffset, model);
    if (findResult.isStringFound()) {
      int newCaretOffset = caret.getOffset() - caret.getSelectionStart() + findResult.getStartOffset();
      EditorActionUtil.makePositionVisible(editor, newCaretOffset);
      Caret newCaret = editor.getCaretModel().addCaret(editor.offsetToVisualPosition(newCaretOffset));
      if (newCaret == null) {
        // this means that the found occurence is already selected
        if (notFoundPreviously) {
          setNotFoundStatus(editor); // to make sure we won't show hint anymore if there are no more occurrences
        }
      }
      else {
        setSelection(editor, newCaret, findResult);
      }
    }
    else {
      setNotFoundStatus(editor);
      showHint(editor);
    }
  }
  else {
    if (wordSelectionRange == null) {
      return;
    }
    setSelection(editor, caret, wordSelectionRange);
    setWholeWordSearch(editor, true);
  }
  editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}