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

The following examples show how to use com.intellij.openapi.util.TextRange#substring() . 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: PantsScalaHighlightVisitor.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
private void tryToExtendInfo(@NotNull HighlightInfo info, @NotNull PsiFile containingFile) {
  List<Pair<HighlightInfo.IntentionActionDescriptor, TextRange>> actionRanges = info.quickFixActionRanges;
  if (actionRanges == null) {
    return;
  }
  for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> actionAndRange : actionRanges) {
    final TextRange textRange = actionAndRange.getSecond();
    final HighlightInfo.IntentionActionDescriptor actionDescriptor = actionAndRange.getFirst();
    final IntentionAction action = actionDescriptor.getAction();
    if (action instanceof CreateTypeDefinitionQuickFix) {
      final String className = textRange.substring(containingFile.getText());
      final List<PantsQuickFix> missingDependencyFixes =
        PantsUnresolvedReferenceFixFinder.findMissingDependencies(className, containingFile);
      for (PantsQuickFix fix : missingDependencyFixes) {
        info.registerFix(fix, null, fix.getName(), textRange, null);
      }
      if (!missingDependencyFixes.isEmpty()) {
        // we should add only one fix per info
        return;
      }
    }
  }
}
 
Example 2
Source File: ProblemDescriptorUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static String extractHighlightedText(@Nonnull CommonProblemDescriptor descriptor, PsiElement psiElement) {
  if (psiElement == null || !psiElement.isValid()) return "";
  String ref = psiElement.getText();
  if (descriptor instanceof ProblemDescriptorBase) {
    TextRange textRange = ((ProblemDescriptorBase)descriptor).getTextRange();
    final TextRange elementRange = psiElement.getTextRange();
    if (textRange != null && elementRange != null) {
      textRange = textRange.shiftRight(-elementRange.getStartOffset());
      if (textRange.getStartOffset() >= 0 && textRange.getEndOffset() <= elementRange.getLength()) {
        ref = textRange.substring(ref);
      }
    }
  }
  ref = StringUtil.replaceChar(ref, '\n', ' ').trim();
  ref = StringUtil.first(ref, 100, true);
  return ref;
}
 
Example 3
Source File: GlobReference.java    From intellij with Apache License 2.0 5 votes vote down vote up
public String getValue() {
  String text = element.getText();
  final TextRange range = getRangeInElement();
  try {
    return range.substring(text);
  } catch (StringIndexOutOfBoundsException e) {
    logger.error(
        "Wrong range in reference " + this + ": " + range + ". Reference text: '" + text + "'",
        e);
    return text;
  }
}
 
Example 4
Source File: BashSimpleTextLiteralEscaper.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@Override
public boolean decode(@NotNull final TextRange rangeInsideHost, @NotNull StringBuilder outChars) {
    ProperTextRange.assertProperRange(rangeInsideHost);
    String subText = rangeInsideHost.substring(myHost.getText());

    Ref<int[]> sourceOffsetsRef = new Ref<int[]>();
    boolean result = TextProcessorUtil.parseStringCharacters(subText, outChars, sourceOffsetsRef);
    this.outSourceOffsets = sourceOffsetsRef.get();

    return result;
}
 
Example 5
Source File: CSharpStringLiteralEscaper.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
public boolean decode(@Nonnull final TextRange rangeInsideHost, @Nonnull StringBuilder outChars)
{
	ProperTextRange.assertProperRange(rangeInsideHost);
	String subText = rangeInsideHost.substring(myHost.getText());
	myOutSourceOffsets = new int[subText.length() + 1];
	return parseStringCharacters(subText, outChars, myOutSourceOffsets);
}
 
Example 6
Source File: FileReferenceSet.java    From consulo with Apache License 2.0 5 votes vote down vote up
public FileReferenceSet(@Nonnull final PsiElement element) {
  myElement = element;
  TextRange range = ElementManipulators.getValueTextRange(element);
  myStartInElement = range.getStartOffset();
  myPathStringNonTrimmed = range.substring(element.getText());
  myPathString = myPathStringNonTrimmed.trim();
  myEndingSlashNotAllowed = true;
  myCaseSensitive = false;

  reparse();
}
 
Example 7
Source File: PsiReferenceBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public String getValue() {
  String text = myElement.getText();
  final TextRange range = getRangeInElement();
  try {
    return range.substring(text);
  }
  catch (StringIndexOutOfBoundsException e) {
    LOG.error("Wrong range in reference " + this + ": " + range + ". Reference text: '" + text + "'", e);
    return text;
  }
}
 
Example 8
Source File: ElementManipulators.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static String getValueText(final PsiElement element) {
  final TextRange valueTextRange = getValueTextRange(element);
  if (valueTextRange.isEmpty()) return "";

  final String text = element.getText();
  if (valueTextRange.getEndOffset() > text.length()) {
    LOG.error("Wrong range for " + element + " text: " + text + " range " + valueTextRange);
  }

  return valueTextRange.substring(text);
}
 
