Search in sources :

Example 1 with AbstractFileType

use of com.intellij.openapi.fileTypes.impl.AbstractFileType in project intellij-community by JetBrains.

the class PluginAdvertiserEditorNotificationProvider method createNotificationPanel.

@Nullable
@Override
public EditorNotificationPanel createNotificationPanel(@NotNull VirtualFile file, @NotNull FileEditor fileEditor) {
    if (file.getFileType() != PlainTextFileType.INSTANCE && !(file.getFileType() instanceof AbstractFileType))
        return null;
    final String extension = file.getExtension();
    final String fileName = file.getName();
    if (extension != null && isIgnored("*." + extension) || isIgnored(fileName))
        return null;
    final PluginsAdvertiser.KnownExtensions knownExtensions = PluginsAdvertiser.loadExtensions();
    if (knownExtensions != null) {
        final EditorNotificationPanel panel = extension != null ? createPanel("*." + extension, knownExtensions) : null;
        if (panel != null) {
            return panel;
        }
        return createPanel(fileName, knownExtensions);
    }
    return null;
}
Also used : AbstractFileType(com.intellij.openapi.fileTypes.impl.AbstractFileType) EditorNotificationPanel(com.intellij.ui.EditorNotificationPanel) Nullable(org.jetbrains.annotations.Nullable)

Example 2 with AbstractFileType

use of com.intellij.openapi.fileTypes.impl.AbstractFileType in project intellij-community by JetBrains.

the class CommentByLineCommentHandler method findCommenter.

@Nullable
private static Commenter findCommenter(Editor editor, PsiFile file, final int line) {
    final FileType fileType = file.getFileType();
    if (fileType instanceof AbstractFileType) {
        return ((AbstractFileType) fileType).getCommenter();
    }
    Document document = editor.getDocument();
    int lineStartOffset = document.getLineStartOffset(line);
    int lineEndOffset = document.getLineEndOffset(line) - 1;
    final CharSequence charSequence = document.getCharsSequence();
    lineStartOffset = Math.max(0, CharArrayUtil.shiftForward(charSequence, lineStartOffset, " \t"));
    lineEndOffset = Math.max(0, CharArrayUtil.shiftBackward(charSequence, lineEndOffset < 0 ? 0 : lineEndOffset, " \t"));
    final Language lineStartLanguage = PsiUtilCore.getLanguageAtOffset(file, lineStartOffset);
    final Language lineEndLanguage = PsiUtilCore.getLanguageAtOffset(file, lineEndOffset);
    return CommentByBlockCommentHandler.getCommenter(file, editor, lineStartLanguage, lineEndLanguage);
}
Also used : AbstractFileType(com.intellij.openapi.fileTypes.impl.AbstractFileType) Language(com.intellij.lang.Language) FileType(com.intellij.openapi.fileTypes.FileType) AbstractFileType(com.intellij.openapi.fileTypes.impl.AbstractFileType) CustomSyntaxTableFileType(com.intellij.openapi.fileTypes.impl.CustomSyntaxTableFileType) Nullable(org.jetbrains.annotations.Nullable)

Example 3 with AbstractFileType

use of com.intellij.openapi.fileTypes.impl.AbstractFileType in project intellij-community by JetBrains.

the class CommentByBlockCommentHandler method findCommenter.

@Nullable
private static Commenter findCommenter(PsiFile file, Editor editor, Caret caret) {
    final FileType fileType = file.getFileType();
    if (fileType instanceof AbstractFileType) {
        return ((AbstractFileType) fileType).getCommenter();
    }
    Language lang = PsiUtilBase.getLanguageInEditor(caret, file.getProject());
    return getCommenter(file, editor, lang, lang);
}
Also used : AbstractFileType(com.intellij.openapi.fileTypes.impl.AbstractFileType) Language(com.intellij.lang.Language) FileType(com.intellij.openapi.fileTypes.FileType) AbstractFileType(com.intellij.openapi.fileTypes.impl.AbstractFileType) CustomSyntaxTableFileType(com.intellij.openapi.fileTypes.impl.CustomSyntaxTableFileType) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with AbstractFileType

use of com.intellij.openapi.fileTypes.impl.AbstractFileType in project intellij-community by JetBrains.

the class FindManagerImpl method findInCommentsAndLiterals.

