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

The following examples show how to use com.intellij.openapi.editor.Editor#logicalPositionToOffset() . 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: NamedElementDuplicateHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, DataContext dataContext) {
  Project project = editor.getProject();
  if (project != null && !editor.getSelectionModel().hasSelection()) {
    PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file != null) {
      VisualPosition caret = editor.getCaretModel().getVisualPosition();
      Pair<LogicalPosition, LogicalPosition> lines = EditorUtil.calcSurroundingRange(editor, caret, caret);
      TextRange toDuplicate = new TextRange(editor.logicalPositionToOffset(lines.first), editor.logicalPositionToOffset(lines.second));

      PsiElement name = findNameIdentifier(editor, file, toDuplicate);
      if (name != null && !name.getTextRange().containsOffset(editor.getCaretModel().getOffset())) {
        editor.getCaretModel().moveToOffset(name.getTextOffset());
      }
    }
  }

  myOriginal.execute(editor, dataContext);
}
 
Example 2
Source File: BackspaceHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean isWhitespaceBeforeCaret(Editor editor) {
  final LogicalPosition caretPos = editor.getCaretModel().getLogicalPosition();
  final CharSequence charSeq = editor.getDocument().getCharsSequence();
  // smart backspace is activated only if all characters in the check range are whitespace characters
  for(int pos=0; pos<caretPos.column; pos++) {
    // use logicalPositionToOffset to make sure tabs are handled correctly
    final LogicalPosition checkPos = new LogicalPosition(caretPos.line, pos);
    final int offset = editor.logicalPositionToOffset(checkPos);
    if (offset < charSeq.length()) {
      final char c = charSeq.charAt(offset);
      if (c != '\t' && c != ' ' && c != '\n') {
        return false;
      }
    }
  }
  return true;
}
 
Example 3
Source File: MergeSearchHelper.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static Change findChangeAt(EditorMouseEvent e, MergePanel2 mergePanel, int index) {
  if (mergePanel.getMergeList() == null) return null;
  Editor editor = e.getEditor();
  LOG.assertTrue(editor == mergePanel.getEditor(index));
  LogicalPosition logicalPosition = editor.xyToLogicalPosition(e.getMouseEvent().getPoint());
  int offset = editor.logicalPositionToOffset(logicalPosition);
  return forMergeList(mergePanel.getMergeList(), index).findChangeAt(offset);
}
 
Example 4
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 5
Source File: ImageOrColorPreviewManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static Collection<PsiElement> getPsiElementsAt(Point point, Editor editor) {
  if (editor.isDisposed()) {
    return Collections.emptySet();
  }

  Project project = editor.getProject();
  if (project == null || project.isDisposed()) {
    return Collections.emptySet();
  }

  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  final Document document = editor.getDocument();
  PsiFile psiFile = documentManager.getPsiFile(document);
  if (psiFile == null || psiFile instanceof PsiCompiledElement || !psiFile.isValid()) {
    return Collections.emptySet();
  }

  final Set<PsiElement> elements = Collections.newSetFromMap(ContainerUtil.createWeakMap());
  final int offset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(point));
  if (documentManager.isCommitted(document)) {
    ContainerUtil.addIfNotNull(elements, InjectedLanguageUtil.findElementAtNoCommit(psiFile, offset));
  }
  for (PsiFile file : psiFile.getViewProvider().getAllFiles()) {
    ContainerUtil.addIfNotNull(elements, file.findElementAt(offset));
  }

  return elements;
}
 
Example 6
Source File: LookupImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public PsiElement getPsiElement() {
  PsiFile file = getPsiFile();
  if (file == null) return null;

  int offset = getLookupStart();
  Editor editor = getEditor();
  if (editor instanceof EditorWindow) {
    offset = editor.logicalPositionToOffset(((EditorWindow)editor).hostToInjected(myEditor.offsetToLogicalPosition(offset)));
  }
  if (offset > 0) return file.findElementAt(offset - 1);

  return file.findElementAt(0);
}
 
