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

The following examples show how to use com.intellij.openapi.editor.Document#getLineCount() . These examples are extracted from open source projects. 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
@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 2
Source Project: consulo   File: CommentUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static IndentData getMinLineIndent(Document document, int line1, int line2, @Nonnull PsiFile file) {
  CharSequence chars = document.getCharsSequence();
  IndentData minIndent = null;
  for (int line = line1; line <= line2; line++) {
    int lineStart = document.getLineStartOffset(line);
    int textStart = CharArrayUtil.shiftForward(chars, lineStart, " \t");
    if (textStart >= document.getTextLength()) {
      textStart = document.getTextLength();
    }
    else {
      char c = chars.charAt(textStart);
      if (c == '\n' || c == '\r') continue; // empty line
    }
    IndentData indent = IndentData.createFrom(chars, lineStart, textStart, CodeStyle.getIndentOptions(file).TAB_SIZE);
    minIndent = IndentData.min(minIndent, indent);
  }
  if (minIndent == null && line1 == line2 && line1 < document.getLineCount() - 1) {
    return getMinLineIndent(document, line1 + 1, line1 + 1, file);
  }
  return minIndent;
}
 
Example 3
Source Project: KodeBeagle   File: EditorDocOps.java    License: 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 4
Source Project: consulo   File: DeleteToWordEndAction.java    License: Apache License 2.0 6 votes vote down vote up
private static int getWordEndOffset(Editor editor, int offset, boolean camelMode) {
  Document document = editor.getDocument();
  CharSequence text = document.getCharsSequence();
  if(offset >= document.getTextLength() - 1)
    return offset;
  int newOffset = offset + 1;
  int lineNumber = editor.getCaretModel().getLogicalPosition().line;
  int maxOffset = document.getLineEndOffset(lineNumber);
  if(newOffset > maxOffset) {
    if(lineNumber+1 >= document.getLineCount())
      return offset;
    maxOffset = document.getLineEndOffset(lineNumber+1);
  }
  for (; newOffset < maxOffset; newOffset++) {
    if (EditorActionUtil.isWordEnd(text, newOffset, camelMode) ||
        EditorActionUtil.isWordStart(text, newOffset, camelMode)) {
      break;
    }
  }
  return newOffset;
}
 
Example 5
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 6
@Override
public final boolean isShowSeparatorLine(int line, @Nonnull Editor editor) {
  Document document = editor.getDocument();
  if ((line + 1) >= document.getLineCount()) {
    return true;
  }

  int markerCount = getMarkerCount(line, document);
  if (markerCount == EVAL_IN_MARKER.length()) {
    return getMarkerCount(line + 1, document) != EVAL_OUT_MARKER.length();
  }
  else if (!isLineRelationshipComputable && markerCount == EVAL_OUT_MARKER.length()) {
    return getMarkerCount(line + 1, document) == EVAL_IN_MARKER.length();
  }
  else if (!isLineRelationshipComputable && markerCount == 0) {
    return getMarkerCount(line + 1, document) != 0 || (line != 0 && getMarkerCount(line - 1, document) != 0);
  }
  else {
    return doIsShowSeparatorLine(line, editor, document);
  }
}
 
Example 7
Source Project: consulo   File: EditorComponentImpl.java    License: 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 8
Source Project: markdown-image-kit   File: MarkdownUtils.java    License: MIT License 5 votes vote down vote up
/**
 * 解析每一行数据, 是有效的 Image mark 才解析
 *
 * @param project     the project           当前项目
 * @param document    the document          当前文本
 * @param virtualFile the virtual file      当前处理的文件
 * @return the list
 */
