Java Code Examples for com.intellij.psi.PsiFile#findElementAt()

The following examples show how to use com.intellij.psi.PsiFile#findElementAt() . 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: CompletionPhase.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static boolean shouldSkipAutoPopup(Editor editor, PsiFile psiFile) {
  int offset = editor.getCaretModel().getOffset();
  int psiOffset = Math.max(0, offset - 1);

  PsiElement elementAt = psiFile.findElementAt(psiOffset);
  if (elementAt == null) return true;

  Language language = PsiUtilCore.findLanguageFromElement(elementAt);

  for (CompletionConfidence confidence : CompletionConfidenceEP.forLanguage(language)) {
    final ThreeState result = confidence.shouldSkipAutopopup(elementAt, psiFile, offset);
    if (result != ThreeState.UNSURE) {
      LOG.debug(confidence + " has returned shouldSkipAutopopup=" + result);
      return result == ThreeState.YES;
    }
  }
  return false;
}
 
Example 2
Source File: CSharpGenerateAction.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Nullable
@RequiredReadAction
public static CSharpTypeDeclaration findTypeDeclaration(@Nonnull Editor editor, @Nonnull PsiFile file)
{
	if(file.getFileType() != CSharpFileType.INSTANCE)
	{
		return null;
	}
	final int offset = editor.getCaretModel().getOffset();
	final PsiElement elementAt = file.findElementAt(offset);
	if(elementAt == null)
	{
		return null;
	}

	PsiElement parent = elementAt.getParent();
	if(parent instanceof CSharpIdentifier)
	{
		parent = parent.getParent();
	}
	return parent instanceof CSharpTypeDeclaration ? (CSharpTypeDeclaration) parent : null;
}
 
Example 3
Source File: RemoveUnusedAtFixBase.java    From bamboo-soy with Apache License 2.0 6 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file)
    throws IncorrectOperationException {
  int offset = editor.getCaretModel().getOffset();
  PsiElement psiElement = file.findElementAt(offset);
  if (psiElement == null || !psiElement.isValid()) {
    return;
  }
  if (psiElement instanceof PsiWhiteSpace && offset > 0) {
    // The caret might be located right after the closing brace and before a newline, in which
    // case the current PsiElement is PsiWhiteSpace.
    psiElement = file.findElementAt(offset - 1);
  }
  AtElementSingle atElementSingle = PsiTreeUtil
      .getParentOfType(psiElement, AtElementSingle.class);
  if (atElementSingle == null) {
    return;
  }
  runFix((T) atElementSingle);
}
 
Example 4
Source File: LightPlatformCodeInsightTestCase.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected static DataContext getCurrentEditorDataContext() {
  final DataContext defaultContext = DataManager.getInstance().getDataContext();
  return new DataContext() {
    @Override
    @javax.annotation.Nullable
    public Object getData(@NonNls Key dataId) {
      if (PlatformDataKeys.EDITOR == dataId) {
        return getEditor();
      }
      if (CommonDataKeys.PROJECT == dataId) {
        return getProject();
      }
      if (LangDataKeys.PSI_FILE == dataId) {
        return getFile();
      }
      if (LangDataKeys.PSI_ELEMENT == dataId) {
        PsiFile file = getFile();
        if (file == null) return null;
        Editor editor = getEditor();
        if (editor == null) return null;
        return file.findElementAt(editor.getCaretModel().getOffset());
      }
      return defaultContext.getData(dataId);
    }
  };
}
 
Example 5
Source File: EditInspectionToolsSettingsInSuppressedPlaceIntention.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static String getSuppressedId(Editor editor, PsiFile file) {
  int offset = editor.getCaretModel().getOffset();
  PsiElement element = file.findElementAt(offset);
  while (element != null && !(element instanceof PsiFile)) {
    for (InspectionExtensionsFactory factory : InspectionExtensionsFactory.EP_NAME.getExtensionList()) {
      final String suppressedIds = factory.getSuppressedInspectionIdsIn(element);
      if (suppressedIds != null) {
        String text = element.getText();
        List<String> ids = StringUtil.split(suppressedIds, ",");
        for (String id : ids) {
          int i = text.indexOf(id);
          if (i == -1) continue;
          int idOffset = element.getTextRange().getStartOffset() + i;
          if (TextRange.from(idOffset, id.length()).contains(offset)) {
            return id;
          }
        }
      }
    }
    element = element.getParent();
  }
  return null;
}
 
