Java Code Examples for com.intellij.openapi.fileTypes.LanguageFileType

The following examples show how to use com.intellij.openapi.fileTypes.LanguageFileType. These examples are extracted from open source projects. 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
/**
 * @param templateFile        Name of the generated file
 * @param destinationPath     Relative path to the target file system entry
 * @param extensionDefinition Extension definition containing all relevant metadata
 * @param context             Template Context variables
 * @param project             Project in context
 */
public static PsiElement fromTemplate(@NotNull String templateFile, @NotNull String destinationPath, @NotNull String destinationFileName, @NotNull TYPO3ExtensionDefinition extensionDefinition, @NotNull Map<String, String> context, Project project) {
    String template = readTemplateToString(templateFile, context);

    VirtualFile targetDirectory = getOrCreateDestinationPath(extensionDefinition.getRootDirectory(), destinationPath);

    LanguageFileType fileType = FileTypes.PLAIN_TEXT;
    if (templateFile.endsWith(".php")) {
        fileType = PhpFileType.INSTANCE;
    }

    PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(destinationFileName, fileType, template);
    CodeStyleManager.getInstance(project).reformat(fileFromText);
    return PsiDirectoryFactory
            .getInstance(project)
            .createDirectory(targetDirectory)
            .add(fileFromText);
}
 
Example 2
Source Project: idea-php-typo3-plugin   Source File: AbstractTestCase.java    License: MIT License 6 votes vote down vote up
public void assertPhpReferenceResolveTo(LanguageFileType languageFileType, String configureByText, ElementPattern<?> pattern) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    psiElement = PsiTreeUtil.getParentOfType(psiElement, PhpReference.class);
    if (psiElement == null) {
        fail("Element is not PhpReference.");
    }

    PsiElement resolve = ((PhpReference) psiElement).resolve();
    if(!pattern.accepts(resolve)) {
        fail(String.format("failed pattern matches element of '%s'", resolve == null ? "null" : resolve.toString()));
    }

    assertTrue(pattern.accepts(resolve));
}
 
Example 3
public void assertPhpReferenceResolveTo(LanguageFileType languageFileType, String configureByText, ElementPattern<?> pattern) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    psiElement = PsiTreeUtil.getParentOfType(psiElement, PhpReference.class);
    if (psiElement == null) {
        fail("Element is not PhpReference.");
    }

    PsiElement resolve = ((PhpReference) psiElement).resolve();
    if(!pattern.accepts(resolve)) {
        fail(String.format("failed pattern matches element of '%s'", resolve == null ? "null" : resolve.toString()));
    }

    assertTrue(pattern.accepts(resolve));
}
 
Example 4
Source Project: silex-idea-plugin   Source File: CodeInsightFixtureTestCase.java    License: MIT License 6 votes vote down vote up
protected void assertSignatureEquals(LanguageFileType languageFileType, @NotNull Class aClass, String configureByText, String typeSignature) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    psiElement = PsiTreeUtil.getParentOfType(psiElement, aClass);

    PhpTypeProvider2[] typeAnalyser = Extensions.getExtensions(PhpTypeProvider2.EP_NAME);

    for (PhpTypeProvider2 provider : typeAnalyser) {

        if (provider instanceof PimplePhpTypeProvider) {

            String providerType = provider.getType(psiElement);
            if (providerType != null) {
                providerType = "#" + provider.getKey() + providerType;
            }

            assertEquals(typeSignature, providerType);
        }
    }
}
 
Example 5
Source Project: consulo   Source File: SubstitutedFileType.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
public static FileType substituteFileType(VirtualFile file, @Nonnull FileType fileType, Project project) {
  if (project == null) {
    return fileType;
  }
  if (fileType instanceof LanguageFileType) {
    final Language language = ((LanguageFileType)fileType).getLanguage();
    final Language substitutedLanguage = LanguageSubstitutors.INSTANCE.substituteLanguage(language, file, project);
    LanguageFileType substFileType = substitutedLanguage.getAssociatedFileType();
    if (!substitutedLanguage.equals(language) && substFileType != null) {
      return new SubstitutedFileType(fileType, substFileType, substitutedLanguage);
    }
  }

  return fileType;
}
 
