com.intellij.util.DocumentUtil Java Examples

The following examples show how to use com.intellij.util.DocumentUtil. 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: 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 #2
Source File: SoftWrapEngine.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int calcSoftWrapOffset(int minOffset, int maxOffset, boolean preferMinOffset) {
  if (canBreakBeforeOrAfterCodePoint(Character.codePointAt(myText, maxOffset))) return maxOffset;
  for (int i = 0, offset = maxOffset; i < BASIC_LOOK_BACK_LENGTH && offset >= minOffset; i++) {
    int prevOffset = Character.offsetByCodePoints(myText, offset, -1);
    if (canBreakBeforeOrAfterCodePoint(Character.codePointAt(myText, prevOffset))) return offset;
    //noinspection AssignmentToForLoopParameter
    offset = prevOffset;
  }

  if (myLineWrapPositionStrategy == null) {
    myLineWrapPositionStrategy = LanguageLineWrapPositionStrategy.INSTANCE.forEditor(myEditor);
  }

  int wrapOffset = myLineWrapPositionStrategy.calculateWrapPosition(myDocument, myEditor.getProject(), minOffset - 1, maxOffset + 1, maxOffset + 1, false, true);
  if (wrapOffset < 0) return preferMinOffset ? minOffset : maxOffset;
  if (wrapOffset < minOffset) return minOffset;
  if (wrapOffset > maxOffset) return maxOffset;
  if (DocumentUtil.isInsideSurrogatePair(myDocument, wrapOffset)) return wrapOffset - 1;
  return wrapOffset;
}
 
Example #3
Source File: DesktopCaretImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void changedUpdateImpl(@Nonnull DocumentEvent e) {
  super.changedUpdateImpl(e);
  if (isValid()) {
    int startOffset = intervalStart();
    int endOffset = intervalEnd();
    if (DocumentUtil.isInsideSurrogatePair(getDocument(), startOffset)) setIntervalStart(startOffset - 1);
    if (DocumentUtil.isInsideSurrogatePair(getDocument(), endOffset)) setIntervalStart(endOffset - 1);
  }
  if (endVirtualOffset > 0 && isValid()) {
    Document document = e.getDocument();
    int startAfter = intervalStart();
    int endAfter = intervalEnd();
    if (!DocumentUtil.isAtLineEnd(endAfter, document) || document.getLineNumber(startAfter) != document.getLineNumber(endAfter)) {
      resetVirtualSelection();
    }
  }
}
 
Example #4
Source File: SoftWrapModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void onUpdated(@Nonnull Inlay inlay) {
  if (myEditor.getDocument().isInBulkUpdate() || inlay.getPlacement() != Inlay.Placement.INLINE && inlay.getPlacement() != Inlay.Placement.AFTER_LINE_END) return;
  if (!isSoftWrappingEnabled()) {
    myDirty = true;
    return;
  }
  if (!myDirty) {
    if (myEditor.getDocument().isInEventsHandling()) {
      if (inlay.getPlacement() == Inlay.Placement.AFTER_LINE_END) {
        myAfterLineEndInlayUpdated = true;
      }
      return;
    }
    int offset = inlay.getOffset();
    if (inlay.getPlacement() == Inlay.Placement.AFTER_LINE_END) {
      offset = DocumentUtil.getLineEndOffset(offset, myEditor.getDocument());
    }
    myApplianceManager.recalculate(Collections.singletonList(new TextRange(offset, offset)));
  }
}
 