Example 6
Source File: BuckTargetAutoPopupHandler.java    From buck with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public Result checkAutoPopup(
    char charTyped, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
  if (!file.getLanguage().isKindOf(BuckLanguage.INSTANCE)
      || (charTyped != '/' && charTyped != ':')) {
    return Result.CONTINUE;
  }
  final PsiElement at = file.findElementAt(editor.getCaretModel().getOffset());
  if (at == null
      || !BuckPsiUtils.hasElementType(
          at,
          BuckTypes.APOSTROPHED_STRING,
          BuckTypes.APOSTROPHED_RAW_STRING,
          BuckTypes.TRIPLE_APOSTROPHED_STRING,
          BuckTypes.TRIPLE_APOSTROPHED_RAW_STRING,
          BuckTypes.QUOTED_STRING,
          BuckTypes.QUOTED_RAW_STRING,
          BuckTypes.TRIPLE_QUOTED_STRING,
          BuckTypes.TRIPLE_QUOTED_RAW_STRING)) {
    return Result.CONTINUE;
  }
  AutoPopupController.getInstance(project).scheduleAutoPopup(editor);
  return Result.STOP;
}
 
Example 7
Source File: MoveElementLeftRightActionHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
@RequiredUIAccess
private static PsiElement[] getElementList(@Nonnull PsiFile file, int rangeStart, int rangeEnd) {
  PsiElement startElement = file.findElementAt(rangeStart);
  if (startElement == null) return null;
  PsiElement endElement = rangeEnd > rangeStart ? file.findElementAt(rangeEnd - 1) : startElement;
  if (endElement == null) return null;
  PsiElement element = PsiTreeUtil.findCommonParent(startElement, endElement);
  while (element != null) {
    List<MoveElementLeftRightHandler> handlers = MoveElementLeftRightHandler.EXTENSION.allForLanguage(element.getLanguage());
    for (MoveElementLeftRightHandler handler : handlers) {
      PsiElement[] elementList = handler.getMovableSubElements(element);
      if (elementList.length > 1) {
        Arrays.sort(elementList, BY_OFFSET);
        PsiElement first = elementList[0];
        PsiElement last = elementList[elementList.length - 1];
        if (rangeStart >= first.getTextRange().getStartOffset() && rangeEnd <= last.getTextRange().getEndOffset() &&
            (rangeStart >= first.getTextRange().getEndOffset() || rangeEnd <= last.getTextRange().getStartOffset())) {
          return elementList;
        }
      }
    }
    element = element.getParent();
  }
  return null;
}
 
Example 8
Source File: DustEnterHandler.java    From Intellij-Dust with MIT License 5 votes vote down vote up
/**
 * Checks to see if {@code Enter} has been typed while the caret is between an open and close tag pair.
 * @return true if between open and close tags, false otherwise
 */
private static boolean isBetweenHbTags(Editor editor, PsiFile file, int offset) {
  if (offset == 0) return false;
  CharSequence chars = editor.getDocument().getCharsSequence();
  if (chars.charAt(offset - 1) != '}') return false;

  EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter();
  HighlighterIterator iterator = highlighter.createIterator(offset - 1);

  final PsiElement openerElement = file.findElementAt(iterator.getStart());

  PsiElement openTag = DustPsiUtil.findParentOpenTagElement(openerElement);

  if (openTag == null) {
    return false;
  }

  iterator.advance();

  if (iterator.atEnd()) {
    // no more tokens, so certainly no close tag
    return false;
  }

  final PsiElement closerElement = file.findElementAt(iterator.getStart());

  PsiElement closeTag = DustPsiUtil.findParentCloseTagElement(closerElement);

  // if we got this far, we're between open and close tags iff this is a close tag
  return closeTag != null;
}
 