Example 6
Source Project: consulo   Source File: CoreStubTreeLoader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean canHaveStub(VirtualFile file) {
  final FileType fileType = file.getFileType();
  if (fileType instanceof LanguageFileType) {
    Language l = ((LanguageFileType)fileType).getLanguage();
    ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(l);
    if (parserDefinition == null) return false;
    final IFileElementType elementType = parserDefinition.getFileNodeType();
    return elementType instanceof IStubFileElementType && ((IStubFileElementType)elementType).shouldBuildStubFor(file);
  }
  else if (fileType.isBinary()) {
    final BinaryFileStubBuilder builder = BinaryFileStubBuilders.INSTANCE.forFileType(fileType);
    return builder != null && builder.acceptsFile(file);
  }
  return false;
}
 
Example 7
public void assertPhpReferenceResolveTo(LanguageFileType languageFileType, String configureByText, ElementPattern<?> pattern) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    psiElement = PsiTreeUtil.getParentOfType(psiElement, PhpReference.class);
    if (psiElement == null) {
        fail("Element is not PhpReference.");
    }

    PsiElement resolve = ((PhpReference) psiElement).resolve();
    if(!pattern.accepts(resolve)) {
        fail(String.format("failed pattern matches element of '%s'", resolve == null ? "null" : resolve.toString()));
    }

    assertTrue(pattern.accepts(resolve));
}
 
Example 8
public void assertCompletionLookupContainsPresentableItem(LanguageFileType languageFileType, String configureByText, LookupElementPresentationAssert.Assert presentationAssert) {

        myFixture.configureByText(languageFileType, configureByText);
        myFixture.completeBasic();

        LookupElement[] lookupElements = myFixture.getLookupElements();
        if(lookupElements == null) {
            fail("failed to find lookup presentable on empty collection");
        }

        for (LookupElement lookupElement : lookupElements) {
            LookupElementPresentation presentation = new LookupElementPresentation();
            lookupElement.renderElement(presentation);

            if(presentationAssert.match(presentation)) {
                return;
            }
        }

        fail("failed to find lookup presentable");
    }
 
Example 9
public void assertPhpReferenceResolveTo(LanguageFileType languageFileType, String configureByText, ElementPattern<?> pattern) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    psiElement = PsiTreeUtil.getParentOfType(psiElement, PhpReference.class);
    if (psiElement == null) {
        fail("Element is not PhpReference.");
    }

    PsiElement resolve = ((PhpReference) psiElement).resolve();
    if(!pattern.accepts(resolve)) {
        fail(String.format("failed pattern matches element of '%s'", resolve == null ? "null" : resolve.toString()));
    }

    assertTrue(pattern.accepts(resolve));
}
 
Example 10
Source Project: consulo   Source File: ScratchTreeStructureProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
static Collection<AbstractTreeNode> getDirectoryChildrenImpl(@Nonnull Project project, @Nullable PsiDirectory directory, @Nonnull ViewSettings settings, @Nonnull PsiFileSystemItemFilter filter) {
  final List<AbstractTreeNode> result = new ArrayList<>();
  PsiElementProcessor<PsiFileSystemItem> processor = new PsiElementProcessor<PsiFileSystemItem>() {
    @Override
    public boolean execute(@Nonnull PsiFileSystemItem element) {
      if (!filter.shouldShow(element)) {
        // skip
      }
      else if (element instanceof PsiDirectory) {
        result.add(new PsiDirectoryNode(project, (PsiDirectory)element, settings, filter) {
          @Override
          public Collection<AbstractTreeNode> getChildrenImpl() {
            //noinspection ConstantConditions
            return getDirectoryChildrenImpl(getProject(), getValue(), getSettings(), getFilter());
          }
        });
      }
      else if (element instanceof PsiFile) {
        result.add(new PsiFileNode(project, (PsiFile)element, settings) {
          @Override
          public Comparable<ExtensionSortKey> getTypeSortKey() {
            PsiFile value = getValue();
            Language language = value == null ? null : value.getLanguage();
            LanguageFileType fileType = language == null ? null : language.getAssociatedFileType();
            return fileType == null ? null : new ExtensionSortKey(fileType.getDefaultExtension());
          }
        });
      }
      return true;
    }
  };

  return AbstractTreeUi.calculateYieldingToWriteAction(() -> {
    if (directory == null || !directory.isValid()) return Collections.emptyList();
    directory.processChildren(processor);
    return result;
  });
}
 
