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

The following examples show how to use com.intellij.psi.PsiElement#getProject() . 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: SmartyFileGoToDeclarationHandler.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
private void attachExtendsFileGoto(PsiElement sourceElement, final List<PsiElement> psiElements) {

        final Project project = sourceElement.getProject();
        final VirtualFile currentFile = sourceElement.getContainingFile().getVirtualFile();

        final String finalText = normalizeFilename(sourceElement.getText());
        TemplateUtil.collectFiles(project, new TemplateUtil.SmartyTemplatePreventSelfVisitor(currentFile) {
            @Override
            public void visitNonSelfFile(VirtualFile virtualFile, String fileName) {

                if (!fileName.equals(finalText)) {
                    return;
                }

                PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
                if (psiFile != null) {
                    psiElements.add(psiFile);
                }

            }
        });

    }
 
Example 2
Source File: ExtractMethodHelper.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void processDuplicates(@Nonnull final PsiElement callElement,
                                     @Nonnull final PsiElement generatedMethod,
                                     @Nonnull final List<PsiElement> scope,
                                     @Nonnull final SimpleDuplicatesFinder finder,
                                     @Nonnull final Editor editor,
                                     @Nonnull final Consumer<Pair<SimpleMatch, PsiElement>> replacer) {
  finder.setReplacement(callElement);
  if (ApplicationManager.getApplication().isUnitTestMode()) {
    replaceDuplicates(callElement, editor, replacer, finder.findDuplicates(scope, generatedMethod));
    return;
  }
  final Project project = callElement.getProject();
  ProgressManager.getInstance().run(new Task.Backgroundable(project, RefactoringBundle.message("searching.for.duplicates"), true) {
    public void run(@Nonnull ProgressIndicator indicator) {
      if (myProject == null || myProject.isDisposed()) return;
      final List<SimpleMatch> duplicates = ApplicationManager.getApplication().runReadAction(new Computable<List<SimpleMatch>>() {
        @Override
        public List<SimpleMatch> compute() {
          return finder.findDuplicates(scope, generatedMethod);
        }
      });

      ApplicationManager.getApplication().invokeLater(() -> replaceDuplicates(callElement, editor, replacer, duplicates));
    }
  });
}
 
Example 3
Source File: AbstractNavigationHandler.java    From NutzCodeInsight with Apache License 2.0 6 votes vote down vote up
@Override
public final void navigate(MouseEvent mouseEvent, PsiElement psiElement) {
    if (canNavigate(psiElement)) {
        final Project project = psiElement.getProject();
        final List<VirtualFile> fileList = findTemplteFileList(psiElement);
        if (fileList.size() == 1) {
            FileEditorManager.getInstance(project).openFile(fileList.get(0), true);
        } else if (fileList.size() > 1) {
            final List<VirtualFile> infos = new ArrayList<>(fileList);
            List<PsiElement> elements = new ArrayList<>();
            PsiManager psiManager = PsiManager.getInstance(psiElement.getProject());
            infos.forEach(virtualFile -> elements.add(psiManager.findFile(virtualFile).getNavigationElement()));
            NavigationUtil.getPsiElementPopup(elements.toArray(new PsiElement[0]), title).show(new RelativePoint(mouseEvent));
        } else {
            if (fileList == null || fileList.size() <= 0) {
                Messages.showErrorDialog("没有找到这个资源文件,请检查!", "错误提示");
            }
        }
    }

}
 
Example 4
Source File: SmartyFileGoToDeclarationHandler.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
private void attachSnippetNamespaceTagGoto(PsiElement sourceElement, final List<PsiElement> psiElements) {

        final Project project = sourceElement.getProject();

        String namespace = sourceElement.getText();
        if(StringUtils.isBlank(namespace)) {
            return;
        }

        final String finalText = normalizeFilename(namespace);
        TemplateUtil.collectFiles(sourceElement.getProject(), (virtualFile, fileName) -> {

            if (!fileName.replaceFirst("[.][^.]+$", "").equals(finalText)) {
                return;
            }

            PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
            if (psiFile != null) {
                psiElements.add(psiFile);
            }
        }, "tpl");

        psiElements.addAll(SnippetUtil.getSnippetNamespaceTargets(sourceElement.getProject(), namespace));
    }
 
Example 5
Source File: DustFormattingModelBuilder.java    From Intellij-Dust with MIT License 6 votes vote down vote up
/**
 * We have to override {@link com.intellij.formatting.templateLanguages.TemplateLanguageFormattingModelBuilder#createModel}
 * since after we delegate to some templated languages, those languages (xml/html for sure, potentially others)
 * delegate right back to us to format the DustTypes.OUTER_TYPE token we tell them to ignore,
 * causing an stack-overflowing loop.
 */
