Java Code Examples for com.intellij.psi.PsiElement#getTextRange()

The following examples show how to use com.intellij.psi.PsiElement#getTextRange() . 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: NavigationGutterIconBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
public RelatedItemLineMarkerInfo<PsiElement> createLineMarkerInfo(@Nonnull PsiElement element) {
  final MyNavigationGutterIconRenderer renderer = createGutterIconRenderer(element.getProject());
  final String tooltip = renderer.getTooltipText();
  NotNullLazyValue<Collection<? extends GotoRelatedItem>> gotoTargets = new NotNullLazyValue<Collection<? extends GotoRelatedItem>>() {
    @Nonnull
    @Override
    protected Collection<? extends GotoRelatedItem> compute() {
      if (myGotoRelatedItemProvider != null) {
        return ContainerUtil.concat(myTargets.getValue(), myGotoRelatedItemProvider);
      }
      return Collections.emptyList();
    }
  };
  return new RelatedItemLineMarkerInfo<PsiElement>(element, element.getTextRange(), renderer.getIcon(), Pass.LINE_MARKERS,
                                                   tooltip == null ? null : new ConstantFunction<PsiElement, String>(tooltip),
                                                   renderer.isNavigateAction() ? renderer : null, renderer.getAlignment(),
                                                   gotoTargets);
}
 
Example 3
Source File: HaxeCommentSelectioner.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
@Override
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
  final TextRange originalRange = e.getTextRange();

  // For the error condition, let the superclass log the standard error and throw an exception.
  if (originalRange.getEndOffset() > editorText.length()) {
    super.select(e, editorText, cursorOffset, editor);
  }

  final TextRange foundRange = SelectionUtil.selectToken(e, cursorOffset);
  final CharSequence token = editorText.subSequence(foundRange.getStartOffset(), foundRange.getEndOffset());

  final List<TextRange> ranges = new ArrayList<TextRange>(1);
  if (isCommentToken(e, token)) {
    ranges.addAll(expandToWholeLine(editorText, originalRange, true));
  } else {
    // Use the more limited defintion of a word when selecting inside of a comment.
    ranges.add(SelectionUtil.selectWord(e, cursorOffset));
  }

  return ranges;
}
 
Example 4
Source File: ParameterInfoController.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static int getParameterIndex(@Nonnull PsiElement[] parameters, @Nonnull IElementType delimiter, int offset) {
  for (int i = 0; i < parameters.length; i++) {
    PsiElement parameter = parameters[i];
    TextRange textRange = parameter.getTextRange();
    int startOffset = textRange.getStartOffset();
    if (offset < startOffset) {
      if (i == 0) return 0;
      PsiElement elementInBetween = parameters[i - 1];
      int currOffset = elementInBetween.getTextRange().getEndOffset();
      while ((elementInBetween = PsiTreeUtil.nextLeaf(elementInBetween)) != null) {
        if (currOffset >= startOffset) break;
        ASTNode node = elementInBetween.getNode();
        if (node != null && node.getElementType() == delimiter) {
          return offset <= currOffset ? i - 1 : i;
        }
        currOffset += elementInBetween.getTextLength();
      }
      return i;
    }
    else if (offset <= textRange.getEndOffset()) {
      return i;
    }
  }
  return Math.max(0, parameters.length - 1);
}
 
Example 5
Source File: SmartyTemplateLineMarkerProvider.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
private LineMarkerInfo getRelatedPopover(String singleItemTitle, String singleItemTooltipPrefix, PsiElement lineMarkerTarget, List<GotoRelatedItem> gotoRelatedItems) {

        // single item has no popup
        String title = singleItemTitle;
        if(gotoRelatedItems.size() == 1) {
            String customName = gotoRelatedItems.get(0).getCustomName();
            if(customName != null) {
                title = String.format(singleItemTooltipPrefix, customName);
            }
        }

        return new LineMarkerInfo<>(
            lineMarkerTarget,
            lineMarkerTarget.getTextRange(),
            ShopwarePluginIcons.SHOPWARE_LINEMARKER,
            6,
            new ConstantFunction<>(title),
            new fr.adrienbrault.idea.symfony2plugin.dic.RelatedPopupGotoLineMarker.NavigationHandler(gotoRelatedItems),
            GutterIconRenderer.Alignment.RIGHT
        );
    }
 
