Java Code Examples for com.intellij.openapi.editor.Document#getTextLength()

The following examples show how to use com.intellij.openapi.editor.Document#getTextLength() . 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: FoldLinesLikeThis.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static String getSingleLineSelection(@Nonnull Editor editor) {
  final SelectionModel model = editor.getSelectionModel();
  final Document document = editor.getDocument();
  if (!model.hasSelection()) {
    final int offset = editor.getCaretModel().getOffset();
    if (offset <= document.getTextLength()) {
      final int lineNumber = document.getLineNumber(offset);
      final String line = document.getText().substring(document.getLineStartOffset(lineNumber), document.getLineEndOffset(lineNumber)).trim();
      if (StringUtil.isNotEmpty(line)) {
        return line;
      }
    }

    return null;
  }
  final int start = model.getSelectionStart();
  final int end = model.getSelectionEnd();
  if (document.getLineNumber(start) == document.getLineNumber(end)) {
    final String selection = document.getText().substring(start, end).trim();
    if (StringUtil.isNotEmpty(selection)) {
      return selection;
    }
  }
  return null;
}
 
Example 2
Source File: UsageInfo.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public Segment getSegment() {
  PsiElement element = getElement();
  if (element == null
      // in case of binary file
      || myPsiFileRange == null && element instanceof PsiFile) return null;
  TextRange range = element.getTextRange();
  TextRange.assertProperRange(range, element);
  if (element instanceof PsiFile) {
    // hack: it's actually a range inside file, use document for range checking since during the "find|replace all" operation, file range might have been changed
    Document document = PsiDocumentManager.getInstance(getProject()).getDocument((PsiFile)element);
    if (document != null) {
      range = new ProperTextRange(0, document.getTextLength());
    }
  }
  ProperTextRange rangeInElement = getRangeInElement();
  if (rangeInElement == null) return null;
  return new ProperTextRange(Math.min(range.getEndOffset(), range.getStartOffset() + rangeInElement.getStartOffset()),
                             Math.min(range.getEndOffset(), range.getStartOffset() + rangeInElement.getEndOffset()));
}
 
Example 3
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 4
Source File: ProblemDescriptorBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public int getLineNumber() {
  if (myLineNumber == -1) {
    PsiElement psiElement = getPsiElement();
    if (psiElement == null) return -1;
    if (!psiElement.isValid()) return -1;
    LOG.assertTrue(psiElement.isPhysical());
    InjectedLanguageManager manager = InjectedLanguageManager.getInstance(psiElement.getProject());
    PsiFile containingFile = manager.getTopLevelFile(psiElement);
    Document document = PsiDocumentManager.getInstance(psiElement.getProject()).getDocument(containingFile);
    if (document == null) return -1;
    TextRange textRange = getTextRange();
    if (textRange == null) return -1;
    textRange = manager.injectedToHost(psiElement, textRange);
    final int startOffset = textRange.getStartOffset();
    final int textLength = document.getTextLength();
    LOG.assertTrue(startOffset <= textLength, getDescriptionTemplate() + " at " + startOffset + ", " + textLength);
    myLineNumber =  document.getLineNumber(startOffset) + 1;
  }
  return myLineNumber;
}
 
Example 5
Source File: EditorComponentImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int getWordAtOffsetEnd(int offset) {
  Document document = myEditor.getDocument();

  CharSequence text = document.getCharsSequence();
  if (offset >= document.getTextLength() - 1 || document.getLineCount() == 0) {
    return offset;
  }

  int newOffset = offset + 1;
  int lineNumber = myEditor.offsetToLogicalPosition(offset).line;
  int maxOffset = document.getLineEndOffset(lineNumber);
  if (newOffset > maxOffset) {
    if (lineNumber + 1 >= document.getLineCount()) {
      return offset;
    }
    maxOffset = document.getLineEndOffset(lineNumber + 1);
  }
  boolean camel = myEditor.getSettings().isCamelWords();
  for (; newOffset < maxOffset; newOffset++) {
    if (EditorActionUtil.isWordEnd(text, newOffset, camel)) {
      break;
    }
  }

  return newOffset;
}
 
Example 6
Source File: CSharpEnterInDocLineCommentHandler.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Override
@RequiredUIAccess
public Result preprocessEnter(@Nonnull final PsiFile file,
		@Nonnull final Editor editor,
		@Nonnull final Ref<Integer> caretOffsetRef,
		@Nonnull final Ref<Integer> caretAdvance,
		@Nonnull final DataContext dataContext,
		final EditorActionHandler originalHandler)
{
	final int caretOffset = caretOffsetRef.get();
	final Document document = editor.getDocument();
	final PsiElement psiAtOffset = file.findElementAt(caretOffset);
	final PsiElement probablyDocComment = psiAtOffset instanceof PsiWhiteSpace && psiAtOffset.getText().startsWith("\n") ? psiAtOffset.getPrevSibling() : psiAtOffset == null && caretOffset > 0
			&& caretOffset == document.getTextLength() ? file.findElementAt(caretOffset - 1) : psiAtOffset;

	if(probablyDocComment != null && PsiTreeUtil.getParentOfType(probablyDocComment, CSharpDocRoot.class, false) != null)
	{
		document.insertString(caretOffset, DOC_LINE_START + " ");
		caretAdvance.set(4);
		return Result.Default;
	}

	return Result.Continue;
}
 