Example 11
Source Project: consulo   Source File: FileContentImpl.java    License: Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
public PsiFile createFileFromText(@Nonnull CharSequence text) {
  Project project = getProject();
  if (project == null) {
    project = DefaultProjectFactory.getInstance().getDefaultProject();
  }
  FileType fileType = getFileTypeWithoutSubstitution();
  if (!(fileType instanceof LanguageFileType)) {
    throw new AssertionError("PSI can be created only for a file with LanguageFileType but actual is " + fileType.getClass() + "." +
                             "\nPlease use a proper FileBasedIndexExtension#getInputFilter() implementation for the caller index");
  }
  return createFileFromText(project, text, (LanguageFileType)fileType, myFile, myFileName);
}
 
Example 12
public void assertPhpReferenceSignatureEquals(LanguageFileType languageFileType, String configureByText, String typeSignature) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    psiElement = PsiTreeUtil.getParentOfType(psiElement, PhpReference.class);
    if (!(psiElement instanceof PhpReference)) {
        fail("Element is not PhpReference.");
    }

    assertEquals(typeSignature, ((PhpReference) psiElement).getSignature());
}
 
Example 13
public void assertNavigationContainsFile(LanguageFileType languageFileType, String configureByText, String targetShortcut) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    Set<String> targets = new HashSet<String>();

    for (GotoDeclarationHandler gotoDeclarationHandler : Extensions.getExtensions(GotoDeclarationHandler.EP_NAME)) {
        PsiElement[] gotoDeclarationTargets = gotoDeclarationHandler.getGotoDeclarationTargets(psiElement, 0, myFixture.getEditor());
        if (gotoDeclarationTargets != null && gotoDeclarationTargets.length > 0) {
            for (PsiElement gotoDeclarationTarget : gotoDeclarationTargets) {
                if(gotoDeclarationTarget instanceof PsiFile) {
                    targets.add(((PsiFile) gotoDeclarationTarget).getVirtualFile().getUrl());
                }
            }
        }
    }

    // its possible to have memory fields,
    // so simple check for ending conditions
    // temp:///src/interchange.en.xlf
    for (String target : targets) {
        if(target.endsWith(targetShortcut)) {
            return;
        }
    }

    fail(String.format("failed that PsiElement (%s) navigate to file %s", psiElement.toString(), targetShortcut));
}
 
Example 14
Source Project: consulo   Source File: OneFileAtProjectTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
protected LanguageVersion resolveLanguageVersion(@Nonnull FileType fileType) {
  if(fileType instanceof LanguageFileType) {
    return LanguageVersionUtil.findDefaultVersion(((LanguageFileType)fileType).getLanguage());
  }
  throw new IllegalArgumentException(fileType.getName() + " is not extends 'LanguageFileType'");
}
 
Example 15
public void assertPhpReferenceSignatureEquals(LanguageFileType languageFileType, String configureByText, String typeSignature) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    psiElement = PsiTreeUtil.getParentOfType(psiElement, PhpReference.class);
    if (!(psiElement instanceof PhpReference)) {
        fail("Element is not PhpReference.");
    }

    assertEquals(typeSignature, ((PhpReference) psiElement).getSignature());
}
 
Example 16
Source Project: consulo   Source File: PsiFileGistImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static PsiFile getPsiFile(@Nonnull Project project, @Nonnull VirtualFile file) {
  PsiFile psi = PsiManager.getInstance(project).findFile(file);
  if (!(psi instanceof PsiFileImpl) || ((PsiFileImpl)psi).isContentsLoaded()) {
    return psi;
  }

  FileType fileType = file.getFileType();
  if (!(fileType instanceof LanguageFileType)) return null;

  return FileContentImpl.createFileFromText(project, psi.getViewProvider().getContents(), (LanguageFileType)fileType, file, file.getName());
}
 
Example 17
public void assertIntentionIsAvailable(LanguageFileType languageFileType, String configureByText, String intentionText) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    for (IntentionAction intentionAction : IntentionManager.getInstance().getIntentionActions()) {
        if(intentionAction.isAvailable(getProject(), getEditor(), psiElement.getContainingFile()) && intentionAction.getText().equals(intentionText)) {
            return;
        }
    }

    fail(String.format("Fail intention action '%s' is available in element '%s'", intentionText, psiElement.getText()));
}
 
