com.intellij.openapi.editor.LogicalPosition Java Examples

The following examples show how to use com.intellij.openapi.editor.LogicalPosition. 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: XVariablesViewBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void selectionChanged(final SelectionEvent e) {
  if (!XDebuggerSettingsManager.getInstance().getDataViewSettings().isValueTooltipAutoShowOnSelection() || myEditor.getCaretModel().getCaretCount() > 1) {
    return;
  }
  final String text = myEditor.getDocument().getText(e.getNewRange());
  if (!StringUtil.isEmpty(text) && !(text.contains("exec(") || text.contains("++") || text.contains("--") || text.contains("="))) {
    final XDebugSession session = getSession(getTree());
    if (session == null) return;
    XDebuggerEvaluator evaluator = myStackFrame.getEvaluator();
    if (evaluator == null) return;
    TextRange range = e.getNewRange();
    ExpressionInfo info = new ExpressionInfo(range);
    int offset = range.getStartOffset();
    LogicalPosition pos = myEditor.offsetToLogicalPosition(offset);
    Point point = myEditor.logicalPositionToXY(pos);
    new XValueHint(myProject, myEditor, point, ValueHintType.MOUSE_OVER_HINT, info, evaluator, session).invokeHint();
  }
}
 
Example #2
Source File: ThreesideTextDiffViewer.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
protected SimpleDiffRequest createRequest() {
  SimpleDiffRequest request = super.createRequest();

  ThreeSide currentSide = getCurrentSide();
  LogicalPosition currentPosition = DiffUtil.getCaretPosition(getCurrentEditor());

  // we won't use DiffUserDataKeysEx.EDITORS_CARET_POSITION to avoid desync scroll position (as they can point to different places)
  // TODO: pass EditorsVisiblePositions in case if view was scrolled without changing caret position ?
  if (currentSide == mySide1) {
    request.putUserData(DiffUserDataKeys.SCROLL_TO_LINE, Pair.create(Side.LEFT, currentPosition.line));
  }
  else if (currentSide == mySide2) {
    request.putUserData(DiffUserDataKeys.SCROLL_TO_LINE, Pair.create(Side.RIGHT, currentPosition.line));
  }
  else {
    LogicalPosition position1 = transferPosition(currentSide, mySide1, currentPosition);
    LogicalPosition position2 = transferPosition(currentSide, mySide2, currentPosition);
    request.putUserData(DiffUserDataKeysEx.EDITORS_CARET_POSITION, new LogicalPosition[]{position1, position2});
  }

  return request;
}
 
Example #3
Source File: SyncScrollSupport.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void syncVerticalScroll(boolean animated) {
  if (getMaster().getDocument().getTextLength() == 0) return;

  Rectangle viewRect = getMaster().getScrollingModel().getVisibleArea();
  int middleY = viewRect.height / 3;

  int offset;
  if (myAnchor == null) {
    LogicalPosition masterPos = getMaster().xyToLogicalPosition(new Point(viewRect.x, viewRect.y + middleY));
    int masterCenterLine = masterPos.line;
    int convertedCenterLine = convertLine(masterCenterLine);

    Point point = getSlave().logicalPositionToXY(new LogicalPosition(convertedCenterLine, masterPos.column));
    int correction = (viewRect.y + middleY) % getMaster().getLineHeight();
    offset = point.y - middleY + correction;
  }
  else {
    double progress = myAnchor.masterStartOffset == myAnchor.masterEndOffset || viewRect.y == myAnchor.masterEndOffset ? 1 :
                      ((double)(viewRect.y - myAnchor.masterStartOffset)) / (myAnchor.masterEndOffset - myAnchor.masterStartOffset);

    offset = myAnchor.slaveStartOffset + (int)((myAnchor.slaveEndOffset - myAnchor.slaveStartOffset) * progress);
  }

  int deltaHeaderOffset = getHeaderOffset(getSlave()) - getHeaderOffset(getMaster());
  doScrollVertically(getSlave(), offset + deltaHeaderOffset, animated);
}
 