Example #5
Source File: SoftWrapModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@TestOnly
void validateState() {
  Document document = myEditor.getDocument();
  if (myEditor.getDocument().isInBulkUpdate()) return;
  FoldingModel foldingModel = myEditor.getFoldingModel();
  List<? extends SoftWrap> softWraps = getRegisteredSoftWraps();
  int lastSoftWrapOffset = -1;
  for (SoftWrap wrap : softWraps) {
    int softWrapOffset = wrap.getStart();
    LOG.assertTrue(softWrapOffset > lastSoftWrapOffset, "Soft wraps are not ordered");
    LOG.assertTrue(softWrapOffset < document.getTextLength(), "Soft wrap is after document's end");
    FoldRegion foldRegion = foldingModel.getCollapsedRegionAtOffset(softWrapOffset);
    LOG.assertTrue(foldRegion == null || foldRegion.getStartOffset() == softWrapOffset, "Soft wrap is inside fold region");
    LOG.assertTrue(softWrapOffset != DocumentUtil.getLineEndOffset(softWrapOffset, document) || foldRegion != null, "Soft wrap before line break");
    LOG.assertTrue(softWrapOffset != DocumentUtil.getLineStartOffset(softWrapOffset, document) || foldingModel.isOffsetCollapsed(softWrapOffset - 1), "Soft wrap after line break");
    LOG.assertTrue(!DocumentUtil.isInsideSurrogatePair(document, softWrapOffset), "Soft wrap inside a surrogate pair");
    lastSoftWrapOffset = softWrapOffset;
  }
}
 
Example #6
Source File: FoldingModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public FoldRegion createFoldRegion(int startOffset, int endOffset, @Nonnull String placeholder, @Nullable FoldingGroup group, boolean neverExpands) {
  assertIsDispatchThreadForEditor();
  if (!myIsBatchFoldingProcessing) {
    LOG.error("Fold regions must be added or removed inside batchFoldProcessing() only.");
    return null;
  }
  if (!isFoldingEnabled() || startOffset >= endOffset ||
      DocumentUtil.isInsideSurrogatePair(myEditor.getDocument(), startOffset) ||
      DocumentUtil.isInsideSurrogatePair(myEditor.getDocument(), endOffset) ||
      !myFoldTree.checkIfValidToCreate(startOffset, endOffset)) return null;

  FoldRegionImpl region = new FoldRegionImpl(myEditor, startOffset, endOffset, placeholder, group, neverExpands);
  myRegionTree.addInterval(region, startOffset, endOffset, false, false, false, 0);
  LOG.assertTrue(region.isValid());
  myFoldRegionsProcessed = true;
  if (group != null) {
    myGroups.putValue(group, region);
  }
  notifyListenersOnFoldRegionStateChange(region);
  LOG.assertTrue(region.isValid());
  return region;
}
 
Example #7
Source File: PasteHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void reformatBlock(final Project project, final Editor editor, final int startOffset, final int endOffset) {
  PsiDocumentManager.getInstance(project).commitAllDocuments();
  Runnable task = new Runnable() {
    @Override
    public void run() {
      PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      try {
        CodeStyleManager.getInstance(project).reformatRange(file, startOffset, endOffset, true);
      }
      catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }
  };

  if (endOffset - startOffset > 1000) {
    DocumentUtil.executeInBulk(editor.getDocument(), true, task);
  }
  else {
    task.run();
  }
}
 
Example #8
Source File: JoinLinesHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void doProcess(int lineCount) {
  List<RangeMarker> markers = new ArrayList<>();
  try {
    myIndicator.setText2("Converting end-of-line comments");
    convertEndComments(lineCount);
    myIndicator.setText2("Removing line-breaks");
    int newCount = processRawJoiners(lineCount);
    DocumentUtil.executeInBulk(myDoc, newCount > 100, () -> removeLineBreaks(newCount, markers));
    myIndicator.setText2("Postprocessing");
    List<RangeMarker> unprocessed = processNonRawJoiners(markers);
    myIndicator.setText2("Adjusting white-space");
    adjustWhiteSpace(unprocessed);
  }
  finally {
    markers.forEach(RangeMarker::dispose);
  }
}
 
Example #9
Source File: DeleteInColumnModeHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  if (editor.isColumnMode() && caret == null && editor.getCaretModel().getCaretCount() > 1) {
    EditorUIUtil.hideCursorInEditor(editor);
    CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
    CopyPasteManager.getInstance().stopKillRings();

    editor.getCaretModel().runForEachCaret(c -> {
      int offset = c.getOffset();
      int lineEndOffset = DocumentUtil.getLineEndOffset(offset, editor.getDocument());
      if (offset < lineEndOffset) myOriginalHandler.execute(editor, c, dataContext);
    });
  }
  else {
    myOriginalHandler.execute(editor, caret, dataContext);
  }
}
 