@NotNull
private FindResult findInCommentsAndLiterals(@NotNull CharSequence text, char[] textArray, int offset, @NotNull FindModel model, @NotNull final VirtualFile file) {
    synchronized (model) {
        FileType ftype = file.getFileType();
        Language lang = null;
        if (ftype instanceof LanguageFileType) {
            lang = ((LanguageFileType) ftype).getLanguage();
        }
        CommentsLiteralsSearchData data = model.getUserData(ourCommentsLiteralsSearchDataKey);
        if (data == null || !Comparing.equal(data.lastFile, file) || !data.model.equals(model)) {
            SyntaxHighlighter highlighter = getHighlighter(file, lang);
            if (highlighter == null) {
                // no syntax highlighter -> no search
                return NOT_FOUND_RESULT;
            }
            TokenSet tokensOfInterest = TokenSet.EMPTY;
            Set<Language> relevantLanguages;
            if (lang != null) {
                final Language finalLang = lang;
                relevantLanguages = ApplicationManager.getApplication().runReadAction(new Computable<Set<Language>>() {

                    @Override
                    public Set<Language> compute() {
                        THashSet<Language> result = new THashSet<>();
                        FileViewProvider viewProvider = PsiManager.getInstance(myProject).findViewProvider(file);
                        if (viewProvider != null) {
                            result.addAll(viewProvider.getLanguages());
                        }
                        if (result.isEmpty()) {
                            result.add(finalLang);
                        }
                        return result;
                    }
                });
                for (Language relevantLanguage : relevantLanguages) {
                    tokensOfInterest = addTokenTypesForLanguage(model, relevantLanguage, tokensOfInterest);
                }
                if (model.isInStringLiteralsOnly()) {
                    // TODO: xml does not have string literals defined so we add XmlAttributeValue element type as convenience
                    final Lexer xmlLexer = getHighlighter(null, Language.findLanguageByID("XML")).getHighlightingLexer();
                    final String marker = "xxx";
                    xmlLexer.start("<a href=\"" + marker + "\" />");
                    while (!marker.equals(xmlLexer.getTokenText())) {
                        xmlLexer.advance();
                        if (xmlLexer.getTokenType() == null)
                            break;
                    }
                    IElementType convenienceXmlAttrType = xmlLexer.getTokenType();
                    if (convenienceXmlAttrType != null) {
                        tokensOfInterest = TokenSet.orSet(tokensOfInterest, TokenSet.create(convenienceXmlAttrType));
                    }
                }
            } else {
                relevantLanguages = ContainerUtil.newHashSet();
                if (ftype instanceof AbstractFileType) {
                    if (model.isInCommentsOnly()) {
                        tokensOfInterest = TokenSet.create(CustomHighlighterTokenType.LINE_COMMENT, CustomHighlighterTokenType.MULTI_LINE_COMMENT);
                    }
                    if (model.isInStringLiteralsOnly()) {
                        tokensOfInterest = TokenSet.orSet(tokensOfInterest, TokenSet.create(CustomHighlighterTokenType.STRING, CustomHighlighterTokenType.SINGLE_QUOTED_STRING));
                    }
                }
            }
            Matcher matcher = model.isRegularExpressions() ? compileRegExp(model, "") : null;
            StringSearcher searcher = matcher != null ? null : new StringSearcher(model.getStringToFind(), model.isCaseSensitive(), true);
            SyntaxHighlighterOverEditorHighlighter highlighterAdapter = new SyntaxHighlighterOverEditorHighlighter(highlighter, file, myProject);
            data = new CommentsLiteralsSearchData(file, relevantLanguages, highlighterAdapter, tokensOfInterest, searcher, matcher, model.clone());
            data.highlighter.restart(text);
            model.putUserData(ourCommentsLiteralsSearchDataKey, data);
        }
        int initialStartOffset = model.isForward() && data.startOffset < offset ? data.startOffset : 0;
        data.highlighter.resetPosition(initialStartOffset);
        final Lexer lexer = data.highlighter.getHighlightingLexer();
        IElementType tokenType;
        TokenSet tokens = data.tokensOfInterest;
        int lastGoodOffset = 0;
        boolean scanningForward = model.isForward();
        FindResultImpl prevFindResult = NOT_FOUND_RESULT;
        while ((tokenType = lexer.getTokenType()) != null) {
            if (lexer.getState() == 0)
                lastGoodOffset = lexer.getTokenStart();
            final TextAttributesKey[] keys = data.highlighter.getTokenHighlights(tokenType);
            if (tokens.contains(tokenType) || (model.isInStringLiteralsOnly() && ChunkExtractor.isHighlightedAsString(keys)) || (model.isInCommentsOnly() && ChunkExtractor.isHighlightedAsComment(keys))) {
                int start = lexer.getTokenStart();
                int end = lexer.getTokenEnd();
                if (model.isInStringLiteralsOnly()) {
                    // skip literal quotes itself from matching
                    char c = text.charAt(start);
                    if (c == '"' || c == '\'') {
                        while (start < end && c == text.charAt(start)) {
                            ++start;
                            if (c == text.charAt(end - 1) && start < end)
                                --end;
                        }
                    }
                }
                while (true) {
                    FindResultImpl findResult = null;
                    if (data.searcher != null) {
                        int matchStart = data.searcher.scan(text, textArray, start, end);
                        if (matchStart != -1 && matchStart >= start) {
                            final int matchEnd = matchStart + model.getStringToFind().length();
                            if (matchStart >= offset || !scanningForward)
                                findResult = new FindResultImpl(matchStart, matchEnd);
                            else {
                                start = matchEnd;
                                continue;
                            }
                        }
                    } else if (start <= end) {
                        data.matcher.reset(StringPattern.newBombedCharSequence(text.subSequence(start, end)));
                        if (data.matcher.find()) {
                            final int matchEnd = start + data.matcher.end();
                            int matchStart = start + data.matcher.start();
                            if (matchStart >= offset || !scanningForward) {
                                findResult = new FindResultImpl(matchStart, matchEnd);
                            } else {
                                int diff = 0;
                                if (start == end) {
                                    diff = scanningForward ? 1 : -1;
                                }
                                start = matchEnd + diff;
                                continue;
                            }
                        }
                    }
                    if (findResult != null) {
                        if (scanningForward) {
                            data.startOffset = lastGoodOffset;
                            return findResult;
                        } else {
                            if (findResult.getEndOffset() >= offset)
                                return prevFindResult;
                            prevFindResult = findResult;
                            start = findResult.getEndOffset();
                            continue;
                        }
                    }
                    break;
                }
            } else {
                Language tokenLang = tokenType.getLanguage();
                if (tokenLang != lang && tokenLang != Language.ANY && !data.relevantLanguages.contains(tokenLang)) {
                    tokens = addTokenTypesForLanguage(model, tokenLang, tokens);
                    data.tokensOfInterest = tokens;
                    data.relevantLanguages.add(tokenLang);
                }
            }
            lexer.advance();
        }
        return prevFindResult;
    }
}
Also used : AbstractFileType(com.intellij.openapi.fileTypes.impl.AbstractFileType) Matcher(java.util.regex.Matcher) TokenSet(com.intellij.psi.tree.TokenSet) TextAttributesKey(com.intellij.openapi.editor.colors.TextAttributesKey) THashSet(gnu.trove.THashSet) LightweightHint(com.intellij.ui.LightweightHint) IElementType(com.intellij.psi.tree.IElementType) Lexer(com.intellij.lexer.Lexer) Language(com.intellij.lang.Language) AbstractFileType(com.intellij.openapi.fileTypes.impl.AbstractFileType) SyntaxHighlighterOverEditorHighlighter(com.intellij.usages.impl.SyntaxHighlighterOverEditorHighlighter) Computable(com.intellij.openapi.util.Computable) StringSearcher(com.intellij.util.text.StringSearcher) NotNull(org.jetbrains.annotations.NotNull)