Example 7
Source File: BackspaceHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void deleteToTargetPosition(@Nonnull Editor editor, @Nonnull LogicalPosition pos) {
  final int offset = editor.getCaretModel().getOffset();
  final int targetOffset = editor.logicalPositionToOffset(pos);
  editor.getSelectionModel().setSelection(targetOffset, offset);
  EditorModificationUtil.deleteSelectedText(editor);
  editor.getCaretModel().moveToLogicalPosition(pos);
}
 
Example 8
Source File: VisibleHighlightingPassFactory.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static ProperTextRange calculateVisibleRange(@Nonnull Editor editor) {
  Rectangle rect = editor.getScrollingModel().getVisibleArea();
  LogicalPosition startPosition = editor.xyToLogicalPosition(new Point(rect.x, rect.y));

  int visibleStart = editor.logicalPositionToOffset(startPosition);
  LogicalPosition endPosition = editor.xyToLogicalPosition(new Point(rect.x + rect.width, rect.y + rect.height));

  int visibleEnd = editor.logicalPositionToOffset(new LogicalPosition(endPosition.line + 1, 0));

  return new ProperTextRange(visibleStart, Math.max(visibleEnd, visibleStart));
}
 
Example 9
Source File: DaemonListeners.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void mouseMoved(@Nonnull EditorMouseEvent e) {
  if (Registry.is("ide.disable.editor.tooltips") || Registry.is("editor.new.mouse.hover.popups")) {
    return;
  }
  Editor editor = e.getEditor();
  if (myProject != editor.getProject()) return;
  if (EditorMouseHoverPopupControl.arePopupsDisabled(editor)) return;

  boolean shown = false;
  try {
    if (e.getArea() == EditorMouseEventArea.EDITING_AREA &&
        !UIUtil.isControlKeyDown(e.getMouseEvent()) &&
        DocumentationManager.getInstance(myProject).getDocInfoHint() == null &&
        EditorUtil.isPointOverText(editor, e.getMouseEvent().getPoint())) {
      LogicalPosition logical = editor.xyToLogicalPosition(e.getMouseEvent().getPoint());
      int offset = editor.logicalPositionToOffset(logical);
      HighlightInfo info = myDaemonCodeAnalyzer.findHighlightByOffset(editor.getDocument(), offset, false);
      if (info == null || info.getDescription() == null || info.getHighlighter() != null && FoldingUtil.isHighlighterFolded(editor, info.getHighlighter())) {
        IdeTooltipManager.getInstance().hideCurrent(e.getMouseEvent());
        return;
      }
      DaemonTooltipUtil.showInfoTooltip(info, editor, offset);
      shown = true;
    }
  }
  finally {
    if (!shown && !TooltipController.getInstance().shouldSurvive(e.getMouseEvent())) {
      DaemonTooltipUtil.cancelTooltips();
    }
  }
}
 
Example 10
Source File: EditorUtils.java    From SmartIM4IntelliJ with Apache License 2.0 5 votes vote down vote up
public static void setLine(Editor editor, int line, int column) {
    if (editor != null) {
        try {
            int startOffset = editor.logicalPositionToOffset(new LogicalPosition(line, column));
            editor.getCaretModel().moveToOffset(startOffset);
            editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
            editor.getSelectionModel().setSelection(startOffset, startOffset);
        } catch (Exception e) {
            // do nothing
        }
    }
}
 
Example 11
Source File: EditorUtils.java    From emacsIDEAs with Apache License 2.0 5 votes vote down vote up
public static TextRange getVisibleTextRange(Editor editor) {
    Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();

    LogicalPosition startLogicalPosition = editor.xyToLogicalPosition(visibleArea.getLocation());

    Double endVisualX = visibleArea.getX() + visibleArea.getWidth();
    Double endVisualY = visibleArea.getY() + visibleArea.getHeight();
    LogicalPosition endLogicalPosition = editor.xyToLogicalPosition(new Point(endVisualX.intValue(), endVisualY.intValue()));

    return new TextRange(editor.logicalPositionToOffset(startLogicalPosition), editor.logicalPositionToOffset(endLogicalPosition));
}
 