Example 7
Source File: ApplyPatchChange.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private MyGutterOperation createOperation(@Nonnull OperationType type) {
  if (isResolved()) return null;

  EditorEx editor = myViewer.getPatchEditor();
  Document document = editor.getDocument();

  int line = getPatchRange().start;
  int offset = line == DiffUtil.getLineCount(document) ? document.getTextLength() : document.getLineStartOffset(line);

  RangeHighlighter highlighter = editor.getMarkupModel().addRangeHighlighter(offset, offset,
                                                                             HighlighterLayer.ADDITIONAL_SYNTAX,
                                                                             null,
                                                                             HighlighterTargetArea.LINES_IN_RANGE);
  return new MyGutterOperation(highlighter, type);
}
 
Example 8
Source File: LazyRangeMarkerFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static int calculateOffset(@Nonnull Document document,
                                   final int line,
                                   final int column,
                                   int tabSize) {
  int offset;
  if (0 <= line && line < document.getLineCount()) {
    final int lineStart = document.getLineStartOffset(line);
    final int lineEnd = document.getLineEndOffset(line);
    final CharSequence docText = document.getCharsSequence();

    offset = lineStart;
    int col = 0;
    while (offset < lineEnd && col < column) {
      col += docText.charAt(offset) == '\t' ? tabSize : 1;
      offset++;
    }
  }
  else {
    offset = document.getTextLength();
  }
  return offset;
}
 
Example 9
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean areTooManyDocumentsInTheQueue(@Nonnull Collection<? extends Document> documents) {
  if (documents.size() > 100) return true;
  int totalSize = 0;
  for (Document document : documents) {
    totalSize += document.getTextLength();
    if (totalSize > FileUtilRt.LARGE_FOR_CONTENT_LOADING) return true;
  }
  return false;
}
 
Example 10
Source File: LazyRangeMarkerFactoryImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid() {
  RangeMarker delegate = myDelegate;
  if (delegate == null) {
    Document document = FileDocumentManager.getInstance().getDocument(myFile);
    return document != null && (document.getTextLength() != 0 || myLine == 0 && myColumn == 0);
  }

  return super.isValid();
}
 
Example 11
Source File: CtrlMouseHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
boolean rangesAreCorrect(@Nonnull Document document) {
  final TextRange docRange = new TextRange(0, document.getTextLength());
  for (TextRange range : getRanges()) {
    if (!docRange.contains(range)) return false;
  }

  return true;
}
 
Example 12
Source File: TailType.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static int insertChar(Editor editor, int tailOffset, char c, boolean overwrite) {
  Document document = editor.getDocument();
  int textLength = document.getTextLength();
  CharSequence chars = document.getCharsSequence();
  if (tailOffset == textLength || !overwrite || chars.charAt(tailOffset) != c){
    document.insertString(tailOffset, String.valueOf(c));
  }
  return moveCaret(editor, tailOffset, 1);
}
 
Example 13
Source File: GotoNextErrorHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static int getNavigationPositionFor(HighlightInfo info, Document document) {
  int start = info.getActualStartOffset();
  if (start >= document.getTextLength()) return document.getTextLength();
  char c = document.getCharsSequence().charAt(start);
  int shift = info.isAfterEndOfLine() && c != '\n' ? 1 : info.navigationShift;

  int offset = info.getActualStartOffset() + shift;
  return Math.min(offset, document.getTextLength());
}
 
Example 14
Source File: RangeHighlighterImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public int getAffectedAreaStartOffset() {
  int startOffset = getStartOffset();
  switch (getTargetArea()) {
    case EXACT_RANGE:
      return startOffset;
    case LINES_IN_RANGE:
      Document document = myModel.getDocument();
      int textLength = document.getTextLength();
      if (startOffset >= textLength) return textLength;
      return document.getLineStartOffset(document.getLineNumber(startOffset));
    default:
      throw new IllegalStateException(getTargetArea().toString());
  }
}
 