Example #10
Source File: JoinLinesHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void adjustWhiteSpace(List<RangeMarker> markers) {
  int size = markers.size();
  if (size == 0) return;
  int[] spacesToAdd = getSpacesToAdd(markers);
  DocumentUtil.executeInBulk(myDoc, size > 100, () -> {
    for (int i = 0; i < size; i++) {
      myIndicator.checkCanceled();
      myIndicator.setFraction(0.95 + 0.05 * i / size);
      RangeMarker marker = markers.get(i);
      if (!marker.isValid()) continue;
      CharSequence docText = myDoc.getCharsSequence();
      int lineEndOffset = marker.getStartOffset();
      int start = StringUtil.skipWhitespaceBackward(docText, lineEndOffset) - 1;
      int end = StringUtil.skipWhitespaceForward(docText, lineEndOffset);
      int replaceStart = start == lineEndOffset ? start : start + 1;
      if (myCaretRestoreOffset == CANNOT_JOIN) myCaretRestoreOffset = replaceStart;
      int spacesToCreate = spacesToAdd[i];
      String spacing = StringUtil.repeatSymbol(' ', spacesToCreate);
      myDoc.replaceString(replaceStart, end, spacing);
    }
  });
  myManager.commitDocument(myDoc);
}
 
Example #11
Source File: TemplateState.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void restoreEmptyVariables(IntArrayList indices) {
  List<TextRange> rangesToRemove = ContainerUtil.newArrayList();
  for (int i = 0; i < indices.size(); i++) {
    int index = indices.get(i);
    rangesToRemove.add(TextRange.create(mySegments.getSegmentStart(index), mySegments.getSegmentEnd(index)));
  }
  Collections.sort(rangesToRemove, (o1, o2) -> {
    int startDiff = o2.getStartOffset() - o1.getStartOffset();
    return startDiff != 0 ? startDiff : o2.getEndOffset() - o1.getEndOffset();
  });
  DocumentUtil.executeInBulk(myDocument, true, () -> {
    if (isDisposed()) {
      return;
    }
    for (TextRange range : rangesToRemove) {
      myDocument.deleteString(range.getStartOffset(), range.getEndOffset());
    }
  });
}
 
Example #12
Source File: DocumentUtils.java    From lsp4intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
public static LogicalPosition getTabsAwarePosition(Editor editor, Position pos) {
    return computableReadAction(() -> {
        try {
            if (editor.isDisposed()) {
                return null;
            }
            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;
            return new LogicalPosition(line, column);
        } catch (IndexOutOfBoundsException e) {
            return null;
        }
    });
}
 
Example #13
Source File: CypherPreFormatter.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public TextRange process(@NotNull ASTNode element, @NotNull TextRange range) {
    PsiElement psiElement = element.getPsi();
    if (psiElement != null && psiElement.isValid()
            && psiElement.getLanguage().is(CypherLanguage.INSTANCE)) {
        FormatterTask converter = new FormatterTask(psiElement, range);

        if (converter.getDocument() != null) {
            DocumentUtil.executeInBulk(converter.getDocument(), true, converter);
        }

        return converter.getTextRange();
    }
    return range;
}
 
Example #14
Source File: DiffDrawUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public List<RangeHighlighter> done() {
  // We won't use addLineHighlighter as it will fail to add marker into empty document.
  //RangeHighlighter highlighter = editor.getMarkupModel().addLineHighlighter(line, HighlighterLayer.SELECTION - 1, null);

  int offset = DocumentUtil.getFirstNonSpaceCharOffset(editor.getDocument(), line);
  RangeHighlighter highlighter = editor.getMarkupModel()
          .addRangeHighlighter(offset, offset, LINE_MARKER_LAYER, null, HighlighterTargetArea.LINES_IN_RANGE);

  highlighter.setLineSeparatorPlacement(placement);
  highlighter.setLineSeparatorRenderer(renderer);
  highlighter.setLineMarkerRenderer(gutterRenderer);

  if (type == null || resolved) return Collections.singletonList(highlighter);

  TextAttributes stripeAttributes = getStripeTextAttributes(type, editor);
  RangeHighlighter stripeHighlighter = editor.getMarkupModel()
          .addRangeHighlighter(offset, offset, STRIPE_LAYER, stripeAttributes, HighlighterTargetArea.LINES_IN_RANGE);

  return ContainerUtil.list(highlighter, stripeHighlighter);
}
 
