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

The following examples show how to use com.intellij.openapi.editor.Document#createRangeMarker() . 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: MypyTerminal.java    From mypy-PyCharm-plugin with Apache License 2.0 6 votes vote down vote up
private void generateMarkers(MypyResult result) {
    for (MypyError error: result.getErrors()) {
        if (error.isError()) {
            String directory = project.getBaseDir().getPath();
            String file = error.getFile();
            int line = max(error.getLine() - 1, 0);
            VirtualFile vf = LocalFileSystem.getInstance().findFileByPath(directory + File.separator + file);
            if (vf != null) {
                Document document = FileDocumentManager.getInstance().getCachedDocument(vf);
                if (document != null) {
                    error.marker = document.createRangeMarker(document.getLineStartOffset(line),
                            document.getLineEndOffset(line));
                }
            }
        }
    }
}
 
Example 2
Source File: LSPIJUtils.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
public static void applyEdit(Editor editor, TextEdit textEdit, Document document) {
    RangeMarker marker = document.createRangeMarker(LSPIJUtils.toOffset(textEdit.getRange().getStart(), document), LSPIJUtils.toOffset(textEdit.getRange().getEnd(), document));
    int startOffset = marker.getStartOffset();
    int endOffset = marker.getEndOffset();
    String text = textEdit.getNewText();
    if (text != null) {
        text = text.replaceAll("\r", "");
    }
    if (text == null || "".equals(text)) {
        document.deleteString(startOffset, endOffset);
    } else if (endOffset - startOffset <= 0) {
        document.insertString(startOffset, text);
    } else {
        document.replaceString(startOffset, endOffset, text);
    }
    if (text != null && !"".equals(text)) {
        editor.getCaretModel().moveCaretRelatively(text.length(), 0, false, false, true);
    }
    marker.dispose();
}
 
Example 3
Source File: WidgetIndentGuideDescriptor.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void track(Document document) {
  if (marker != null) {
    // TODO(jacobr): it does indicate a bit of a logic bug if we are calling this method twice.
    assert (marker.getDocument() == document);
    return;
  }

  // Create a range marker that goes from the start of the indent for the line
  // to the column of the actual entity.
  final int docLength = document.getTextLength();
  final Location location = attribute.getValueLocation();
  final int startOffset = Math.min(location.getOffset(), docLength);
  final int endOffset = Math.min(startOffset + location.getLength(), docLength);

  marker = document.createRangeMarker(startOffset, endOffset);
}
 
Example 4
Source File: WidgetIndentGuideDescriptor.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void track(Document document) {
  if (marker != null) {
    // TODO(jacobr): it does indicate a bit of a logic bug if we are calling this method twice.
    assert (marker.getDocument() == document);
    return;
  }

  // Create a range marker that goes from the start of the indent for the line
  // to the column of the actual entity.
  final int docLength = document.getTextLength();
  final Location location = attribute.getValueLocation();
  final int startOffset = Math.min(location.getOffset(), docLength);
  final int endOffset = Math.min(startOffset + location.getLength(), docLength);

  marker = document.createRangeMarker(startOffset, endOffset);
}
 
Example 5
Source File: CodeInsightUtilCore.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
public static <T extends PsiElement> T forcePsiPostprocessAndRestoreElement(@Nonnull T element,
                                                                            boolean useFileLanguage) {
  final PsiFile psiFile = element.getContainingFile();
  final Document document = psiFile.getViewProvider().getDocument();
  //if (document == null) return element;
  final Language language = useFileLanguage ? psiFile.getLanguage() : PsiUtilCore.getDialect(element);
  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(psiFile.getProject());
  final RangeMarker rangeMarker = document.createRangeMarker(element.getTextRange());
  documentManager.doPostponedOperationsAndUnblockDocument(document);
  documentManager.commitDocument(document);

  T elementInRange = findElementInRange(psiFile, rangeMarker.getStartOffset(), rangeMarker.getEndOffset(),
                                        (Class<? extends T>)element.getClass(),
                                        language, element);
  rangeMarker.dispose();
  return elementInRange;
}
 
Example 6
Source File: MoveRenameUsageInfo.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void init(final PsiElement element, PsiReference reference, final PsiElement referencedElement) {
  final Project project = element.getProject();
  myReferencedElement = referencedElement;
  if (referencedElement != null) {
    myReferencedElementPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(referencedElement);
  }
  if (reference == null) reference = element.getReference();
  PsiFile containingFile = element.getContainingFile();
  if (reference == null) {
    final TextRange textRange = element.getTextRange();
    if (textRange != null) {
      reference = containingFile.findReferenceAt(textRange.getStartOffset());
    }
  }
  myReference = reference;
  if (reference != null) {
    Document document = PsiDocumentManager.getInstance(project).getDocument(containingFile);
    if (document != null) {
      int elementStart = reference.getElement().getTextRange().getStartOffset();
      myReferenceRangeMarker = document.createRangeMarker(elementStart + reference.getRangeInElement().getStartOffset(),
                                                          elementStart + reference.getRangeInElement().getEndOffset());
    }
    myDynamicUsage = reference.resolve() == null;
  }
}
 
