Java Code Examples for com.intellij.openapi.editor.Editor#offsetToLogicalPosition()

The following examples show how to use com.intellij.openapi.editor.Editor#offsetToLogicalPosition() . 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: CSharpDeclarationMover.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
private static LineRange memberRange(@Nonnull PsiElement member, Editor editor, LineRange lineRange)
{
	final TextRange textRange = member.getTextRange();
	if(editor.getDocument().getTextLength() < textRange.getEndOffset())
	{
		return null;
	}
	final int startLine = editor.offsetToLogicalPosition(textRange.getStartOffset()).line;
	final int endLine = editor.offsetToLogicalPosition(textRange.getEndOffset()).line + 1;
	if(!isInsideDeclaration(member, startLine, endLine, lineRange, editor))
	{
		return null;
	}

	return new LineRange(startLine, endLine);
}
 
Example 2
Source File: CSharpDeclarationMover.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Override
public void beforeMove(@Nonnull final Editor editor, @Nonnull final MoveInfo info, final boolean down)
{
	super.beforeMove(editor, info, down);

	if(myEnumToInsertSemicolonAfter != null)
	{
		TreeElement semicolon = Factory.createSingleLeafElement(CSharpTokens.SEMICOLON, ";", 0, 1, null, myEnumToInsertSemicolonAfter.getManager());

		try
		{
			PsiElement inserted = myEnumToInsertSemicolonAfter.getParent().addAfter(semicolon.getPsi(), myEnumToInsertSemicolonAfter);
			inserted = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(inserted);
			final LogicalPosition position = editor.offsetToLogicalPosition(inserted.getTextRange().getEndOffset());

			info.toMove2 = new LineRange(position.line + 1, position.line + 1);
		}
		catch(IncorrectOperationException e)
		{
			LOG.error(e);
		}
		finally
		{
			myEnumToInsertSemicolonAfter = null;
		}
	}
}
 
Example 3
Source File: CSharpStatementMover.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
private static LineRange expandLineRangeToCoverPsiElements(final LineRange range, Editor editor, final PsiFile file)
{
	Pair<PsiElement, PsiElement> psiRange = getElementRange(editor, file, range);
	if(psiRange == null)
	{
		return null;
	}
	final PsiElement parent = PsiTreeUtil.findCommonParent(psiRange.getFirst(), psiRange.getSecond());
	Pair<PsiElement, PsiElement> elementRange = getElementRange(parent, psiRange.getFirst(), psiRange.getSecond());
	if(elementRange == null)
	{
		return null;
	}
	int endOffset = elementRange.getSecond().getTextRange().getEndOffset();
	Document document = editor.getDocument();
	if(endOffset > document.getTextLength())
	{
		LOG.assertTrue(!PsiDocumentManager.getInstance(file.getProject()).isUncommited(document));
		LOG.assertTrue(PsiDocumentManagerImpl.checkConsistency(file, document));
	}
	int endLine;
	if(endOffset == document.getTextLength())
	{
		endLine = document.getLineCount();
	}
	else
	{
		endLine = editor.offsetToLogicalPosition(endOffset).line + 1;
		endLine = Math.min(endLine, document.getLineCount());
	}
	int startLine = Math.min(range.startLine, editor.offsetToLogicalPosition(elementRange.getFirst().getTextOffset()).line);
	endLine = Math.max(endLine, range.endLine);
	return new LineRange(startLine, endLine);
}
 
Example 4
Source File: LineMover.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean checkAvailable(@Nonnull final Editor editor, @Nonnull final PsiFile file, @Nonnull final MoveInfo info, final boolean down) {
  LineRange range = StatementUpDownMover.getLineRangeFromSelection(editor);

  LogicalPosition maxLinePos = editor.offsetToLogicalPosition(editor.getDocument().getTextLength());
  int maxLine = maxLinePos.column == 0? maxLinePos.line : maxLinePos.line + 1;
  if (range.startLine == 0 && !down) return false;
  if (range.endLine >= maxLine && down) return false;

  int nearLine = down ? range.endLine : range.startLine - 1;
  info.toMove = range;
  info.toMove2 = new LineRange(nearLine, nearLine + 1);

  return true;
}
 