private static List<MarkdownImage> getImageInfoFromFiles(Project project, Document document, VirtualFile virtualFile) {
    List<MarkdownImage> markdownImageList = new ArrayList<>();

    if (document != null) {
        int lineCount = document.getLineCount();
        // 解析每一行文本
        for (int line = 0; line < lineCount; line++) {
            // 获取指定行的第一个字符在全文中的偏移量,行号的取值范围为:[0,getLineCount()-1]
            int startOffset = document.getLineStartOffset(line);
            // 获取指定行的最后一个字符在全文中的偏移量,行号的取值范围为:[0,getLineCount()-1]
            int endOffset = document.getLineEndOffset(line);
            TextRange currentLineTextRange = TextRange.create(startOffset, endOffset);
            String originalLineText = document.getText(currentLineTextRange);

            if (illegalImageMark(project, originalLineText)) {
                continue;
            }
            log.trace("originalLineText: {}", originalLineText);
            MarkdownImage markdownImage;
            if ((markdownImage = analysisImageMark(virtualFile, originalLineText, line)) != null) {
                markdownImageList.add(markdownImage);
            }
        }
    }
    return markdownImageList;
}
 
Example 9
@Nonnull
private static Range expand(@Nonnull Range range, @Nonnull Document document, @Nonnull Document uDocument) {
  boolean canExpandBefore = range.getLine1() != 0 && range.getVcsLine1() != 0;
  boolean canExpandAfter = range.getLine2() < document.getLineCount() && range.getVcsLine2() < uDocument.getLineCount();
  int offset1 = range.getLine1() - (canExpandBefore ? 1 : 0);
  int uOffset1 = range.getVcsLine1() - (canExpandBefore ? 1 : 0);
  int offset2 = range.getLine2() + (canExpandAfter ? 1 : 0);
  int uOffset2 = range.getVcsLine2() + (canExpandAfter ? 1 : 0);
  return new Range(offset1, offset2, uOffset1, uOffset2);
}
 
Example 10
WidgetIndentHitTester(List<WidgetIndentGuideDescriptor> descriptors, Document document) {
  final int lineCount = document.getLineCount();
  lines = new boolean[lineCount];
  // TODO(jacobr): optimize using a more clever data structure.
  for (WidgetIndentGuideDescriptor descriptor : descriptors) {
    // if (descriptor.parent)
    {
      final int last = min(lines.length, descriptor.endLine + 1);
      for (int i = max(descriptor.startLine - 1, 0); i < last; i++) {
        lines[i] = true;
      }
    }
  }
}
 
Example 11
Source Project: KodeBeagle   File: EditorDocOps.java    License: Apache License 2.0 5 votes vote down vote up
public final Pair<Integer, Integer> getLineOffSets(final Editor projectEditor,
                                                   final int distance) {
    Document document = projectEditor.getDocument();
    SelectionModel selectionModel = projectEditor.getSelectionModel();
    int head = 0;
    int tail = document.getLineCount() - 1;
    if (selectionModel.hasSelection()) {
        head = document.getLineNumber(selectionModel.getSelectionStart());
        tail = document.getLineNumber(selectionModel.getSelectionEnd());
        /*Selection model gives one more line if line is selected completely.
          By Checking if complete line is slected and decreasing tail*/
        if ((document.getLineStartOffset(tail) == selectionModel.getSelectionEnd())) {
            tail--;
        }

    } else {
        int currentLine = document.getLineNumber(projectEditor.getCaretModel().getOffset());

        if (currentLine - distance >= 0) {
            head = currentLine - distance;
        }

        if (currentLine + distance <= document.getLineCount() - 1) {
            tail = currentLine + distance;
        }
    }
    int start = document.getLineStartOffset(head);
    int end = document.getLineEndOffset(tail);
    Pair<Integer, Integer> pair = new Pair<>(start, end);
    return pair;
}
 