Example #15
Source File: TemplateState.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void executeChanges(@Nonnull List<TemplateDocumentChange> changes) {
  if (isDisposed() || changes.isEmpty()) {
    return;
  }
  if (changes.size() > 1) {
    ContainerUtil.sort(changes, (o1, o2) -> {
      int startDiff = o2.startOffset - o1.startOffset;
      return startDiff != 0 ? startDiff : o2.endOffset - o1.endOffset;
    });
  }
  DocumentUtil.executeInBulk(myDocument, true, () -> {
    for (TemplateDocumentChange change : changes) {
      replaceString(change.newValue, change.startOffset, change.endOffset, change.segmentNumber);
    }
  });
}
 
Example #16
Source File: PersistentRangeHighlighterImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void changedUpdateImpl(@Nonnull DocumentEvent e) {
  // todo Denis Zhdanov
  DocumentEventImpl event = (DocumentEventImpl)e;
  final boolean shouldTranslateViaDiff = isValid() && PersistentRangeMarkerUtil.shouldTranslateViaDiff(event, getStartOffset(), getEndOffset());
  boolean wasTranslatedViaDiff = shouldTranslateViaDiff;
  if (shouldTranslateViaDiff) {
    wasTranslatedViaDiff = translatedViaDiff(e, event);
  }
  if (!wasTranslatedViaDiff) {
    super.changedUpdateImpl(e);
    if (isValid()) {
      myLine = getDocument().getLineNumber(getStartOffset());
      int endLine = getDocument().getLineNumber(getEndOffset());
      if (endLine != myLine) {
        setIntervalEnd(getDocument().getLineEndOffset(myLine));
      }
    }
  }
  if (isValid() && getTargetArea() == HighlighterTargetArea.LINES_IN_RANGE) {
    setIntervalStart(DocumentUtil.getFirstNonSpaceCharOffset(getDocument(), myLine));
    setIntervalEnd(getDocument().getLineEndOffset(myLine));
  }
}
 
Example #17
Source File: DiffUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
public static void executeWriteCommand(@Nullable Project project,
                                       @Nonnull Document document,
                                       @Nullable String commandName,
                                       @Nullable String commandGroupId,
                                       @Nonnull UndoConfirmationPolicy confirmationPolicy,
                                       boolean underBulkUpdate,
                                       @Nonnull Runnable task) {
  if (!makeWritable(project, document)) {
    VirtualFile file = FileDocumentManager.getInstance().getFile(document);
    LOG.warn("Document is read-only" + (file != null ? ": " + file.getPresentableName() : ""));
    return;
  }

  ApplicationManager.getApplication().runWriteAction(() -> {
    CommandProcessor.getInstance().executeCommand(project, () -> {
      if (underBulkUpdate) {
        DocumentUtil.executeInBulk(document, true, task);
      }
      else {
        task.run();
      }
    }, commandName, commandGroupId, confirmationPolicy, document);
  });
}
 
Example #18
Source File: SoftWrapApplianceManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void documentChanged(DocumentEvent event, boolean processAlsoLineEnd) {
  LOG.assertTrue(myDocumentChangedEvent != null);
  recalculate(myDocumentChangedEvent);
  if (processAlsoLineEnd) {
    int lineEndOffset = DocumentUtil.getLineEndOffset(myDocumentChangedEvent.getMandatoryEndOffset(), event.getDocument());
    if (lineEndOffset > myDocumentChangedEvent.getActualEndOffset()) {
      recalculate(new IncrementalCacheUpdateEvent(lineEndOffset, lineEndOffset, myEditor));
    }
  }
  myDocumentChangedEvent = null;
}
 
