public static boolean isValidName( final Project project, final PsiElement psiElement, final String newName) { if (newName == null || newName.length() == 0) { return false; } final Condition<String> inputValidator = RenameInputValidatorRegistry.getInputValidator(psiElement); if (inputValidator != null) { return inputValidator.value(newName); } if (psiElement instanceof PsiFile || psiElement instanceof PsiDirectory) { return newName.indexOf('\\') < 0 && newName.indexOf('/') < 0; } if (psiElement instanceof PomTargetPsiElement) { return !StringUtil.isEmptyOrSpaces(newName); } final PsiFile file = psiElement.getContainingFile(); final Language elementLanguage = psiElement.getLanguage(); final Language fileLanguage = file == null ? null : file.getLanguage(); Language language = fileLanguage == null ? elementLanguage : fileLanguage.isKindOf(elementLanguage) ? fileLanguage : elementLanguage; return LanguageNamesValidation.INSTANCE .forLanguage(language) .isIdentifier(newName.trim(), project); }
@Override public boolean isInContext(@NotNull final PsiFile file, final int offset) { PsiElement at = file.findElementAt(offset); if (at == null && offset == file.getTextLength()) { at = file.findElementAt(offset - 1); } Language language = at != null ? at.getParent().getLanguage() : null; if (language instanceof XMLLanguage) { final PsiLanguageInjectionHost host = PsiTreeUtil.getParentOfType(at, PsiLanguageInjectionHost.class, false); if (host != null) { final Ref<Boolean> hasJsInjection = new Ref<Boolean>(Boolean.FALSE); InjectedLanguageUtil.enumerate( host, new JSResolveUtil.JSInjectedFilesVisitor() { @Override protected void process(final JSFile file) { hasJsInjection.set(Boolean.TRUE); } }); if (hasJsInjection.get()) { language = JavaScriptSupportLoader.JAVASCRIPT.getLanguage(); } } } return language != null && language.isKindOf(JavaScriptSupportLoader.JAVASCRIPT.getLanguage()); }
@Nullable public static Commenter getCommenter( final PsiFile file, final Editor editor, final Language lineStartLanguage, final Language lineEndLanguage) { final FileViewProvider viewProvider = file.getViewProvider(); for (MultipleLangCommentProvider provider : MultipleLangCommentProvider.EP_NAME.getExtensions()) { if (provider.canProcess(file, viewProvider)) { return provider.getLineCommenter(file, editor, lineStartLanguage, lineEndLanguage); } } final Language fileLanguage = file.getLanguage(); Language lang = lineStartLanguage == null || LanguageCommenters.INSTANCE.forLanguage(lineStartLanguage) == null || fileLanguage.getBaseLanguage() == lineStartLanguage // file language is a more specific dialect of the line // language ? fileLanguage : lineStartLanguage; if (viewProvider instanceof TemplateLanguageFileViewProvider && lang == ((TemplateLanguageFileViewProvider) viewProvider).getTemplateDataLanguage()) { lang = viewProvider.getBaseLanguage(); } return LanguageCommenters.INSTANCE.forLanguage(lang); }
public static void invokeImpl( Project project, Editor editor, final PsiFile file, Injectable injectable) { final PsiLanguageInjectionHost host = findInjectionHost(editor, file); if (host == null) return; if (defaultFunctionalityWorked(host, injectable.getId())) return; try { host.putUserData(FIX_KEY, null); Language language = injectable.toLanguage(); for (LanguageInjectionSupport support : InjectorUtils.getActiveInjectionSupports()) { if (support.isApplicableTo(host) && support.addInjectionInPlace(language, host)) { return; } } if (TemporaryPlacesRegistry.getInstance(project) .getLanguageInjectionSupport() .addInjectionInPlace(language, host)) { final Processor<PsiLanguageInjectionHost> data = host.getUserData(FIX_KEY); String text = StringUtil.escapeXml(language.getDisplayName()) + " was temporarily injected."; if (data != null) { if (!ApplicationManager.getApplication().isUnitTestMode()) { final SmartPsiElementPointer<PsiLanguageInjectionHost> pointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(host); final TextRange range = host.getTextRange(); HintManager.getInstance() .showQuestionHint( editor, text + "<br>Do you want to insert annotation? " + KeymapUtil.getFirstKeyboardShortcutText( ActionManager.getInstance() .getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS)), range.getStartOffset(), range.getEndOffset(), new QuestionAction() { @Override public boolean execute() { return data.process(pointer.getElement()); } }); } } else { HintManager.getInstance().showInformationHint(editor, text); } } } finally { if (injectable.getLanguage() != null) { // no need for reference injection FileContentUtil.reparseFiles(project, Collections.<VirtualFile>emptyList(), true); } else { ((PsiModificationTrackerImpl) PsiManager.getInstance(project).getModificationTracker()) .incCounter(); DaemonCodeAnalyzer.getInstance(project).restart(); } } }
@Nullable public static Language findJavaOrLikeLanguage(@NotNull final PsiFile file) { final Set<Language> languages = file.getViewProvider().getLanguages(); for (final Language language : languages) { if (language == StdLanguages.JAVA) return language; } for (final Language language : languages) { if (language.isKindOf(StdLanguages.JAVA)) return language; } return null; }
public static void initState( ErrorState state, PsiBuilder builder, IElementType root, TokenSet[] extendsSets) { state.extendsSets = extendsSets; PsiFile file = builder.getUserDataUnprotected(FileContextUtil.CONTAINING_FILE_KEY); state.completionState = file == null ? null : file.getUserData(COMPLETION_STATE_KEY); Language language = file == null ? root.getLanguage() : file.getLanguage(); state.caseSensitive = language.isCaseSensitive(); PairedBraceMatcher matcher = LanguageBraceMatching.INSTANCE.forLanguage(language); state.braces = matcher == null ? null : matcher.getPairs(); if (state.braces != null && state.braces.length == 0) state.braces = null; }
@Nullable private static LanguageFileType substituteFileType( Language language, VirtualFile vFile, Project project) { LanguageFileType fileType = null; if (vFile != null && project != null) { Language substLanguage = LanguageSubstitutors.INSTANCE.substituteLanguage(language, vFile, project); if (substLanguage != language) { fileType = substLanguage.getAssociatedFileType(); } } return fileType; }
private static void initState(IElementType root, PsiBuilder builder, ErrorState state) { PsiFile file = builder.getUserDataUnprotected(FileContextUtil.CONTAINING_FILE_KEY); state.completionState = file == null ? null : file.getUserData(COMPLETION_STATE_KEY); Language language = file == null ? root.getLanguage() : file.getLanguage(); state.caseSensitive = language.isCaseSensitive(); ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(language); if (parserDefinition != null) { state.commentTokens = parserDefinition.getCommentTokens(); state.whitespaceTokens = parserDefinition.getWhitespaceTokens(); } PairedBraceMatcher matcher = LanguageBraceMatching.INSTANCE.forLanguage(language); state.braces = matcher == null ? null : matcher.getPairs(); if (state.braces != null && state.braces.length == 0) state.braces = null; }
private static boolean defaultFunctionalityWorked(final PsiLanguageInjectionHost host) { final THashSet<String> languages = new THashSet<String>(); final List<Pair<PsiElement, TextRange>> files = InjectedLanguageUtil.getInjectedPsiFiles(host); if (files == null) return false; for (Pair<PsiElement, TextRange> pair : files) { for (Language lang = pair.first.getLanguage(); lang != null; lang = lang.getBaseLanguage()) { languages.add(lang.getID()); } } // todo there is a problem: host i.e. literal expression is confused with "target" i.e. // parameter // todo therefore this part doesn't work for java return Configuration.getInstance().setHostInjectionEnabled(host, languages, false); }
@Nullable protected DaemonCodeAnalyzerStatus getDaemonCodeAnalyzerStatus( boolean fillErrorsCount, SeverityRegistrar severityRegistrar) { if (myFile == null || myProject.isDisposed() || !myDaemonCodeAnalyzer.isHighlightingAvailable(myFile)) return null; List<String> noInspectionRoots = new ArrayList<String>(); List<String> noHighlightingRoots = new ArrayList<String>(); FileViewProvider provider = myFile.getViewProvider(); Set<Language> languages = provider.getLanguages(); for (Language language : languages) { PsiFile root = provider.getPsi(language); if (!HighlightLevelUtil.shouldHighlight(root)) { noHighlightingRoots.add(language.getID()); } else if (!HighlightLevelUtil.shouldInspect(root)) { noInspectionRoots.add(language.getID()); } } DaemonCodeAnalyzerStatus status = new DaemonCodeAnalyzerStatus(); status.noInspectionRoots = noInspectionRoots.isEmpty() ? null : ArrayUtil.toStringArray(noInspectionRoots); status.noHighlightingRoots = noHighlightingRoots.isEmpty() ? null : ArrayUtil.toStringArray(noHighlightingRoots); status.errorCount = errorCount.clone(); status.rootsNumber = languages.size(); fillDaemonCodeAnalyzerErrorsStatus(status, fillErrorsCount, severityRegistrar); List<TextEditorHighlightingPass> passes = myDaemonCodeAnalyzer.getPassesToShowProgressFor(myDocument); status.passStati = passes.isEmpty() ? Collections.<ProgressableTextEditorHighlightingPass>emptyList() : new ArrayList<ProgressableTextEditorHighlightingPass>(passes.size()); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < passes.size(); i++) { TextEditorHighlightingPass tepass = passes.get(i); if (!(tepass instanceof ProgressableTextEditorHighlightingPass)) continue; ProgressableTextEditorHighlightingPass pass = (ProgressableTextEditorHighlightingPass) tepass; if (pass.getProgress() < 0) continue; status.passStati.add(pass); } status.errorAnalyzingFinished = myDaemonCodeAnalyzer.isAllAnalysisFinished(myFile); status.enabled = myDaemonCodeAnalyzer.isUpdateByTimerEnabled(); return status; }
@Override public int hashCode() { return ((31 * myVirtualFile.hashCode() + myIndex) * 31 + (myElementType == null ? 0 : myElementType.hashCode())) * 31 + myLanguage.hashCode(); }
/** Created by Michal on 18.11.2015. */ public class VaadinDesignParserDefinition implements ParserDefinition { public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE); public static final TokenSet STRING_LITERALS = TokenSet.create(VDTypes.ATTR_VALUE); // public static final TokenSet COMMENTS = TokenSet.create(SimpleTypes.COMMENT); public static final IFileElementType FILE = new IFileElementType( Language.<VaadinDeclarativeLanguage>findInstance(VaadinDeclarativeLanguage.class)); @NotNull @Override public Lexer createLexer(Project project) { return new FlexAdapter(new VaadinDesignLexer(null)); } @Override public PsiParser createParser(Project project) { return new VaadinDesignParser(); } @Override public IFileElementType getFileNodeType() { return FILE; } @NotNull @Override public TokenSet getWhitespaceTokens() { return WHITE_SPACES; } @NotNull @Override public TokenSet getCommentTokens() { return TokenSet.EMPTY; } @NotNull @Override public TokenSet getStringLiteralElements() { return STRING_LITERALS; } @NotNull @Override public PsiElement createElement(ASTNode node) { return VDTypes.Factory.createElement(node); } @Override public PsiFile createFile(FileViewProvider viewProvider) { return new VaadinDesignFile(viewProvider); } @Override public SpaceRequirements spaceExistanceTypeBetweenTokens(ASTNode left, ASTNode right) { return SpaceRequirements.MAY; } }
@Nullable private String verifyInnerClassDestination() { PsiClass targetClass = findTargetClass(); if (targetClass == null) return null; for (PsiElement element : myElementsToMove) { if (PsiTreeUtil.isAncestor(element, targetClass, false)) { return RefactoringBundle.message("move.class.to.inner.move.to.self.error"); } final Language targetClassLanguage = targetClass.getLanguage(); if (!element.getLanguage().equals(targetClassLanguage)) { return RefactoringBundle.message( "move.to.different.language", UsageViewUtil.getType(element), ((PsiClass) element).getQualifiedName(), targetClass.getQualifiedName()); } if (element.getLanguage().equals(Language.findLanguageByID("Groovy"))) { return RefactoringBundle.message("dont.support.inner.classes", "Groovy"); } } while (targetClass != null) { if (targetClass.getContainingClass() != null && !targetClass.hasModifierProperty(PsiModifier.STATIC)) { return RefactoringBundle.message("move.class.to.inner.nonstatic.error"); } targetClass = targetClass.getContainingClass(); } return null; }
@Nullable public PsiElement findElementAt(int offset, Class<? extends Language> lang) { final PsiFile mainRoot = getPsi(getBaseLanguage()); PsiElement ret = null; for (final Language language : getLanguages()) { if (!ReflectionCache.isAssignable(lang, language.getClass())) continue; if (lang.equals(Language.class) && !getLanguages().contains(language)) continue; final PsiFile psiRoot = getPsi(language); final PsiElement psiElement = findElementAt(psiRoot, offset); if (psiElement == null || psiElement instanceof OuterLanguageElement) continue; if (ret == null || psiRoot != mainRoot) { ret = psiElement; } } return ret; }
public void injectAll(Disposable parent) { injectVariousStuffEverywhere(parent, myPsiManager); Project project = myPsiManager.getProject(); Language ql = Language.findLanguageByID("JPAQL"); Language js = Language.findLanguageByID("JavaScript"); registerForStringVarInitializer(parent, project, ql, "ql", null, null); registerForStringVarInitializer(parent, project, ql, "qlPrefixed", "xxx", null); registerForStringVarInitializer(parent, project, js, "js", null, null); registerForStringVarInitializer(parent, project, js, "jsSeparated", " + ", " + 'separator'"); registerForStringVarInitializer(parent, project, js, "jsBrokenPrefix", "xx ", ""); registerForStringVarInitializer( parent, project, Language.findLanguageByID("Oracle"), "oracle", null, null); registerForParameterValue(parent, project, Language.findLanguageByID("Groovy"), "groovy"); }
/** @author fernandohur */ public class EamlParserDefinition implements ParserDefinition { public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE); public static final IFileElementType FILE = new IFileElementType(Language.<EamlLanguage>findInstance(EamlLanguage.class)); @NotNull @Override public Lexer createLexer(final Project project) { return new EamlLexerAdapter(); } @NotNull @Override public TokenSet getWhitespaceTokens() { return WHITE_SPACES; } @NotNull @Override public TokenSet getCommentTokens() { return TokenSet.EMPTY; } @NotNull @Override public TokenSet getStringLiteralElements() { return TokenSet.EMPTY; } @Override public PsiParser createParser(final Project project) { return new EamlParser(); } @Override public IFileElementType getFileNodeType() { return FILE; } @Override public PsiFile createFile(final FileViewProvider fileViewProvider) { return new EamlFile(fileViewProvider); } @Override public SpaceRequirements spaceExistanceTypeBetweenTokens( final ASTNode astNode, final ASTNode astNode1) { return SpaceRequirements.MAY; } @NotNull @Override public PsiElement createElement(final ASTNode astNode) { return EamlTypes.Factory.createElement(astNode); } }
@NotNull public static FileType substituteFileType( VirtualFile file, @NotNull 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); } } return fileType; }
@Nullable private static FileType getFileType(final Language language) { final FileType[] fileTypes = FileTypeManager.getInstance().getRegisteredFileTypes(); for (FileType fileType : fileTypes) { if (fileType instanceof LanguageFileType && language.equals(((LanguageFileType) fileType).getLanguage())) return fileType; } return null; }
@Override public boolean containsWhiteSpaceSymbolsOnly(int startOffset, int endOffset) { WhiteSpaceFormattingStrategy strategy = myWhiteSpaceStrategy; if (strategy.check(myDocument.getCharsSequence(), startOffset, endOffset) >= endOffset) { return true; } PsiElement injectedElement = myFile != null ? InjectedLanguageUtil.findElementAtNoCommit(myFile, startOffset) : null; if (injectedElement != null) { Language injectedLanguage = injectedElement.getLanguage(); if (!injectedLanguage.equals(myFile.getLanguage())) { WhiteSpaceFormattingStrategy localStrategy = WhiteSpaceFormattingStrategyFactory.getStrategy(injectedLanguage); if (localStrategy != null) { return localStrategy.check(myDocument.getCharsSequence(), startOffset, endOffset) >= endOffset; } } } return false; }
@Override protected EditorEx createEditor() { final EditorEx ex = super.createEditor(); if (myLanguage != null) { final FileType fileType = myLanguage.getAssociatedFileType(); ex.setHighlighter(HighlighterFactory.createHighlighter(myProject, fileType)); } ex.setEmbeddedIntoDialogWrapper(true); return ex; }
public class PerlParserDefinition implements ParserDefinition { public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE); public static final TokenSet COMMENT = TokenSet.create(PerlTypes.COMMENT); public static final TokenSet LITERAL = TokenSet.create(PerlTypes.LITERAL); public static final IFileElementType FILE = new IFileElementType(Language.<PerlLanguage>findInstance(PerlLanguage.class)); @NotNull @Override public Lexer createLexer(Project project) { return new FlexAdapter(new PerlLexer((Reader) null)); } @NotNull public TokenSet getWhitespaceTokens() { return WHITE_SPACES; } @NotNull public TokenSet getCommentTokens() { return COMMENT; } @NotNull public TokenSet getStringLiteralElements() { return LITERAL; } @NotNull public PsiParser createParser(final Project project) { return new PerlParser(); } @Override public IFileElementType getFileNodeType() { return FILE; } public PsiFile createFile(FileViewProvider viewProvider) { return new PerlFile(viewProvider); } public SpaceRequirements spaceExistanceTypeBetweenTokens(ASTNode left, ASTNode right) { return SpaceRequirements.MAY; } @NotNull public PsiElement createElement(ASTNode node) { return PerlTypes.Factory.createElement(node); } }
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PsiFileReference)) return false; PsiFileReference reference = (PsiFileReference) o; if (!myFile.equals(reference.myFile)) return false; if (!myLanguage.equals(reference.myLanguage)) return false; if (!myProject.equals(reference.myProject)) return false; return true; }
private void layoutVertical(final JPanel panel) { for (Language language : mySliders.keySet()) { JSlider slider = mySliders.get(language); JPanel borderPanel = new JPanel(new BorderLayout()); slider.setPreferredSize(new Dimension(100, 100)); borderPanel.add(new JLabel(language.getID()), BorderLayout.NORTH); borderPanel.add(slider, BorderLayout.CENTER); panel.add( borderPanel, new GridBagConstraints( GridBagConstraints.RELATIVE, 1, 1, 1, 0, 1, GridBagConstraints.CENTER, GridBagConstraints.VERTICAL, new Insets(0, 5, 0, 5), 0, 0)); } }
@Override public FoldingBuilder forLanguage(Language l) { FoldingBuilder cached = l.getUserData(getLanguageCache()); if (cached != null) return cached; List<FoldingBuilder> extensions = forKey(l); FoldingBuilder result; if (extensions.isEmpty()) { Language base = l.getBaseLanguage(); if (base != null) { result = forLanguage(base); } else { result = getDefaultImplementation(); } } else { return (extensions.size() == 1) ? extensions.get(0) : myBuilder == null ? myBuilder = new CompositeFoldingBuilder(extensions) : myBuilder; } l.putUserData(getLanguageCache(), result); return result; }
public LanguageTextField( @Nullable Language language, @Nullable Project project, @NotNull String value, @NotNull DocumentCreator documentCreator, boolean oneLineMode) { super( documentCreator.createDocument(value, language, project), project, language != null ? language.getAssociatedFileType() : StdFileTypes.PLAIN_TEXT, language == null, oneLineMode); myLanguage = language; myProject = project; setEnabled(language != null); }
private static List<LanguageDefinition> collectLibraryLanguages( final ConvertContext context, final Collection<PsiClass> allLanguages) { return ContainerUtil.mapNotNull( Language.getRegisteredLanguages(), (NullableFunction<Language, LanguageDefinition>) language -> { if (language.getID().isEmpty() || language instanceof DependentLanguage) { return null; } final PsiClass psiClass = DomJavaUtil.findClass( language.getClass().getName(), context.getInvocationElement(), true); if (psiClass == null || !allLanguages.contains(psiClass)) { return null; } final LanguageFileType type = language.getAssociatedFileType(); final Icon icon = type != null ? type.getIcon() : null; return new LanguageDefinition( language.getID(), psiClass, icon, language.getDisplayName()); }); }
private static Document createDocument( String value, @Nullable Language language, Project project, @NotNull SimpleDocumentCreator documentCreator) { if (language != null) { final PsiFileFactory factory = PsiFileFactory.getInstance(project); final FileType fileType = language.getAssociatedFileType(); assert fileType != null; final long stamp = LocalTimeCounter.currentTime(); final PsiFile psiFile = factory.createFileFromText( "Dummy." + fileType.getDefaultExtension(), fileType, value, stamp, true, false); documentCreator.customizePsiFile(psiFile); final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile); assert document != null; return document; } else { return EditorFactory.getInstance().createDocument(value); } }
/** * This method searches ast node that could be reparsed incrementally and returns pair of target * reparseable node and new replacement node. Returns null if there is no any chance to make * incremental parsing. */ @Nullable public Couple<ASTNode> findReparseableRoots( @NotNull PsiFileImpl file, @NotNull TextRange changedPsiRange, @NotNull CharSequence newFileText) { Project project = file.getProject(); final FileElement fileElement = file.getTreeElement(); final CharTable charTable = fileElement.getCharTable(); int lengthShift = newFileText.length() - fileElement.getTextLength(); if (fileElement.getElementType() instanceof ITemplateDataElementType || isTooDeep(file)) { // unable to perform incremental reparse for template data in JSP, or in exceptionally deep // trees return null; } final ASTNode leafAtStart = fileElement.findLeafElementAt(Math.max(0, changedPsiRange.getStartOffset() - 1)); final ASTNode leafAtEnd = fileElement.findLeafElementAt( Math.min(changedPsiRange.getEndOffset(), fileElement.getTextLength() - 1)); ASTNode node = leafAtStart != null && leafAtEnd != null ? TreeUtil.findCommonParent(leafAtStart, leafAtEnd) : fileElement; Language baseLanguage = file.getViewProvider().getBaseLanguage(); while (node != null && !(node instanceof FileElement)) { IElementType elementType = node.getElementType(); if (elementType instanceof IReparseableElementType) { final TextRange textRange = node.getTextRange(); final IReparseableElementType reparseable = (IReparseableElementType) elementType; if (baseLanguage.isKindOf(reparseable.getLanguage()) && textRange.getLength() + lengthShift > 0) { final int start = textRange.getStartOffset(); final int end = start + textRange.getLength() + lengthShift; if (end > newFileText.length()) { reportInconsistentLength(file, newFileText, node, start, end); break; } CharSequence newTextStr = newFileText.subSequence(start, end); if (reparseable.isParsable(node.getTreeParent(), newTextStr, baseLanguage, project)) { ASTNode chameleon = reparseable.createNode(newTextStr); if (chameleon != null) { DummyHolder holder = DummyHolderFactory.createHolder( file.getManager(), null, node.getPsi(), charTable); holder.getTreeElement().rawAddChildren((TreeElement) chameleon); if (holder.getTextLength() != newTextStr.length()) { String details = ApplicationManager.getApplication().isInternal() ? "text=" + newTextStr + "; treeText=" + holder.getText() + ";" : ""; LOG.error("Inconsistent reparse: " + details + " type=" + elementType); } return Couple.of(node, chameleon); } } } } node = node.getTreeParent(); } return null; }
public HaskellPsiFileImpl( @NotNull FileViewProvider viewProvider, @NotNull HaskellFileType fileType) { super(viewProvider, Language.findInstance(HaskellLanguage.class)); this.fileType = fileType; }
public Language getLanguageById() { return Language.findLanguageByID(myLanguage); }