Example 12
Source File: CSharpStatementMover.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
@RequiredReadAction
public boolean checkAvailable(@Nonnull final Editor editor, @Nonnull final PsiFile file, @Nonnull final MoveInfo info, final boolean down)
{
	//if (!(file instanceof PsiJavaFile)) return false;
	final boolean available = super.checkAvailable(editor, file, info, down);
	if(!available)
	{
		return false;
	}
	LineRange range = info.toMove;

	range = expandLineRangeToCoverPsiElements(range, editor, file);
	if(range == null)
	{
		return false;
	}
	info.toMove = range;
	final int startOffset = editor.logicalPositionToOffset(new LogicalPosition(range.startLine, 0));
	final int endOffset = editor.logicalPositionToOffset(new LogicalPosition(range.endLine, 0));
	final PsiElement[] statements = CSharpRefactoringUtil.findStatementsInRange(file, startOffset, endOffset);
	if(statements.length == 0)
	{
		return false;
	}
	range.firstElement = statements[0];
	range.lastElement = statements[statements.length - 1];

	if(!checkMovingInsideOutside(file, editor, range, info, down))
	{
		info.toMove2 = null;
		return true;
	}
	return true;
}
 
Example 13
Source File: SortLinesBySubSelectionAction.java    From StringManipulation with Apache License 2.0 5 votes vote down vote up
@NotNull
private List<SubSelectionSortLine> getLines(Editor editor, @NotNull SortSettings sortSettings, List<CaretState> caretsAndSelections) {
	List<SubSelectionSortLine> lines = new ArrayList<SubSelectionSortLine>();
	for (CaretState caretsAndSelection : caretsAndSelections) {
		LogicalPosition selectionStart = caretsAndSelection.getSelectionStart();
		int selectionStartOffset = editor.logicalPositionToOffset(selectionStart);
		LogicalPosition selectionEnd = caretsAndSelection.getSelectionEnd();
		int selectionEndOffset = editor.logicalPositionToOffset(selectionEnd);
		LogicalPosition caretPosition = caretsAndSelection.getCaretPosition();
		// no selection -> expand to end of line
		if (selectionStartOffset == selectionEndOffset) {
			String text = editor.getDocument().getText();
			selectionEndOffset = text.indexOf("\n", selectionStartOffset);
			if (selectionEndOffset == -1) {
				selectionEndOffset = text.length();
			}
			Caret caret = getCaretAt(editor, caretsAndSelection.getCaretPosition());
			caret.setSelection(selectionStartOffset, selectionEndOffset);
		}

		String selection = editor.getDocument().getText(
				new TextRange(selectionStartOffset, selectionEndOffset));

		int lineNumber = editor.getDocument().getLineNumber(selectionStartOffset);
		int lineStartOffset = editor.getDocument().getLineStartOffset(lineNumber);
		int lineEndOffset = editor.getDocument().getLineEndOffset(lineNumber);
		String line = editor.getDocument().getText(new TextRange(lineStartOffset, lineEndOffset));

		lines.add(new SubSelectionSortLine(sortSettings, line, selection, lineStartOffset, lineEndOffset,
				selectionStartOffset - lineStartOffset, selectionEndOffset - lineStartOffset
		));
	}
	return lines;
}
 