Example 5 with AbstractFileType

use of com.intellij.openapi.fileTypes.impl.AbstractFileType in project intellij-community by JetBrains.

the class PsiViewerDialog method init.

@Override
protected void init() {
    initMnemonics();
    initTree(myPsiTree);
    final TreeCellRenderer renderer = myPsiTree.getCellRenderer();
    myPsiTree.setCellRenderer(new TreeCellRenderer() {

        @Override
        public Component getTreeCellRendererComponent(@NotNull JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            final Component c = renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
            if (value instanceof DefaultMutableTreeNode) {
                final Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
                if (userObject instanceof ViewerNodeDescriptor) {
                    final Object element = ((ViewerNodeDescriptor) userObject).getElement();
                    if (c instanceof NodeRenderer) {
                        ((NodeRenderer) c).setToolTipText(element == null ? null : element.getClass().getName());
                    }
                    if (element instanceof PsiElement && FileContextUtil.getFileContext(((PsiElement) element).getContainingFile()) != null || element instanceof ViewerTreeStructure.Inject) {
                        final TextAttributes attr = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.INJECTED_LANGUAGE_FRAGMENT);
                        c.setBackground(attr.getBackgroundColor());
                    }
                }
            }
            return c;
        }
    });
    myPsiTreeBuilder = new ViewerTreeBuilder(myProject, myPsiTree);
    Disposer.register(getDisposable(), myPsiTreeBuilder);
    myPsiTree.addTreeSelectionListener(new MyPsiTreeSelectionListener());
    final GoToListener listener = new GoToListener();
    myRefs.addKeyListener(listener);
    myRefs.addMouseListener(listener);
    myRefs.getSelectionModel().addListSelectionListener(listener);
    myRefs.setCellRenderer(new DefaultListCellRenderer() {

        @Override
        public Component getListCellRendererComponent(@NotNull JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            final Component comp = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            try {
                if (resolve(index) == null) {
                    comp.setForeground(JBColor.RED);
                }
            } catch (IndexNotReadyException ignore) {
            }
            return comp;
        }
    });
    initTree(myBlockTree);
    myEditor.getSettings().setFoldingOutlineShown(false);
    myEditor.getDocument().addDocumentListener(myEditorListener);
    myEditor.getSelectionModel().addSelectionListener(myEditorListener);
    myEditor.getCaretModel().addCaretListener(myEditorListener);
    getPeer().getWindow().setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() {

        @Override
        public Component getInitialComponent(@NotNull Window window) {
            return myEditor.getComponent();
        }
    });
    PsiViewerSettings settings = PsiViewerSettings.getSettings();
    VirtualFile file = myExternalDocument ? FileDocumentManager.getInstance().getFile(myEditor.getDocument()) : null;
    Language curLanguage = LanguageUtil.getLanguageForPsi(myProject, file);
    String type = curLanguage != null ? curLanguage.getDisplayName() : settings.type;
    SourceWrapper lastUsed = null;
    for (PsiViewerExtension extension : Extensions.getExtensions(PsiViewerExtension.EP_NAME)) {
        SourceWrapper wrapper = new SourceWrapper(extension);
        mySourceWrappers.add(wrapper);
    }
    Set<FileType> allFileTypes = ContainerUtil.newHashSet();
    Collections.addAll(allFileTypes, FileTypeManager.getInstance().getRegisteredFileTypes());
    for (Language language : Language.getRegisteredLanguages()) {
        FileType fileType = language.getAssociatedFileType();
        if (fileType != null) {
            allFileTypes.add(fileType);
        }
    }
    for (FileType fileType : allFileTypes) {
        if (fileType != StdFileTypes.GUI_DESIGNER_FORM && fileType != StdFileTypes.IDEA_MODULE && fileType != StdFileTypes.IDEA_PROJECT && fileType != StdFileTypes.IDEA_WORKSPACE && fileType != FileTypes.ARCHIVE && fileType != FileTypes.UNKNOWN && fileType != FileTypes.PLAIN_TEXT && !(fileType instanceof AbstractFileType) && !fileType.isBinary() && !fileType.isReadOnly()) {
            final SourceWrapper wrapper = new SourceWrapper(fileType);
            mySourceWrappers.add(wrapper);
            if (lastUsed == null && wrapper.getText().equals(type))
                lastUsed = wrapper;
            if (curLanguage != null && wrapper.myFileType == curLanguage.getAssociatedFileType()) {
                lastUsed = wrapper;
            }
        }
    }
    myFileTypeComboBox.setModel(new CollectionComboBoxModel<>(ContainerUtil.newArrayList(mySourceWrappers), lastUsed));
    myFileTypeComboBox.setRenderer(new ListCellRendererWrapper<SourceWrapper>() {

        @Override
        public void customize(JList list, SourceWrapper value, int index, boolean selected, boolean hasFocus) {
            if (value != null) {
                setText(value.getText());
                setIcon(value.getIcon());
            }
        }
    });
    new ComboboxSpeedSearch(myFileTypeComboBox) {

        @Override
        protected String getElementText(Object element) {
            return element instanceof SourceWrapper ? ((SourceWrapper) element).getText() : null;
        }
    };
    myFileTypeComboBox.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(@NotNull ActionEvent e) {
            updateDialectsCombo(null);
            updateExtensionsCombo();
            updateEditor();
        }
    });
    myDialectComboBox.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(@NotNull ActionEvent e) {
            updateEditor();
        }
    });
    new ComboboxSpeedSearch(myDialectComboBox) {

        @Override
        protected String getElementText(Object element) {
            return element instanceof Language ? ((Language) element).getDisplayName() : "<default>";
        }
    };
    myFileTypeComboBox.addFocusListener(new AutoExpandFocusListener(myFileTypeComboBox));
    if (!myExternalDocument && lastUsed == null && mySourceWrappers.size() > 0) {
        myFileTypeComboBox.setSelectedIndex(0);
    }
    myDialectComboBox.setRenderer(new ListCellRendererWrapper<Language>() {

        @Override
        public void customize(final JList list, final Language value, final int index, final boolean selected, final boolean hasFocus) {
            setText(value != null ? value.getDisplayName() : "<default>");
        }
    });
    myDialectComboBox.addFocusListener(new AutoExpandFocusListener(myDialectComboBox));
    myExtensionComboBox.setRenderer(new ListCellRendererWrapper<String>() {

        @Override
        public void customize(JList list, String value, int index, boolean selected, boolean hasFocus) {
            if (value != null)
                setText("." + value);
        }
    });
    myExtensionComboBox.addFocusListener(new AutoExpandFocusListener(myExtensionComboBox));
    final ViewerTreeStructure psiTreeStructure = getTreeStructure();
    myShowWhiteSpacesBox.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(@NotNull ActionEvent e) {
            psiTreeStructure.setShowWhiteSpaces(myShowWhiteSpacesBox.isSelected());
            myPsiTreeBuilder.queueUpdate();
        }
    });
    myShowTreeNodesCheckBox.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(@NotNull ActionEvent e) {
            psiTreeStructure.setShowTreeNodes(myShowTreeNodesCheckBox.isSelected());
            myPsiTreeBuilder.queueUpdate();
        }
    });
    myShowWhiteSpacesBox.setSelected(settings.showWhiteSpaces);
    psiTreeStructure.setShowWhiteSpaces(settings.showWhiteSpaces);
    myShowTreeNodesCheckBox.setSelected(settings.showTreeNodes);
    psiTreeStructure.setShowTreeNodes(settings.showTreeNodes);
    myShowBlocksCheckBox.setSelected(settings.showBlocks);
    myBlockStructurePanel.setVisible(settings.showBlocks);
    myShowBlocksCheckBox.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(@NotNull ActionEvent e) {
            if (!myShowBlocksCheckBox.isSelected()) {
                settings.blockRefDividerLocation = myBlockRefSplitPane.getDividerLocation();
            } else {
                myBlockRefSplitPane.setDividerLocation(settings.blockRefDividerLocation);
            }
            myBlockStructurePanel.setVisible(myShowBlocksCheckBox.isSelected());
            myBlockStructurePanel.repaint();
        }
    });
    myTextPanel.setLayout(new BorderLayout());
    myTextPanel.add(myEditor.getComponent(), BorderLayout.CENTER);
    updateDialectsCombo(settings.dialect);
    updateExtensionsCombo();
    registerCustomKeyboardActions();
    final Dimension size = DimensionService.getInstance().getSize(getDimensionServiceKey(), myProject);
    if (size == null) {
        DimensionService.getInstance().setSize(getDimensionServiceKey(), JBUI.size(800, 600));
    }
    myTextSplit.setDividerLocation(settings.textDividerLocation);
    myTreeSplit.setDividerLocation(settings.treeDividerLocation);
    myBlockRefSplitPane.setDividerLocation(settings.blockRefDividerLocation);
    updateEditor();
    super.init();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) LightVirtualFile(com.intellij.testFramework.LightVirtualFile) AbstractFileType(com.intellij.openapi.fileTypes.impl.AbstractFileType) NodeRenderer(com.intellij.ide.util.treeView.NodeRenderer) Language(com.intellij.lang.Language) AbstractFileType(com.intellij.openapi.fileTypes.impl.AbstractFileType) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException)