Example 7
Source File: SmartTodoItemPointer.java    From consulo with Apache License 2.0 5 votes vote down vote up
public SmartTodoItemPointer(@Nonnull TodoItem todoItem, @Nonnull Document document) {
  myTodoItem = todoItem;
  myDocument = document;
  TextRange textRange = myTodoItem.getTextRange();
  myRangeMarker = document.createRangeMarker(textRange);
  myAdditionalRangeMarkers = ContainerUtil.map(todoItem.getAdditionalTextRanges(), document::createRangeMarker);
}
 
Example 8
Source File: TemplateSegments.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void replaceSegmentAt(int index, int start, int end, boolean preserveGreediness) {
  RangeMarker rangeMarker = mySegments.get(index);
  boolean greedyToLeft = rangeMarker.isGreedyToLeft();
  boolean greedyToRight = rangeMarker.isGreedyToRight();
  rangeMarker.dispose();

  Document doc = myEditor.getDocument();
  rangeMarker = doc.createRangeMarker(start, end);
  rangeMarker.setGreedyToLeft(greedyToLeft || !preserveGreediness);
  rangeMarker.setGreedyToRight(greedyToRight || !preserveGreediness);
  mySegments.set(index, rangeMarker);
}
 
Example 9
Source File: StatisticsUpdate.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void trackStatistics(InsertionContext context) {
  if (ourPendingUpdate != this) {
    return;
  }

  if (!context.getOffsetMap().containsOffset(CompletionInitializationContext.START_OFFSET)) {
    return;
  }

  final Document document = context.getDocument();
  int startOffset = context.getStartOffset();
  int tailOffset = context.getEditor().getCaretModel().getOffset();
  if (startOffset < 0 || tailOffset <= startOffset) {
    return;
  }

  final RangeMarker marker = document.createRangeMarker(startOffset, tailOffset);
  final DocumentAdapter listener = new DocumentAdapter() {
    @Override
    public void beforeDocumentChange(DocumentEvent e) {
      if (!marker.isValid() || e.getOffset() > marker.getStartOffset() && e.getOffset() < marker.getEndOffset()) {
        cancelLastCompletionStatisticsUpdate();
      }
    }
  };

  ourStatsAlarm.addRequest(() -> {
    if (ourPendingUpdate == this) {
      applyLastCompletionStatisticsUpdate();
    }
  }, 20 * 1000);

  document.addDocumentListener(listener);
  Disposer.register(this, () -> {
    document.removeDocumentListener(listener);
    marker.dispose();
    ourStatsAlarm.cancelAllRequests();
  });
}
 
Example 10
Source File: LazyRangeMarkerFactoryImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public RangeMarker createDelegate(@Nonnull VirtualFile file, @Nonnull Document document) {
  if (document.getTextLength() == 0 && !(myLine == 0 && myColumn == 0)) {
    return null;
  }

  int offset = calculateOffset(document, myLine, myColumn, myTabSize);
  return document.createRangeMarker(offset, offset);
}
 
Example 11
Source File: CodeInsightTestFixtureImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private SelectionAndCaretMarkupLoader(Project project, String fileText, String filePath) {
  this.filePath = filePath;
  final Document document = EditorFactory.getInstance().createDocument(fileText);

  int caretIndex = fileText.indexOf(CARET_MARKER);
  int selStartIndex = fileText.indexOf(SELECTION_START_MARKER);
  int selEndIndex = fileText.indexOf(SELECTION_END_MARKER);
  int blockStartIndex = fileText.indexOf(BLOCK_START_MARKER);
  int blockEndIndex = fileText.indexOf(BLOCK_END_MARKER);

  caretMarker = caretIndex >= 0 ? document.createRangeMarker(caretIndex, caretIndex + CARET_MARKER.length()) : null;
  if (selStartIndex >= 0 || selEndIndex >= 0) {
    blockSelection = false;
    selStartMarker = selStartIndex >= 0 ? document.createRangeMarker(selStartIndex, selStartIndex + SELECTION_START_MARKER.length()) : null;
    selEndMarker = selEndIndex >= 0 ? document.createRangeMarker(selEndIndex, selEndIndex + SELECTION_END_MARKER.length()) : null;
  }
  else {
    selStartMarker = blockStartIndex >= 0 ? document.createRangeMarker(blockStartIndex, blockStartIndex + BLOCK_START_MARKER.length()) : null;
    selEndMarker = blockEndIndex >= 0 ? document.createRangeMarker(blockEndIndex, blockEndIndex + BLOCK_END_MARKER.length()) : null;
    blockSelection = selStartMarker != null || selEndMarker != null;
  }

  new WriteCommandAction(project) {
    @Override
    protected void run(Result result) throws Exception {
      if (caretMarker != null) {
        document.deleteString(caretMarker.getStartOffset(), caretMarker.getEndOffset());
      }
      if (selStartMarker != null) {
        document.deleteString(selStartMarker.getStartOffset(), selStartMarker.getEndOffset());
      }
      if (selEndMarker != null) {
        document.deleteString(selEndMarker.getStartOffset(), selEndMarker.getEndOffset());
      }
    }
  }.execute();

  newFileText = document.getText();
}
 