Example 14
Source File: ErrorAnnotator.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
@Nullable
@Override
public Collection<ErrorAnnotator.BsbErrorAnnotation> collectInformation(@NotNull PsiFile file, @NotNull Editor editor, boolean hasErrors) {
    List<BsbErrorAnnotation> result = null;

    String filename = file.getVirtualFile().getName();
    ErrorsManager service = ServiceManager.getService(file.getProject(), ErrorsManager.class);
    Collection<OutputInfo> collectedInfo = service.getInfo(filename);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Collected info for file " + filename + ": " + collectedInfo.size());
    }

    result = new ArrayList<>();

    for (OutputInfo info : collectedInfo) {
        LogicalPosition start = new LogicalPosition(info.lineStart < 1 ? 0 : info.lineStart - 1, info.colStart < 1 ? 0 : info.colStart);
        LogicalPosition end = new LogicalPosition(info.lineEnd < 1 ? 0 : info.lineEnd - 1, info.colEnd < 1 ? 0 : info.colEnd);
        String message = info.message.replace('\n', ' ').replaceAll("\\s+", " ").trim();

        int startOffset = editor.logicalPositionToOffset(start);
        int endOffset = editor.logicalPositionToOffset(end);
        if (0 < startOffset && 0 < endOffset && startOffset < endOffset) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("annotate " + startOffset + ":" + endOffset + " '" + message + "'");
            }
            TextRangeInterval range = new TextRangeInterval(startOffset - 1, endOffset - 1);
            result.add(new BsbErrorAnnotation(info.isError, message, range, start));
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Failed to locate info: " + start + "->" + end + ", offsets " + startOffset + "->" + endOffset + ", info " + info);
            }
        }
    }

    return result;
}
 
Example 15
Source File: TestRuleAction.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/** Only show if selection is a grammar and in a rule */
@Override
public void update(AnActionEvent e) {
	Presentation presentation = e.getPresentation();
	presentation.setText("Test ANTLR Rule"); // default text

	VirtualFile grammarFile = MyActionUtils.getGrammarFileFromEvent(e);
	if ( grammarFile==null ) { // we clicked somewhere outside text or non grammar file
		presentation.setEnabled(false);
		presentation.setVisible(false);
		return;
	}

	ParserRuleRefNode r = null;
	InputEvent inputEvent = e.getInputEvent();
	if ( inputEvent instanceof MouseEvent ) { // this seems to be after update() called 2x and we have selected the action
		r = MyActionUtils.getParserRuleSurroundingRef(e);
	}
	else {
		// If editor component, mouse event not happened yet to update caret so must ask for mouse position
		Editor editor = e.getData(PlatformDataKeys.EDITOR);
		if ( editor!=null ) {
			Point mousePosition = editor.getContentComponent().getMousePosition();
			if ( mousePosition!=null ) {
				LogicalPosition pos = editor.xyToLogicalPosition(mousePosition);
				int offset = editor.logicalPositionToOffset(pos);
				PsiFile file = e.getData(LangDataKeys.PSI_FILE);
				if ( file!=null ) {
					PsiElement el = file.findElementAt(offset);
					if ( el!=null ) {
						r = MyActionUtils.getParserRuleSurroundingRef(el);
					}
				}
			}
		}
		if ( r==null ) {
			r = MyActionUtils.getParserRuleSurroundingRef(e);
		}
	}
	if ( r==null ) {
		presentation.setEnabled(false);
		return;
	}

	presentation.setVisible(true);
	String ruleName = r.getText();
	if ( Character.isLowerCase(ruleName.charAt(0)) ) {
		presentation.setEnabled(true);
		presentation.setText("Test Rule "+ruleName);
	}
	else {
		presentation.setEnabled(false);
	}
}
 
Example 16
Source File: AbstractValueHint.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static int calculateOffset(@Nonnull Editor editor, @Nonnull Point point) {
  return editor.logicalPositionToOffset(editor.xyToLogicalPosition(point));
}
 