Aggregations

AbstractFileType (com.intellij.openapi.fileTypes.impl.AbstractFileType)8 FileType (com.intellij.openapi.fileTypes.FileType)5 Language (com.intellij.lang.Language)4 Nullable (org.jetbrains.annotations.Nullable)3 CustomSyntaxTableFileType (com.intellij.openapi.fileTypes.impl.CustomSyntaxTableFileType)2 NodeRenderer (com.intellij.ide.util.treeView.NodeRenderer)1 Commenter (com.intellij.lang.Commenter)1 Lexer (com.intellij.lexer.Lexer)1 TextAttributesKey (com.intellij.openapi.editor.colors.TextAttributesKey)1 IndexNotReadyException (com.intellij.openapi.project.IndexNotReadyException)1 Computable (com.intellij.openapi.util.Computable)1 VirtualFile (com.intellij.openapi.vfs.VirtualFile)1 PsiElement (com.intellij.psi.PsiElement)1 IElementType (com.intellij.psi.tree.IElementType)1 TokenSet (com.intellij.psi.tree.TokenSet)1 LightVirtualFile (com.intellij.testFramework.LightVirtualFile)1 EditorNotificationPanel (com.intellij.ui.EditorNotificationPanel)1 LightweightHint (com.intellij.ui.LightweightHint)1 SyntaxHighlighterOverEditorHighlighter (com.intellij.usages.impl.SyntaxHighlighterOverEditorHighlighter)1 StringSearcher (com.intellij.util.text.StringSearcher)1