Example #4
Source File: SortTokensGui.java    From StringManipulation with Apache License 2.0 6 votes vote down vote up
protected void preview() {
	List<CaretState> caretsAndSelections = editor.getCaretModel().getCaretsAndSelections();
	IdeUtils.sort(caretsAndSelections);
	List<String> lines = new ArrayList<String>();
	for (CaretState caretsAndSelection : caretsAndSelections) {
		LogicalPosition selectionStart = caretsAndSelection.getSelectionStart();
		LogicalPosition selectionEnd = caretsAndSelection.getSelectionEnd();
		String text = editor.getDocument().getText(
				new TextRange(editor.logicalPositionToOffset(selectionStart),
						editor.logicalPositionToOffset(selectionEnd)));

		String[] split = text.split("\n");
		lines.addAll(Arrays.asList(split));
	}

	SortTokens columnAligner = new SortTokens(lines, getModel());
	List<String> result = columnAligner.sortLines();

	ApplicationManager.getApplication().runWriteAction(() -> {
		myEditor.getDocument().setText(Joiner.on("\n").join(result));
		myPreviewPanel.validate();
		myPreviewPanel.repaint();
	});
}
 
Example #5
Source File: EditorDocOps.java    From KodeBeagle with Apache License 2.0 6 votes vote down vote up
public final void gotoLine(final int pLineNumber, final Document document) {
    int lineNumber = pLineNumber;
    Editor projectEditor =
            FileEditorManager.getInstance(windowObjects.getProject()).getSelectedTextEditor();

    if (projectEditor != null) {
        CaretModel caretModel = projectEditor.getCaretModel();

        //document is 0-indexed
        if (lineNumber > document.getLineCount()) {
            lineNumber = document.getLineCount() - 1;
        } else {
            lineNumber = lineNumber - 1;
        }

        caretModel.moveToLogicalPosition(new LogicalPosition(lineNumber, 0));

        ScrollingModel scrollingModel = projectEditor.getScrollingModel();
        scrollingModel.scrollToCaret(ScrollType.CENTER);
    }
}
 
Example #6
Source File: ORFileEditorListener.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
@Override
public void documentChanged(@NotNull DocumentEvent event) {
    Document document = event.getDocument();

    // When document lines count change, we move the type annotations
    int newLineCount = document.getLineCount();
    if (newLineCount != m_oldLinesCount) {
        CodeLensView.CodeLensInfo userData = m_project.getUserData(CodeLensView.CODE_LENS);
        if (userData != null) {
            VirtualFile file = FileDocumentManager.getInstance().getFile(document);
            if (file != null) {
                FileEditor selectedEditor = FileEditorManager.getInstance(m_project).getSelectedEditor(file);
                if (selectedEditor instanceof TextEditor) {
                    TextEditor editor = (TextEditor) selectedEditor;
                    LogicalPosition cursorPosition = editor.getEditor().offsetToLogicalPosition(event.getOffset());
                    int direction = newLineCount - m_oldLinesCount;
                    userData.move(file, cursorPosition, direction);
                }
            }
        }
    }

    m_queue.queue(m_project, document);
}
 
Example #7
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 #8
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 #9
Source File: IndentsModelImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public IndentGuideDescriptor getCaretIndentGuide() {
  final LogicalPosition pos = myEditor.getCaretModel().getLogicalPosition();
  final int column = pos.column;
  final int line = pos.line;

  if (column > 0) {
    for (IndentGuideDescriptor indent : myIndents) {
      if (column == indent.indentLevel && line >= indent.startLine && line < indent.endLine) {
        return indent;
      }
    }
  }
  return null;
}
 
Example #10
Source File: MultiCaretHandlerHandler.java    From StringManipulation with Apache License 2.0 5 votes vote down vote up
protected final void singleSelection(Editor editor, List<CaretState> caretsAndSelections, T additionalParameter) {
	CaretState caretsAndSelection = caretsAndSelections.get(0);
	LogicalPosition selectionStart = caretsAndSelection.getSelectionStart();
	LogicalPosition selectionEnd = caretsAndSelection.getSelectionEnd();
	String text = editor.getDocument().getText(
			new TextRange(editor.logicalPositionToOffset(selectionStart),
					editor.logicalPositionToOffset(selectionEnd)));

	String charSequence = processSingleSelection(text, additionalParameter);

	editor.getDocument().replaceString(editor.logicalPositionToOffset(selectionStart),
			editor.logicalPositionToOffset(selectionEnd), charSequence);
}
 