Example 6
Source File: EvaluateExpansionQuickfix.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
    TextRange r = startElement.getTextRange();

    Document document = PsiDocumentManager.getInstance(project).getDocument(file);

    String replacement = ValueExpansionUtil.expand(startElement.getText(), enableBash4);
    if (replacement != null && document != null) {
        editor.getDocument().replaceString(r.getStartOffset(), r.getEndOffset(), replacement);
        PsiDocumentManager.getInstance(project).commitDocument(document);
    }
}
 
Example 7
Source File: I18nReferenceProvider.java    From yiistorm with MIT License 5 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) {
    project = element.getProject();
    properties = PropertiesComponent.getInstance(project);
    String searchStringFull = CommonHelper.rmQuotes(element.getText());
    String searchString = searchStringFull;
    PsiFile currentFile = element.getContainingFile();

    String protectedPath = CommonHelper.searchCurrentProtected(CommonHelper.getFilePath(currentFile));
    if (protectedPath != null) {
        protectedPath = CommonHelper.getRelativePath(project, protectedPath);
        String[] result = I18NHelper.findMessageSource(searchStringFull, protectedPath, project);
        if (result != null) {
            protectedPath = result[0];
            searchString = result[2];
        } else {
            protectedPath += "/messages/" + I18NHelper.getLang(project);
        }
        try {
            String relativePath = protectedPath + "/" + searchString + ".php";
            VirtualFile viewfile = project.getBaseDir().findFileByRelativePath(relativePath);

            if (viewfile != null) {
                PsiReference ref = new I18nFileReference(
                        viewfile,
                        element,
                        element.getTextRange(),
                        project);
                return new PsiReference[]{ref};
            }
        } catch (Exception e) {
            System.err.println("error" + e.getMessage());
        }
    }
    return PsiReference.EMPTY_ARRAY;
}
 
Example 8
Source File: BashLineMarkerProvider.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement element) {
    if (element.getNode().getElementType() == BashTokenTypes.WORD && element.getParent() instanceof BashFunctionDefName && element.getParent().getParent() instanceof BashFunctionDef) {
        return new LineMarkerInfo<>(element, element.getTextRange(), PlatformIcons.METHOD_ICON, Pass.UPDATE_ALL, null, null, GutterIconRenderer.Alignment.LEFT);
    }

    return null;
}
 
Example 9
Source File: UnityScriptEventFunctionLineMarkerProvider.java    From consulo-unity3d with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public LineMarkerInfo getLineMarkerInfo(@Nonnull PsiElement element)
{
	if(element.getNode().getElementType() == JSTokenTypes.IDENTIFIER && element.getParent() instanceof JSReferenceExpression && element.getParent().getParent() instanceof JSFunction)
	{
		UnityFunctionManager functionManager = UnityFunctionManager.getInstance();
		Map<String, UnityFunctionManager.FunctionInfo> map = functionManager.getFunctionsByType().get(Unity3dTypes.UnityEngine.MonoBehaviour);
		if(map == null)
		{
			return null;
		}
		UnityFunctionManager.FunctionInfo functionInfo = map.get(element.getText());
		if(functionInfo == null)
		{
			return null;
		}
		Unity3dModuleExtension extension = ModuleUtilCore.getExtension(element, Unity3dModuleExtension.class);
		if(extension == null)
		{
			return null;
		}
		JSFunction jsFunction = (JSFunction) element.getParent().getParent();
		if(jsFunction.getParent() instanceof JSFile)
		{
			if(!isEqualParameters(functionInfo.getParameters(), jsFunction))
			{
				return null;
			}

			return new LineMarkerInfo<>(element, element.getTextRange(), Unity3dIcons.EventMethod, Pass.LINE_MARKERS, new ConstantFunction<>(functionInfo.getDescription()), null,
					GutterIconRenderer.Alignment.LEFT);
		}
	}
	return null;
}
 
