com.intellij.openapi.editor.ex.util.EditorUtil Java Examples

The following examples show how to use com.intellij.openapi.editor.ex.util.EditorUtil. 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: VisualLinesIterator.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void advance() {
  checkEnd();
  if (y != UNSET) {
    y += EditorUtil.getTotalInlaysHeight(getBlockInlaysBelow());
    y += myLineHeight;
  }
  if (myNextLocation == null) {
    myLocation.advance();
  }
  else {
    myLocation = myNextLocation;
    myNextLocation = null;
  }
  myInlaysSet = false;
  if (y != UNSET && !atEnd()) {
    y += EditorUtil.getTotalInlaysHeight(getBlockInlaysAbove());
  }
}
 
Example #2
Source File: ViewStructureAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static FileStructurePopup createPopup(@Nonnull Project project, @Nonnull FileEditor fileEditor) {
  PsiDocumentManager.getInstance(project).commitAllDocuments();
  StructureViewBuilder builder = fileEditor.getStructureViewBuilder();
  if (builder == null) return null;
  StructureView structureView;
  StructureViewModel treeModel;
  if (builder instanceof TreeBasedStructureViewBuilder) {
    structureView = null;
    treeModel = ((TreeBasedStructureViewBuilder)builder).createStructureViewModel(EditorUtil.getEditorEx(fileEditor));
  }
  else {
    structureView = builder.createStructureView(fileEditor, project);
    treeModel = createStructureViewModel(project, fileEditor, structureView);
  }
  if (treeModel instanceof PlaceHolder) {
    //noinspection unchecked
    ((PlaceHolder)treeModel).setPlace(TreeStructureUtil.PLACE);
  }
  FileStructurePopup popup = new FileStructurePopup(project, fileEditor, treeModel);
  if (structureView != null) Disposer.register(popup, structureView);
  return popup;
}
 
Example #3
Source File: LivePreview.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void showBalloon(Editor editor, String replacementPreviewText) {
  if (ApplicationManager.getApplication().isUnitTestMode()) {
    myReplacementPreviewText = replacementPreviewText;
    return;
  }

  ReplacementView replacementView = new ReplacementView(replacementPreviewText);

  BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createBalloonBuilder(replacementView);
  balloonBuilder.setFadeoutTime(0);
  balloonBuilder.setFillColor(IdeTooltipManager.GRAPHITE_COLOR);
  balloonBuilder.setAnimationCycle(0);
  balloonBuilder.setHideOnClickOutside(false);
  balloonBuilder.setHideOnKeyOutside(false);
  balloonBuilder.setHideOnAction(false);
  balloonBuilder.setCloseButtonEnabled(true);
  myReplacementBalloon = balloonBuilder.createBalloon();
  EditorUtil.disposeWithEditor(editor, myReplacementBalloon);
  myReplacementBalloon.show(new ReplacementBalloonPositionTracker(editor), Balloon.Position.below);
}
 
Example #4
Source File: ShowExpressionTypeHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@RequiredReadAction
private static Map<PsiElement, ExpressionTypeProvider> getExpressions(@Nonnull PsiFile file, @Nonnull Editor editor, @Nonnull Set<? extends ExpressionTypeProvider> handlers) {
  if (handlers.isEmpty()) return Collections.emptyMap();
  boolean exactRange = false;
  TextRange range = EditorUtil.getSelectionInAnyMode(editor);
  final Map<PsiElement, ExpressionTypeProvider> map = new LinkedHashMap<>();
  int offset = !range.isEmpty() ? range.getStartOffset() : TargetElementUtil.adjustOffset(file, editor.getDocument(), range.getStartOffset());
  for (int i = 0; i < 3 && map.isEmpty() && offset >= i; i++) {
    PsiElement elementAt = file.findElementAt(offset - i);
    if (elementAt == null) continue;
    for (ExpressionTypeProvider handler : handlers) {
      for (PsiElement element : ((ExpressionTypeProvider<? extends PsiElement>)handler).getExpressionsAt(elementAt)) {
        TextRange r = element.getTextRange();
        if (exactRange && !r.equals(range) || !r.contains(range)) continue;
        if (!exactRange) exactRange = r.equals(range);
        map.put(element, handler);
      }
    }
  }
  return map;
}
 