Example #11
Source File: FoldingTransformation.java    From consulo with Apache License 2.0 5 votes vote down vote up
public int transform(int line) {
  FoldRegion foldRegion = findFoldRegion(line);
  int yOffset = 0;
  if (foldRegion != null) {
    int startLine = getStartLine(foldRegion);
    yOffset = (int)((double)(line - startLine) / getLineLength(foldRegion) * myEditor.getLineHeight());
    line = startLine;
  }
  yOffset += myEditor.logicalPositionToXY(new LogicalPosition(line, 0)).y;

  final JComponent header = myEditor.getHeaderComponent();
  int headerOffset = header == null ? 0 : header.getHeight();

  return yOffset - myEditor.getScrollingModel().getVerticalScrollOffset() + headerOffset;
}
 
Example #12
Source File: GraphQLValidationAnnotator.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
private LogicalPosition getLogicalPositionFromOffset(PsiFile psiFile, int offset) {
    com.intellij.openapi.editor.Document document = PsiDocumentManager.getInstance(psiFile.getProject()).getDocument(getTopLevelFile(psiFile));
    if (document != null) {
        final int lineNumber = document.getLineNumber(offset);
        final int lineStartOffset = document.getLineStartOffset(lineNumber);
        return new LogicalPosition(lineNumber, offset - lineStartOffset);
    }
    return new LogicalPosition(-1, -1);
}
 
Example #13
Source File: GraphQLCompletionContributor.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
private void completeTopLevelKeywords() {
    CompletionProvider<CompletionParameters> provider = new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(@NotNull final CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
            final LogicalPosition completionPos = parameters.getEditor().offsetToLogicalPosition(parameters.getOffset());
            final PsiElement prevVisibleLeaf = PsiTreeUtil.prevVisibleLeaf(parameters.getPosition());
            if (prevVisibleLeaf != null) {
                // NOTE: "type Foo <completion>" would grammatically allow a new definition to follow immediately
                // but this completion at that position is likely to be unexpected and would interfere with "implements" on types
                // so we expect top level keywords to be the first visible element on the line to complete
                if (completionPos.line == parameters.getEditor().offsetToLogicalPosition(prevVisibleLeaf.getTextOffset()).line) {
                    return;
                }
            }
            for (String keyword : TOP_LEVEL_KEYWORDS) {
                // TODO filter schema if already declared
                LookupElementBuilder element = LookupElementBuilder.create(keyword).withBoldness(true);
                if (keyword.equals("{")) {
                    element = element.withInsertHandler((ctx, item) -> {
                        EditorModificationUtil.insertStringAtCaret(ctx.getEditor(), "}");
                        PsiDocumentManager.getInstance(ctx.getProject()).commitDocument(ctx.getEditor().getDocument());
                        ctx.getEditor().getCaretModel().moveCaretRelatively(-1, 0, false, false, false);
                    });
                } else {
                    element = element.withInsertHandler(AddSpaceInsertHandler.INSTANCE_WITH_AUTO_POPUP);
                }
                result.addElement(element);
            }
        }
    };
    extend(CompletionType.BASIC, TOP_LEVEL_KEYWORD_PATTERN, provider);
}
 
Example #14
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 #15
Source File: InitialScrollPositionSupport.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static LogicalPosition[] doGetCaretPositions(@Nonnull List<? extends Editor> editors) {
  LogicalPosition[] carets = new LogicalPosition[editors.size()];
  for (int i = 0; i < editors.size(); i++) {
    carets[i] = DiffUtil.getCaretPosition(editors.get(i));
  }
  return carets;
}
 
Example #16
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 #17
Source File: EditorView.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public VisualPosition logicalToVisualPosition(@Nonnull LogicalPosition pos, boolean beforeSoftWrap) {
  assertIsDispatchThread();
  assertNotInBulkMode();
  myEditor.getSoftWrapModel().prepareToMapping();
  return myMapper.logicalToVisualPosition(pos, beforeSoftWrap);
}
 