Example 10
Source File: DocumentFileLocationMapper.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
@Override
public TextRange getIdentifierRange(int line, int column) {
  if (psiFile == null) {
    return null;
  }

  // Convert to zero based line and column indices.
  line = line - 1;
  column = column - 1;

  if (document == null || line >= document.getLineCount() || document.isLineModified(line)) {
    return null;
  }

  final XSourcePosition pos = debuggerUtil.createPosition(virtualFile, line, column);
  if (pos == null) {
    return null;
  }
  final int offset = pos.getOffset();
  PsiElement element = psiFile.getOriginalFile().findElementAt(offset);
  if (element == null) {
    return null;
  }

  // Handle named constructors gracefully. For example, for the constructor
  // Image.asset(...) we want to return "Image.asset" instead of "asset".
  if (element.getParent() instanceof DartId) {
    element = element.getParent();
  }
  while (element.getParent() instanceof DartReferenceExpression) {
    element = element.getParent();
  }
  return element.getTextRange();
}
 
Example 11
Source File: DocumentFileLocationMapper.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
@Override
public TextRange getIdentifierRange(int line, int column) {
  if (psiFile == null) {
    return null;
  }

  // Convert to zero based line and column indices.
  line = line - 1;
  column = column - 1;

  if (document == null || line >= document.getLineCount() || document.isLineModified(line)) {
    return null;
  }

  final XSourcePosition pos = debuggerUtil.createPosition(virtualFile, line, column);
  if (pos == null) {
    return null;
  }
  final int offset = pos.getOffset();
  PsiElement element = psiFile.getOriginalFile().findElementAt(offset);
  if (element == null) {
    return null;
  }

  // Handle named constructors gracefully. For example, for the constructor
  // Image.asset(...) we want to return "Image.asset" instead of "asset".
  if (element.getParent() instanceof DartId) {
    element = element.getParent();
  }
  while (element.getParent() instanceof DartReferenceExpression) {
    element = element.getParent();
  }
  return element.getTextRange();
}
 
Example 12
Source File: LineMarkersPass.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static LineMarkerInfo<PsiElement> createMethodSeparatorLineMarker(@Nonnull PsiElement startFrom, @Nonnull EditorColorsManager colorsManager) {
  LineMarkerInfo<PsiElement> info = new LineMarkerInfo<>(startFrom, startFrom.getTextRange(), null, Pass.LINE_MARKERS, FunctionUtil.<Object, String>nullConstant(), null, GutterIconRenderer.Alignment.RIGHT);
  EditorColorsScheme scheme = colorsManager.getGlobalScheme();
  info.separatorColor = scheme.getColor(CodeInsightColors.METHOD_SEPARATORS_COLOR);
  info.separatorPlacement = SeparatorPlacement.TOP;
  return info;
}
 
Example 13
Source File: ExtendWordSelectionHandlerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
  final TextRange originalRange = e.getTextRange();
  LOG.assertTrue(originalRange.getEndOffset() <= editorText.length(), getClass() + "; " + e);

  List<TextRange> ranges = expandToWholeLine(editorText, originalRange, true);

  if (ranges.size() == 1 && ranges.contains(originalRange)) {
    return expandToWholeLine(editorText, originalRange, false);
  }

  return ranges;
}
 
Example 14
Source File: IdentifierMixin.java    From bamboo-soy with Apache License 2.0 5 votes vote down vote up
@Override
public PsiReference getReference() {
  PsiElement element = getNode().getPsi();
  String identifier = element.getText();

  if (identifier.startsWith("$")) {
    String fullIdentifier = identifier.substring(1);
    String[] fragments = fullIdentifier.split("\\.");

    int dollarFragmentLength = fragments[0].length() + 1;
    return new VariableDefinitionReference(
        element,
        fragments[0],
        new TextRange(
            element.getTextRange().getStartOffset(),
            element.getTextRange().getStartOffset() + dollarFragmentLength),
        new TextRange(1, dollarFragmentLength));
  } else if (identifier.startsWith(".")) {
    return new TemplateDefinitionReference(element, element.getTextRange());
  } else {
    if (identifier.split("\\.").length >= 2) {
      // Fully qualified template identifier.
      return new TemplateDefinitionReference(element, element.getTextRange());
    }
  }

  return null;
}
 
Example 15
Source File: PsiAwareLineWrapPositionStrategy.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Allows to check if line wrap at the text range defined by the given element is allowed.
 * 
 * @param element     element that defines target text range
 * @return            <code>true</code> if wrapping at the text range defined by the given element is allowed;
 *                    <code>false</code> otherwise
 */