Example 12
Source File: DocumentFragmentContent.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static RangeMarker createRangeMarker(@Nonnull Document document, @Nonnull TextRange range) {
  RangeMarker rangeMarker = document.createRangeMarker(range.getStartOffset(), range.getEndOffset(), true);
  rangeMarker.setGreedyToLeft(true);
  rangeMarker.setGreedyToRight(true);
  return rangeMarker;
}
 
Example 13
Source File: OutlineLocation.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void track(Document document) {
  if (marker != null) {
    assert (document == marker.getDocument());
    return;
  }
  // Create a range marker that goes from the start of the indent for the line
  // to the column of the actual entity.
  final int docLength = document.getTextLength();
  final int startOffset = Math.min(rawRange.getStartOffset(), docLength);
  final int endOffset = Math.min(rawRange.getEndOffset(), docLength);

  endingWord = getCurrentWord(document, endOffset - 1);
  marker = document.createRangeMarker(startOffset, endOffset);
}
 
Example 14
Source File: OutlineLocation.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void track(Document document) {
  if (marker != null) {
    assert (document == marker.getDocument());
    return;
  }
  // Create a range marker that goes from the start of the indent for the line
  // to the column of the actual entity.
  final int docLength = document.getTextLength();
  final int startOffset = Math.min(rawRange.getStartOffset(), docLength);
  final int endOffset = Math.min(rawRange.getEndOffset(), docLength);

  endingWord = getCurrentWord(document, endOffset - 1);
  marker = document.createRangeMarker(startOffset, endOffset);
}
 
Example 15
Source File: LazyRangeMarkerFactoryImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@Nonnull
public RangeMarker createDelegate(@Nonnull VirtualFile file, @Nonnull final Document document) {
  final int offset = Math.min(myInitialOffset, document.getTextLength());
  return document.createRangeMarker(offset, offset);
}
 
Example 16
Source File: DiffRangeMarker.java    From consulo with Apache License 2.0 4 votes vote down vote up
DiffRangeMarker(@Nonnull Document document, @Nonnull TextRange range, RangeInvalidListener listener) {
  myRangeMarker = document.createRangeMarker(range.getStartOffset(), range.getEndOffset());
  if (listener != null) {
    InvalidRangeDispatcher.addClient(document, this, listener);
  }
}
 
Example 17
Source File: AsyncFilterRunner.java    From consulo with Apache License 2.0 4 votes vote down vote up
DeltaTracker(Document document, int offset) {
  initialMarkerOffset = offset;
  endMarker = document.createRangeMarker(initialMarkerOffset, initialMarkerOffset);
}
 
Example 18
Source File: SmartEnterProcessor.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected RangeMarker createRangeMarker(final PsiElement elt) {
  final PsiFile psiFile = elt.getContainingFile();
  final PsiDocumentManager instance = PsiDocumentManager.getInstance(elt.getProject());
  final Document document = instance.getDocument(psiFile);
  return document.createRangeMarker(elt.getTextRange());
}
 
Example 19
Source File: MypyTerminal.java    From mypy-PyCharm-plugin with Apache License 2.0 4 votes vote down vote up
private void openError(int index) {
    if ((index >= errorsList.getModel().getSize()) | (index < 0)) {
        return;
    }
    if (runner.isRunning()) {
        return;
    }
    MypyError error = errorsList.getModel().getElementAt(index);
    String directory = project.getBaseDir().getPath();
    if (error.isError()) {
        String file = error.getFile();
        int line = max(error.getLine() - 1, 0);
        int column = max(error.getColumn() - 1, 0);
        VirtualFile vf = LocalFileSystem.getInstance().findFileByPath(directory + File.separator + file);
        // May be null if an error is shown in a file beyond repository
        // (e.g. typeshed or a deleted file because of a bug).
        if (vf != null) {
            FileEditor[] editors = FileEditorManagerEx.getInstanceEx(project).openFile(vf, true);
            if (editors[0] instanceof TextEditor) {
                Editor editor = ((TextEditor) editors[0]).getEditor();
                if (error.marker == null) {
                    // Try re-creating markers, likely the file was not in cache after the type check.
                    // TODO: do this on document opening for all documents?
                    Document document = FileDocumentManager.getInstance().getCachedDocument(vf);
                    if (document != null) {
                        for (MypyError e: errorMap.get(error.getFile())) {
                            int errorLine = max(e.getLine() - 1, 0);
                            e.marker = document.createRangeMarker(document.getLineStartOffset(errorLine),
                                    document.getLineEndOffset(errorLine));
                        }
                    }
                }
                if (error.marker != null && error.marker.isValid()) {
                    editor.getCaretModel().getPrimaryCaret().moveToOffset(error.marker.getStartOffset());
                }
                else {
                    LogicalPosition pos = new LogicalPosition(line, column);
                    editor.getCaretModel().getPrimaryCaret().moveToLogicalPosition(pos);
                }
                editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
                if (error.marker != null && error.marker.isValid()) {
                    editor.getSelectionModel().selectLineAtCaret();
                }
            }
        }
    }
}