Example 9
Source File: MuleConfigLiveTemplateContextType.java    From mule-intellij-plugins with Apache License 2.0 5 votes vote down vote up
public boolean isInContext(@NotNull final PsiFile file, final int offset)
{
  if (!MuleConfigUtils.isMuleFile(file))
  {
      return false;
  }
  PsiElement element = file.findElementAt(offset);
  return element != null && PsiTreeUtil.getParentOfType(element, XmlText.class) != null;
}
 
Example 10
Source File: ConvertQuotesIntention.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
  PsiElement place = file.findElementAt(editor.getCaretModel().getOffset());
  expression = PsiTreeUtil.getParentOfType(place, HaxeStringLiteralExpression.class);

  return expression != null && canSwitchQuotes(expression);
}
 
Example 11
Source File: InTemplateDeclarationVariableProvider.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
private static PsiElement extractLanguagePsiElementForElementAtPosition(@NotNull Language language, @NotNull PsiElement psiElement, int offset) {
    FileViewProvider viewProvider = psiElement.getContainingFile().getViewProvider();

    PsiFile psi = viewProvider.getPsi(language);

    PsiElement elementAt = psi.findElementAt(offset);
    if (elementAt == null) {
        return null;
    }

    return elementAt.getParent();
}
 
Example 12
Source File: FluidTemplateContext.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@Override
public boolean isInContext(@NotNull PsiFile psiFile, int i) {
    PsiElement elementAt = psiFile.findElementAt(i);
    if (elementAt != null) {
        return psiFile.getLanguage().is(FluidLanguage.INSTANCE) && !elementAt.getLanguage().is(FluidLanguage.INSTANCE);
    }
    return false;
}
 
Example 13
Source File: DefaultHighlightVisitorBasedInspection.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void checkFile(@Nonnull PsiFile originalFile,
                      @Nonnull final InspectionManager manager,
                      @Nonnull ProblemsHolder problemsHolder,
                      @Nonnull final GlobalInspectionContext globalContext,
                      @Nonnull final ProblemDescriptionsProcessor problemDescriptionsProcessor) {
  for (Pair<PsiFile, HighlightInfo> pair : runGeneralHighlighting(originalFile, highlightErrorElements, runAnnotators,
                                                                  problemsHolder.isOnTheFly())) {
    PsiFile file = pair.first;
    HighlightInfo info = pair.second;
    TextRange range = new TextRange(info.startOffset, info.endOffset);
    PsiElement element = file.findElementAt(info.startOffset);

    while (element != null && !element.getTextRange().contains(range)) {
      element = element.getParent();
    }

    if (element == null) {
      element = file;
    }

    GlobalInspectionUtil.createProblem(
            element,
            info,
            range.shiftRight(-element.getNode().getStartOffset()),
            info.getProblemGroup(),
            manager,
            problemDescriptionsProcessor,
            globalContext
    );

  }
}
 
Example 14
Source File: ClosingTagHandler.java    From bamboo-soy with Apache License 2.0 5 votes vote down vote up
@Nullable
private TagBlockElement findEnclosingTagBlockElement(PsiFile file, int offset) {
  PsiElement el = file.findElementAt(offset - 1);
  return (TagBlockElement) PsiTreeUtil
      .findFirstParent(el,
          parent -> parent instanceof TagBlockElement && !(parent instanceof SoyChoiceClause));
}
 
Example 15
Source File: CSharpStatementContextType.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
@RequiredReadAction
public boolean isInContext(@Nonnull PsiFile file, int offset)
{
	PsiElement elementAt = file.findElementAt(offset);

	CSharpLocalVariable localVariable = PsiTreeUtil.getParentOfType(elementAt, CSharpLocalVariable.class);
	return localVariable != null && CSharpPsiUtilImpl.isNullOrEmpty(localVariable);
}
 