Example 5
Source File: BreakpointItem.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected static void showInEditor(DetailView panel, VirtualFile virtualFile, int line) {
  TextAttributes attributes =
          EditorColorsManager.getInstance().getGlobalScheme().getAttributes(DebuggerColors.BREAKPOINT_ATTRIBUTES);

  DetailView.PreviewEditorState state = DetailView.PreviewEditorState.create(virtualFile, line, attributes);

  if (state.equals(panel.getEditorState())) {
    return;
  }

  panel.navigateInPreviewEditor(state);

  TextAttributes softerAttributes = attributes.clone();
  Color backgroundColor = softerAttributes.getBackgroundColor();
  if (backgroundColor != null) {
    softerAttributes.setBackgroundColor(ColorUtil.softer(backgroundColor));
  }

  final Editor editor = panel.getEditor();
  final MarkupModel editorModel = editor.getMarkupModel();
  final MarkupModel documentModel =
          DocumentMarkupModel.forDocument(editor.getDocument(), editor.getProject(), false);

  for (RangeHighlighter highlighter : documentModel.getAllHighlighters()) {
    if (highlighter.getUserData(DebuggerColors.BREAKPOINT_HIGHLIGHTER_KEY) == Boolean.TRUE) {
      final int line1 = editor.offsetToLogicalPosition(highlighter.getStartOffset()).line;
      if (line1 != line) {
        editorModel.addLineHighlighter(line1,
                                       DebuggerColors.BREAKPOINT_HIGHLIGHTER_LAYER + 1, softerAttributes);
      }
    }
  }
}
 
Example 6
Source File: ShowContainerInfoHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean isDeclarationVisible(PsiElement container, Editor editor) {
  Rectangle viewRect = editor.getScrollingModel().getVisibleArea();
  final TextRange range = DeclarationRangeUtil.getPossibleDeclarationAtRange(container);
  if (range == null) {
    return false;
  }

  LogicalPosition pos = editor.offsetToLogicalPosition(range.getStartOffset());
  Point loc = editor.logicalPositionToXY(pos);
  return loc.y >= viewRect.y;
}
 
Example 7
Source File: CtrlMouseHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void showHint(@Nonnull LightweightHint hint, @Nonnull Editor editor) {
  if (ApplicationManager.getApplication().isUnitTestMode() || editor.isDisposed()) return;
  final HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl();
  short constraint = HintManager.ABOVE;
  LogicalPosition position = editor.offsetToLogicalPosition(getOffset(editor));
  Point p = HintManagerImpl.getHintPosition(hint, editor, position, constraint);
  if (p.y - hint.getComponent().getPreferredSize().height < 0) {
    constraint = HintManager.UNDER;
    p = HintManagerImpl.getHintPosition(hint, editor, position, constraint);
  }
  hintManager.showEditorHint(hint, editor, p, HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE | HintManager.HIDE_BY_SCROLLING, 0, false,
                             HintManagerImpl.createHintHint(editor, p, hint, constraint).setContentActive(false));
}
 
Example 8
Source File: EmacsStyleIndentAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public void invoke(@Nonnull final Project project, @Nonnull final Editor editor, @Nonnull final PsiFile file) {
  if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return;
  PsiDocumentManager.getInstance(project).commitAllDocuments();

  if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
    return;
  }

  EmacsProcessingHandler emacsProcessingHandler = LanguageEmacsExtension.INSTANCE.forLanguage(file.getLanguage());
  if (emacsProcessingHandler != null) {
    EmacsProcessingHandler.Result result = emacsProcessingHandler.changeIndent(project, editor, file);
    if (result == EmacsProcessingHandler.Result.STOP) {
      return;
    }
  }

  final Document document = editor.getDocument();
  final int startOffset = editor.getCaretModel().getOffset();
  final int line = editor.offsetToLogicalPosition(startOffset).line;
  final int col = editor.getCaretModel().getLogicalPosition().column;
  final int lineStart = document.getLineStartOffset(line);
  final int initLineEnd = document.getLineEndOffset(line);
  try{
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    final int newPos = codeStyleManager.adjustLineIndent(file, lineStart);
    final int newCol = newPos - lineStart;
    final int lineInc = document.getLineEndOffset(line) - initLineEnd;
    if (newCol >= col + lineInc && newCol >= 0) {
      final LogicalPosition pos = new LogicalPosition(line, newCol);
      editor.getCaretModel().moveToLogicalPosition(pos);
      editor.getSelectionModel().removeSelection();
      editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    }
  }
  catch(IncorrectOperationException e){
    LOG.error(e);
  }
}
 