Example #5
Source File: EditorWindowImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int calcOffset(int col, int lineNumber, int lineStartOffset) {
  CharSequence text = myDocumentWindow.getImmutableCharSequence();
  int tabSize = EditorUtil.getTabSize(myDelegate);
  int end = myDocumentWindow.getLineEndOffset(lineNumber);
  int currentColumn = 0;
  for (int i = lineStartOffset; i < end; i++) {
    char c = text.charAt(i);
    if (c == '\t') {
      currentColumn = (currentColumn / tabSize + 1) * tabSize;
    }
    else {
      currentColumn++;
    }
    if (col < currentColumn) return i;
  }
  return end;
}
 
Example #6
Source File: ExpressionInputComponent.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void showHistory() {
  List<XExpression> expressions = myExpressionEditor.getRecentExpressions();
  if (!expressions.isEmpty()) {
    ListPopupImpl popup = new ListPopupImpl(new BaseListPopupStep<XExpression>(null, expressions) {
      @Override
      public PopupStep onChosen(XExpression selectedValue, boolean finalChoice) {
        myExpressionEditor.setExpression(selectedValue);
        myExpressionEditor.requestFocusInEditor();
        return FINAL_CHOICE;
      }
    }) {
      @Override
      protected ListCellRenderer getListElementRenderer() {
        return new ColoredListCellRenderer<XExpression>() {
          @Override
          protected void customizeCellRenderer(@Nonnull JList list, XExpression value, int index, boolean selected, boolean hasFocus) {
            append(value.getExpression());
          }
        };
      }
    };
    popup.getList().setFont(EditorUtil.getEditorFont());
    popup.showUnderneathOf(myExpressionEditor.getEditorComponent());
  }
}
 
Example #7
Source File: IterationState.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void retreat(int offset) {
  for (int j = i - 2; j >= 0; j--) {
    RangeHighlighterEx highlighter = highlighters[j];
    if (skipHighlighter(highlighter)) continue;
    if (getAlignedStartOffset(highlighter) > offset) {
      myNextHighlighter = highlighter;
      i = j + 1;
    }
    else {
      break;
    }
  }
  myMarkupModel.processRangeHighlightersOverlappingWith(offset, offset, h -> {
    if ((!myOnlyFullLine || h.getTargetArea() == HighlighterTargetArea.LINES_IN_RANGE) &&
        (!myOnlyFontOrForegroundAffecting || EditorUtil.attributesImpactFontStyleOrColor(h.getTextAttributes())) &&
        !skipHighlighter(h)) {
      myCurrentHighlighters.add(h);
    }
    return true;
  });
}
 
Example #8
Source File: DeleteLineAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static TextRange getRangeToDelete(Editor editor, Caret caret) {
  int selectionStart = caret.getSelectionStart();
  int selectionEnd = caret.getSelectionEnd();
  int startOffset = EditorUtil.getNotFoldedLineStartOffset(editor, selectionStart);
  // There is a possible case that selection ends at the line start, i.e. something like below ([...] denotes selected text,
  // '|' is a line start):
  //   |line 1
  //   |[line 2
  //   |]line 3
  // We don't want to delete line 3 here. However, the situation below is different:
  //   |line 1
  //   |[line 2
  //   |line] 3
  // Line 3 must be removed here.
  int endOffset = EditorUtil.getNotFoldedLineEndOffset(editor, selectionEnd > 0 && selectionEnd != selectionStart ? selectionEnd - 1 : selectionEnd);
  if (endOffset < editor.getDocument().getTextLength()) {
    endOffset++;
  }
  else if (startOffset > 0) {
    startOffset--;
  }
  return new TextRange(startOffset, endOffset);
}
 