Example 12
Source Project: KodeBeagle   File: EditorDocOps.java    License: Apache License 2.0 5 votes vote down vote up
public final void addHighlighting(final List<Integer> linesForHighlighting,
                                  final Document document) {
    TextAttributes attributes = new TextAttributes();
    JBColor color = JBColor.GREEN;
    attributes.setEffectColor(color);
    attributes.setEffectType(EffectType.SEARCH_MATCH);
    attributes.setBackgroundColor(HIGHLIGHTING_COLOR);
    Editor projectEditor =
            FileEditorManager.getInstance(windowObjects.getProject()).getSelectedTextEditor();
    if (projectEditor != null) {
        PsiFile psiFile =
                PsiDocumentManager.getInstance(windowObjects.getProject()).
                        getPsiFile(projectEditor.getDocument());
        MarkupModel markupModel = projectEditor.getMarkupModel();
        if (markupModel != null) {
            markupModel.removeAllHighlighters();

            for (int line : linesForHighlighting) {
                line = line - 1;
                if (line < document.getLineCount()) {
                    int startOffset = document.getLineStartOffset(line);
                    int endOffset = document.getLineEndOffset(line);
                    String lineText =
                            document.getCharsSequence().
                                    subSequence(startOffset, endOffset).toString();
                    int lineStartOffset =
                            startOffset + lineText.length() - lineText.trim().length();
                    markupModel.addRangeHighlighter(lineStartOffset, endOffset,
                            HighlighterLayer.ERROR, attributes,
                            HighlighterTargetArea.EXACT_RANGE);
                    if (psiFile != null && psiFile.findElementAt(lineStartOffset) != null) {
                        HighlightUsagesHandler.doHighlightElements(projectEditor,
                                new PsiElement[]{psiFile.findElementAt(lineStartOffset)},
                                attributes, false);
                    }
                }
            }
        }
    }
}
 
Example 13
Source Project: KodeBeagle   File: EditorDocOps.java    License: Apache License 2.0 5 votes vote down vote up
public final String getContentsInLines(final String fileContents,
                                       final List<Integer> lineNumbersList) {
    Document document = EditorFactory.getInstance().createDocument(fileContents);
    Set<Integer> lineNumbersSet = new TreeSet<Integer>(lineNumbersList);

    StringBuilder stringBuilder = new StringBuilder();
    int prev = lineNumbersSet.iterator().next();

    for (int line : lineNumbersSet) {
        //Document is 0 indexed
        line = line - 1;
        if (line < document.getLineCount() - 1) {
            if (prev != line - 1) {
                stringBuilder.append(System.lineSeparator());
                prev = line;
            }
            int startOffset = document.getLineStartOffset(line);
            int endOffset = document.getLineEndOffset(line)
                    + document.getLineSeparatorLength(line);
            String code = document.getCharsSequence().
                    subSequence(startOffset, endOffset).
                    toString().trim()
                    + System.lineSeparator();
            stringBuilder.append(code);
        }
    }
    return stringBuilder.toString();
}
 
Example 14
@RequiredReadAction
private static LineRange expandLineRangeToCoverPsiElements(final LineRange range, Editor editor, final PsiFile file)
{
	Pair<PsiElement, PsiElement> psiRange = getElementRange(editor, file, range);
	if(psiRange == null)
	{
		return null;
	}
	final PsiElement parent = PsiTreeUtil.findCommonParent(psiRange.getFirst(), psiRange.getSecond());
	Pair<PsiElement, PsiElement> elementRange = getElementRange(parent, psiRange.getFirst(), psiRange.getSecond());
	if(elementRange == null)
	{
		return null;
	}
	int endOffset = elementRange.getSecond().getTextRange().getEndOffset();
	Document document = editor.getDocument();
	if(endOffset > document.getTextLength())
	{
		LOG.assertTrue(!PsiDocumentManager.getInstance(file.getProject()).isUncommited(document));
		LOG.assertTrue(PsiDocumentManagerImpl.checkConsistency(file, document));
	}
	int endLine;
	if(endOffset == document.getTextLength())
	{
		endLine = document.getLineCount();
	}
	else
	{
		endLine = editor.offsetToLogicalPosition(endOffset).line + 1;
		endLine = Math.min(endLine, document.getLineCount());
	}
	int startLine = Math.min(range.startLine, editor.offsetToLogicalPosition(elementRange.getFirst().getTextOffset()).line);
	endLine = Math.max(endLine, range.endLine);
	return new LineRange(startLine, endLine);
}
 