@NotNull
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {

  final PsiFile file = element.getContainingFile();
  Block rootBlock;

  ASTNode node = element.getNode();

  if (node.getElementType() == DustFileViewProvider.OUTER_TYPE) {
    // If we're looking at a DustTypes.HTML element, then we've been invoked by our templated
    // language.  Make a dummy block to allow that formatter to continue
    return new SimpleTemplateLanguageFormattingModelBuilder().createModel(element, settings);
  } else {
    rootBlock = getRootBlock(file, file.getViewProvider(), settings);
  }

  return new DocumentBasedFormattingModel(rootBlock, element.getProject(), settings, file.getFileType(), file);
}
 
Example 6
Source File: UsageHolder.java    From consulo with Apache License 2.0 6 votes vote down vote up
public UsageHolder(PsiElement element, UsageInfo[] usageInfos) {
  Project project = element.getProject();
  myElementPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(element);

  GeneratedSourcesFilter[] filters = GeneratedSourcesFilter.EP_NAME.getExtensions();
  for (UsageInfo usageInfo : usageInfos) {
    if (!(usageInfo instanceof SafeDeleteReferenceUsageInfo)) continue;
    final SafeDeleteReferenceUsageInfo usage = (SafeDeleteReferenceUsageInfo)usageInfo;
    if (usage.getReferencedElement() != element) continue;

    if (!usage.isSafeDelete()) {
      myUnsafeUsages++;
      if (usage.isNonCodeUsage || isInGeneratedCode(usage, project, filters)) {
        myNonCodeUnsafeUsages++;
      }
    }
  }
}
 
Example 7
Source File: ToolsImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@javax.annotation.Nullable
public InspectionToolWrapper getEnabledTool(PsiElement element) {
  if (!myEnabled) return null;
  if (myTools == null || element == null) {
    return myDefaultState.isEnabled() ? myDefaultState.getTool() : null;
  }
  final Project project = element.getProject();
  final DependencyValidationManager manager = DependencyValidationManager.getInstance(project);
  for (ScopeToolState state : myTools) {
    final NamedScope scope = state.getScope(project);
    if (scope != null) {
      final PackageSet set = scope.getValue();
      if (set != null && set.contains(element.getContainingFile(), manager)) {
        return state.isEnabled() ? state.getTool() : null;
      }
    }
  }
  return myDefaultState.isEnabled() ? myDefaultState.getTool() : null;
}
 
Example 8
Source File: SimpleTemplateLanguageFormattingModelBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public FormattingModel createModel(final PsiElement element, final CodeStyleSettings settings) {
  if (element instanceof PsiFile) {
    final FileViewProvider viewProvider = ((PsiFile)element).getViewProvider();
    if (viewProvider instanceof TemplateLanguageFileViewProvider) {
      final Language language = ((TemplateLanguageFileViewProvider)viewProvider).getTemplateDataLanguage();
      FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forLanguage(language);
      if (builder != null) {
        return builder.createModel(viewProvider.getPsi(language), settings);
      }
    }
  }

  final PsiFile file = element.getContainingFile();
  return new DocumentBasedFormattingModel(new AbstractBlock(element.getNode(), Wrap.createWrap(WrapType.NONE, false), Alignment.createAlignment()) {
    @Override
    protected List<Block> buildChildren() {
      return Collections.emptyList();
    }

    @Override
    public Spacing getSpacing(final Block child1, @Nonnull final Block child2) {
      return Spacing.getReadOnlySpacing();
    }

    @Override
    public boolean isLeaf() {
      return true;
    }
  }, element.getProject(), settings, file.getFileType(), file);
}
 