Example 9
Source File: ClickNavigator.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void navigate(final Editor editor, boolean select,
                      LogicalPosition pos,
                      final SyntaxHighlighter highlighter,
                      final HighlightData[] data, final boolean isBackgroundImportant) {
  int offset = editor.logicalPositionToOffset(pos);

  if (!isBackgroundImportant && editor.offsetToLogicalPosition(offset).column != pos.column) {
    if (!select) {
      setCursor(editor, Cursor.TEXT_CURSOR);
      return;
    }
  }

  if (data != null) {
    for (HighlightData highlightData : data) {
      if (highlightDataContainsOffset(highlightData, editor.logicalPositionToOffset(pos))) {
        if (!select) setCursor(editor, Cursor.HAND_CURSOR);
        setSelectedItem(highlightData.getHighlightType(), select);
        return;
      }
    }
  }

  if (highlighter != null) {
    HighlighterIterator itr = ((EditorEx)editor).getHighlighter().createIterator(offset);
    boolean selection = selectItem(select, itr, highlighter);
    if (!select && selection) {
      setCursor(editor, Cursor.HAND_CURSOR);
    }
    else {
      setCursor(editor, Cursor.TEXT_CURSOR);
    }
  }
}
 
Example 10
Source File: ExtractMethodHelper.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void highlightInEditor(@Nonnull final Project project, @Nonnull final SimpleMatch match,
                                      @Nonnull final Editor editor, Map<SimpleMatch, RangeHighlighter> highlighterMap) {
  final List<RangeHighlighter> highlighters = new ArrayList<>();
  final HighlightManager highlightManager = HighlightManager.getInstance(project);
  final EditorColorsManager colorsManager = EditorColorsManager.getInstance();
  final TextAttributes attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
  final int startOffset = match.getStartElement().getTextRange().getStartOffset();
  final int endOffset = match.getEndElement().getTextRange().getEndOffset();
  highlightManager.addRangeHighlight(editor, startOffset, endOffset, attributes, true, highlighters);
  highlighterMap.put(match, highlighters.get(0));
  final LogicalPosition logicalPosition = editor.offsetToLogicalPosition(startOffset);
  editor.getScrollingModel().scrollTo(logicalPosition, ScrollType.MAKE_VISIBLE);
}
 
Example 11
Source File: ExtractIncludeFileBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void highlightInEditor(final Project project, final IncludeDuplicate pair, final Editor editor) {
  final HighlightManager highlightManager = HighlightManager.getInstance(project);
  EditorColorsManager colorsManager = EditorColorsManager.getInstance();
  TextAttributes attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
  final int startOffset = pair.getStart().getTextRange().getStartOffset();
  final int endOffset = pair.getEnd().getTextRange().getEndOffset();
  highlightManager.addRangeHighlight(editor, startOffset, endOffset, attributes, true, null);
  final LogicalPosition logicalPosition = editor.offsetToLogicalPosition(startOffset);
  editor.getScrollingModel().scrollTo(logicalPosition, ScrollType.MAKE_VISIBLE);
}
 
Example 12
Source File: BuildEnterHandler.java    From intellij with Apache License 2.0 4 votes vote down vote up
/**
 * Returns null if an appropriate indent cannot be found. In that case we do nothing, and pass it
 * along to the next EnterHandler.
 */