Example #9
Source File: EventLogConsole.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void addConfigureNotificationAction(@Nonnull EditorEx editor, @Nonnull EditorMouseEvent event, @Nonnull final DefaultActionGroup actions) {
  LogicalPosition position = editor.xyToLogicalPosition(event.getMouseEvent().getPoint());
  if (EditorUtil.inVirtualSpace(editor, position)) {
    return;
  }
  int offset = editor.logicalPositionToOffset(position);
  editor.getMarkupModel().processRangeHighlightersOverlappingWith(offset, offset, new Processor<RangeHighlighterEx>() {
    @Override
    public boolean process(RangeHighlighterEx rangeHighlighter) {
      String groupId = GROUP_ID.get(rangeHighlighter);
      if (groupId != null) {
        addConfigureNotificationAction(actions, groupId);
        return false;
      }
      return true;
    }
  });
}
 
Example #10
Source File: EditorCoordinateMapper.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int visualLineStartOffset(int offset, boolean leanForward) {
  DesktopEditorImpl editor = myView.getEditor();
  offset = DocumentUtil.alignToCodePointBoundary(myDocument, offset);
  int result = EditorUtil.getNotFoldedLineStartOffset(editor, offset);

  SoftWrapModelImpl softWrapModel = editor.getSoftWrapModel();
  List<? extends SoftWrap> softWraps = softWrapModel.getRegisteredSoftWraps();
  int currentOrPrevWrapIndex = softWrapModel.getSoftWrapIndex(offset);
  SoftWrap currentOrPrevWrap;
  if (currentOrPrevWrapIndex < 0) {
    currentOrPrevWrapIndex = -currentOrPrevWrapIndex - 2;
    currentOrPrevWrap = currentOrPrevWrapIndex < 0 || currentOrPrevWrapIndex >= softWraps.size() ? null : softWraps.get(currentOrPrevWrapIndex);
  }
  else {
    currentOrPrevWrap = leanForward ? softWraps.get(currentOrPrevWrapIndex) : null;
  }
  if (currentOrPrevWrap != null && currentOrPrevWrap.getStart() > result) {
    result = currentOrPrevWrap.getStart();
  }
  return result;
}
 
Example #11
Source File: IterationState.java    From consulo with Apache License 2.0 6 votes vote down vote up
private HighlighterSweep(@Nonnull MarkupModelEx markupModel, int start, int end, final boolean onlyFullLine, final boolean onlyFontOrForegroundAffecting) {
  myMarkupModel = markupModel;
  myOnlyFullLine = onlyFullLine;
  myOnlyFontOrForegroundAffecting = onlyFontOrForegroundAffecting;
  // we have to get all highlighters in advance and sort them by affected offsets
  // since these can be different from the real offsets the highlighters are sorted by in the tree.  (See LINES_IN_RANGE perverts)
  final List<RangeHighlighterEx> list = new ArrayList<>();
  markupModel.processRangeHighlightersOverlappingWith(myReverseIteration ? end : start, myReverseIteration ? start : end, new CommonProcessors.CollectProcessor<RangeHighlighterEx>(list) {
    @Override
    protected boolean accept(RangeHighlighterEx ex) {
      return (!onlyFullLine || ex.getTargetArea() == HighlighterTargetArea.LINES_IN_RANGE) && (!onlyFontOrForegroundAffecting || EditorUtil.attributesImpactFontStyleOrColor(ex.getTextAttributes()));
    }
  });
  highlighters = list.isEmpty() ? RangeHighlighterEx.EMPTY_ARRAY : list.toArray(RangeHighlighterEx.EMPTY_ARRAY);
  Arrays.sort(highlighters, myReverseIteration ? BY_AFFECTED_END_OFFSET_REVERSED : RangeHighlighterEx.BY_AFFECTED_START_OFFSET);

  while (i < highlighters.length) {
    RangeHighlighterEx highlighter = highlighters[i++];
    if (!skipHighlighter(highlighter)) {
      myNextHighlighter = highlighter;
      break;
    }
  }
}
 