Example 9
Source File: NutzLocalizationFoldingBuilder.java    From NutzCodeInsight with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
    Project project = root.getProject();
    String localizationPackage = NutzLocalUtil.getLocalizationPackage(project);
    if (null == localizationPackage) {
        return FoldingDescriptor.EMPTY;
    }
    List<FoldingDescriptor> descriptors = new ArrayList<>();
    Collection<VirtualFile> propertiesFiles = FilenameIndex.getAllFilesByExt(project, "properties", GlobalSearchScope.projectScope(project));
    Collection<PsiLiteralExpression> literalExpressions = PsiTreeUtil.findChildrenOfType(root, PsiLiteralExpression.class);
    for (final PsiLiteralExpression literalExpression : literalExpressions) {
        if (!NutzLocalUtil.isLocal(literalExpression)) {
            continue;
        }
        String key = literalExpression.getValue() instanceof String ? (String) literalExpression.getValue() : null;
        if (key != null) {
            final List<String> properties = NutzLocalUtil.findProperties(project, propertiesFiles, localizationPackage, key);
            TextRange textRange = new TextRange(literalExpression.getTextRange().getStartOffset() + 1, literalExpression.getTextRange().getEndOffset() - 1);
            String value;
            if (properties.size() == 1) {
                value = properties.get(0);
            } else if (properties.size() > 1) {
                value = properties.get(0) + "[该键值存在多个配置文件中!]";
            } else {
                value = "国际化信息中不存在[" + key + "],使用时可能产生异常,请检查!";
            }
            descriptors.add(new NutzLocalizationFoldingDescriptor(literalExpression.getNode(), textRange, value));
        }
    }
    return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
 
Example 10
Source File: PimpleCompletionContributor.java    From silex-idea-plugin with MIT License 5 votes vote down vote up
public void addCompletions(@NotNull CompletionParameters parameters,
                           ProcessingContext context,
                           @NotNull CompletionResultSet resultSet) {

    PsiElement element = parameters.getPosition().getParent();
    Project project = element.getProject();

    if(!ProjectComponent.isEnabled(project)) {
        return;
    }

    if (!(element instanceof StringLiteralExpression)) {
        return;
    }

    Container container = Utils.findContainerForFirstParameterOfPimpleMethod((StringLiteralExpression) element);
    if (container == null){
        return;
    }

    for (Service service : container.getServices().values()) {
        resultSet.addElement(new ServiceLookupElement(service, project));
    }

    for (Parameter parameter : container.getParameters().values()) {
        resultSet.addElement(new ParameterLookupElement(parameter));
    }

    resultSet.stopHere();
}
 
Example 11
Source File: TwigTemplateCompletionContributor.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
public void addCompletions(@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull CompletionResultSet resultSet) {
    PsiElement position = parameters.getPosition();
    if(!Symfony2ProjectComponent.isEnabled(position)) {
        return;
    }

    Project project = position.getProject();
    for (Map.Entry<String, TwigExtension> entry : TwigExtensionParser.getOperators(project).entrySet()) {
        resultSet.addElement(new TwigExtensionLookupElement(project, entry.getKey(), entry.getValue()));
    }
}
 
Example 12
Source File: BuckGotoProvider.java    From buck with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
PsiElement getGotoDeclarationTarget(@Nullable PsiElement element) {
  if (element == null || !(element.getLanguage() instanceof BuckLanguage)) {
    return null;
  }
  Project project = element.getProject();
  if (project.isDefault()) {
    return null;
  }
  VirtualFile sourceFile = element.getContainingFile().getVirtualFile();
  if (sourceFile == null) {
    return null;
  }
  BuckLoadArgument buckLoadArgument =
      PsiTreeUtil.getParentOfType(element, BuckLoadArgument.class);
  if (buckLoadArgument != null) {
    return resolveAsLoadArgument(project, sourceFile, buckLoadArgument);
  }
  BuckIdentifier buckIdentifier =
      PsiTreeUtil.getParentOfType(element, BuckIdentifier.class, false);
  if (buckIdentifier != null) {
    return resolveAsIdentifier(project, buckIdentifier);
  }
  BuckString buckString = PsiTreeUtil.getParentOfType(element, BuckString.class, false);
  if (buckString != null) {
    return resolveAsBuckString(project, sourceFile, buckString);
  }
  return null;
}
 
Example 13
Source File: FlowRenameDialog.java    From mule-intellij-plugins with Apache License 2.0 5 votes vote down vote up
public FlowRenameDialog(@Nullable Editor editor, @NotNull PsiElement element, @NotNull XmlTag tag) {
    super(element.getProject(), true);
    this.myEditor = editor;
    this.myElement = element;
    this.myTag = tag;
    this.setTitle(REFACTORING_NAME);
    this.createNewNameComponent();
    this.init();
    this.myTitleLabel.setText("Rename Mule flow '" + tag.getAttributeValue("name") + "' and its usages to:");
    this.validateButtons();
}
 
Example 14
Source File: IconDescriptorUpdaters.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@RequiredReadAction
public static Image getIconWithoutCache(@Nonnull PsiElement element, int flags) {
  Project project = element.getProject();
  IconDescriptor iconDescriptor = new IconDescriptor(null);
  IconDescriptorUpdater.EP_NAME.composite(project).updateIcon(iconDescriptor, element, flags);
  return iconDescriptor.toIcon();
}
 
