Java Code Examples for com.intellij.openapi.util.TextRange#create()

The following examples show how to use com.intellij.openapi.util.TextRange#create() . 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: DuneFoldingBuilder.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
@Nullable
private FoldingDescriptor fold(@Nullable PsiElement root) {
    if (root == null) {
        return null;
    }

    // find next element
    ASTNode element = root.getFirstChild().getNode();
    ASTNode nextElement = element == null ? null : ORUtil.nextSiblingNode(element);
    ASTNode nextNextElement = nextElement == null ? null : ORUtil.nextSiblingNode(nextElement);

    if (nextNextElement != null) {
        TextRange rootRange = root.getTextRange();
        TextRange nextRange = nextElement.getTextRange();
        return new FoldingDescriptor(root, TextRange.create(nextRange.getEndOffset(), rootRange.getEndOffset() - 1));
    }

    return null;
}
 
Example 2
Source File: CsvShiftColumnIntentionAction.java    From intellij-csv-validator with Apache License 2.0 6 votes vote down vote up
protected static TextRange findPreviousSeparatorOrCRLF(PsiElement psiElement) {
    TextRange textRange;
    PsiElement separator = CsvHelper.getPreviousSeparator(psiElement);
    if (separator == null) {
        separator = CsvHelper.getPreviousCRLF(psiElement.getParent());
        if (separator == null) {
            separator = psiElement.getParent().getParent().getFirstChild();
            textRange = TextRange.create(separator.getTextRange().getStartOffset(), separator.getTextRange().getStartOffset());
        } else {
            textRange = separator.getTextRange();
        }
    } else {
        textRange = separator.getTextRange();
    }
    return textRange;
}
 
Example 3
Source File: CodeFormatterFacade.java    From consulo with Apache License 2.0 6 votes vote down vote up
private TextRange preprocessEnabledRanges(@Nonnull final ASTNode node, @Nonnull TextRange range) {
  TextRange result = TextRange.create(range.getStartOffset(), range.getEndOffset());
  List<TextRange> enabledRanges = myTagHandler.getEnabledRanges(node, result);
  int delta = 0;
  for (TextRange enabledRange : enabledRanges) {
    enabledRange = enabledRange.shiftRight(delta);
    for (PreFormatProcessor processor : PreFormatProcessor.EP_NAME.getExtensionList()) {
      if (processor.changesWhitespacesOnly() || !myCanChangeWhitespaceOnly) {
        TextRange processedRange = processor.process(node, enabledRange);
        delta += processedRange.getLength() - enabledRange.getLength();
      }
    }
  }
  result = result.grown(delta);
  return result;
}
 
Example 4
Source File: BashKeywordManipulator.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public TextRange getRangeInElement(@NotNull BashKeyword element) {
    PsiElement keywordElement = element.keywordElement();
    if (keywordElement == null) {
        return TextRange.create(0, element.getTextLength());
    }

    return TextRange.create(0, keywordElement.getTextLength());
}
 
Example 5
Source File: InjectedSelfElementInfo.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
PsiFile restoreFile(@Nonnull SmartPointerManagerImpl manager) {
  PsiFile hostFile = myHostContext.getContainingFile();
  if (hostFile == null || !hostFile.isValid()) return null;

  PsiElement hostContext = myHostContext.getElement();
  if (hostContext == null) return null;

  Segment segment = myInjectedFileRangeInHostFile.getPsiRange();
  if (segment == null) return null;
  final TextRange rangeInHostFile = TextRange.create(segment);
  return getInjectedFileIn(hostContext, hostFile, rangeInHostFile);
}
 
Example 6
Source File: FoldingBuilder.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
private void foldTag(@NotNull List<FoldingDescriptor> descriptors, @NotNull PsiTag tag) {
    PsiTagStart start = ORUtil.findImmediateFirstChildOfClass(tag, PsiTagStart.class);
    PsiTagClose close = start == null ? null : ORUtil.findImmediateFirstChildOfClass(tag, PsiTagClose.class);
    // Auto-closed tags are not foldable
    if (close != null) {
        PsiElement lastChild = start.getLastChild();
        TextRange textRange = TextRange.create(lastChild.getTextOffset(), tag.getTextRange().getEndOffset() - 1);
        descriptors.add(new FoldingDescriptor(tag, textRange));
    }
}
 