Example #12
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 #13
Source File: TogglePresentationModeAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void tweakEditorAndFireUpdateUI(UISettings settings, boolean inPresentation) {
  EditorColorsScheme globalScheme = EditorColorsManager.getInstance().getGlobalScheme();
  int fontSize = inPresentation ? settings.PRESENTATION_MODE_FONT_SIZE : globalScheme.getEditorFontSize();
  if (inPresentation) {
    ourSavedConsoleFontSize = globalScheme.getConsoleFontSize();
    globalScheme.setConsoleFontSize(fontSize);
  }
  else {
    globalScheme.setConsoleFontSize(ourSavedConsoleFontSize);
  }
  for (Editor editor : EditorFactory.getInstance().getAllEditors()) {
    if (editor instanceof EditorEx) {
      ((EditorEx)editor).setFontSize(fontSize);
    }
  }
  UISettings.getInstance().fireUISettingsChanged();
  LafManager.getInstance().updateUI();
  EditorUtil.reinitSettings();
}
 
Example #14
Source File: EditorHyperlinkSupport.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public Runnable getLinkNavigationRunnable(final LogicalPosition logical) {
  if (EditorUtil.inVirtualSpace(myEditor, logical)) {
    return null;
  }

  final RangeHighlighter range = findLinkRangeAt(myEditor.logicalPositionToOffset(logical));
  if (range != null) {
    final HyperlinkInfo hyperlinkInfo = getHyperlinkInfo(range);
    if (hyperlinkInfo != null) {
      return () -> {
        if (hyperlinkInfo instanceof HyperlinkInfoBase) {
          final Point point = myEditor.logicalPositionToXY(logical);
          final MouseEvent event = new MouseEvent(myEditor.getContentComponent(), 0, 0, 0, point.x, point.y, 1, false);
          ((HyperlinkInfoBase)hyperlinkInfo).navigate(myProject, new RelativePoint(event));
        }
        else {
          hyperlinkInfo.navigate(myProject);
        }
        linkFollowed(myEditor, getHyperlinks(0, myEditor.getDocument().getTextLength(), myEditor), range);
      };
    }
  }
  return null;
}
 
Example #15
Source File: IncrementalCacheUpdateEvent.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static VisualLineInfo getVisualLineInfo(@Nonnull DesktopEditorImpl editor, int offset, boolean beforeSoftWrap) {
  Document document = editor.getDocument();
  int textLength = document.getTextLength();
  if (offset <= 0 || textLength == 0) return new VisualLineInfo(0, false);
  offset = Math.min(offset, textLength);

  int startOffset = EditorUtil.getNotFoldedLineStartOffset(editor, offset);

  SoftWrapModelImpl softWrapModel = editor.getSoftWrapModel();
  int wrapIndex = softWrapModel.getSoftWrapIndex(offset);
  int prevSoftWrapIndex = wrapIndex < 0 ? -wrapIndex - 2 : wrapIndex - (beforeSoftWrap ? 1 : 0);
  SoftWrap prevSoftWrap = prevSoftWrapIndex < 0 ? null : softWrapModel.getRegisteredSoftWraps().get(prevSoftWrapIndex);

  int visualLineStartOffset = prevSoftWrap == null ? startOffset : Math.max(startOffset, prevSoftWrap.getStart());
  return new VisualLineInfo(visualLineStartOffset, prevSoftWrap != null && prevSoftWrap.getStart() == visualLineStartOffset);
}
 
Example #16
Source File: DesktopCaretImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateVisualLineInfo() {
  myVisualLineStart = myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line, 0)));
  myVisualLineEnd = myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line + 1, 0)));

  int y = myEditor.visualLineToY(myVisibleCaret.line);

  int logicalLineStartY;
  if (myEditor.getSoftWrapModel().getSoftWrap(myVisualLineStart) == null) {
    logicalLineStartY = y;
  }
  else {
    int startVisualLine = myEditor.myView.offsetToVisualLine(EditorUtil.getNotFoldedLineStartOffset(myEditor, getOffset()), false);
    logicalLineStartY = myEditor.visualLineToY(startVisualLine);
  }

  int logicalLineEndY;
  if (myEditor.getSoftWrapModel().getSoftWrap(myVisualLineEnd) == null) {
    logicalLineEndY = y;
  }
  else {
    int endVisualLine = myEditor.myView.offsetToVisualLine(EditorUtil.getNotFoldedLineEndOffset(myEditor, getOffset()), true);
    logicalLineEndY = myEditor.visualLineToY(endVisualLine);
  }

  myVerticalInfo = new VerticalInfo(y, logicalLineStartY, logicalLineEndY - logicalLineStartY + myEditor.getLineHeight());
}
 
