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

The following examples show how to use com.intellij.openapi.editor.Caret#getOffset() . 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: 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 2
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 3
Source File: EditorAPI.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns whether the given selection range represent a backwards selection in the given editor.
 *
 * <p>A backwards selection is defined by the start of the selection being located before the end
 * of the selection. This is checked by using the caret position in the editor.
 *
 * <p>Returns <code>false</code> as the default value if the selection start matches the selection
 * end or the caret position in the editor matches neither the start nor the end of the selection
 * range.
 *
 * @param editor the editor for the selection
 * @param selectionStart the selection start
 * @param selectionEnd the selection end
 * @return whether the given selection range represent a backwards selection in the given editor
 *     or <code>false</code> if the selection start matches the selection end or the caret
 *     position in the editor matches neither the start nor the end of the selection range.
 */
private static boolean isBackwardsSelection(
    @NotNull Editor editor, int selectionStart, int selectionEnd) {
  if (selectionStart == selectionEnd) {
    return false;
  }

  CaretModel caretModel = editor.getCaretModel();

  Caret caret = caretModel.getPrimaryCaret();

  int caretOffset = caret.getOffset();

  if (caretOffset == selectionEnd) {
    return false;
  } else if (caretOffset == selectionStart) {
    return true;
  } else {
    VirtualFile file = FileDocumentManager.getInstance().getFile(editor.getDocument());

    log.warn(
        "Encountered caret for file "
            + file
            + " which is located neither at the start nor at the end of the selection."
            + " Returning 'isBackwardsSelection=false' by default - caret offset: "
            + caretOffset
            + ", selection start: "
            + selectionStart
            + ", selection end: "
            + selectionEnd);

    return false;
  }
}
 
Example 4
Source File: EditorComponentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void caretPositionChanged(CaretEvent e) {
  Caret caret = e.getCaret();
  if (caret == null) {
    return;
  }
  int dot = caret.getOffset();
  int mark = caret.getLeadSelectionOffset();
  if (myCaretPos != dot) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    firePropertyChange(ACCESSIBLE_CARET_PROPERTY,
                       new Integer(myCaretPos), new Integer(dot));

    if (SystemInfo.isMac) {
      // For MacOSX we also need to fire a caret event to anyone listening
      // to our Document, since *that* rather than the accessible property
      // change is the only way to trigger a speech update
      //fireJTextComponentCaretChange(dot, mark);
      fireJTextComponentCaretChange(e);
    }

    myCaretPos = dot;
  }

  if (mark != dot) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    firePropertyChange(ACCESSIBLE_SELECTION_PROPERTY, null,
                       getSelectedText());
  }
}
 
Example 5
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 6
Source File: PrevNextParameterHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute(@Nonnull 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);
  }
}
 
Example 7
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 8
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 9
Source File: SearchResults.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void caretPositionChanged(@Nonnull CaretEvent event) {
  Caret caret = event.getCaret();
  if (caret != null && myEditor.getCaretModel().getAllCarets().size() == 1 && caret.isUpToDate()) {
    int offset = caret.getOffset();
    FindResult occurrenceAtCaret = getOccurrenceAtCaret();
    if (occurrenceAtCaret != null && occurrenceAtCaret != myCursor) {
      moveCursorTo(occurrenceAtCaret, false, false);
      myEditor.getCaretModel().moveToOffset(offset);
    }
  }
  notifyCursorMoved();
}
 
Example 10
Source File: ScratchFileActions.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
static Language getLanguageFromCaret(@Nonnull 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;
  Language language = file.getLanguage();
  return language;
}
 
Example 11
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 12
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 13
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 14
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);
}