Example 15
Source Project: consulo   File: DesktopEditorErrorPanel.java    License: Apache License 2.0 5 votes vote down vote up
private int offsetToLine(int offset, Document document) {
  if (offset < 0) {
    return 0;
  }
  if (offset > document.getTextLength()) {
    return document.getLineCount();
  }
  return myEditor.offsetToVisualLine(offset);
}
 
Example 16
Source Project: consulo   File: DocumentUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static int getEndLine(RangeMarker range) {
  Document document = range.getDocument();
  int endOffset = range.getEndOffset();

  int endLine = document.getLineNumber(endOffset);
  if (document.getTextLength() == endOffset && lastLineIsNotEmpty(document, endLine)) {
    return document.getLineCount();
  }
  return endLine;
}
 
Example 17
private static int getLineStartSafeOffset(final Document document, int line) {
  if (line >= document.getLineCount()) return document.getTextLength();
  return document.getLineStartOffset(line);
}
 
Example 18
void doPrintNotification(final Notification notification) {
    Editor editor = myLogEditor.getValue();
    if (editor.isDisposed()) {
        return;
    }

    Document document = editor.getDocument();
    boolean scroll = document.getTextLength() == editor.getCaretModel().getOffset() || !editor.getContentComponent().hasFocus();

    Long notificationTime = myProjectModel.getNotificationTime(notification);
    if (notificationTime == null) {
        return;
    }

    String date = DateFormatUtil.formatTimeWithSeconds(notificationTime) + " ";
    append(document, date);

    int startLine = document.getLineCount() - 1;

    ConsoleLog.LogEntry pair = ConsoleLog.formatForLog(notification, StringUtil.repeatSymbol(' ', date.length()));

    final NotificationType type = notification.getType();
    TextAttributesKey key = type == NotificationType.ERROR
        ? ConsoleViewContentType.LOG_ERROR_OUTPUT_KEY
        : type == NotificationType.INFORMATION
        ? ConsoleViewContentType.NORMAL_OUTPUT_KEY
        : ConsoleViewContentType.LOG_WARNING_OUTPUT_KEY;

    int msgStart = document.getTextLength();
    String message = pair.message;
    append(document, message);

    TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(key);
    int layer = HighlighterLayer.CARET_ROW + 1;
    editor.getMarkupModel().addRangeHighlighter(msgStart, document.getTextLength(), layer, attributes, HighlighterTargetArea.EXACT_RANGE);

    for (Pair<TextRange, HyperlinkInfo> link : pair.links) {
        final RangeHighlighter rangeHighlighter = myHyperlinkSupport.getValue()
            .createHyperlink(link.first.getStartOffset() + msgStart, link.first.getEndOffset() + msgStart, null, link.second);
        if (link.second instanceof ConsoleLog.ShowBalloon) {
            ((ConsoleLog.ShowBalloon)link.second).setRangeHighlighter(rangeHighlighter);
        }
    }

    append(document, "\n");

    if (scroll) {
        editor.getCaretModel().moveToOffset(document.getTextLength());
        editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    }

    if (notification.isImportant()) {
        highlightNotification(notification, pair.status, startLine, document.getLineCount() - 1);
    }
}
 
Example 19
Source Project: consulo   File: UsageInfo2UsageAdapter.java    License: Apache License 2.0 4 votes vote down vote up
private static int getLineNumber(@Nonnull Document document, final int startOffset) {
  if (document.getTextLength() == 0) return 0;
  if (startOffset >= document.getTextLength()) return document.getLineCount();
  return document.getLineNumber(startOffset);
}
 
Example 20
Source Project: consulo   File: EditorFragmentComponent.java    License: 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));
}