Example #19
Source File: FoldRegionImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void alignToSurrogateBoundaries() {
  Document document = getDocument();
  int start = intervalStart();
  int end = intervalEnd();
  if (DocumentUtil.isInsideSurrogatePair(document, start)) {
    setIntervalStart(start - 1);
  }
  if (DocumentUtil.isInsideSurrogatePair(document, end)) {
    setIntervalEnd(end - 1);
  }
}
 
Example #20
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 #21
Source File: LanguageConsoleImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
protected String addToHistoryInner(@Nonnull final TextRange textRange, @Nonnull final EditorEx editor, boolean erase, final boolean preserveMarkup) {
  ApplicationManager.getApplication().assertIsDispatchThread();

  String result = addTextRangeToHistory(textRange, editor, preserveMarkup);
  if (erase) {
    DocumentUtil.writeInRunUndoTransparentAction(() -> editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset()));
  }
  // always scroll to end on user input
  scrollToEnd();
  return result;
}
 
Example #22
Source File: SoftWrapApplianceManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void doRecalculateSoftWrapsRoughly(IncrementalCacheUpdateEvent event) {
  Document document = myEditor.getDocument();
  int lineCount = document.getLineCount();
  int offset = event.getStartOffset();
  int line = document.getLineNumber(offset);
  int mandatoryEnd = event.getMandatoryEndOffset();
  while (true) {
    if ((offset += QUICK_WRAP_CHAR_COUNT) >= document.getLineEndOffset(line)) {
      if (++line >= lineCount) {
        offset = document.getTextLength();
        break;
      }
      offset = document.getLineStartOffset(line);
      if (offset > mandatoryEnd && myEditor.getFoldingModel().getCollapsedRegionAtOffset(offset - 1) == null) break;
      else continue;
    }
    FoldRegion foldRegion = myEditor.getFoldingModel().getCollapsedRegionAtOffset(offset);
    if (foldRegion != null) {
      offset = foldRegion.getEndOffset();
      line = document.getLineNumber(offset);
    }
    if (DocumentUtil.isInsideSurrogatePair(document, offset)) offset++;
    if (offset < document.getLineEndOffset(line)) {
      SoftWrapImpl wrap = new SoftWrapImpl(new TextChangeImpl("\n", offset), 1, 1);
      myStorage.storeOrReplace(wrap);
      if (offset > mandatoryEnd && myDataMapper.matchesOldSoftWrap(wrap, event.getLengthDiff())) break;
    }
  }
  event.setActualEndOffset(offset);
}
 
Example #23
Source File: ActionUsagePanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void reset(final String usageText, final FileType fileType) {
  reinitViews();
  SwingUtilities.invokeLater(() -> {
    if (myEditor.isDisposed()) return;
    DocumentUtil.writeInRunUndoTransparentAction(() -> configureByText(usageText, fileType));
  });
}
 
Example #24
Source File: SoftWrapApplianceManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * This method is assumed to be called in a situation when visible area width is exceeded. It tries to create and register
 * new soft wrap which data is defined in accordance with the given parameters.
 * <p/>
 * There is a possible case that no soft wrap is created and registered. That is true, for example, for a situation when
 * we have a long line of text that doesn't contain white spaces, operators or any other symbols that may be used
 * as a {@code 'wrap points'}. We just left such lines as-is.
 *
 * @param minOffset       min line {@code 'wrap point'} offset
 * @param preferredOffset preferred {@code 'wrap point'} offset, i.e. max offset which symbol doesn't exceed right margin
 * @param maxOffset       max line {@code 'wrap point'} offset
 * @param spaceSize       current space width in pixels
 * @param lineData        object that encapsulates information about currently processed logical line
 * @return newly created and registered soft wrap if any; {@code null} otherwise
 */