Example 15
Source File: LookupImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static int insertLookupInDocument(int caretOffset, Document document, int prefix, String lookupString) {
  int lookupStart = Math.min(caretOffset, Math.max(caretOffset - prefix, 0));
  int len = document.getTextLength();
  LOG.assertTrue(lookupStart >= 0 && lookupStart <= len, "ls: " + lookupStart + " caret: " + caretOffset + " prefix:" + prefix + " doc: " + len);
  LOG.assertTrue(caretOffset >= 0 && caretOffset <= len, "co: " + caretOffset + " doc: " + len);
  document.replaceString(lookupStart, caretOffset, lookupString);
  return lookupStart + lookupString.length();
}
 
Example 16
Source File: LexerEditorHighlighter.java    From consulo with Apache License 2.0 4 votes vote down vote up
private boolean isInSyncWithDocument() {
  Document document = getDocument();
  return document == null || document.getTextLength() == 0 || mySegments.getSegmentCount() > 0;
}
 
Example 17
Source File: InspectorService.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static InspectorService.Location outlineToLocation(Project project,
                                                          VirtualFile file,
                                                          FlutterOutline outline,
                                                          Document document) {
  if (file == null) return null;
  if (document == null) return null;
  if (outline == null || outline.getClassName() == null) return null;
  final int documentLength = document.getTextLength();
  int nodeOffset = Math.max(0, Math.min(outline.getCodeOffset(), documentLength));
  final int nodeEndOffset = Math.max(0, Math.min(outline.getCodeOffset() + outline.getCodeLength(), documentLength));

  // The DartOutline will give us the offset of
  // 'child: Foo.bar(...)'
  // but we need the offset of 'bar(...)' for consistentency with the
  // Flutter kernel transformer.
  if (outline.getClassName() != null) {
    final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
    if (psiFile != null) {
      final PsiElement element = psiFile.findElementAt(nodeOffset);
      final DartCallExpression callExpression = PsiTreeUtil.getParentOfType(element, DartCallExpression.class);
      PsiElement match = null;
      if (callExpression != null) {
        final DartExpression expression = callExpression.getExpression();
        if (expression instanceof DartReferenceExpression) {
          final DartReferenceExpression referenceExpression = (DartReferenceExpression)expression;
          final PsiElement[] children = referenceExpression.getChildren();
          if (children.length > 1) {
            // This case handles expressions like 'ClassName.namedConstructor'
            // and 'libraryPrefix.ClassName.namedConstructor'
            match = children[children.length - 1];
          }
          else {
            // this case handles the simple 'ClassName' case.
            match = referenceExpression;
          }
        }
      }
      if (match != null) {
        nodeOffset = match.getTextOffset();
      }
    }
  }
  final int line = document.getLineNumber(nodeOffset);
  final int lineStartOffset = document.getLineStartOffset(line);
  final int column = nodeOffset - lineStartOffset;
  return new InspectorService.Location(file, line + 1, column + 1, nodeOffset);
}
 