@Nullable
private static Integer determineIndent(
    PsiFile file, Editor editor, int offset, CodeStyleSettings settings) {
  if (offset == 0) {
    return null;
  }
  Document doc = editor.getDocument();
  PsiElement element = getRelevantElement(file, doc, offset);
  PsiElement parent = element != null ? element.getParent() : null;
  if (parent == null) {
    return null;
  }

  IndentOptions indentOptions = settings.getIndentOptions(file.getFileType());
  BuildCodeStyleSettings buildSettings = settings.getCustomSettings(BuildCodeStyleSettings.class);
  if (endsBlock(element)) {
    // current line indent subtract block indent
    return Math.max(0, getIndent(doc, element) - indentOptions.INDENT_SIZE);
  }

  if (parent instanceof BuildListType) {
    BuildListType list = (BuildListType) parent;
    if (endsList(list, element) && element.getTextOffset() < offset) {
      return null;
    }
    int listOffset = list.getStartOffset();
    LogicalPosition caretPosition = editor.getCaretModel().getLogicalPosition();
    LogicalPosition listStart = editor.offsetToLogicalPosition(listOffset);
    if (listStart.line != caretPosition.line) {
      // take the minimum of the current line's indent and the current caret position
      return indentOfLineUpToCaret(doc, caretPosition.line, offset);
    }
    BuildElement firstChild = ((BuildListType) parent).getFirstElement();
    if (firstChild != null && firstChild.getNode().getStartOffset() < offset) {
      return getIndent(doc, firstChild);
    }
    return lineIndent(doc, listStart.line)
        + additionalIndent(parent, buildSettings, indentOptions);
  }
  if (parent instanceof StatementListContainer && afterColon(doc, offset)) {
    return getIndent(doc, parent) + additionalIndent(parent, buildSettings, indentOptions);
  }
  return null;
}
 
Example 13
Source File: SmartIndentingBackspaceHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected void doBeforeCharDeleted(char c, PsiFile file, Editor editor) {
  Project project = file.getProject();
  Document document = editor.getDocument();
  CharSequence charSequence = document.getImmutableCharSequence();
  CaretModel caretModel = editor.getCaretModel();
  int caretOffset = caretModel.getOffset();
  LogicalPosition pos = caretModel.getLogicalPosition();
  int lineStartOffset = document.getLineStartOffset(pos.line);
  int beforeWhitespaceOffset = CharArrayUtil.shiftBackward(charSequence, caretOffset - 1, " \t") + 1;
  if (beforeWhitespaceOffset != lineStartOffset) {
    myReplacement = null;
    return;
  }
  PsiDocumentManager.getInstance(project).commitDocument(document);
  CodeStyleFacade codeStyleFacade = CodeStyleFacade.getInstance(project);
  myReplacement = codeStyleFacade.getLineIndent(document, lineStartOffset);
  if (myReplacement == null) {
    return;
  }
  int tabSize = codeStyleFacade.getTabSize(file.getFileType());
  int targetColumn = getWidth(myReplacement, tabSize);
  int endOffset = CharArrayUtil.shiftForward(charSequence, caretOffset, " \t");
  LogicalPosition logicalPosition = caretOffset < endOffset ? editor.offsetToLogicalPosition(endOffset) : pos;
  int currentColumn = logicalPosition.column;
  if (currentColumn > targetColumn) {
    myStartOffset = lineStartOffset;
  }
  else if (logicalPosition.line == 0) {
    myStartOffset = 0;
    myReplacement = "";
  }
  else {
    int prevLineEndOffset = document.getLineEndOffset(logicalPosition.line - 1);
    myStartOffset = CharArrayUtil.shiftBackward(charSequence, prevLineEndOffset - 1, " \t") + 1;
    if (myStartOffset != document.getLineStartOffset(logicalPosition.line - 1)) {
      int spacing = CodeStyleManager.getInstance(project).getSpacing(file, endOffset);
      myReplacement = StringUtil.repeatSymbol(' ', Math.max(0, spacing));
    }
  }
}
 