Example 16
Source File: ReturnStatementExpression.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
public static PsiElement getCaretElement(ExpressionContext context)
{
	Project project = context.getProject();

	PsiDocumentManager.getInstance(project).commitAllDocuments();

	Editor editor = context.getEditor();
	if(editor == null)
	{
		return null;
	}
	PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
	return file == null ? null : file.findElementAt(editor.getCaretModel().getOffset());
}
 
Example 17
Source File: ConvertAction.java    From data-mediator with Apache License 2.0 5 votes vote down vote up
private PsiClass getPsiClassFromContext(AnActionEvent e) {
    PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
    Editor editor = e.getData(PlatformDataKeys.EDITOR);
   // psiFile.getViewProvider().getVirtualFile()

    if (psiFile == null || editor == null) {
        return null;
    }
    int offset = editor.getCaretModel().getOffset();
    PsiElement element = psiFile.findElementAt(offset);

    return PsiTreeUtil.getParentOfType(element, PsiClass.class);
}
 
Example 18
Source File: AbstractInflateViewAction.java    From idea-android-studio-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
    int offset = editor.getCaretModel().getOffset();
    PsiElement psiElement = file.findElementAt(offset);

    if(!PlatformPatterns.psiElement().inside(PsiLocalVariable.class).accepts(psiElement)) {
        return false;
    }

    PsiLocalVariable psiLocalVariable = PsiTreeUtil.getParentOfType(psiElement, PsiLocalVariable.class);
    return InflateViewAnnotator.matchInflate(psiLocalVariable) != null;
}
 
Example 19
Source File: SuppressIntentionAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
private static PsiElement getElement(@Nonnull Editor editor, @Nonnull PsiFile file) {
  CaretModel caretModel = editor.getCaretModel();
  int position = caretModel.getOffset();
  return file.findElementAt(position);
}
 
Example 20
Source File: CSharpIntroduceHandler.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
public void performAction(CSharpIntroduceOperation operation)
{
	final PsiFile file = operation.getFile();
	if(!CommonRefactoringUtil.checkReadOnlyStatus(file))
	{
		return;
	}
	final Editor editor = operation.getEditor();
	if(editor.getSettings().isVariableInplaceRenameEnabled())
	{
		final TemplateState templateState = TemplateManagerImpl.getTemplateState(operation.getEditor());
		if(templateState != null && !templateState.isFinished())
		{
			return;
		}
	}

	PsiElement element1 = null;
	PsiElement element2 = null;
	final SelectionModel selectionModel = editor.getSelectionModel();
	if(selectionModel.hasSelection())
	{
		element1 = file.findElementAt(selectionModel.getSelectionStart());
		element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1);
		if(element1 instanceof PsiWhiteSpace)
		{
			int startOffset = element1.getTextRange().getEndOffset();
			element1 = file.findElementAt(startOffset);
		}
		if(element2 instanceof PsiWhiteSpace)
		{
			int endOffset = element2.getTextRange().getStartOffset();
			element2 = file.findElementAt(endOffset - 1);
		}
	}
	else
	{
		if(smartIntroduce(operation))
		{
			return;
		}
		final CaretModel caretModel = editor.getCaretModel();
		final Document document = editor.getDocument();
		int lineNumber = document.getLineNumber(caretModel.getOffset());
		if((lineNumber >= 0) && (lineNumber < document.getLineCount()))
		{
			element1 = file.findElementAt(document.getLineStartOffset(lineNumber));
			element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1);
		}
	}
	final Project project = operation.getProject();
	if(element1 == null || element2 == null)
	{
		showCannotPerformError(project, editor);
		return;
	}

	element1 = CSharpRefactoringUtil.getSelectedExpression(project, file, element1, element2);
	if(element1 == null)
	{
		showCannotPerformError(project, editor);
		return;
	}

	if(!checkIntroduceContext(file, editor, element1))
	{
		return;
	}
	operation.setElement(element1);
	performActionOnElement(operation);
}