Example 18
Source File: EditorFragmentComponent.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void doInit(Component anchorComponent, EditorEx editor, int startLine, int endLine, boolean showFolding, boolean showGutter) {
  boolean newRendering = editor instanceof DesktopEditorImpl;
  int savedScrollOffset = newRendering ? 0 : editor.getScrollingModel().getHorizontalScrollOffset();

  FoldingModelEx foldingModel = editor.getFoldingModel();
  boolean isFoldingEnabled = foldingModel.isFoldingEnabled();
  if (!showFolding) {
    foldingModel.setFoldingEnabled(false);
  }
  int textImageWidth;
  int markersImageWidth;
  int textImageHeight;
  BufferedImage textImage;
  BufferedImage markersImage;
  JComponent rowHeader;
  try {
    Document doc = editor.getDocument();
    int endOffset = endLine < doc.getLineCount() ? doc.getLineEndOffset(Math.max(0, endLine - 1)) : doc.getTextLength();
    int widthAdjustment = newRendering ? EditorUtil.getSpaceWidth(Font.PLAIN, editor) : 0;
    textImageWidth = Math.min(editor.getMaxWidthInRange(doc.getLineStartOffset(startLine), endOffset) + widthAdjustment, getWidthLimit(editor));

    Point p1 = editor.logicalPositionToXY(new LogicalPosition(startLine, 0));
    Point p2 = editor.logicalPositionToXY(new LogicalPosition(Math.max(endLine, startLine + 1), 0));
    int y1 = p1.y;
    int y2 = p2.y;
    textImageHeight = y2 - y1 == 0 ? editor.getLineHeight() : y2 - y1;
    LOG.assertTrue(textImageHeight > 0, "Height: " + textImageHeight + "; startLine:" + startLine + "; endLine:" + endLine + "; p1:" + p1 + "; p2:" + p2);

    if (savedScrollOffset > 0) {
      editor.getScrollingModel().scrollHorizontally(0);
    }

    textImage = UIUtil.createImage(anchorComponent == null ? editor.getContentComponent() : anchorComponent, textImageWidth, textImageHeight, BufferedImage.TYPE_INT_RGB);
    Graphics textGraphics = textImage.getGraphics();
    EditorUIUtil.setupAntialiasing(textGraphics);

    if (showGutter) {
      rowHeader = editor.getGutterComponentEx();
      markersImageWidth = Math.max(1, rowHeader.getWidth());

      markersImage = UIUtil.createImage(editor.getComponent(), markersImageWidth, textImageHeight, BufferedImage.TYPE_INT_RGB);
      Graphics markerGraphics = markersImage.getGraphics();
      EditorUIUtil.setupAntialiasing(markerGraphics);

      markerGraphics.translate(0, -y1);
      markerGraphics.setClip(0, y1, rowHeader.getWidth(), textImageHeight);
      markerGraphics.setColor(getBackgroundColor(editor));
      markerGraphics.fillRect(0, y1, rowHeader.getWidth(), textImageHeight);
      rowHeader.paint(markerGraphics);
    }
    else {
      markersImageWidth = 0;
      rowHeader = null;
      markersImage = null;
    }

    textGraphics.translate(0, -y1);
    textGraphics.setClip(0, y1, textImageWidth, textImageHeight);
    boolean wasVisible = editor.setCaretVisible(false);
    editor.getContentComponent().paint(textGraphics);
    if (wasVisible) {
      editor.setCaretVisible(true);
    }
  }
  finally {
    if (!showFolding) {
      foldingModel.setFoldingEnabled(isFoldingEnabled);
    }
  }

  if (savedScrollOffset > 0) {
    editor.getScrollingModel().scrollHorizontally(savedScrollOffset);
  }

  JComponent component = new JComponent() {
    @Override
    public Dimension getPreferredSize() {
      return new Dimension(textImageWidth + markersImageWidth, textImageHeight);
    }

    @Override
    protected void paintComponent(Graphics graphics) {
      if (markersImage != null) {
        UIUtil.drawImage(graphics, markersImage, 0, 0, null);
        UIUtil.drawImage(graphics, textImage, rowHeader.getWidth(), 0, null);
      }
      else {
        UIUtil.drawImage(graphics, textImage, 0, 0, null);
      }
    }
  };

  setLayout(new BorderLayout());
  add(component);

  setBorder(createEditorFragmentBorder(editor));
}
 
Example 19
Source File: ConsoleLog.java    From aem-ide-tooling-4-intellij with Apache License 2.0 4 votes vote down vote up
private static boolean parseHtmlContent(String text, Notification notification,
                                        Document document,
                                        AtomicBoolean showMore,
                                        Map<RangeMarker, HyperlinkInfo> links, List<RangeMarker> lineSeparators) {
    String content = StringUtil.convertLineSeparators(text);

    int initialLen = document.getTextLength();
    boolean hasHtml = false;
    while(true) {
        Matcher tagMatcher = TAG_PATTERN.matcher(content);
        if(!tagMatcher.find()) {
            appendText(document, content);
            break;
        }

        String tagStart = tagMatcher.group();
        appendText(document, content.substring(0, tagMatcher.start()));
        Matcher aMatcher = A_PATTERN.matcher(tagStart);
        if(aMatcher.matches()) {
            final String href = aMatcher.group(2);
            int linkEnd = content.indexOf(A_CLOSING, tagMatcher.end());
            if(linkEnd > 0) {
                String linkText = content.substring(tagMatcher.end(), linkEnd).replaceAll(TAG_PATTERN.pattern(), "");
                int linkStart = document.getTextLength();
                appendText(document, linkText);
                links.put(document.createRangeMarker(new TextRange(linkStart, document.getTextLength())),
                    new NotificationHyperlinkInfo(notification, href));
                content = content.substring(linkEnd + A_CLOSING.length());
                continue;
            }
        }

        hasHtml = true;
        if(NEW_LINES.contains(tagStart)) {
            if(initialLen != document.getTextLength()) {
                lineSeparators.add(document.createRangeMarker(TextRange.from(document.getTextLength(), 0)));
            }
        } else if(!"<html>".equals(tagStart) && !"</html>".equals(tagStart) && !"<body>".equals(tagStart) && !"</body>".equals(tagStart)) {
            showMore.set(true);
        }
        content = content.substring(tagMatcher.end());
    }
    for(Iterator<RangeMarker> iterator = lineSeparators.iterator(); iterator.hasNext(); ) {
        RangeMarker next = iterator.next();
        if(next.getEndOffset() == document.getTextLength()) {
            iterator.remove();
        }
    }
    return hasHtml;
}
 
Example 20
Source File: CopyPasteIndentProcessor.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static int getLineStartSafeOffset(final Document document, int line) {
  if (line >= document.getLineCount()) return document.getTextLength();
  return document.getLineStartOffset(line);
}