Java Code Examples for com.intellij.openapi.util.text.StringUtil#countNewLines()

The following examples show how to use com.intellij.openapi.util.text.StringUtil#countNewLines() . 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: RecentLocationsDataModel.java    From consulo with Apache License 2.0 6 votes vote down vote up
private TextRange getTrimmedRange(Document document, int lineNumber) {
  TextRange range = getLinesRange(document, lineNumber);
  String text = document.getText(TextRange.create(range.getStartOffset(), range.getEndOffset()));

  int newLinesBefore = StringUtil.countNewLines(Objects.requireNonNull(StringUtil.substringBefore(text, StringUtil.trimLeading(text))));
  int newLinesAfter = StringUtil.countNewLines(Objects.requireNonNull(StringUtil.substringAfter(text, StringUtil.trimTrailing(text))));

  int firstLine = document.getLineNumber(range.getStartOffset());
  int firstLineAdjusted = firstLine + newLinesBefore;

  int lastLine = document.getLineNumber(range.getEndOffset());
  int lastLineAdjusted = lastLine - newLinesAfter;

  int startOffset = document.getLineStartOffset(firstLineAdjusted);
  int endOffset = document.getLineEndOffset(lastLineAdjusted);

  return TextRange.create(startOffset, endOffset);
}
 
Example 2
Source File: EditorEventManager.java    From lsp4intellij with Apache License 2.0 4 votes vote down vote up
public void documentChanged(DocumentEvent event) {
    if (editor.isDisposed()) {
        return;
    }
    if (event.getDocument() == editor.getDocument()) {
        //Todo - restore when adding hover support
        // long predTime = System.nanoTime(); //So that there are no hover events while typing
        changesParams.getTextDocument().setVersion(version++);

        if (syncKind == TextDocumentSyncKind.Incremental) {
            TextDocumentContentChangeEvent changeEvent = changesParams.getContentChanges().get(0);
            CharSequence newText = event.getNewFragment();
            int offset = event.getOffset();
            int newTextLength = event.getNewLength();
            Position lspPosition = DocumentUtils.offsetToLSPPos(editor, offset);
            int startLine = lspPosition.getLine();
            int startColumn = lspPosition.getCharacter();
            CharSequence oldText = event.getOldFragment();

            //if text was deleted/replaced, calculate the end position of inserted/deleted text
            int endLine, endColumn;
            if (oldText.length() > 0) {
                endLine = startLine + StringUtil.countNewLines(oldText);
                String[] oldLines = oldText.toString().split("\n");
                int oldTextLength = oldLines.length == 0 ? 0 : oldLines[oldLines.length - 1].length();
                endColumn = oldLines.length == 1 ? startColumn + oldTextLength : oldTextLength;
            } else { //if insert or no text change, the end position is the same
                endLine = startLine;
                endColumn = startColumn;
            }
            Range range = new Range(new Position(startLine, startColumn), new Position(endLine, endColumn));
            changeEvent.setRange(range);
            changeEvent.setRangeLength(newTextLength);
            changeEvent.setText(newText.toString());
        } else if (syncKind == TextDocumentSyncKind.Full) {
            changesParams.getContentChanges().get(0).setText(editor.getDocument().getText());
        }
        requestManager.didChange(changesParams);
    } else {
        LOG.error("Wrong document for the EditorEventManager");
    }
}
 
Example 3
Source File: DiffUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static int countLinesShift(@Nonnull DocumentEvent e) {
  return StringUtil.countNewLines(e.getNewFragment()) - StringUtil.countNewLines(e.getOldFragment());
}
 
Example 4
Source File: ChangeList.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static int countLines(@Nullable DiffString text) {
  if (text == null) return 0;
  return StringUtil.countNewLines(text);
}
 
Example 5
Source File: DesktopEditorImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static int countLineFeeds(@Nonnull CharSequence c) {
  return StringUtil.countNewLines(c);
}
 
Example 6
Source File: LineFragmentsCollector.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static int countLines(@Nullable DiffString text) {
  if (text == null || text.isEmpty()) return 0;
  int count = StringUtil.countNewLines(text);
  if (text.charAt(text.length() - 1) != '\n') count++;
  return count;
}
 