Example #17
Source File: DesktopEditorImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void onInlayUpdated(@Nonnull Inlay inlay) {
  if (myDocument.isInEventsHandling() || myDocument.isInBulkUpdate()) return;
  validateSize();
  int offset = inlay.getOffset();
  Inlay.Placement placement = inlay.getPlacement();
  if (placement == Inlay.Placement.INLINE) {
    repaint(offset, offset, false);
  }
  else if (placement == Inlay.Placement.AFTER_LINE_END) {
    int lineEndOffset = DocumentUtil.getLineEndOffset(offset, myDocument);
    repaint(lineEndOffset, lineEndOffset, false);
  }
  else {
    int visualLine = offsetToVisualLine(offset);
    int y = visualLineToY(visualLine) - EditorUtil.getTotalInlaysHeight(myInlayModel.getBlockElementsForVisualLine(visualLine, true));
    repaintToScreenBottomStartingFrom(y);
  }
}
 
Example #18
Source File: DesktopSelectionModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void doSelectLineAtCaret(Caret caret) {
  Editor editor = caret.getEditor();
  int lineNumber = caret.getLogicalPosition().line;
  Document document = editor.getDocument();
  if (lineNumber >= document.getLineCount()) {
    return;
  }

  Pair<LogicalPosition, LogicalPosition> lines = EditorUtil.calcCaretLineRange(caret);
  LogicalPosition lineStart = lines.first;
  LogicalPosition nextLineStart = lines.second;

  int start = editor.logicalPositionToOffset(lineStart);
  int end = editor.logicalPositionToOffset(nextLineStart);

  editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
  caret.removeSelection();
  caret.setSelection(start, end);
}
 
Example #19
Source File: ConsoleGutterComponent.java    From consulo with Apache License 2.0 6 votes vote down vote up
public ConsoleGutterComponent(@Nonnull Editor editor, @Nonnull GutterContentProvider gutterContentProvider, boolean atLineStart) {
  this.editor = (DesktopEditorImpl)editor;
  this.gutterContentProvider = gutterContentProvider;
  this.atLineStart = atLineStart;

  if (atLineStart) {
    setOpaque(gutterContentProvider.getLineStartGutterOverlap(editor) == 0);
  }
  else {
    addListeners();
    setOpaque(false);
  }

  int spaceWidth = EditorUtil.getSpaceWidth(Font.PLAIN, editor);
  // at line start: icon/one-char symbol + space
  gap = atLineStart ? spaceWidth * GutterContentProvider.MAX_LINE_END_GUTTER_WIDTH_IN_CHAR : spaceWidth;
  maxContentWidth = atLineStart ? gap : 0;
}
 
Example #20
Source File: EditorGutterComponentImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void calcAnnotationExtraSize() {
  myTextAnnotationExtraSize = 0;
  if (!myEditor.isInDistractionFreeMode() || isMirrored()) return;

  Window frame = SwingUtilities.getWindowAncestor(myEditor.getComponent());
  if (frame == null) return;

  EditorSettings settings = myEditor.getSettings();
  int rightMargin = settings.getRightMargin(myEditor.getProject());
  if (rightMargin <= 0) return;

  JComponent editorComponent = myEditor.getComponent();
  RelativePoint point = new RelativePoint(editorComponent, new Point(0, 0));
  Point editorLocationInWindow = point.getPoint(frame);

  int editorLocationX = (int)editorLocationInWindow.getX();
  int rightMarginX = rightMargin * EditorUtil.getSpaceWidth(Font.PLAIN, myEditor) + editorLocationX;

  int width = editorLocationX + editorComponent.getWidth();
  if (rightMarginX < width && editorLocationX < width - rightMarginX) {
    int centeredSize = (width - rightMarginX - editorLocationX) / 2 - (getLineMarkerAreaWidth() + getLineNumberAreaWidth() + getFoldingAreaWidth() + 2 * getGapBetweenAreas());
    myTextAnnotationExtraSize = Math.max(0, centeredSize - myTextAnnotationGuttersSize);
  }
}
 