Example 15
Source File: KeywordCollector.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
@NotNull
private Collection<String> suggestKeywordsBasedOnParserExpectedKeywords(@NotNull PsiElement position) {
    String text = getPrecedingText(position, CompletionInitializationContext.DUMMY_IDENTIFIER);
    Project project = position.getProject();
    PsiFile temporaryFileForCompletionCheck = createFileForText(project, text + "          ");
    int completionOffset = calculateCompletionOffset(position);
    GeneratedParserUtilBase.CompletionState completionStateInTemporaryFile = getCompletionStateForKeywords(completionOffset);
    temporaryFileForCompletionCheck.putUserData(COMPLETION_STATE_KEY, completionStateInTemporaryFile);
    triggerParsingInFile(temporaryFileForCompletionCheck);
    List<String> stripped = stringPrecedingText(StringUtils.normalizeWhitespaces(text), completionStateInTemporaryFile.items);
    return expandMultiWordOptions(stripped);
}
 
Example 16
Source File: LayoutSpecMethodAnnotationsProvider.java    From litho with Apache License 2.0 5 votes vote down vote up
@Override
protected void addCompletions(
    CompletionParameters parameters, ProcessingContext context, CompletionResultSet result) {
  PsiElement position = parameters.getPosition();
  if (!CompletionUtils.findFirstParent(position, LithoPluginUtils::isLayoutSpec).isPresent())
    return;

  final Project project = position.getProject();
  for (String annotationFQN : ANNOTATION_QUALIFIED_NAMES) {
    LookupElement lookup =
        PrioritizedLookupElement.withPriority(
            createLookup(annotationFQN, project), Integer.MAX_VALUE);
    result.addElement(lookup);
  }
}
 
Example 17
Source File: ModuleCompletionProvider.java    From reasonml-idea-plugin with MIT License 4 votes vote down vote up
public static void addCompletions(@NotNull ORTypes types, @NotNull PsiElement element, @NotNull CompletionResultSet resultSet) {
    LOG.debug("MODULE expression completion");

    Project project = element.getProject();
    GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    PsiFinder psiFinder = PsiFinder.getInstance(project);

    // Compute module path (all module names before the last dot)
    ModulePath modulePath = computePathFromPsi(types, element);
    if (LOG.isDebugEnabled()) {
        LOG.debug("  module path", modulePath.toString());
    }

    if (modulePath.isEmpty()) {
        // First module to complete, use the list of files
        Set<PsiFakeModule> topModules = psiFinder.findTopModules(true, scope);
        for (PsiFakeModule topModule : topModules) {
            FileBase topFile = (FileBase) topModule.getContainingFile();
            if (!topFile.equals(element.getContainingFile())) {
                resultSet.addElement(LookupElementBuilder.
                        create(topModule.getModuleName()).
                        withTypeText(FileHelper.shortLocation(project, topFile.getVirtualFile().getPath())).
                        withIcon(IconProvider.getFileModuleIcon(topFile)));
            }

        }

        // Add virtual namespaces
        Collection<String> namespaces = FileModuleIndexService.getService().getNamespaces(project);
        LOG.debug("  namespaces", namespaces);

        for (String namespace : namespaces) {
            resultSet.addElement(LookupElementBuilder.
                    create(namespace).
                    withTypeText("Generated namespace").
                    withIcon(ORIcons.VIRTUAL_NAMESPACE));
        }
    } else {
        Set<PsiModule> modulesFromQn = psiFinder.findModulesFromQn(modulePath.toString(), true, interfaceOrImplementation, scope);
        PsiModule foundModule = modulesFromQn.isEmpty() ? null : modulesFromQn.iterator().next();
        if (foundModule != null) {
            LOG.debug("  Found module", foundModule);
            for (PsiModule module : foundModule.getModules()) {
                resultSet.addElement(LookupElementBuilder.
                        create(module).
                        withIcon(PsiIconUtil.getProvidersIcon(module, 0)));
            }
        }
    }
}
 