Example 18
Source Project: reasonml-idea-plugin   Source File: JsInjector.java    License: MIT License 5 votes vote down vote up
public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host,
                                 @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) {
    if (host instanceof PsiRawBody) {
        FileType jsFileType = FileTypeManager.getInstance().getFileTypeByExtension("js");
        if (jsFileType instanceof LanguageFileType) {
            Language jsLanguage = ((LanguageFileType) jsFileType).getLanguage();
            PsiRawBody macroHost = (PsiRawBody) host;
            TextRange macroTextRange = macroHost.getMacroTextRange();
            injectionPlacesRegistrar.addPlace(jsLanguage, macroTextRange, null, null);
        }
    }
}
 
Example 19
Source Project: idea-php-typo3-plugin   Source File: AbstractTestCase.java    License: MIT License 5 votes vote down vote up
@NotNull
private PsiElement assertGetPhpReference(LanguageFileType languageFileType, String configureByText) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    psiElement = PsiTreeUtil.getParentOfType(psiElement, PhpReference.class);
    if (psiElement == null) {
        fail("Element is not PhpReference.");
    }

    return psiElement;
}
 
Example 20
Source Project: consulo   Source File: DummyHolder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public FileType getFileType() {
  PsiElement context = getContext();
  if (context != null) {
    PsiFile containingFile = context.getContainingFile();
    if (containingFile != null) return containingFile.getFileType();
  }
  final LanguageFileType fileType = myLanguage.getAssociatedFileType();
  return fileType != null ? fileType : PlainTextFileType.INSTANCE;
}
 
Example 21
Source Project: consulo   Source File: SubstitutedFileType.java    License: Apache License 2.0 5 votes vote down vote up
private SubstitutedFileType(@Nonnull FileType originalFileType,
                            @Nonnull LanguageFileType substitutionFileType,
                            @Nonnull Language substitutedLanguage) {
  super(substitutedLanguage);
  myOriginalFileType = originalFileType;
  myFileType = substitutionFileType;
}
 
Example 22
Source Project: consulo   Source File: PsiParserFacadeImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public PsiComment createLineCommentFromText(@Nonnull final LanguageFileType fileType, @Nonnull final String text) throws IncorrectOperationException {
  Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(fileType.getLanguage());
  assert commenter != null;
  String prefix = commenter.getLineCommentPrefix();
  if (prefix == null) {
    throw new IncorrectOperationException("No line comment prefix defined for language " + fileType.getLanguage().getID());
  }

  PsiFile aFile = createDummyFile(prefix + text, fileType);
  return findPsiCommentChild(aFile);
}
 
Example 23
public void assertCompletionIsEmpty(LanguageFileType languageFileType, String configureByText) {

        myFixture.configureByText(languageFileType, configureByText);
        myFixture.completeBasic();

        List<String> lookupElements = myFixture.getLookupElementStrings();

        if (lookupElements == null) {
            return;
        }

        if (!lookupElements.isEmpty()) {
            fail("Failed that completion is empty.");
        }
    }
 
Example 24
Source Project: consulo   Source File: PlatformIdTableBuilding.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public static DataIndexer<TodoIndexEntry, Integer, FileContent> getTodoIndexer(FileType fileType, Project project, final VirtualFile virtualFile) {
  final DataIndexer<TodoIndexEntry, Integer, FileContent> extIndexer;
  if (fileType instanceof SubstitutedFileType && !((SubstitutedFileType)fileType).isSameFileType()) {
    SubstitutedFileType sft = (SubstitutedFileType)fileType;
    extIndexer = new CompositeTodoIndexer(getTodoIndexer(sft.getOriginalFileType(), project, virtualFile), getTodoIndexer(sft.getFileType(), project, virtualFile));
  }
  else {
    extIndexer = TodoIndexers.INSTANCE.forFileType(fileType);
  }
  if (extIndexer != null) {
    return extIndexer;
  }

  if (fileType instanceof LanguageFileType) {
    final Language lang = ((LanguageFileType)fileType).getLanguage();
    final ParserDefinition parserDef = LanguageParserDefinitions.INSTANCE.forLanguage(lang);
    LanguageVersion languageVersion = LanguageVersionUtil.findLanguageVersion(lang, project, virtualFile);
    final TokenSet commentTokens = parserDef != null ? parserDef.getCommentTokens(languageVersion) : null;
    if (commentTokens != null) {
      return new TokenSetTodoIndexer(commentTokens, languageVersion, virtualFile, project);
    }
  }

  if (fileType instanceof CustomSyntaxTableFileType) {
    return new TokenSetTodoIndexer(ABSTRACT_FILE_COMMENT_TOKENS, null, virtualFile, project);
  }

  return null;
}
 