Example #21
Source File: EditorComponentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
  if (orientation == SwingConstants.VERTICAL) {
    return myEditor.getLineHeight();
  }
  // if orientation == SwingConstants.HORIZONTAL
  return EditorUtil.getSpaceWidth(Font.PLAIN, myEditor);
}
 
Example #22
Source File: BigPopupUI.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void init() {
  withBackground(JBUI.CurrentTheme.BigPopup.headerBackground());

  myResultsList = createList();

  JPanel topLeftPanel = createTopLeftPanel();
  JPanel settingsPanel = createSettingsPanel();
  mySearchField = createSearchField();
  mySearchField.addBorders(BorderStyle.EMPTY, null, 4);
  (TargetAWT.to(mySearchField)).setFocusTraversalKeysEnabled(false);
  suggestionsPanel = createSuggestionsPanel();

  myResultsList.setFocusable(false);
  myResultsList.setCellRenderer(createCellRenderer());

  if (Registry.is("new.search.everywhere.use.editor.font")) {
    Font editorFont = EditorUtil.getEditorFont();
    myResultsList.setFont(editorFont);
  }

  installScrollingActions();

  JPanel topPanel = new JPanel(new BorderLayout());
  topPanel.setOpaque(false);
  topPanel.add(topLeftPanel, BorderLayout.WEST);
  topPanel.add(settingsPanel, BorderLayout.EAST);
  topPanel.add(TargetAWT.to(mySearchField), BorderLayout.SOUTH);

  WindowMoveListener moveListener = new WindowMoveListener(this);
  topPanel.addMouseListener(moveListener);
  topPanel.addMouseMotionListener(moveListener);

  addToTop(topPanel);
  addToCenter(suggestionsPanel);

  MnemonicHelper.init(this);
}
 
Example #23
Source File: EditorGutterComponentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private int convertPointToLineNumber(final Point p) {
  DocumentEx document = myEditor.getDocument();
  int line = EditorUtil.yPositionToLogicalLine(myEditor, p);
  if (!isValidLine(document, line)) return -1;

  int startOffset = document.getLineStartOffset(line);
  final FoldRegion region = myEditor.getFoldingModel().getCollapsedRegionAtOffset(startOffset);
  if (region != null) {
    return document.getLineNumber(region.getEndOffset());
  }
  return line;
}
 
Example #24
Source File: SelectWordAtCaretAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  SelectionModel selectionModel = editor.getSelectionModel();
  Document document = editor.getDocument();

  if (EditorUtil.isPasswordEditor(editor)) {
    selectionModel.setSelection(0, document.getTextLength());
    return;
  }

  int lineNumber = editor.getCaretModel().getLogicalPosition().line;
  int caretOffset = editor.getCaretModel().getOffset();
  if (lineNumber >= document.getLineCount()) {
    return;
  }

  boolean camel = editor.getSettings().isCamelWords();
  List<TextRange> ranges = new ArrayList<TextRange>();

  int textLength = document.getTextLength();
  if (caretOffset == textLength) caretOffset--;
  if (caretOffset < 0) return;

  SelectWordUtil.addWordOrLexemeSelection(camel, editor, caretOffset, ranges);

  if (ranges.isEmpty()) return;

  final TextRange selectionRange = new TextRange(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd());

  TextRange minimumRange = new TextRange(0, document.getTextLength());
  for (TextRange range : ranges) {
    if (range.contains(selectionRange) && !range.equals(selectionRange)) {
      if (minimumRange.contains(range)) {
        minimumRange = range;
      }
    }
  }

  selectionModel.setSelection(minimumRange.getStartOffset(), minimumRange.getEndOffset());
}
 