@Nullable
private SoftWrapImpl registerSoftWrap(int minOffset, int preferredOffset, int maxOffset, int spaceSize, LogicalLineData lineData) {
  int softWrapOffset = calculateBackwardSpaceOffsetIfPossible(minOffset, preferredOffset);
  if (softWrapOffset < 0) {
    softWrapOffset = calculateBackwardOffsetForEasternLanguageIfPossible(minOffset, preferredOffset);
  }
  if (softWrapOffset < 0) {
    Document document = myEditor.getDocument();

    // Performance optimization implied by profiling results analysis.
    if (myLineWrapPositionStrategy == null) {
      myLineWrapPositionStrategy = LanguageLineWrapPositionStrategy.INSTANCE.forEditor(myEditor);
    }

    softWrapOffset = myLineWrapPositionStrategy.calculateWrapPosition(document, myEditor.getProject(), minOffset, maxOffset, preferredOffset, true, true);
    if (DocumentUtil.isInsideSurrogatePair(document, softWrapOffset)) softWrapOffset--;
  }

  if (softWrapOffset >= lineData.endLineOffset ||
      softWrapOffset < 0 ||
      softWrapOffset <= minOffset ||
      myCustomIndentUsedLastTime && softWrapOffset == lineData.nonWhiteSpaceSymbolOffset ||
      softWrapOffset > preferredOffset && myContext.lastFoldStartPosition != null // Prefer to wrap on fold region backwards
      && myContext.lastFoldStartPosition.offset <= preferredOffset)              // to wrapping forwards.
  {
    return null;
  }

  return registerSoftWrap(softWrapOffset, spaceSize, lineData);
}
 
Example #25
Source File: InlayModelImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public <T extends EditorCustomElementRenderer> Inlay<T> addInlineElement(int offset, boolean relatesToPrecedingText, @Nonnull T renderer) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  Document document = myEditor.getDocument();
  if (DocumentUtil.isInsideSurrogatePair(document, offset)) return null;
  offset = Math.max(0, Math.min(document.getTextLength(), offset));
  InlineInlayImpl<T> inlay = new InlineInlayImpl<>(myEditor, offset, relatesToPrecedingText, renderer);
  notifyAdded(inlay);
  return inlay;
}
 
Example #26
Source File: RecentLocationsDataModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private TextRange getLinesRange(Document document, int line) {
  int lineCount = document.getLineCount();
  if (lineCount == 0) {
    return TextRange.EMPTY_RANGE;
  }

  int beforeAfterLinesCount = Registry.intValue("recent.locations.lines.before.and.after", 2);

  int before = Math.min(beforeAfterLinesCount, line);
  int after = Math.min(beforeAfterLinesCount, lineCount - line);

  int linesBefore = before + beforeAfterLinesCount - after;
  int linesAfter = after + beforeAfterLinesCount - before;

  int startLine = Math.max(line - linesBefore, 0);
  int endLine = Math.min(line + linesAfter, lineCount - 1);

  int startOffset = document.getLineStartOffset(startLine);
  int endOffset = document.getLineEndOffset(endLine);

  if (startOffset <= endOffset) {
    return TextRange.create(startOffset, endOffset);
  }
  else {
    return TextRange.create(DocumentUtil.getLineTextRange(document, line));
  }
}
 