Example #18
Source File: DocumentUtils.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Transforms an LSP position to an editor offset
 *
 * @param editor The editor
 * @param pos    The LSPPos
 * @return The offset
 */
public static int LSPPosToOffset(Editor editor, Position pos) {
    return computableReadAction(() -> {
        try {
            if (editor.isDisposed()) {
                return -1;
            }

            Document doc = editor.getDocument();
            int line = Math.max(0, Math.min(pos.getLine(), doc.getLineCount()));
            String lineText = doc.getText(DocumentUtil.getLineTextRange(doc, line));
            String lineTextForPosition = !lineText.isEmpty() ?
                    lineText.substring(0, min(lineText.length(), pos.getCharacter())) :
                    "";
            int tabs = StringUtil.countChars(lineTextForPosition, '\t');
            int tabSize = editor.getSettings().getTabSize(editor.getProject());
            int column = tabs * tabSize + lineTextForPosition.length() - tabs;
            int offset = editor.logicalPositionToOffset(new LogicalPosition(line, column));
            if (pos.getCharacter() >= lineText.length()) {
                LOG.warn(String.format("LSPPOS outofbounds : %s line : %s column : %d offset : %d", pos,
                        lineText, column, offset));
            }
            int docLength = doc.getTextLength();
            if (offset > docLength) {
                LOG.warn(String.format("Offset greater than text length : %d > %d", offset, docLength));
            }
            return Math.min(Math.max(offset, 0), docLength);
        } catch (IndexOutOfBoundsException e) {
            return -1;
        }
    });
}
 
Example #19
Source File: LSPReferencesAction.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
private void showReferences(Editor editor, List<PsiElement2UsageTargetAdapter> targets, LogicalPosition position) {
    if (targets.isEmpty()) {
        short constraint = HintManager.ABOVE;
        int flags = HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE | HintManager.HIDE_BY_SCROLLING;
        JLabel label = new JLabel("No references found");
        label.setBackground(new JBColor(new Color(150, 0, 0), new Color(150, 0, 0)));
        LightweightHint hint = new LightweightHint(label);
        Point p = HintManagerImpl.getHintPosition(hint, editor, position, constraint);
        HintManagerImpl.getInstanceImpl().showEditorHint(hint, editor, p, flags, 0, false,
                HintManagerImpl.createHintHint(editor, p, hint, constraint).setContentActive(false));
    } else {
        List<Usage> usages = new ArrayList<>();
        targets.forEach(ut -> {
            PsiElement elem = ut.getElement();
            usages.add(new UsageInfo2UsageAdapter(new UsageInfo(elem, -1, -1, false)));
        });

        if (editor == null) {
            return;
        }
        Project project = editor.getProject();
        if (project == null) {
            return;
        }
        UsageViewPresentation presentation = createPresentation(targets.get(0).getElement(),
                new FindUsagesOptions(editor.getProject()), false);
        UsageViewManager.getInstance(project)
                .showUsages(new UsageTarget[] { targets.get(0) }, usages.toArray(new Usage[usages.size()]),
                        presentation);
    }
}
 
Example #20
Source File: InitialScrollPositionSupport.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void updateContext(@Nonnull DiffRequest request) {
  LogicalPosition[] carets = getCaretPositions();
  EditorsVisiblePositions visiblePositions = getVisiblePositions();

  request.putUserData(DiffUserDataKeysEx.SCROLL_TO_CHANGE, null);
  request.putUserData(EditorsVisiblePositions.KEY, visiblePositions);
  request.putUserData(DiffUserDataKeysEx.EDITORS_CARET_POSITION, carets);
}
 
Example #21
Source File: SortLinesBySubSelectionAction.java    From StringManipulation with Apache License 2.0 5 votes vote down vote up
protected Caret getCaretAt(Editor editor, LogicalPosition position) {
	List<Caret> allCarets = editor.getCaretModel().getAllCarets();
	for (Caret caret : allCarets) {
		if (caret.getLogicalPosition().equals(position)) {
			return caret;
		}
	}
	throw new IllegalStateException("caret not found for " + position + "allCarets:" + allCarets);
}
 