Example 17
Source File: QuickDocOnMouseOverManager.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void processMouseMove(@Nonnull EditorMouseEvent e) {
  if (!myApplicationActive || !myEnabled || e.getArea() != EditorMouseEventArea.EDITING_AREA) {
    // Skip if the mouse is not at the editing area.
    closeQuickDocIfPossible();
    return;
  }

  if (e.getMouseEvent().getModifiers() != 0) {
    // Don't show the control when any modifier is active (e.g. Ctrl or Alt is hold). There is a common situation that a user
    // wants to navigate via Ctrl+click or perform quick evaluate by Alt+click.
    return;
  }

  Editor editor = e.getEditor();
  if (EditorMouseHoverPopupControl.arePopupsDisabled(editor)) {
    return;
  }

  if (editor.isOneLineMode()) {
    // Don't want auto quick doc to mess at, say, editor used for debugger condition.
    return;
  }

  Project project = editor.getProject();
  if (project == null) {
    return;
  }

  DocumentationManager documentationManager = DocumentationManager.getInstance(project);
  JBPopup hint = documentationManager.getDocInfoHint();
  if (hint != null) {

    // Skip the event if the control is shown because of explicit 'show quick doc' action call.
    DocumentationManager manager = getDocManager();
    if (manager == null || !manager.isCloseOnSneeze()) {
      return;
    }

    // Skip the event if the mouse is under the opened quick doc control.
    Point hintLocation = hint.getLocationOnScreen();
    Dimension hintSize = hint.getSize();
    int mouseX = e.getMouseEvent().getXOnScreen();
    int mouseY = e.getMouseEvent().getYOnScreen();
    int resizeZoneWidth = editor.getLineHeight();
    if (mouseX >= hintLocation.x - resizeZoneWidth && mouseX <= hintLocation.x + hintSize.width + resizeZoneWidth &&
        mouseY >= hintLocation.y - resizeZoneWidth && mouseY <= hintLocation.y + hintSize.height + resizeZoneWidth) {
      return;
    }
  }

  PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  if (psiFile == null) {
    closeQuickDocIfPossible();
    return;
  }

  Point point = e.getMouseEvent().getPoint();
  if (editor instanceof EditorEx && ((EditorEx)editor).getFoldingModel().getFoldingPlaceholderAt(point) != null) {
    closeQuickDocIfPossible();
    return;
  }

  VisualPosition visualPosition = editor.xyToVisualPosition(point);
  if (editor.getSoftWrapModel().isInsideOrBeforeSoftWrap(visualPosition)) {
    closeQuickDocIfPossible();
    return;
  }

  int mouseOffset = editor.logicalPositionToOffset(editor.visualToLogicalPosition(visualPosition));
  PsiElement elementUnderMouse = psiFile.findElementAt(mouseOffset);
  if (elementUnderMouse == null || elementUnderMouse instanceof PsiWhiteSpace || elementUnderMouse instanceof PsiPlainText) {
    closeQuickDocIfPossible();
    return;
  }

  if (elementUnderMouse.equals(SoftReference.dereference(myActiveElements.get(editor))) && (!myAlarm.isEmpty() // Request to show documentation for the target component has been already queued.
                                                                                            || hint != null)) // Documentation for the target component is being shown.
  {
    return;
  }
  allowUpdateFromContext(project, false);
  closeQuickDocIfPossible();
  myActiveElements.put(editor, new WeakReference<>(elementUnderMouse));

  myAlarm.cancelAllRequests();
  if (myCurrentRequest != null) myCurrentRequest.cancel();
  myCurrentRequest = new MyShowQuickDocRequest(documentationManager, editor, mouseOffset, elementUnderMouse);
  myAlarm.addRequest(myCurrentRequest, EditorSettingsExternalizable.getInstance().getTooltipsDelay());
}
 
Example 18
Source File: MyActionUtils.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static int getMouseOffset(Editor editor) {
	Point mousePosition = editor.getContentComponent().getMousePosition();
	LogicalPosition pos=editor.xyToLogicalPosition(mousePosition);
	int offset = editor.logicalPositionToOffset(pos);
	return offset;
}
 
Example 19
Source File: MyActionUtils.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static int getMouseOffset(MouseEvent mouseEvent, Editor editor) {
	Point point=new Point(mouseEvent.getPoint());
	LogicalPosition pos=editor.xyToLogicalPosition(point);
	return editor.logicalPositionToOffset(pos);
}
 
Example 20
Source File: EditorAPI.java    From saros with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Calculates the text based offset for the start of the given line in the given editor.
 *
 * @param editor the editor to use for the calculations
 * @param lineNumber the line number whose offset to calculate
 * @return the text based offset for the start of the given line in the given editor
 */
private static int calculateLineOffset(@NotNull Editor editor, int lineNumber) {
  return editor.logicalPositionToOffset(new LogicalPosition(lineNumber, 0, true));
}