Example 25
Source Project: consulo   Source File: ClassSearchEverywhereContributor.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
static PersistentSearchEverywhereContributorFilter<Language> createLanguageFilter(@Nonnull Project project) {
  List<Language> items = Language.getRegisteredLanguages().stream().filter(lang -> lang != Language.ANY && !(lang instanceof DependentLanguage)).sorted(LanguageUtil.LANGUAGE_COMPARATOR)
          .collect(Collectors.toList());
  GotoClassSymbolConfiguration persistentConfig = GotoClassSymbolConfiguration.getInstance(project);
  return new PersistentSearchEverywhereContributorFilter<>(items, persistentConfig, Language::getDisplayName, language -> {
    final LanguageFileType fileType = language.getAssociatedFileType();
    return fileType != null ? fileType.getIcon() : null;
  });
}
 
Example 26
public void assertNavigationContainsFile(LanguageFileType languageFileType, String configureByText, String targetShortcut) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    Set<String> targets = new HashSet<String>();

    for (GotoDeclarationHandler gotoDeclarationHandler : Extensions.getExtensions(GotoDeclarationHandler.EP_NAME)) {
        PsiElement[] gotoDeclarationTargets = gotoDeclarationHandler.getGotoDeclarationTargets(psiElement, 0, myFixture.getEditor());
        if (gotoDeclarationTargets != null && gotoDeclarationTargets.length > 0) {
            for (PsiElement gotoDeclarationTarget : gotoDeclarationTargets) {
                if(gotoDeclarationTarget instanceof PsiFile) {
                    targets.add(((PsiFile) gotoDeclarationTarget).getVirtualFile().getUrl());
                }
            }
        }
    }

    // its possible to have memory fields,
    // so simple check for ending conditions
    // temp:///src/interchange.en.xlf
    for (String target : targets) {
        if(target.endsWith(targetShortcut)) {
            return;
        }
    }

    fail(String.format("failed that PsiElement (%s) navigate to file %s", psiElement.toString(), targetShortcut));
}
 
Example 27
Source Project: consulo   Source File: XDebuggerEditorsProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public Collection<Language> getSupportedLanguages(@Nonnull Project project, @Nullable XSourcePosition sourcePosition) {
  FileType type = getFileType();
  if (type instanceof LanguageFileType) {
    return Collections.singleton(((LanguageFileType)type).getLanguage());
  }
  return Collections.emptyList();
}
 
Example 28
Source Project: consulo   Source File: TypedHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
static FileType getFileType(@Nonnull PsiFile file, @Nonnull Editor editor) {
  FileType fileType = file.getFileType();
  Language language = PsiUtilBase.getLanguageInEditor(editor, file.getProject());
  if (language != null && language != PlainTextLanguage.INSTANCE) {
    LanguageFileType associatedFileType = language.getAssociatedFileType();
    if (associatedFileType != null) fileType = associatedFileType;
  }
  return fileType;
}
 
Example 29
public void assertPhpReferenceNotResolveTo(LanguageFileType languageFileType, String configureByText, ElementPattern<?> pattern) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    psiElement = PsiTreeUtil.getParentOfType(psiElement, PhpReference.class);
    if (psiElement == null) {
        fail("Element is not PhpReference.");
    }

    assertFalse(pattern.accepts(((PhpReference) psiElement).resolve()));
}
 
Example 30
Source Project: editorconfig-jetbrains   Source File: CodeStyleManager.java    License: MIT License 5 votes vote down vote up
private void applyCodeStyleSettings(final List<OutPair> outPairs, final CodeStyleSettings codeStyleSettings,
                                    final VirtualFile file) {
    // Apply indent options
    final String indentSize = Utils.configValueForKey(outPairs, indentSizeKey);
    final String tabWidth = Utils.configValueForKey(outPairs, tabWidthKey);
    final String indentStyle = Utils.configValueForKey(outPairs, indentStyleKey);
    final FileType fileType = file.getFileType();
    final Language language = fileType instanceof LanguageFileType ? ((LanguageFileType)fileType).getLanguage() :
        PlainTextLanguage.INSTANCE;
    final CommonCodeStyleSettings commonSettings = codeStyleSettings.getCommonSettings(language);
    final CommonCodeStyleSettings.IndentOptions indentOptions = commonSettings.getIndentOptions();
    applyIndentOptions(indentOptions, indentSize, tabWidth, indentStyle, file.getCanonicalPath());
}