Example 14
Source File: LookupUi.java    From consulo with Apache License 2.0 4 votes vote down vote up
Rectangle calculatePosition() {
  final JComponent lookupComponent = myLookup.getComponent();
  Dimension dim = lookupComponent.getPreferredSize();
  int lookupStart = myLookup.getLookupStart();
  Editor editor = myLookup.getTopLevelEditor();
  if (lookupStart < 0 || lookupStart > editor.getDocument().getTextLength()) {
    LOG.error(lookupStart + "; offset=" + editor.getCaretModel().getOffset() + "; element=" + myLookup.getPsiElement());
  }

  LogicalPosition pos = editor.offsetToLogicalPosition(lookupStart);
  Point location = editor.logicalPositionToXY(pos);
  location.y += editor.getLineHeight();
  location.x -= myLookup.myCellRenderer.getTextIndent();
  // extra check for other borders
  final Window window = UIUtil.getWindow(lookupComponent);
  if (window != null) {
    final Point point = SwingUtilities.convertPoint(lookupComponent, 0, 0, window);
    location.x -= point.x;
  }

  SwingUtilities.convertPointToScreen(location, editor.getContentComponent());
  final Rectangle screenRectangle = ScreenUtil.getScreenRectangle(editor.getContentComponent());

  if (!isPositionedAboveCaret()) {
    int shiftLow = screenRectangle.y + screenRectangle.height - (location.y + dim.height);
    myPositionedAbove = shiftLow < 0 && shiftLow < location.y - dim.height && location.y >= dim.height;
  }
  if (isPositionedAboveCaret()) {
    location.y -= dim.height + editor.getLineHeight();
    if (pos.line == 0) {
      location.y += 1;
      //otherwise the lookup won't intersect with the editor and every editor's resize (e.g. after typing in console) will close the lookup
    }
  }

  if (!screenRectangle.contains(location)) {
    location = ScreenUtil.findNearestPointOnBorder(screenRectangle, location);
  }

  Rectangle candidate = new Rectangle(location, dim);
  ScreenUtil.cropRectangleToFitTheScreen(candidate);

  JRootPane rootPane = editor.getComponent().getRootPane();
  if (rootPane != null) {
    SwingUtilities.convertPointFromScreen(location, rootPane.getLayeredPane());
  }
  else {
    LOG.error("editor.disposed=" + editor.isDisposed() + "; lookup.disposed=" + myLookup.isLookupDisposed() + "; editorShowing=" + editor.getContentComponent().isShowing());
  }

  myMaximumHeight = candidate.height;
  return new Rectangle(location.x, location.y, dim.width, candidate.height);
}
 
Example 15
Source File: EditorAPI.java    From saros with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Calculates the line base position value for the given text base offset in the given editor.
 *
 * <p>This method is used for performance optimization. It accepts a pair containing a line number
 * and the start offset of that line and also returns the calculated line number and start offset
 * of that line. This information can be used to skip calculations of line start offsets when
 * multiple text positions are located in the same line.
 *
 * <p>This method does not validate the input. The input is expected to be validated beforehand by
 * the caller.
 *
 * @param editor the editor to use for the calculation
 * @param offset the text based offset
 * @return the line base position value for the given text base offsets in the given editor
 * @throws IllegalArgumentException if the the given offset is negative
 */
private static Pair<TextPosition, Pair<Integer, Integer>> calculatePositionInternal(
    Editor editor, int offset, @Nullable Pair<Integer, Integer> knownLineStartOffset) {

  LogicalPosition logicalPosition = editor.offsetToLogicalPosition(offset);

  int lineNumber = logicalPosition.line;

  int lineStartOffset;
  Pair<Integer, Integer> returnedKnownLineStartOffset;

  if (knownLineStartOffset != null && knownLineStartOffset.first == lineNumber) {
    lineStartOffset = knownLineStartOffset.second;

    returnedKnownLineStartOffset = knownLineStartOffset;

  } else {
    lineStartOffset = calculateLineOffset(editor, lineNumber);

    returnedKnownLineStartOffset = new Pair<>(lineNumber, lineStartOffset);
  }

  // necessary as the logical position counts a tab char as it's displayed width
  int correctedInLineOffset = offset - lineStartOffset;

  TextPosition textPosition = new TextPosition(lineNumber, correctedInLineOffset);

  return new Pair<>(textPosition, returnedKnownLineStartOffset);
}