com.intellij.openapi.util.TextRange Java Examples
The following examples show how to use
com.intellij.openapi.util.TextRange.
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: FileStatusMap.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull private static RangeMarker combineScopes(RangeMarker old, @Nonnull TextRange scope, int textLength, @Nonnull Document document) { if (old == null) { if (scope.equalsToRange(0, textLength)) return WHOLE_FILE_DIRTY_MARKER; return document.createRangeMarker(scope); } if (old == WHOLE_FILE_DIRTY_MARKER) return old; TextRange oldRange = TextRange.create(old); TextRange union = scope.union(oldRange); if (old.isValid() && union.equals(oldRange)) { return old; } if (union.getEndOffset() > textLength) { union = union.intersection(new TextRange(0, textLength)); } assert union != null; return document.createRangeMarker(union); }
Example #2
Source File: LatteFoldingBuilder.java From intellij-latte with MIT License | 6 votes |
@SuppressWarnings("unchecked") @NotNull @Override public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) { List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>(); if (!quick) { Collection<LatteMacroClassic> nodes = PsiTreeUtil.findChildrenOfAnyType(root, LatteMacroClassic.class); for (PsiElement node : nodes) { int start = node.getFirstChild().getTextRange().getEndOffset(); int end = node.getLastChild().getTextRange().getEndOffset(); if (end == start) { continue; } if (node instanceof LatteMacroClassic) { start--; end--; } descriptors.add(new FoldingDescriptor(node, TextRange.create(start, end))); } } return descriptors.toArray(new FoldingDescriptor[descriptors.size()]); }
Example #3
Source File: SelectionUtil.java From intellij-haxe with Apache License 2.0 | 6 votes |
static private TextRange findTokenLimits(PsiElement e, int offset, boolean useWhitespace) { final int tokenOffset = e.getTextOffset(); int startPos = offset - tokenOffset; int endPos = startPos; final String text = e.getText(); final int length = text.length(); // While scanning for the beginning and end of a word, we don't have to // worry about escaped characters ("\n") because they are split apart into // separate REGULAR_STRING_PART lexemes. Thus, they are automatically string // separators. // Scan backward for the start of the word. If the offset is a space, then // we want the word before the startPos. while (startPos > 0 && !isDelimiter(text.charAt(startPos - 1), useWhitespace)) { --startPos; } // Scan forward to find the end of the word. If this offset is whitespace, then // we are done. while (endPos < length && !isDelimiter(text.charAt(endPos), useWhitespace)) { ++endPos; } return new TextRange(startPos + tokenOffset, endPos + tokenOffset); }
Example #4
Source File: PsiTreeUtil.java From consulo with Apache License 2.0 | 6 votes |
@Nullable public static <T extends PsiElement> T findElementOfClassAtOffset(@Nonnull PsiFile file, int offset, @Nonnull Class<T> clazz, boolean strictStart) { final List<PsiFile> psiRoots = file.getViewProvider().getAllFiles(); T result = null; for (PsiElement root : psiRoots) { final PsiElement elementAt = root.findElementAt(offset); if (elementAt != null) { final T parent = getParentOfType(elementAt, clazz, strictStart); if (parent != null) { final TextRange range = parent.getTextRange(); if (!strictStart || range.getStartOffset() == offset) { if (result == null || result.getTextRange().getEndOffset() > range.getEndOffset()) { result = parent; } } } } } return result; }
Example #5
Source File: BlockUtil.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull public static List<DataLanguageBlockWrapper> filterBlocksByRange(@Nonnull List<DataLanguageBlockWrapper> list, @Nonnull TextRange textRange) { int i = 0; while (i < list.size()) { final DataLanguageBlockWrapper wrapper = list.get(i); final TextRange range = wrapper.getTextRange(); if (textRange.contains(range)) { i++; } else if (range.intersectsStrict(textRange)) { list.remove(i); list.addAll(i, buildChildWrappers(wrapper.getOriginal())); } else { list.remove(i); } } return list; }
Example #6
Source File: CodeFormatterFacade.java From consulo with Apache License 2.0 | 6 votes |
@Nullable static ASTNode findContainingNode(@Nonnull PsiFile file, @Nullable TextRange range) { Language language = file.getLanguage(); if (range == null) return null; final FileViewProvider viewProvider = file.getViewProvider(); final PsiElement startElement = viewProvider.findElementAt(range.getStartOffset(), language); final PsiElement endElement = viewProvider.findElementAt(range.getEndOffset() - 1, language); final PsiElement commonParent = startElement != null && endElement != null ? PsiTreeUtil.findCommonParent(startElement, endElement) : null; ASTNode node = null; if (commonParent != null) { node = commonParent.getNode(); // Find the topmost parent with the same range. ASTNode parent = node.getTreeParent(); while (parent != null && parent.getTextRange().equals(commonParent.getTextRange())) { node = parent; parent = parent.getTreeParent(); } } if (node == null) { node = file.getNode(); } return node; }
Example #7
Source File: OffsetsElementSignatureProvider.java From consulo with Apache License 2.0 | 6 votes |
@Override public String getSignature(@Nonnull PsiElement element) { TextRange range = element.getTextRange(); if (range.isEmpty()) { return null; } StringBuilder buffer = new StringBuilder(); buffer.append(TYPE_MARKER).append("#"); buffer.append(range.getStartOffset()); buffer.append(ELEMENT_TOKENS_SEPARATOR); buffer.append(range.getEndOffset()); // There is a possible case that given PSI element has a parent or child that targets the same range. So, we remember // not only target range offsets but 'hierarchy index' as well. int index = 0; for (PsiElement e = element.getParent(); e != null && range.equals(e.getTextRange()); e = e.getParent()) { index++; } buffer.append(ELEMENT_TOKENS_SEPARATOR).append(index); return buffer.toString(); }
Example #8
Source File: DocumentFoldingInfo.java From consulo with Apache License 2.0 | 6 votes |
void loadFromEditor(@Nonnull Editor editor) { ApplicationManager.getApplication().assertIsDispatchThread(); LOG.assertTrue(!editor.isDisposed()); clear(); FoldRegion[] foldRegions = editor.getFoldingModel().getAllFoldRegions(); for (FoldRegion region : foldRegions) { if (!region.isValid()) continue; boolean expanded = region.isExpanded(); String signature = region.getUserData(UpdateFoldRegionsOperation.SIGNATURE); if (signature == UpdateFoldRegionsOperation.NO_SIGNATURE) continue; Boolean storedCollapseByDefault = region.getUserData(UpdateFoldRegionsOperation.COLLAPSED_BY_DEFAULT); boolean collapseByDefault = storedCollapseByDefault != null && storedCollapseByDefault && !FoldingUtil.caretInsideRange(editor, TextRange.create(region)); if (collapseByDefault == expanded || signature == null) { if (signature != null) { myInfos.add(new Info(signature, expanded)); } else { RangeMarker marker = editor.getDocument().createRangeMarker(region.getStartOffset(), region.getEndOffset()); myRangeMarkers.add(marker); marker.putUserData(FOLDING_INFO_KEY, new FoldingInfo(region.getPlaceholderText(), expanded)); } } } }
Example #9
Source File: CSharpGenericParameterInfoHandler.java From consulo-csharp with Apache License 2.0 | 6 votes |
@Override public void updateUI(DotNetGenericParameterListOwner p, ParameterInfoUIContext context) { if(p == null) { context.setUIComponentEnabled(false); return; } CSharpGenericParametersInfo build = CSharpGenericParametersInfo.build(p); if(build == null) { context.setUIComponentEnabled(false); return; } String text = build.getText(); TextRange parameterRange = build.getParameterRange(context.getCurrentParameterIndex()); context.setupUIComponentPresentation(text, parameterRange.getStartOffset(), parameterRange.getEndOffset(), !context.isUIComponentEnabled(), false, false, context.getDefaultParameterColor()); }
Example #10
Source File: UnterminatedCommentAnnotator.java From bamboo-soy with Apache License 2.0 | 6 votes |
@Override public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder annotationHolder) { if (element instanceof PsiComment) { IElementType commentTokenType = ((PsiComment) element).getTokenType(); if (commentTokenType != SoyTypes.DOC_COMMENT_BLOCK && commentTokenType != SoyTypes.COMMENT_BLOCK) { return; } if (!element.getText().endsWith("*/")) { int start = element.getTextRange().getEndOffset() - 1; int end = start + 1; annotationHolder .createErrorAnnotation(TextRange.create(start, end), "Unterminated comment"); } } }
Example #11
Source File: ProjectViewRearranger.java From intellij with Apache License 2.0 | 6 votes |
@Override public List<Entry> parse( PsiElement root, @Nullable Document document, Collection<TextRange> ranges, ArrangementSettings settings) { if (root instanceof ProjectViewPsiListSection) { Entry entry = fromListSection(ranges, (ProjectViewPsiListSection) root); return entry != null ? ImmutableList.of(entry) : ImmutableList.of(); } if (root instanceof ProjectViewPsiFile) { return Arrays.stream( ((ProjectViewPsiFile) root).findChildrenByClass(ProjectViewPsiListSection.class)) .map(section -> fromListSection(ranges, section)) .filter(Objects::nonNull) .collect(toImmutableList()); } return ImmutableList.of(); }
Example #12
Source File: RequirejsPsiReferenceProvider.java From WebStormRequireJsPlugin with MIT License | 6 votes |
@NotNull @Override public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement, @NotNull ProcessingContext processingContext) { RequirejsProjectComponent projectComponent = psiElement.getProject().getComponent(RequirejsProjectComponent.class); if (!projectComponent.isEnabled()) { return PsiReference.EMPTY_ARRAY; } String path = psiElement.getText(); if (isRequireCall(psiElement) || isDefineFirstCollection(psiElement)) { PsiReference ref = new RequirejsReference(psiElement, new TextRange(1, path.length() - 1)); return new PsiReference[] {ref}; } return new PsiReference[0]; }
Example #13
Source File: DiagnosticsTreeCellRenderer.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
public void appendColoredFragments(final MultiIconSimpleColoredComponent simpleColoredComponent, final String text, Iterable<TextRange> colored, final SimpleTextAttributes plain, final SimpleTextAttributes highlighted) { final List<Pair<String, Integer>> searchTerms = new ArrayList<>(); for (TextRange fragment : colored) { searchTerms.add(Pair.create(fragment.substring(text), fragment.getStartOffset())); } int lastOffset = 0; for (Pair<String, Integer> pair : searchTerms) { if (pair.second > lastOffset) { simpleColoredComponent.append(text.substring(lastOffset, pair.second), plain); } simpleColoredComponent.append(text.substring(pair.second, pair.second + pair.first.length()), highlighted); lastOffset = pair.second + pair.first.length(); } if (lastOffset < text.length()) { simpleColoredComponent.append(text.substring(lastOffset), plain); } }
Example #14
Source File: CodeStyleManagerImpl.java From consulo with Apache License 2.0 | 6 votes |
private static PsiElement reformatRangeImpl(final @Nonnull PsiElement element, final int startOffset, final int endOffset, boolean canChangeWhiteSpacesOnly) throws IncorrectOperationException { LOG.assertTrue(element.isValid()); CheckUtil.checkWritable(element); if (!SourceTreeToPsiMap.hasTreeElement(element)) { return element; } ASTNode treeElement = element.getNode(); final PsiFile file = element.getContainingFile(); if (ExternalFormatProcessor.useExternalFormatter(file)) { return ExternalFormatProcessor.formatElement(element, TextRange.create(startOffset, endOffset), canChangeWhiteSpacesOnly); } final CodeFormatterFacade codeFormatter = new CodeFormatterFacade(getSettings(file), element.getLanguage()); final PsiElement formatted = codeFormatter.processRange(treeElement, startOffset, endOffset).getPsi(); return canChangeWhiteSpacesOnly ? formatted : postProcessElement(file, formatted); }
Example #15
Source File: Identikit.java From consulo with Apache License 2.0 | 6 votes |
@Nullable private PsiElement findParent(int startOffset, int endOffset, PsiElement anchor) { TextRange range = anchor.getTextRange(); if (range.getStartOffset() != startOffset) return null; while (range.getEndOffset() < endOffset) { anchor = anchor.getParent(); if (anchor == null || anchor instanceof PsiDirectory) { return null; } range = anchor.getTextRange(); } while (range.getEndOffset() == endOffset) { if (isAcceptable(anchor)) { return anchor; } anchor = anchor.getParent(); if (anchor == null || anchor instanceof PsiDirectory) break; range = anchor.getTextRange(); } return null; }
Example #16
Source File: DeleteLineAction.java From consulo with Apache License 2.0 | 6 votes |
private static TextRange getRangeToDelete(Editor editor, Caret caret) { int selectionStart = caret.getSelectionStart(); int selectionEnd = caret.getSelectionEnd(); int startOffset = EditorUtil.getNotFoldedLineStartOffset(editor, selectionStart); // There is a possible case that selection ends at the line start, i.e. something like below ([...] denotes selected text, // '|' is a line start): // |line 1 // |[line 2 // |]line 3 // We don't want to delete line 3 here. However, the situation below is different: // |line 1 // |[line 2 // |line] 3 // Line 3 must be removed here. int endOffset = EditorUtil.getNotFoldedLineEndOffset(editor, selectionEnd > 0 && selectionEnd != selectionStart ? selectionEnd - 1 : selectionEnd); if (endOffset < editor.getDocument().getTextLength()) { endOffset++; } else if (startOffset > 0) { startOffset--; } return new TextRange(startOffset, endOffset); }
Example #17
Source File: RangeMarkerTest.java From consulo with Apache License 2.0 | 6 votes |
public void testPsi2DocSurround() throws Exception { StringBuilder buffer = new StringBuilder("0123456789"); RangeMarker marker = createMarker(buffer.toString(), 2, 5); synchronizer.startTransaction(getProject(), document, psiFile); synchronizer.replaceString(document, 3, 5, "3a4"); buffer.replace(3, 5, "3a4"); synchronizer.insertString(document, 3, "b"); buffer.insert(3, "b"); synchronizer.insertString(document, 7, "d"); buffer.insert(7, "d"); final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = synchronizer.getTransaction(document); final Map<TextRange, CharSequence> affectedFragments = transaction.getAffectedFragments(); assertEquals(3, affectedFragments.size()); synchronizer.commitTransaction(document); assertEquals(buffer.toString(), document.getText()); assertValidMarker(marker, 2, 7); }
Example #18
Source File: HaxeDocumentModel.java From intellij-haxe with Apache License 2.0 | 6 votes |
/** * Replace the text within the given range and reformat it according to the user's * code style/formatting rules. * * NOTE: The PSI may be entirely invalidated and re-created by this call. * * @param range Range of text or PsiElements to replace. * @param text Replacement text (may be null). */ public void replaceAndFormat(@NotNull final TextRange range, @Nullable String text) { if (null == text) { text = ""; } // Mark the beginning and end so that we have the proper range after adding text. // Greedy means that the text immediately added at the beginning/end of the marker are included. RangeMarker marker = document.createRangeMarker(range); marker.setGreedyToLeft(true); marker.setGreedyToRight(true); try { document.replaceString(range.getStartOffset(), range.getEndOffset(), text); //PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); // force update PSI. if (marker.isValid()) { // If the range wasn't reduced to zero. CodeStyleManager.getInstance(file.getProject()).reformatText(file, marker.getStartOffset(), marker.getEndOffset()); } } finally { marker.dispose(); } }
Example #19
Source File: RearrangeCodeProcessor.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull @Override protected FutureTask<Boolean> prepareTask(@Nonnull final PsiFile file, final boolean processChangedTextOnly) { return new FutureTask<Boolean>(new Callable<Boolean>() { @Override public Boolean call() throws Exception { try { Collection<TextRange> ranges = getRangesToFormat(file, processChangedTextOnly); Document document = PsiDocumentManager.getInstance(myProject).getDocument(file); if (document != null && Rearranger.EXTENSION.forLanguage(file.getLanguage()) != null) { PsiDocumentManager.getInstance(myProject).doPostponedOperationsAndUnblockDocument(document); PsiDocumentManager.getInstance(myProject).commitDocument(document); Runnable command = prepareRearrangeCommand(file, ranges); try { CommandProcessor.getInstance().executeCommand(myProject, command, COMMAND_NAME, null); } finally { PsiDocumentManager.getInstance(myProject).commitDocument(document); } } return true; } catch (FilesTooBigForDiffException e) { handleFileTooBigException(LOG, e, file); return false; } } }); }
Example #20
Source File: LineMarkerInfo.java From consulo with Apache License 2.0 | 5 votes |
/** * @deprecated use {@link LineMarkerInfo#LineMarkerInfo(PsiElement, TextRange, Image, int, Function, GutterIconNavigationHandler, GutterIconRenderer.Alignment)} instead */ public LineMarkerInfo(@Nonnull T element, int startOffset, Image icon, int updatePass, @Nullable Function<? super T, String> tooltipProvider, @Nullable GutterIconNavigationHandler<T> navHandler, @Nonnull GutterIconRenderer.Alignment alignment) { this(element, new TextRange(startOffset, startOffset), icon, updatePass, tooltipProvider, navHandler, alignment); }
Example #21
Source File: LookupCellRenderer.java From consulo with Apache License 2.0 | 5 votes |
private void renderItemName(LookupElement item, Color foreground, boolean selected, @SimpleTextAttributes.StyleAttributeConstant int style, String name, final SimpleColoredComponent nameComponent) { final SimpleTextAttributes base = new SimpleTextAttributes(style, foreground); final String prefix = item instanceof EmptyLookupItem ? "" : myLookup.itemPattern(item); if (prefix.length() > 0) { Iterable<TextRange> ranges = getMatchingFragments(prefix, name); if (ranges != null) { SimpleTextAttributes highlighted = new SimpleTextAttributes(style, selected ? SELECTED_PREFIX_FOREGROUND_COLOR : PREFIX_FOREGROUND_COLOR); SpeedSearchUtil.appendColoredFragments(nameComponent, name, ranges, base, highlighted); return; } } nameComponent.append(name, base); }
Example #22
Source File: WolfTheProblemSolverImpl.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull private static TextRange getTextRange(@Nonnull final VirtualFile virtualFile, int line, final int column) { Document document = FileDocumentManager.getInstance().getDocument(virtualFile); if (line > document.getLineCount()) line = document.getLineCount(); line = line <= 0 ? 0 : line - 1; int offset = document.getLineStartOffset(line) + (column <= 0 ? 0 : column - 1); return new TextRange(offset, offset); }
Example #23
Source File: JsonnetFoldingBuilder.java From intellij-jsonnet with Apache License 2.0 | 5 votes |
@NotNull @Override public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) { List<FoldingDescriptor> descriptors = new ArrayList<>(); Collection<PsiElement> literalExpressions = PsiTreeUtil.findChildrenOfType(root, JsonnetObj.class); literalExpressions.addAll(PsiTreeUtil.findChildrenOfType(root, JsonnetArr.class)); literalExpressions.addAll(PsiTreeUtil.findChildrenOfType(root, JsonnetArrcomp.class)); for (final PsiElement literalExpression : literalExpressions) { FoldingGroup group = FoldingGroup.newGroup( "jsonnet-" + literalExpression.getTextRange().getStartOffset() + "-" + literalExpression.getTextRange().getEndOffset() ); int start = literalExpression.getTextRange().getStartOffset() + 1; int end = literalExpression.getTextRange().getEndOffset() - 1; if (end > start) descriptors.add( new FoldingDescriptor( literalExpression.getNode(), new TextRange(start, end), group ) { @Override public String getPlaceholderText() { return "..."; } } ); } return descriptors.toArray(new FoldingDescriptor[0]); }
Example #24
Source File: BashSimpleTextLiteralEscaper.java From BashSupport with Apache License 2.0 | 5 votes |
public int getOffsetInHost(int offsetInDecoded, @NotNull final TextRange rangeInsideHost) { int result = offsetInDecoded < outSourceOffsets.length ? outSourceOffsets[offsetInDecoded] : -1; if (result == -1) { return -1; } return rangeInsideHost.getStartOffset() + (result <= rangeInsideHost.getLength() ? result : rangeInsideHost.getLength()); }
Example #25
Source File: MinusculeMatcherImpl.java From consulo with Apache License 2.0 | 5 votes |
@Nullable private FList<TextRange> matchInsideFragment(@Nonnull String name, int patternIndex, int nameIndex, boolean isAsciiName, int fragmentLength) { // exact middle matches have to be at least of length 3, to prevent too many irrelevant matches int minFragment = isMiddleMatch(name, patternIndex, nameIndex) ? 3 : 1; FList<TextRange> camelHumpRanges = improveCamelHumps(name, patternIndex, nameIndex, isAsciiName, fragmentLength, minFragment); if (camelHumpRanges != null) { return camelHumpRanges; } return findLongestMatchingPrefix(name, patternIndex, nameIndex, isAsciiName, fragmentLength, minFragment); }
Example #26
Source File: SpringReformatter.java From spring-javaformat with Apache License 2.0 | 5 votes |
private void reformat(PsiFile file, Collection<TextRange> ranges, Document document) { if (document != null) { Formatter formatter = new Formatter(); String source = document.getText(); IRegion[] regions = EclipseRegionAdapter.asArray(ranges); TextEdit edit = formatter.format(source, regions, NORMALIZED_LINE_SEPARATOR); applyEdit(document, edit); } }
Example #27
Source File: ExpandMacroToPathMap.java From consulo with Apache License 2.0 | 5 votes |
private static String replaceMacro(String text, String macroName, String replacement) { while (true) { int start = findMacroIndex(text, macroName); if (start < 0) { break; } int end = start + macroName.length() + 2; int slashCount = getSlashCount(text, end); String actualReplacement = slashCount > 0 && !replacement.endsWith("/") ? replacement + "/" : replacement; text = StringUtil.replaceSubstring(text, new TextRange(start, end + slashCount), actualReplacement); } return text; }
Example #28
Source File: MarkupModelWindow.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull @Override public RangeHighlighterEx addRangeHighlighterAndChangeAttributes(int startOffset, int endOffset, int layer, TextAttributes textAttributes, @Nonnull HighlighterTargetArea targetArea, boolean isPersistent, Consumer<? super RangeHighlighterEx> changeAttributesAction) { TextRange hostRange = myDocument.injectedToHost(new ProperTextRange(startOffset, endOffset)); return myHostModel.addRangeHighlighterAndChangeAttributes(hostRange.getStartOffset(), hostRange.getEndOffset(), layer, textAttributes, targetArea, isPersistent, changeAttributesAction); }
Example #29
Source File: TextRangeCalculator.java From intellij-xquery with Apache License 2.0 | 5 votes |
public TextRange calculateTextRange(XQueryFunctionDecl functionDeclaration) { int startOffset = functionDeclaration.getTextRange().getStartOffset(); int endOffset = functionDeclaration.getParamList() != null ? functionDeclaration.getParamList().getTextRange().getEndOffset() : functionDeclaration.getTextRange().getEndOffset(); return new TextRange(startOffset, endOffset); }
Example #30
Source File: TwoSideChange.java From consulo with Apache License 2.0 | 5 votes |
protected SideChange(@Nonnull V twoSideChange, @Nonnull ChangeList changeList, @Nonnull ChangeType type, @Nonnull FragmentSide mergeSide, @Nonnull TextRange versionRange) { myTwoSideChange = twoSideChange; myChangeList = changeList; myOriginalSide = new SimpleChangeSide(mergeSide, new DiffRangeMarker((DocumentEx)twoSideChange.getOriginalDocument(mergeSide), versionRange, this)); myType = type; }