Example #25
Source File: EditorComponentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Object getData(@Nonnull Key<?> dataId) {
  if (myEditor.isDisposed() || myEditor.isRendererMode()) return null;

  if (CommonDataKeys.EDITOR == dataId) {
    return myEditor;
  }
  if (CommonDataKeys.CARET == dataId) {
    return myEditor.getCaretModel().getCurrentCaret();
  }
  if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER == dataId) {
    return myEditor.getDeleteProvider();
  }
  if (PlatformDataKeys.CUT_PROVIDER == dataId) {
    return myEditor.getCutProvider();
  }
  if (PlatformDataKeys.COPY_PROVIDER == dataId) {
    return myEditor.getCopyProvider();
  }
  if (PlatformDataKeys.PASTE_PROVIDER == dataId) {
    return myEditor.getPasteProvider();
  }
  if (CommonDataKeys.EDITOR_VIRTUAL_SPACE == dataId) {
    LogicalPosition location = myEditor.myLastMousePressedLocation;
    if (location == null) {
      location = myEditor.getCaretModel().getLogicalPosition();
    }
    return EditorUtil.inVirtualSpace(myEditor, location);
  }
  return null;
}
 
Example #26
Source File: EditorWindowImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private int calcLogicalColumnNumber(int offsetInLine, int lineNumber, int lineStartOffset) {
  if (myDocumentWindow.getTextLength() == 0) return 0;

  if (offsetInLine == 0) return 0;
  int end = myDocumentWindow.getLineEndOffset(lineNumber);
  if (offsetInLine > end - lineStartOffset) offsetInLine = end - lineStartOffset;

  CharSequence text = myDocumentWindow.getCharsSequence();
  return EditorUtil.calcColumnNumber(this, text, lineStartOffset, lineStartOffset + offsetInLine);
}
 
Example #27
Source File: SoftWrapApplianceManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
private int getEndOffsetUpperEstimate(IncrementalCacheUpdateEvent event) {
  int endOffsetUpperEstimate = EditorUtil.getNotFoldedLineEndOffset(myEditor, event.getMandatoryEndOffset());
  int line = myEditor.getDocument().getLineNumber(endOffsetUpperEstimate);
  if (line < myEditor.getDocument().getLineCount() - 1) {
    endOffsetUpperEstimate = myEditor.getDocument().getLineStartOffset(line + 1);
  }
  return endOffsetUpperEstimate;
}
 
Example #28
Source File: ListTemplatesHandler.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 PsiFile file) {
  if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return;
  if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
    return;
  }
  EditorUtil.fillVirtualSpaceUntilCaret(editor);

  PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
  int offset = editor.getCaretModel().getOffset();
  List<TemplateImpl> applicableTemplates = TemplateManagerImpl.listApplicableTemplateWithInsertingDummyIdentifier(editor, file, false);

  Map<TemplateImpl, String> matchingTemplates = filterTemplatesByPrefix(applicableTemplates, editor, offset, false, true);
  MultiMap<String, CustomLiveTemplateLookupElement> customTemplatesLookupElements = getCustomTemplatesLookupItems(editor, file, offset);

  if (matchingTemplates.isEmpty()) {
    for (TemplateImpl template : applicableTemplates) {
      matchingTemplates.put(template, null);
    }
  }

  if (matchingTemplates.isEmpty() && customTemplatesLookupElements.isEmpty()) {
    HintManager.getInstance().showErrorHint(editor, CodeInsightBundle.message("templates.no.defined"));
    return;
  }

  showTemplatesLookup(project, editor, file, matchingTemplates, customTemplatesLookupElements);
}
 
Example #29
Source File: BaseIndentEnterHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static int calcLogicalLength(Editor editor, CharSequence lineIndent) {
  int result = 0;
  for (int i = 0; i < lineIndent.length(); i++) {
    if (lineIndent.charAt(i) == '\t') {
      result += EditorUtil.getTabSize(editor);
    } else {
      result++;
    }
  }
  return result;
}
 
Example #30
Source File: SoftWrapApplianceManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
private int[] calculateNewX(int c) {
  if (c == '\t') {
    int xStart = myContext.currentPosition.x + myContext.getInlaysPrefixWidth();
    int xEnd = EditorUtil.nextTabStop(xStart, myEditor);
    return new int[]{xEnd + myContext.getInlaysSuffixWidth(), xEnd - xStart};
  }
  else {
    int width = SoftWrapModelImpl.getEditorTextRepresentationHelper(myEditor).charWidth(c, myContext.fontType);
    return new int[]{myContext.currentPosition.x + width + myContext.getInlaysWidth(), width};
  }
}