Example #22
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 #23
Source File: CaretEvent.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated Use {@link #CaretEvent(Caret, LogicalPosition, LogicalPosition)} instead.
 */
@Deprecated
public CaretEvent(@Nonnull Editor editor, @Nullable Caret caret, @Nonnull LogicalPosition oldPosition, @Nonnull LogicalPosition newPosition) {
  super(editor);
  myCaret = caret;
  myOldPosition = oldPosition;
  myNewPosition = newPosition;
}
 
Example #24
Source File: AlignToColumnsForm.java    From StringManipulation with Apache License 2.0 5 votes vote down vote up
protected void preview() {
	List<CaretState> caretsAndSelections = editor.getCaretModel().getCaretsAndSelections();
	IdeUtils.sort(caretsAndSelections);
	List<String> lines = new ArrayList<String>();
	for (CaretState caretsAndSelection : caretsAndSelections) {
		LogicalPosition selectionStart = caretsAndSelection.getSelectionStart();
		LogicalPosition selectionEnd = caretsAndSelection.getSelectionEnd();
		String text = editor.getDocument().getText(
			new TextRange(editor.logicalPositionToOffset(selectionStart),
				editor.logicalPositionToOffset(selectionEnd)));

		String[] split = text.split("\n");
		lines.addAll(Arrays.asList(split));
	}

	ColumnAligner columnAligner = new ColumnAligner(getModel());
	List<String> result = columnAligner.align(lines);

	debugValues.removeAll();
	List<String> debug = columnAligner.getDebugValues();
	for (String s : debug) {
		debugValues.add(new JLabel(s));
	}
	debugValues.revalidate();
	debugValues.repaint();


	ApplicationManager.getApplication().runWriteAction(() -> {
		myPreviewEditor.getDocument().setText(Joiner.on("\n").join(result));
		myPreviewPanel.validate();
		myPreviewPanel.repaint();
	});
}
 
Example #25
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 #26
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 #27
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 #28
Source File: RequirejsTestCase.java    From WebStormRequireJsPlugin with MIT License 5 votes vote down vote up
protected PsiReference getReferenceForPosition(int line, int column) {
    myFixture
            .getEditor()
            .getCaretModel()
            .moveToLogicalPosition(new LogicalPosition(line, column));
    return myFixture.getReferenceAtCaretPosition();
}
 
Example #29
Source File: SurroundWithHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
static void doSurround(final Project project, final Editor editor, final Surrounder surrounder, final PsiElement[] elements) {
  if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
    return;
  }

  try {
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    int col = editor.getCaretModel().getLogicalPosition().column;
    int line = editor.getCaretModel().getLogicalPosition().line;
    if (!editor.getCaretModel().supportsMultipleCarets()) {
      LogicalPosition pos = new LogicalPosition(0, 0);
      editor.getCaretModel().moveToLogicalPosition(pos);
    }
    TextRange range = surrounder.surroundElements(project, editor, elements);
    if (range != CARET_IS_OK) {
      if (TemplateManager.getInstance(project).getActiveTemplate(editor) == null &&
          InplaceRefactoring.getActiveInplaceRenamer(editor) == null) {
        LogicalPosition pos1 = new LogicalPosition(line, col);
        editor.getCaretModel().moveToLogicalPosition(pos1);
      }
      if (range != null) {
        int offset = range.getStartOffset();
        editor.getCaretModel().removeSecondaryCarets();
        editor.getCaretModel().moveToOffset(offset);
        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
        editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
      }
    }
  }
  catch (IncorrectOperationException e) {
    LOG.error(e);
  }
}
 
Example #30
Source File: SyncScrollSupport.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void scrollEditor(@Nonnull Editor editor, int logicalLine) {
  editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(logicalLine, 0));
  ScrollingModel scrollingModel = editor.getScrollingModel();
  scrollingModel.disableAnimation();
  scrollingModel.scrollToCaret(ScrollType.CENTER);
  scrollingModel.enableAnimation();
}