Example 7
Source File: SoyFoldingBuilder.java    From bamboo-soy with Apache License 2.0 5 votes vote down vote up
@Nullable
private static TextRange buildMeaningfulTextRange(
    TagBlockElement element, PsiElement commentElement) {
  if (commentElement == null) {
    return element.getTextRange();
  }
  PsiElement firstMeaningfulElement = WhitespaceUtils.getNextMeaningSibling(commentElement);
  if (firstMeaningfulElement != null) {
    return TextRange.create(
        firstMeaningfulElement.getTextOffset(), element.getTextRange().getEndOffset());
  }
  return null;
}
 
Example 8
Source File: BlazeIssueParser.java    From intellij with Apache License 2.0 5 votes vote down vote up
/** The range of a filename to highlight. Links the full file path range. */
@Nullable
public static TextRange fileHighlightRange(Matcher matcher, int capturingGroup) {
  int start = matcher.start(capturingGroup);
  int end = matcher.end(capturingGroup);
  if (start == -1 || start >= end) {
    return null;
  }
  return TextRange.create(start, end);
}
 
Example 9
Source File: IgnoreEntryManipulator.java    From idea-gitignore with MIT License 5 votes vote down vote up
/**
 * Returns range of the entry. Skips negation element.
 *
 * @param element element to be changed
 * @return range
 */
@NotNull
@Override
public TextRange getRangeInElement(@NotNull IgnoreEntry element) {
    IgnoreNegation negation = element.getNegation();
    if (negation != null) {
        return TextRange.create(
                negation.getStartOffsetInParent() + negation.getTextLength(),
                element.getTextLength()
        );
    }
    return super.getRangeInElement(element);
}
 
Example 10
Source File: CommentByBlockCommentHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean isWhiteSpaceOrComment(@Nonnull PsiElement element, @Nonnull TextRange range) {
  final TextRange textRange = element.getTextRange();
  TextRange intersection = range.intersection(textRange);
  if (intersection == null) {
    return false;
  }
  intersection = TextRange.create(Math.max(intersection.getStartOffset() - textRange.getStartOffset(), 0), Math.min(intersection.getEndOffset() - textRange.getStartOffset(), textRange.getLength()));
  return isWhiteSpaceOrComment(element) || intersection.substring(element.getText()).trim().length() == 0;
}
 
Example 11
Source File: RunIdeConsoleAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@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: PantsTargetReferenceSet.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
@NotNull
private PantsTargetReference createTargetSegmentReference(
  @NotNull PyStringLiteralExpression expression,
  @NotNull PartialTargetAddress address
) {
  final TextRange range = TextRange.create(
    expression.valueOffsetToTextOffset(address.startOfExplicitTarget()),
    expression.valueOffsetToTextOffset(address.valueLength)
  );
  return new PantsTargetReference(
    myStringLiteralExpression,
    range, address.explicitTarget, address.normalizedPath
  );
}
 
Example 13
Source File: FragmentContent.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static FragmentContent fromRangeMarker(RangeMarker rangeMarker, Project project) {
  Document document = rangeMarker.getDocument();
  VirtualFile file = FileDocumentManager.getInstance().getFile(document);
  FileType type = file.getFileType();
  return new FragmentContent(new DocumentContent(project, document), TextRange.create(rangeMarker), project, type);
}
 
Example 14
Source File: BashHereDocManipulator.java    From BashSupport with Apache License 2.0 4 votes vote down vote up
@NotNull
@Override
public TextRange getRangeInElement(@NotNull BashHereDoc element) {
    return TextRange.create(0, element.getTextLength());
}
 