Example 9
Source File: LanguageConsoleImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static String printWithHighlighting(@Nonnull LanguageConsoleView console, @Nonnull Editor inputEditor, @Nonnull TextRange textRange) {
  String text;
  EditorHighlighter highlighter;
  if (inputEditor instanceof EditorWindow) {
    PsiFile file = ((EditorWindow)inputEditor).getInjectedFile();
    highlighter = HighlighterFactory.createHighlighter(file.getVirtualFile(), EditorColorsManager.getInstance().getGlobalScheme(), console.getProject());
    String fullText = InjectedLanguageUtil.getUnescapedText(file, null, null);
    highlighter.setText(fullText);
    text = textRange.substring(fullText);
  }
  else {
    text = inputEditor.getDocument().getText(textRange);
    highlighter = ((EditorEx)inputEditor).getHighlighter();
  }
  SyntaxHighlighter syntax = highlighter instanceof LexerEditorHighlighter ? ((LexerEditorHighlighter)highlighter).getSyntaxHighlighter() : null;
  LanguageConsoleImpl consoleImpl = (LanguageConsoleImpl)console;
  consoleImpl.doAddPromptToHistory();
  if (syntax != null) {
    ConsoleViewUtil.printWithHighlighting(console, text, syntax, () -> {
      String identPrompt = consoleImpl.myConsoleExecutionEditor.getConsolePromptDecorator().getIndentPrompt();
      if (StringUtil.isNotEmpty(identPrompt)) {
        consoleImpl.addPromptToHistoryImpl(identPrompt);
      }
    });
  }
  else {
    console.print(text, ConsoleViewContentType.USER_INPUT);
  }
  console.print("\n", ConsoleViewContentType.NORMAL_OUTPUT);
  return text;
}
 
Example 10
Source File: KeywordCollector.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
private String getPrecedingText(PsiElement position, String defaultText) {
    TextRange range = getPrecedingTextRange(position);
    PsiFile posFile = position.getContainingFile();
    return range.isEmpty() ? defaultText : range.substring(posFile.getText());
}
 
Example 11
Source File: CreateRuleFix.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public CreateRuleFix(TextRange textRange, PsiFile file) {
	this.textRange = textRange;
	ruleName = textRange.substring(file.getText());
}
 
Example 12
Source File: MockDocument.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public String getText(@Nonnull TextRange range) {
  return range.substring(myText.toString());
}
 
Example 13
Source File: Document.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Contract(pure = true)
default String getText(@Nonnull TextRange range) {
  return range.substring(getText());
}
 
Example 14
Source File: ShowImplementationsAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void performForContext(@Nonnull DataContext dataContext, boolean invokedByShortcut) {
  final Project project = dataContext.getData(CommonDataKeys.PROJECT);
  if (project == null) return;
  PsiDocumentManager.getInstance(project).commitAllDocuments();

  PsiFile file = dataContext.getData(CommonDataKeys.PSI_FILE);
  Editor editor = getEditor(dataContext);

  PsiElement element = dataContext.getData(CommonDataKeys.PSI_ELEMENT);
  boolean isInvokedFromEditor = dataContext.getData(CommonDataKeys.EDITOR) != null;
  element = getElement(project, file, editor, element);

  if (element == null && file == null) return;
  PsiFile containingFile = element != null ? element.getContainingFile() : file;
  if (containingFile == null || !containingFile.getViewProvider().isPhysical()) return;


  PsiReference ref = null;
  if (editor != null) {
    ref = TargetElementUtil.findReference(editor, editor.getCaretModel().getOffset());
    if (element == null && ref != null) {
      element = TargetElementUtil.adjustReference(ref);
    }
  }

  //check attached sources if any
  if (element instanceof PsiCompiledElement) {
    element = element.getNavigationElement();
  }

  String text = "";
  PsiElement[] impls = PsiElement.EMPTY_ARRAY;
  if (element != null) {
    impls = getSelfAndImplementations(editor, element, createImplementationsSearcher());
    text = SymbolPresentationUtil.getSymbolPresentableText(element);
  }

  if (impls.length == 0 && ref instanceof PsiPolyVariantReference) {
    final PsiPolyVariantReference polyReference = (PsiPolyVariantReference)ref;
    PsiElement refElement = polyReference.getElement();
    TextRange rangeInElement = polyReference.getRangeInElement();
    String refElementText = refElement.getText();
    LOG.assertTrue(rangeInElement.getEndOffset() <= refElementText.length(), "Ref:" + polyReference + "; refElement: " + refElement + "; refText:" + refElementText);
    text = rangeInElement.substring(refElementText);
    final ResolveResult[] results = polyReference.multiResolve(false);
    final List<PsiElement> implsList = new ArrayList<>(results.length);

    for (ResolveResult result : results) {
      final PsiElement resolvedElement = result.getElement();

      if (resolvedElement != null && resolvedElement.isPhysical()) {
        implsList.add(resolvedElement);
      }
    }

    if (!implsList.isEmpty()) {
      impls = implsList.toArray(new PsiElement[implsList.size()]);
    }
  }


  showImplementations(impls, project, text, editor, file, element, isInvokedFromEditor, invokedByShortcut);
}
 
Example 15
Source File: EncodingReferenceInjector.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public PsiReference[] getReferences(@Nonnull PsiElement element, @Nonnull ProcessingContext context, @Nonnull TextRange range) {
  return new PsiReference[]{new EncodingReference(element, range.substring(element.getText()), range)};
}
 
Example 16
Source File: ParagraphFillHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
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);

}