Java Code Examples for com.intellij.util.DocumentUtil#executeInBulk()

The following examples show how to use com.intellij.util.DocumentUtil#executeInBulk() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
Source File: IndentSelectionAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
static void doIndent(final int endIndex, final int startIndex, final Document document, final Project project, final Editor editor,
                     final int blockIndent) {
  final int[] caretOffset = {editor.getCaretModel().getOffset()};

  boolean bulkMode = endIndex - startIndex > 50;
  DocumentUtil.executeInBulk(document, bulkMode, ()-> {
    List<Integer> nonModifiableLines = new ArrayList<>();
    if (project != null) {
      PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
      IndentStrategy indentStrategy = LanguageIndentStrategy.getIndentStrategy(file);
      if (!LanguageIndentStrategy.isDefault(indentStrategy)) {
        for (int i = startIndex; i <= endIndex; i++) {
          if (!canIndent(document, file, i, indentStrategy)) {
            nonModifiableLines.add(i);
          }
        }
      }
    }
    for(int i=startIndex; i<=endIndex; i++) {
      if (!nonModifiableLines.contains(i)) {
        caretOffset[0] = EditorActionUtil.indentLine(project, editor, i, blockIndent, caretOffset[0]);
      }
    }
  });

  editor.getCaretModel().moveToOffset(caretOffset[0]);
}
 
Example 8
Source File: ConvertIndentsActionBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static int processIndents(Document document, int tabSize, TextRange textRange, IndentBuilder indentBuilder) {
  int[] changedLines = {0};
  DocumentUtil.executeInBulk(document, true, () -> {
    int startLine = document.getLineNumber(textRange.getStartOffset());
    int endLine = document.getLineNumber(textRange.getEndOffset());
    for (int line = startLine; line <= endLine; line++) {
      int indent = 0;
      final int lineStart = document.getLineStartOffset(line);
      final int lineEnd = document.getLineEndOffset(line);
      int indentEnd = lineEnd;
      for(int offset = Math.max(lineStart, textRange.getStartOffset()); offset < lineEnd; offset++) {
        char c = document.getCharsSequence().charAt(offset);
        if (c == ' ') {
          indent++;
        }
        else if (c == '\t') {
          indent = ((indent / tabSize) + 1) * tabSize;
        }
        else {
          indentEnd = offset;
          break;
        }
      }
      if (indent > 0) {
        String oldIndent = document.getCharsSequence().subSequence(lineStart, indentEnd).toString();
        String newIndent = indentBuilder.buildIndent(indent, tabSize);
        if (!oldIndent.equals(newIndent)) {
          document.replaceString(lineStart, indentEnd, newIndent);
          changedLines[0]++;
        }
      }
    }
  });
  return changedLines[0];
}
 
Example 9
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 10
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);
    }
  });
}
 
Example 11
Source File: ConsoleViewImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void doClear() {
  ApplicationManager.getApplication().assertIsDispatchThread();

  if (isDisposed()) return;
  final DocumentEx document = myEditor.getDocument();
  synchronized (LOCK) {
    clearHyperlinkAndFoldings();
  }
  final int documentTextLength = document.getTextLength();
  if (documentTextLength > 0) {
    DocumentUtil.executeInBulk(document, true, () -> document.deleteString(0, documentTextLength));
  }
  MarkupModel model = DocumentMarkupModel.forDocument(myEditor.getDocument(), getProject(), true);
  model.removeAllHighlighters(); // remove all empty highlighters leftovers if any
}
 
Example 12
Source File: TemplateState.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void smartIndent(int startOffset, int endOffset) {
  int startLineNum = myDocument.getLineNumber(startOffset);
  int endLineNum = myDocument.getLineNumber(endOffset);
  if (endLineNum == startLineNum) {
    return;
  }

  int selectionIndent = -1;
  int selectionStartLine = -1;
  int selectionEndLine = -1;
  int selectionSegment = myTemplate.getVariableSegmentNumber(TemplateImpl.SELECTION);
  if (selectionSegment >= 0) {
    int selectionStart = myTemplate.getSegmentOffset(selectionSegment);
    selectionIndent = 0;
    String templateText = myTemplate.getTemplateText();
    while (selectionStart > 0 && templateText.charAt(selectionStart - 1) == ' ') {
      // TODO handle tabs
      selectionIndent++;
      selectionStart--;
    }
    selectionStartLine = myDocument.getLineNumber(mySegments.getSegmentStart(selectionSegment));
    selectionEndLine = myDocument.getLineNumber(mySegments.getSegmentEnd(selectionSegment));
  }

  int indentLineNum = startLineNum;

  int lineLength = 0;
  for (; indentLineNum >= 0; indentLineNum--) {
    lineLength = myDocument.getLineEndOffset(indentLineNum) - myDocument.getLineStartOffset(indentLineNum);
    if (lineLength > 0) {
      break;
    }
  }
  if (indentLineNum < 0) {
    return;
  }
  StringBuilder buffer = new StringBuilder();
  CharSequence text = myDocument.getCharsSequence();
  for (int i = 0; i < lineLength; i++) {
    char ch = text.charAt(myDocument.getLineStartOffset(indentLineNum) + i);
    if (ch != ' ' && ch != '\t') {
      break;
    }
    buffer.append(ch);
  }
  if (buffer.length() == 0 && selectionIndent <= 0 || startLineNum >= endLineNum) {
    return;
  }
  String stringToInsert = buffer.toString();
  int finalSelectionStartLine = selectionStartLine;
  int finalSelectionEndLine = selectionEndLine;
  int finalSelectionIndent = selectionIndent;
  DocumentUtil.executeInBulk(myDocument, true, () -> {
    for (int i = startLineNum + 1; i <= endLineNum; i++) {
      if (i > finalSelectionStartLine && i <= finalSelectionEndLine) {
        myDocument.insertString(myDocument.getLineStartOffset(i), StringUtil.repeatSymbol(' ', finalSelectionIndent));
      }
      else {
        myDocument.insertString(myDocument.getLineStartOffset(i), stringToInsert);
      }
    }
  });
}