Example 15
Source File: ParameterInfoComponent.java    From consulo with Apache License 2.0 4 votes vote down vote up
private String setup(String text,
                     Function<? super String, String> escapeFunction,
                     int highlightStartOffset,
                     int highlightEndOffset,
                     boolean isDisabled,
                     boolean strikeout,
                     boolean isDisabledBeforeHighlight,
                     Color background) {
  StringBuilder buf = new StringBuilder(text.length());
  setBackground(background);

  String[] lines = UIUtil.splitText(text, getFontMetrics(BOLD_FONT),
                                    // disable splitting by width, to avoid depending on platform's font in tests
                                    ApplicationManager.getApplication().isUnitTestMode() ? Integer.MAX_VALUE : myWidthLimit, ',');

  int lineOffset = 0;

  boolean hasHighlighting = highlightStartOffset >= 0 && highlightEndOffset > highlightStartOffset;
  TextRange highlightingRange = hasHighlighting ? new TextRange(highlightStartOffset, highlightEndOffset) : null;

  for (int i = 0; i < lines.length; i++) {
    String line = lines[i];
    OneLineComponent component = getOneLineComponent(i);

    TextRange lRange = new TextRange(lineOffset, lineOffset + line.length());
    TextRange hr = highlightingRange == null ? null : lRange.intersection(highlightingRange);
    hr = hr == null ? null : hr.shiftRight(-lineOffset);

    String before = escapeString(hr == null ? line : line.substring(0, hr.getStartOffset()), escapeFunction);
    String in = hr == null ? "" : escapeString(hr.substring(line), escapeFunction);
    String after = hr == null ? "" : escapeString(line.substring(hr.getEndOffset()), escapeFunction);

    TextRange escapedHighlightingRange = in.isEmpty() ? null : TextRange.create(before.length(), before.length() + in.length());
    buf.append(component.setup(before + in + after, isDisabled, strikeout, background, escapedHighlightingRange,
                               isDisabledBeforeHighlight && (highlightStartOffset < 0 || highlightEndOffset > lineOffset)));

    lineOffset += line.length();
  }
  trimComponents(lines.length);
  return buf.toString();
}
 
Example 16
Source File: DocTagNameAnnotationReferenceContributor.java    From idea-php-annotation-plugin with MIT License 4 votes vote down vote up
@NotNull
@Override
public TextRange getRangeInElement() {
    return TextRange.create(0, myElement.getTextLength());
}
 
Example 17
Source File: JSGraphQLEndpointEnterHandlerDelegate.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
@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;
}
 
Example 18
Source File: PhpPackFormatSpecificationParser.java    From idea-php-advanced-autocomplete with MIT License 4 votes vote down vote up
static HashMap<Integer, PackSpecification> parseFormat(@NotNull String expression, boolean singleQuote, int parametersCount) {
    int index = 0;
    int num = 0;
    HashMap<Integer, PackSpecification> result = new HashMap<>();
    List<String> codesList = Arrays.asList(PhpCompletionTokens.packCodes);

    while (index < expression.length()) {
        char c = expression.charAt(index);

        // Cancel when we hit variables inside string
        if (!singleQuote && charAtEqualsToAny(expression, index, '$')) {
            return result;
        }

        if (!codesList.contains(Character.toString(c)) || charAtEqualsToAny(expression, index, 'x', 'X')) {
            ++index;
            continue;
        }

        int endIndex = index;
        int repeater = 1;

        TextRange width = parseUnsignedInt(expression, index+1);
        if (width != null && !charAtEqualsToAny(expression, index, 'a', 'A', 'h', 'H')) {
            endIndex = width.getEndOffset() - 1;
            repeater = Integer.parseUnsignedInt(width.substring(expression));
        }

        boolean repeatToEnd = charAtEqualsToAny(expression, index + 1, '*');
        if (repeatToEnd) {
            ++endIndex;
            repeater = parametersCount - num;
        }

        TextRange range = TextRange.create(index, endIndex + 1);
        result.put(num, new PackSpecification(range, repeater));

        if (repeatToEnd) {
            return result;
        }
        ++num;
        ++index;
    }
    return result;
}
 
Example 19
Source File: DocumentUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static TextRange getLineTextRange(@Nonnull Document document, int line) {
  return TextRange.create(document.getLineStartOffset(line), document.getLineEndOffset(line));
}
 
Example 20
Source File: BraceHighlightingHandler.java    From consulo with Apache License 2.0 3 votes vote down vote up
private void highlightRightBrace(@Nonnull HighlighterIterator iterator, @Nonnull FileType fileType) {
  TextRange brace1 = TextRange.create(iterator.getStart(), iterator.getEnd());

  boolean matched = BraceMatchingUtil.matchBrace(myDocument.getCharsSequence(), fileType, iterator, false);

  TextRange brace2 = iterator.atEnd() ? null : TextRange.create(iterator.getStart(), iterator.getEnd());

  highlightBraces(brace2, brace1, matched, false, fileType);
}