private boolean allowToWrapInside(@Nonnull PsiElement element) {
  TextRange textRange = element.getTextRange();
  if (textRange == null) {
    return false;
  } 
  for (PsiElement parent = element; parent != null && textRange.equals(parent.getTextRange()); parent = parent.getParent()) {
    ASTNode parentNode = parent.getNode();
    if (parentNode != null && myEnabledTypes.contains(parentNode.getElementType())) {
      return true;
    }
  }
  return false;
}
 
Example 16
Source File: RequiredPropLineMarkerProvider.java    From litho with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public LineMarkerInfo getLineMarkerInfo(PsiElement element) {
  final List<PsiReferenceExpression> methodCalls = new ArrayList<>();
  final List<Collection<String>> missingPropNames = new ArrayList<>();
  // One annotation per statement
  RequiredPropAnnotator.annotate(
      element,
      (missingRequiredPropNames, createMethodCall) -> {
        methodCalls.add(createMethodCall);
        missingPropNames.add(missingRequiredPropNames);
      },
      generatedClassResolver);
  if (methodCalls.isEmpty()) {
    return null;
  }
  PsiElement leaf = methodCalls.get(0);
  final Collection<String> missingProps = missingPropNames.get(0);
  while (leaf.getFirstChild() != null) {
    leaf = leaf.getFirstChild();
  }
  return new LineMarkerInfo<>(
      leaf,
      leaf.getTextRange(),
      LithoPluginIcons.ERROR_ACTION,
      0,
      ignored -> RequiredPropAnnotator.createErrorMessage(missingProps),
      null,
      GutterIconRenderer.Alignment.CENTER);
}
 
Example 17
Source File: UsageCountLineProvider.java    From Android-Resource-Usage-Count with MIT License 4 votes vote down vote up
public MyLineMarkerInfo(PsiElement element, int count) {
    super(element, element.getTextRange(), new MyIcon(count), Pass.UPDATE_ALL, null, null, GutterIconRenderer.Alignment.RIGHT);
    separatorPlacement = SeparatorPlacement.BOTTOM;
}
 
Example 18
Source File: HaxeDocumentModel.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
public void addTextAfterElement(final PsiElement element, final String text) {
  if (element == null) return;
  TextRange range = element.getTextRange();
  replaceAndFormat(range, text);
}
 
Example 19
Source File: PsiCrumb.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public TextRange getHighlightRange() {
  PsiElement element = anchor.retrieve();
  return element != null ? element.getTextRange() : null;
}
 
Example 20
Source File: PsiAwareLineWrapPositionStrategy.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public int calculateWrapPosition(@Nonnull Document document,
                                 @javax.annotation.Nullable Project project,
                                 int startOffset,
                                 int endOffset,
                                 int maxPreferredOffset,
                                 boolean allowToBeyondMaxPreferredOffset,
                                 boolean virtual) {
  if (virtual && myNonVirtualOnly) {
    LineWrapPositionStrategy implementation = LanguageLineWrapPositionStrategy.INSTANCE.getDefaultImplementation();
    return implementation.calculateWrapPosition(
      document, project, startOffset, endOffset, maxPreferredOffset, allowToBeyondMaxPreferredOffset, virtual
    );
  }

  if (project == null) {
    return -1;
  }

  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  if (documentManager == null) {
    return -1;
  }

  PsiFile psiFile = documentManager.getPsiFile(document);
  if (psiFile == null) {
    return -1;
  }

  PsiElement element = psiFile.findElementAt(maxPreferredOffset);
  if (element == null) {
    return -1;
  }

  for (; element != null && element.getTextRange().getEndOffset() > startOffset; element = getPrevious(element)) {
    if (allowToWrapInside(element)) {
      TextRange textRange = element.getTextRange();
      int start = Math.max(textRange.getStartOffset(), startOffset);
      int end = Math.min(textRange.getEndOffset(), endOffset);
      int result = doCalculateWrapPosition(document, project, start, end, end, false, virtual);
      if (result >= 0) {
        return result;
      }

      // Assume that it's possible to wrap on token boundary (makes sense at least for the tokens that occupy one symbol only).
      if (end <= maxPreferredOffset) {
        return end;
      }

      if (start > startOffset) {
        return start;
      }
    }
  }
  return -1;
}