Example 18
Source File: VariableNameCompletionProvider.java    From BashSupport with Apache License 2.0 4 votes vote down vote up
@Override
protected void addBashCompletions(String currentText, CompletionParameters parameters, ProcessingContext context, CompletionResultSet result) {
    PsiElement element = parameters.getPosition();

    BashVar varElement = PsiTreeUtil.getContextOfType(element, BashVar.class, false);
    boolean dollarPrefix = currentText != null && currentText.startsWith("$");
    boolean insideExpansion = element.getParent() != null && element.getParent().getParent() instanceof BashParameterExpansion;
    if (varElement == null && !dollarPrefix && !insideExpansion) {
        return;
    }

    int invocationCount = parameters.getInvocationCount();
    int resultLength = 0;

    PsiElement original = parameters.getOriginalPosition();
    BashVar varElementOriginal = original != null ? PsiTreeUtil.getContextOfType(original, BashVar.class, false) : null;

    if (varElement != null) {
        // only keep vars of included files when starting in the original file
        PsiElement originalRef = varElementOriginal != null ? varElementOriginal : original;
        if (originalRef != null) {
            resultLength += addCollectedVariables(original, result, new BashVarVariantsProcessor(originalRef, false, true));
        }

        // only keep vars of the dummy file when starting in the dummy file
        resultLength += addCollectedVariables(element, result, new BashVarVariantsProcessor(varElement, true, false));
    } else {
        // not in a variable element, but collect all known variable names at this offset in the current file
        if (original != null) {
            resultLength += addCollectedVariables(original, result, new BashVarVariantsProcessor(original, false, true));
        }
        resultLength += addCollectedVariables(element, result, new BashVarVariantsProcessor(element, false, true));
    }

    if (currentText != null && (dollarPrefix || insideExpansion) && (invocationCount >= 2 || resultLength == 0)) {
        Project project = element.getProject();
        addBuiltInVariables(result, project);
        addGlobalVariables(result, project);
    } else {
        result.addLookupAdvertisement("Press twice for global variables");
    }
}
 
Example 19
Source File: MsilDelegateTypeRef.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
public MsilDelegateTypeRef(@Nonnull PsiElement scope, @Nonnull DotNetTypeRef typeRef)
{
	super(scope.getProject());
	myTypeRef = typeRef;
}
 
Example 20
Source File: BashEvalElementType.java    From BashSupport with Apache License 2.0 4 votes vote down vote up
@Override
protected ASTNode doParseContents(@NotNull ASTNode chameleon, @NotNull PsiElement psi) {
    Project project = psi.getProject();
    boolean supportEvalEscapes = BashProjectSettings.storedSettings(project).isEvalEscapesEnabled();

    String originalText = chameleon.getChars().toString();
    ParserDefinition def = LanguageParserDefinitions.INSTANCE.forLanguage(BashFileType.BASH_LANGUAGE);

    boolean isDoubleQuoted = originalText.startsWith("\"") && originalText.endsWith("\"");
    boolean isSingleQuoted = originalText.startsWith("'") && originalText.endsWith("'");
    boolean isEscapingSingleQuoted = originalText.startsWith("$'") && originalText.endsWith("'");
    boolean isUnquoted = !isDoubleQuoted && !isSingleQuoted && !isEscapingSingleQuoted;

    String prefix = isUnquoted ? "" : originalText.subSequence(0, isEscapingSingleQuoted ? 2 : 1).toString();
    String content = isUnquoted ? originalText : originalText.subSequence(isEscapingSingleQuoted ? 2 : 1, originalText.length() - 1).toString();
    String suffix = isUnquoted ? "" : originalText.subSequence(originalText.length() - 1, originalText.length()).toString();

    TextPreprocessor textProcessor;
    if (supportEvalEscapes) {
        if (isEscapingSingleQuoted) {
            textProcessor = new BashEnhancedTextPreprocessor(TextRange.from(prefix.length(), content.length()));
        } else if (isSingleQuoted) {
            //no escape handling for single-quoted strings
            textProcessor = new BashIdentityTextPreprocessor(TextRange.from(prefix.length(), content.length()));
        } else {
            //fallback to simple escape handling
            textProcessor = new BashSimpleTextPreprocessor(TextRange.from(prefix.length(), content.length()));
        }
    } else {
        textProcessor = new BashIdentityTextPreprocessor(TextRange.from(prefix.length(), content.length()));
    }

    StringBuilder unescapedContent = new StringBuilder(content.length());
    textProcessor.decode(content, unescapedContent);

    Lexer lexer = isUnquoted
            ? def.createLexer(project)
            : new PrefixSuffixAddingLexer(def.createLexer(project), prefix, TokenType.WHITE_SPACE, suffix, TokenType.WHITE_SPACE);

    PsiBuilder psiBuilder = new UnescapingPsiBuilder(project,
            def,
            lexer,
            chameleon,
            originalText,
            prefix + unescapedContent + suffix,
            textProcessor);

    return def.createParser(project).parse(this, psiBuilder).getFirstChildNode();
}