Java Code Examples for com.intellij.openapi.util.TextRange#isEmpty()
The following examples show how to use
com.intellij.openapi.util.TextRange#isEmpty() .
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: BuckFoldingBuilder.java From buck with Apache License 2.0 | 6 votes |
private static void foldLoadCalls( PsiElement root, Collection<BuckLoadCall> loadCalls, List<FoldingDescriptor> descriptors) { BuckLoadCall first = Iterables.getFirst(loadCalls, null); if (first == null) { return; } BuckLoadCall last = Iterables.getLast(loadCalls); TextRange textRange = rangeExcludingWhitespace(first, last); if (!textRange.isEmpty()) { FoldingDescriptor descriptor = new FoldingDescriptor(root.getNode(), textRange) { @Nullable @Override public String getPlaceholderText() { return "load ..."; } }; descriptors.add(descriptor); } }
Example 2
Source File: BuckFoldingBuilder.java From buck with Apache License 2.0 | 6 votes |
private static void foldFunctionTrailer( BuckFunctionTrailer functionTrailer, List<FoldingDescriptor> descriptors) { TextRange textRange = rangeExcludingWhitespace(functionTrailer, functionTrailer); if (!textRange.isEmpty()) { FoldingDescriptor descriptor = new FoldingDescriptor(functionTrailer.getNode(), textRange) { @Nullable @Override public String getPlaceholderText() { List<BuckArgument> argumentList = functionTrailer.getArgumentList(); if (argumentList.size() > 1) { for (BuckArgument argument : argumentList) { BuckIdentifier identifier = argument.getIdentifier(); if (identifier != null && identifier.getText().equals("name")) { return "(" + argument.getText() + ", ...)"; } } } return "(...)"; } }; descriptors.add(descriptor); } }
Example 3
Source File: PhpHighlightPackParametersUsagesHandler.java From idea-php-advanced-autocomplete with MIT License | 6 votes |
@NotNull private static HashMap<Integer, RelativeRange> getRelativeSpecificationRanges(HashMap<Integer, PhpPackFormatSpecificationParser.PackSpecification> specifications, List<StringLiteralExpression> targets) { Map<TextRange, StringLiteralExpression> rangesInsideResultingFormatString = getRangesWithExpressionInsideResultingFormatString(targets); HashMap<Integer, RelativeRange> result = new HashMap<>(); for (Map.Entry<Integer, PhpPackFormatSpecificationParser.PackSpecification> entry : specifications.entrySet()) { PhpPackFormatSpecificationParser.PackSpecification specification = entry.getValue(); for (Map.Entry<TextRange, StringLiteralExpression> e : rangesInsideResultingFormatString.entrySet()) { TextRange expressionRangeInsideFormatString = e.getKey(); TextRange specificationRangeInsideFormatString = expressionRangeInsideFormatString.intersection(specification.getRangeInElement()); if (specificationRangeInsideFormatString != null && !specificationRangeInsideFormatString.isEmpty()) { result.put(entry.getKey(), new RelativeRange(e.getValue(), specificationRangeInsideFormatString.shiftLeft(expressionRangeInsideFormatString.getStartOffset()))); } } } return result; }
Example 4
Source File: ShowExpressionTypeHandler.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull @RequiredReadAction private static Map<PsiElement, ExpressionTypeProvider> getExpressions(@Nonnull PsiFile file, @Nonnull Editor editor, @Nonnull Set<? extends ExpressionTypeProvider> handlers) { if (handlers.isEmpty()) return Collections.emptyMap(); boolean exactRange = false; TextRange range = EditorUtil.getSelectionInAnyMode(editor); final Map<PsiElement, ExpressionTypeProvider> map = new LinkedHashMap<>(); int offset = !range.isEmpty() ? range.getStartOffset() : TargetElementUtil.adjustOffset(file, editor.getDocument(), range.getStartOffset()); for (int i = 0; i < 3 && map.isEmpty() && offset >= i; i++) { PsiElement elementAt = file.findElementAt(offset - i); if (elementAt == null) continue; for (ExpressionTypeProvider handler : handlers) { for (PsiElement element : ((ExpressionTypeProvider<? extends PsiElement>)handler).getExpressionsAt(elementAt)) { TextRange r = element.getTextRange(); if (exactRange && !r.equals(range) || !r.contains(range)) continue; if (!exactRange) exactRange = r.equals(range); map.put(element, handler); } } } return map; }
Example 5
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 6
Source File: TemplateDataElementType.java From consulo with Apache License 2.0 | 5 votes |
public void addRange(@Nonnull TextRange newRange) { if (newRange.isEmpty()) { return; } if (!myRanges.isEmpty()) { int lastItemIndex = myRanges.size() - 1; TextRange lastRange = myRanges.get(lastItemIndex); if (lastRange.getEndOffset() == newRange.getStartOffset()) { myRanges.set(lastItemIndex, TextRange.create(lastRange.getStartOffset(), newRange.getEndOffset())); return; } } myRanges.add(newRange); }
Example 7
Source File: BuckFoldingBuilder.java From buck with Apache License 2.0 | 5 votes |
private static void foldParameterList( BuckParameterList parameterList, List<FoldingDescriptor> descriptors) { TextRange textRange = rangeIncludingWhitespace(parameterList, parameterList); if (!textRange.isEmpty()) { FoldingDescriptor descriptor = new FoldingDescriptor(parameterList.getNode(), textRange); descriptors.add(descriptor); } }
Example 8
Source File: BuckFoldingBuilder.java From buck with Apache License 2.0 | 5 votes |
private static void foldSuite(BuckSuite suite, List<FoldingDescriptor> descriptors) { TextRange textRange = rangeExcludingWhitespace(suite, suite); if (!textRange.isEmpty()) { FoldingDescriptor descriptor = new FoldingDescriptor(suite.getNode(), textRange); descriptors.add(descriptor); } }
Example 9
Source File: BuckFoldingBuilder.java From buck with Apache License 2.0 | 5 votes |
private static void foldDictMaker(BuckDictMaker dictMaker, List<FoldingDescriptor> descriptors) { if (dictMaker.getDictEntryList().size() < 5) { return; } TextRange textRange = rangeIncludingWhitespace(dictMaker, dictMaker); if (!textRange.isEmpty()) { FoldingDescriptor descriptor = new FoldingDescriptor(dictMaker.getParent().getNode(), textRange); descriptors.add(descriptor); } }
Example 10
Source File: BuckFoldingBuilder.java From buck with Apache License 2.0 | 5 votes |
private static void foldExpressionListOrComprehension( BuckExpressionListOrComprehension expressionListOrComprehension, List<FoldingDescriptor> descriptors) { if (expressionListOrComprehension.getExpressionList().size() <= 1) { return; } TextRange textRange = rangeIncludingWhitespace(expressionListOrComprehension, expressionListOrComprehension); if (!textRange.isEmpty()) { FoldingDescriptor descriptor = new FoldingDescriptor(expressionListOrComprehension.getParent().getNode(), textRange); descriptors.add(descriptor); } }
Example 11
Source File: RunIdeConsoleAction.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull private static String getCommandText(@Nonnull Project project, @Nonnull Editor editor) { TextRange selectedRange = EditorUtil.getSelectionInAnyMode(editor); Document document = editor.getDocument(); if (selectedRange.isEmpty()) { int line = document.getLineNumber(selectedRange.getStartOffset()); selectedRange = TextRange.create(document.getLineStartOffset(line), document.getLineEndOffset(line)); // try detect a non-trivial composite PSI element if there's a PSI file PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file != null && file.getFirstChild() != null && file.getFirstChild() != file.getLastChild()) { PsiElement e1 = file.findElementAt(selectedRange.getStartOffset()); PsiElement e2 = file.findElementAt(selectedRange.getEndOffset()); while (e1 != e2 && (e1 instanceof PsiWhiteSpace || e1 != null && StringUtil.isEmptyOrSpaces(e1.getText()))) { e1 = ObjectUtils.chooseNotNull(e1.getNextSibling(), PsiTreeUtil.getDeepestFirst(e1.getParent())); } while (e1 != e2 && (e2 instanceof PsiWhiteSpace || e2 != null && StringUtil.isEmptyOrSpaces(e2.getText()))) { e2 = ObjectUtils.chooseNotNull(e2.getPrevSibling(), PsiTreeUtil.getDeepestLast(e2.getParent())); } if (e1 instanceof LeafPsiElement) e1 = e1.getParent(); if (e2 instanceof LeafPsiElement) e2 = e2.getParent(); PsiElement parent = e1 == null ? e2 : e2 == null ? e1 : PsiTreeUtil.findCommonParent(e1, e2); if (parent != null && parent != file) { selectedRange = parent.getTextRange(); } } } return document.getText(selectedRange); }
Example 12
Source File: FormattingRangesExtender.java From consulo with Apache License 2.0 | 5 votes |
private TextRange processRange(@Nonnull TextRange originalRange) { TextRange validRange = ensureRangeIsValid(originalRange); ASTNode containingNode = CodeFormatterFacade.findContainingNode(myFile, expandToLine(validRange)); if (containingNode != null && !validRange.isEmpty()) { return narrowToMaxExtensionLines(validRange, getRangeWithSiblings(containingNode)); } return validRange; }
Example 13
Source File: NameSuggestionsField.java From consulo with Apache License 2.0 | 5 votes |
public NameSuggestionsField(final String[] suggestedNames, final Project project, final FileType fileType, @Nullable final Editor editor) { this(suggestedNames, project, fileType); if (editor == null) return; // later here because EditorTextField creates Editor during addNotify() final Runnable selectionRunnable = new Runnable() { @Override public void run() { final int offset = editor.getCaretModel().getOffset(); List<TextRange> ranges = new ArrayList<TextRange>(); SelectWordUtil.addWordSelection(editor.getSettings().isCamelWords(), editor.getDocument().getCharsSequence(), offset, ranges); Editor myEditor = getEditor(); if (myEditor == null) return; for (TextRange wordRange : ranges) { String word = editor.getDocument().getText(wordRange); if (!word.equals(getEnteredName())) continue; final SelectionModel selectionModel = editor.getSelectionModel(); myEditor.getSelectionModel().removeSelection(); final int wordRangeStartOffset = wordRange.getStartOffset(); int myOffset = offset - wordRangeStartOffset; myEditor.getCaretModel().moveToOffset(myOffset); TextRange selected = new TextRange(Math.max(0, selectionModel.getSelectionStart() - wordRangeStartOffset), Math.max(0, selectionModel.getSelectionEnd() - wordRangeStartOffset)); selected = selected.intersection(new TextRange(0, myEditor.getDocument().getTextLength())); if (selectionModel.hasSelection() && selected != null && !selected.isEmpty()) { myEditor.getSelectionModel().setSelection(selected.getStartOffset(), selected.getEndOffset()); } else if (shouldSelectAll()) { myEditor.getSelectionModel().setSelection(0, myEditor.getDocument().getTextLength()); } break; } } }; SwingUtilities.invokeLater(selectionRunnable); }
Example 14
Source File: UnifiedEditorHighlighter.java From consulo with Apache License 2.0 | 4 votes |
private void init(@Nonnull HighlighterIterator it1, @Nonnull HighlighterIterator it2, @Nonnull List<HighlightRange> ranges, int textLength) { ApplicationManager.getApplication().assertReadAccessAllowed(); int offset = 0; for (HighlightRange range : ranges) { TextRange base = range.getBase(); TextRange changed = range.getChanged(); if (base.isEmpty()) continue; if (base.getStartOffset() > offset) { addElement(new Element(offset, base.getStartOffset(), null, TextAttributes.ERASE_MARKER)); offset = base.getStartOffset(); } HighlighterIterator it = range.getSide().select(it1, it2); while (!it.atEnd() && changed.getStartOffset() >= it.getEnd()) { it.advance(); } if (it.atEnd()) { LOG.error("Unexpected end of highlighter"); break; } if (changed.getEndOffset() <= it.getStart()) { continue; } while (true) { int relativeStart = Math.max(it.getStart() - changed.getStartOffset(), 0); int relativeEnd = Math.min(it.getEnd() - changed.getStartOffset(), changed.getLength() + 1); addElement(new Element(offset + relativeStart, offset + relativeEnd, it.getTokenType(), it.getTextAttributes())); if (changed.getEndOffset() <= it.getEnd()) { offset += changed.getLength(); break; } it.advance(); if (it.atEnd()) { LOG.error("Unexpected end of highlighter"); break; } } } if (offset < textLength) { addElement(new Element(offset, textLength, null, TextAttributes.ERASE_MARKER)); } }
Example 15
Source File: InjectedLanguageManagerImpl.java From consulo with Apache License 2.0 | 4 votes |
/** * intersection may spread over several injected fragments * * @param rangeToEdit range in encoded(raw) PSI * @return list of ranges in encoded (raw) PSI */ @SuppressWarnings("ConstantConditions") @Override @Nonnull public List<TextRange> intersectWithAllEditableFragments(@Nonnull PsiFile injectedPsi, @Nonnull TextRange rangeToEdit) { Place shreds = InjectedLanguageUtil.getShreds(injectedPsi); if (shreds == null) return Collections.emptyList(); Object result = null; // optimization: TextRange or ArrayList int count = 0; int offset = 0; for (PsiLanguageInjectionHost.Shred shred : shreds) { TextRange encodedRange = TextRange.from(offset + shred.getPrefix().length(), shred.getRangeInsideHost().getLength()); TextRange intersection = encodedRange.intersection(rangeToEdit); if (intersection != null) { count++; if (count == 1) { result = intersection; } else if (count == 2) { TextRange range = (TextRange)result; if (range.isEmpty()) { result = intersection; count = 1; } else if (intersection.isEmpty()) { count = 1; } else { List<TextRange> list = new ArrayList<>(); list.add(range); list.add(intersection); result = list; } } else if (intersection.isEmpty()) { count--; } else { //noinspection unchecked ((List<TextRange>)result).add(intersection); } } offset += shred.getPrefix().length() + shred.getRangeInsideHost().getLength() + shred.getSuffix().length(); } //noinspection unchecked return count == 0 ? Collections.emptyList() : count == 1 ? Collections.singletonList((TextRange)result) : (List<TextRange>)result; }
Example 16
Source File: PathReferenceManagerImpl.java From consulo with Apache License 2.0 | 4 votes |
private static boolean intersect(final TextRange range1, final TextRange range2) { return range2.intersectsStrict(range1) || range2.intersects(range1) && (range1.isEmpty() || range2.isEmpty()); }
Example 17
Source File: ParagraphFillHandler.java From consulo with Apache License 2.0 | 4 votes |
protected void performOnElement(@Nonnull final PsiElement element, @Nonnull final Editor editor) { final Document document = editor.getDocument(); final TextRange textRange = getTextRange(element, editor); if (textRange.isEmpty()) return; final String text = textRange.substring(element.getContainingFile().getText()); final List<String> subStrings = StringUtil.split(text, "\n", true); final String prefix = getPrefix(element); final String postfix = getPostfix(element); final StringBuilder stringBuilder = new StringBuilder(); appendPrefix(element, text, stringBuilder); for (String string : subStrings) { final String startTrimmed = StringUtil.trimStart(string.trim(), prefix.trim()); final String str = StringUtil.trimEnd(startTrimmed, postfix.trim()); final String finalString = str.trim(); if (!StringUtil.isEmptyOrSpaces(finalString)) stringBuilder.append(finalString).append(" "); } appendPostfix(element, text, stringBuilder); final String replacementText = stringBuilder.toString(); CommandProcessor.getInstance().executeCommand(element.getProject(), () -> { document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), replacementText); final CodeFormatterFacade codeFormatter = new CodeFormatterFacade( CodeStyleSettingsManager.getSettings(element.getProject()), element.getLanguage()); final PsiFile file = element.getContainingFile(); FormatterTagHandler formatterTagHandler = new FormatterTagHandler(CodeStyleSettingsManager.getSettings(file.getProject())); List<TextRange> enabledRanges = formatterTagHandler.getEnabledRanges(file.getNode(), TextRange.create(0, document.getTextLength())); codeFormatter.doWrapLongLinesIfNecessary(editor, element.getProject(), document, textRange.getStartOffset(), textRange.getStartOffset() + replacementText.length() + 1, enabledRanges); }, null, document); }
Example 18
Source File: GraphQLTemplateFragmentLanguageInjector.java From js-graphql-intellij-plugin with MIT License | 4 votes |
@Override public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) { if(GraphQLLanguageInjectionUtil.isJSGraphQLLanguageInjectionTarget(context)) { final JSStringTemplateExpression template = (JSStringTemplateExpression)context; final TextRange graphQlTextRange = GraphQLLanguageInjectionUtil.getGraphQLTextRange(template); if(graphQlTextRange.isEmpty()) { // all whitespace return; } registrar.startInjecting(GraphQLLanguage.INSTANCE); final StringBuilder sb = new StringBuilder(); final TextRange[] stringRanges = template.getStringRanges(); int stringIndex = 0; boolean insideTemplate = false; for (ASTNode astNode : template.getNode().getChildren(null)) { if(astNode.getElementType() == JSTokenTypes.BACKQUOTE) { insideTemplate = true; continue; } if(astNode.getElementType() == JSTokenTypes.STRING_TEMPLATE_PART) { registrar.addPlace(sb.toString(), "", (PsiLanguageInjectionHost) template, stringRanges[stringIndex]); stringIndex++; sb.setLength(0); } else if(insideTemplate) { sb.append(astNode.getText()); } } registrar.doneInjecting(); // update graphql config notifications final VirtualFile virtualFile = context.getContainingFile().getVirtualFile(); if(virtualFile != null && !ApplicationManager.getApplication().isUnitTestMode()) { EditorNotifications.getInstance(context.getProject()).updateNotifications(virtualFile); } } }
Example 19
Source File: KeywordCollector.java From intellij-xquery with Apache License 2.0 | 4 votes |
private String getPrecedingText(PsiElement position, String defaultText) { TextRange range = getPrecedingTextRange(position); PsiFile posFile = position.getContainingFile(); return range.isEmpty() ? defaultText : range.substring(posFile.getText()); }
Example 20
Source File: JSGraphQLEndpointEnterHandlerDelegate.java From js-graphql-intellij-plugin with MIT License | 4 votes |
@Override public Result preprocessEnter(@NotNull PsiFile file, @NotNull Editor editor, @NotNull Ref<Integer> caretOffsetRef, @NotNull Ref<Integer> caretAdvance, @NotNull DataContext dataContext, EditorActionHandler originalHandler) { if (file instanceof JSGraphQLEndpointDocFile) { int caretPos = caretOffsetRef.get(); final TextRange lineTextRange = DocumentUtil.getLineTextRange(editor.getDocument(), editor.offsetToLogicalPosition(caretPos).line); final TextRange lineBeforeCaret = TextRange.create(lineTextRange.getStartOffset(), caretPos); final TextRange lineAfterCaret = TextRange.create(caretPos, lineTextRange.getEndOffset()); if (!lineBeforeCaret.isEmpty()) { final String lineBeforeCaretText = editor.getDocument().getText(lineBeforeCaret); if (lineBeforeCaretText.contains("#")) { EditorModificationUtil.insertStringAtCaret(editor, "# "); if (lineAfterCaret.isEmpty()) { caretAdvance.set(2); } else { // if there's text after the caret, the injected doc editor will be broken into two editors // this means that we get an assertion error for isValid in case we try to move the caret // instead, we schedule a re-indent plus end of line if (editor instanceof EditorWindow) { final Project project = file.getProject(); final Editor parentEditor = ((EditorWindow) editor).getDelegate(); final Application application = ApplicationManager.getApplication(); application.invokeLater(() -> { final PsiFile parentPsiFile = PsiDocumentManager.getInstance(project).getPsiFile(parentEditor.getDocument()); if (parentPsiFile != null) { application.runWriteAction(() -> { new WriteCommandAction.Simple(project) { @Override protected void run() throws Throwable { if(!parentPsiFile.isValid()) { return; } CodeStyleManager.getInstance(project).adjustLineIndent(parentPsiFile, parentEditor.getCaretModel().getOffset()); AnAction editorLineEnd = ActionManager.getInstance().getAction("EditorLineEnd"); if (editorLineEnd != null) { final AnActionEvent actionEvent = AnActionEvent.createFromDataContext( ActionPlaces.UNKNOWN, null, new DataManagerImpl.MyDataContext(parentEditor.getComponent()) ); editorLineEnd.actionPerformed(actionEvent); } } }.execute(); }); } }); } } } } } return Result.Continue; }