Example 7
Source File: DummyDiffFragmentsProcessor.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static int countLines(String text) {
  if (text == null || text.isEmpty()) return 0;
  int count = StringUtil.countNewLines(text);
  if (text.charAt(text.length() - 1) != '\n') count++;
  return count;
}
 
Example 8
Source File: DocumentWindowImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public int getLineCount() {
  return 1 + StringUtil.countNewLines(getText());
}
 
Example 9
Source File: AlignmentInColumnsHelper.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Allows to answer if given node should be aligned to the previous node of the same type according to the given alignment config
 * assuming that given node is a variable declaration.
 *
 * @param node                         target node which alignment strategy is to be defined
 * @param config                       alignment config to use for processing
 * @param blankLinesToBeKeptOnReformat corresponding KEEP_LINE_IN_* formatting setting
 * @return <code>true</code> if given node should be aligned to the previous one; <code>false</code> otherwise
 */
@SuppressWarnings({"MethodMayBeStatic"})
public boolean useDifferentVarDeclarationAlignment(ASTNode node, AlignmentInColumnsConfig config, int blankLinesToBeKeptOnReformat) {
  ASTNode prev = getPreviousAdjacentNodeOfTargetType(node, config, blankLinesToBeKeptOnReformat);
  if (prev == null) {
    return true;
  }

  ASTNode curr = deriveNodeOfTargetType(node, TokenSet.create(prev.getElementType()));
  if (curr == null) {
    return true;
  }

  // The main idea is to avoid alignment like the one below:
  //     private final int    i;
  //                   double d;
  // I.e. we want to avoid alignment-implied long indents from the start of line.
  // Please note that we do allow alignment like below:
  //     private final int    i;
  //     private       double d;
  ASTNode prevSubNode = getSubNodeThatStartsNewLine(prev.getFirstChildNode(), config);
  ASTNode currSubNode = getSubNodeThatStartsNewLine(curr.getFirstChildNode(), config);
  while (true) {
    boolean prevNodeIsDefined = prevSubNode != null;
    boolean currNodeIsDefined = currSubNode != null;
    // Check if one sub-node starts from new line and another one doesn't start.
    if (prevNodeIsDefined ^ currNodeIsDefined) {
      return true;
    }
    if (prevSubNode == null) {
      break;
    }
    if (prevSubNode.getElementType() != currSubNode.getElementType()
        /*|| StringUtil.countNewLines(prevSubNode.getChars()) != StringUtil.countNewLines(currSubNode.getChars())*/) {
      return true;
    }
    prevSubNode = getSubNodeThatStartsNewLine(prevSubNode.getTreeNext(), config);
    currSubNode = getSubNodeThatStartsNewLine(currSubNode.getTreeNext(), config);
  }

  // There is a possible declaration like the one below
  //     int i1 = 1;
  //     int i2, i3 = 2;
  // Three fields are declared here - 'i1', 'i2' and 'i3'. So, the check if field 'i2' contains assignment should be
  // performed against 'i3'.
  ASTNode currentFieldToUse = curr;
  ASTNode nextNode = curr.getTreeNext();

  for (; nextNode != null && nextNode.getTreeParent() == curr.getTreeParent(); nextNode = nextNode.getTreeNext()) {
    IElementType type = nextNode.getElementType();
    if (config.getWhiteSpaceTokenTypes().contains(type)) {
      ASTNode previous = nextNode.getTreePrev();
      if ((previous != null && previous.getElementType() == curr.getElementType()) || StringUtil.countNewLines(nextNode.getChars()) > 1) {
        break;
      }
      continue;
    }

    if (config.getCommentTokenTypes().contains(type)) {
      continue;
    }

    if (type == curr.getElementType()) {
      currentFieldToUse = nextNode;
    }
  }

  List<IElementType> prevTypes = findSubNodeTypes(prev, config.getDistinguishableTypes());
  List<IElementType> currTypes = findSubNodeTypes(currentFieldToUse, config.getDistinguishableTypes());

  return !prevTypes.equals(currTypes);
}