Example #27
Source File: XSourcePositionImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * do not call this method from plugins, use {@link XDebuggerUtil#createPositionByOffset(VirtualFile, int)} instead
 */
@Nullable
public static XSourcePositionImpl createByOffset(@Nullable VirtualFile file, final int offset) {
  if (file == null) return null;

  return new XSourcePositionImpl(file) {
    private final AtomicNotNullLazyValue<Integer> myLine = new AtomicNotNullLazyValue<Integer>() {
      @Nonnull
      @Override
      protected Integer compute() {
        return ReadAction.compute(() -> {
          Document document = FileDocumentManager.getInstance().getDocument(file);
          if (document == null) {
            return -1;
          }
          return DocumentUtil.isValidOffset(offset, document) ? document.getLineNumber(offset) : -1;
        });
      }
    };

    @Override
    public int getLine() {
      return myLine.getValue();
    }

    @Override
    public int getOffset() {
      return offset;
    }
  };
}
 
Example #28
Source File: ExecutionPointHighlighter.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void addHighlighter() {
  disableMouseHoverPopups(myEditor, true);
  int line = mySourcePosition.getLine();
  Document document = myEditor.getDocument();
  if (line < 0 || line >= document.getLineCount()) return;

  //if (myNotTopFrame) {
  //  myEditor.getSelectionModel().setSelection(document.getLineStartOffset(line), document.getLineEndOffset(line) + document.getLineSeparatorLength(line));
  //  return;
  //}

  if (myRangeHighlighter != null) return;

  EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
  TextAttributes attributes = myNotTopFrame ? scheme.getAttributes(DebuggerColors.NOT_TOP_FRAME_ATTRIBUTES) : scheme.getAttributes(DebuggerColors.EXECUTIONPOINT_ATTRIBUTES);
  MarkupModel markupModel = DocumentMarkupModel.forDocument(document, myProject, true);
  if (mySourcePosition instanceof HighlighterProvider) {
    TextRange range = ((HighlighterProvider)mySourcePosition).getHighlightRange();
    if (range != null) {
      TextRange lineRange = DocumentUtil.getLineTextRange(document, line);
      if (!range.equals(lineRange)) {
        myRangeHighlighter = markupModel.addRangeHighlighter(range.getStartOffset(), range.getEndOffset(), DebuggerColors.EXECUTION_LINE_HIGHLIGHTERLAYER, attributes, HighlighterTargetArea.EXACT_RANGE);
      }
    }
  }
  if (myRangeHighlighter == null) {
    myRangeHighlighter = markupModel.addLineHighlighter(line, DebuggerColors.EXECUTION_LINE_HIGHLIGHTERLAYER, attributes);
  }
  myRangeHighlighter.putUserData(EXECUTION_POINT_HIGHLIGHTER_TOP_FRAME_KEY, !myNotTopFrame);
  myRangeHighlighter.setEditorFilter(MarkupEditorFilterFactory.createIsNotDiffFilter());
  myRangeHighlighter.setGutterIconRenderer(myGutterIconRenderer);
}
 
Example #29
Source File: CommentByLineCommentHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void doDefaultCommenting(final Block block) {
  final Document document = block.editor.getDocument();
  DocumentUtil.executeInBulk(document, block.endLine - block.startLine >= Registry.intValue("comment.by.line.bulk.lines.trigger"), () -> {
    for (int line = block.endLine; line >= block.startLine; line--) {
      int offset = document.getLineStartOffset(line);
      commentLine(block, line, offset);
    }
  });
}
 
Example #30
Source File: CommentByLineCommentHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void doIndentCommenting(final Block block) {
  final Document document = block.editor.getDocument();
  final CharSequence chars = document.getCharsSequence();
  final IndentData minIndent = computeMinIndent(block.editor, block.psiFile, block.startLine, block.endLine);
  final CommonCodeStyleSettings.IndentOptions indentOptions = CodeStyle.getIndentOptions(block.psiFile);

  DocumentUtil.executeInBulk(document, block.endLine - block.startLine > Registry.intValue("comment.by.line.bulk.lines.trigger"), () -> {
    for (int line = block.endLine; line >= block.startLine; line--) {
      int lineStart = document.getLineStartOffset(line);
      int offset = lineStart;
      final StringBuilder buffer = new StringBuilder();
      while (true) {
        IndentData indent = IndentData.createFrom(buffer, 0, buffer.length(), indentOptions.TAB_SIZE);
        if (indent.getTotalSpaces() >= minIndent.getTotalSpaces()) break;
        char c = chars.charAt(offset);
        if (c != ' ' && c != '\t') {
          String newSpace = minIndent.createIndentInfo().generateNewWhiteSpace(indentOptions);
          document.replaceString(lineStart, offset, newSpace);
          offset = lineStart + newSpace.length();
          break;
        }
        buffer.append(c);
        offset++;
      }
      commentLine(block, line, offset);
    }
  });
}