Search in sources :

Example 1 with EditorWindow

use of com.intellij.injected.editor.EditorWindow in project intellij-community by JetBrains.

the class PythonConsoleView method addTextRangeToHistory.

@NotNull
protected String addTextRangeToHistory(@NotNull TextRange textRange, @NotNull EditorEx inputEditor, boolean preserveMarkup) {
    String text;
    EditorHighlighter highlighter;
    if (inputEditor instanceof EditorWindow) {
        PsiFile file = ((EditorWindow) inputEditor).getInjectedFile();
        highlighter = HighlighterFactory.createHighlighter(file.getVirtualFile(), EditorColorsManager.getInstance().getGlobalScheme(), getProject());
        String fullText = InjectedLanguageUtil.getUnescapedText(file, null, null);
        highlighter.setText(fullText);
        text = textRange.substring(fullText);
    } else {
        text = inputEditor.getDocument().getText(textRange);
        highlighter = inputEditor.getHighlighter();
    }
    SyntaxHighlighter syntax = highlighter instanceof LexerEditorHighlighter ? ((LexerEditorHighlighter) highlighter).getSyntaxHighlighter() : null;
    doAddPromptToHistory(true);
    if (syntax != null) {
        ConsoleViewUtil.printWithHighlighting(this, text, syntax, () -> doAddPromptToHistory(false));
    } else {
        print(text, ConsoleViewContentType.USER_INPUT);
    }
    print("\n", ConsoleViewContentType.NORMAL_OUTPUT);
    return text;
}
Also used : PsiFile(com.intellij.psi.PsiFile) SyntaxHighlighter(com.intellij.openapi.fileTypes.SyntaxHighlighter) LexerEditorHighlighter(com.intellij.openapi.editor.ex.util.LexerEditorHighlighter) LexerEditorHighlighter(com.intellij.openapi.editor.ex.util.LexerEditorHighlighter) EditorHighlighter(com.intellij.openapi.editor.highlighter.EditorHighlighter) EditorWindow(com.intellij.injected.editor.EditorWindow) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with EditorWindow

use of com.intellij.injected.editor.EditorWindow in project intellij-community by JetBrains.

the class BaseIntroduceAction method extractFromExpression.

private void extractFromExpression(Editor e, final XPathExpression expression) {
    final Editor editor = (e instanceof EditorWindow) ? ((EditorWindow) e).getDelegate() : e;
    final HighlightManager highlightManager = HighlightManager.getInstance(expression.getProject());
    final Set<XPathExpression> matchingExpressions = RefactoringUtil.collectMatchingExpressions(expression);
    final List<XmlTag> otherMatches = new ArrayList<>(matchingExpressions.size());
    final ArrayList<RangeHighlighter> highlighters = new ArrayList<>(matchingExpressions.size() + 1);
    if (matchingExpressions.size() > 0) {
        final SelectionModel selectionModel = editor.getSelectionModel();
        highlightManager.addRangeHighlight(editor, selectionModel.getSelectionStart(), selectionModel.getSelectionEnd(), EditorColors.SEARCH_RESULT_ATTRIBUTES.getDefaultAttributes(), false, highlighters);
        for (XPathExpression expr : matchingExpressions) {
            final TextRange range = XsltCodeInsightUtil.getRangeInsideHostingFile(expr);
            highlightManager.addRangeHighlight(editor, range.getStartOffset(), range.getEndOffset(), EditorColors.SEARCH_RESULT_ATTRIBUTES.getDefaultAttributes(), false, highlighters);
            final XmlTag tag = PsiTreeUtil.getContextOfType(expr, XmlTag.class, true);
            assert tag != null;
            otherMatches.add(tag);
        }
    }
    final Settings dlg = getSettings(expression, matchingExpressions);
    if (dlg == null || dlg.isCanceled())
        return;
    if (getCommandName() != null) {
        new WriteCommandAction.Simple(e.getProject(), getCommandName()) {

            protected void run() throws Throwable {
                if (extractImpl(expression, matchingExpressions, otherMatches, dlg)) {
                    for (RangeHighlighter highlighter : highlighters) {
                        highlighter.dispose();
                    }
                }
            }
        }.execute();
    } else {
        extractImpl(expression, matchingExpressions, otherMatches, dlg);
    }
}
Also used : XPathExpression(org.intellij.lang.xpath.psi.XPathExpression) WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) HighlightManager(com.intellij.codeInsight.highlighting.HighlightManager) ArrayList(java.util.ArrayList) TextRange(com.intellij.openapi.util.TextRange) EditorWindow(com.intellij.injected.editor.EditorWindow) RangeHighlighter(com.intellij.openapi.editor.markup.RangeHighlighter) SelectionModel(com.intellij.openapi.editor.SelectionModel) Editor(com.intellij.openapi.editor.Editor) XmlTag(com.intellij.psi.xml.XmlTag)

Example 3 with EditorWindow

use of com.intellij.injected.editor.EditorWindow in project intellij-community by JetBrains.

the class VariableInlineHandler method invoke.

public static void invoke(@NotNull final XPathVariable variable, Editor editor) {
    final String type = LanguageFindUsages.INSTANCE.forLanguage(variable.getLanguage()).getType(variable);
    final Project project = variable.getProject();
    final XmlTag tag = ((XsltElement) variable).getTag();
    final String expression = tag.getAttributeValue("select");
    if (expression == null) {
        CommonRefactoringUtil.showErrorHint(project, editor, MessageFormat.format("{0} ''{1}'' has no value.", StringUtil.capitalize(type), variable.getName()), TITLE, null);
        return;
    }
    final Collection<PsiReference> references = ReferencesSearch.search(variable, new LocalSearchScope(tag.getParentTag()), false).findAll();
    if (references.size() == 0) {
        CommonRefactoringUtil.showErrorHint(project, editor, MessageFormat.format("{0} ''{1}'' is never used.", variable.getName()), TITLE, null);
        return;
    }
    boolean hasExternalRefs = false;
    if (XsltSupport.isTopLevelElement(tag)) {
        final Query<PsiReference> query = ReferencesSearch.search(variable, GlobalSearchScope.allScope(project), false);
        hasExternalRefs = !query.forEach(new Processor<PsiReference>() {

            int allRefs = 0;

            public boolean process(PsiReference psiReference) {
                if (++allRefs > references.size()) {
                    return false;
                } else if (!references.contains(psiReference)) {
                    return false;
                }
                return true;
            }
        });
    }
    final HighlightManager highlighter = HighlightManager.getInstance(project);
    final ArrayList<RangeHighlighter> highlighters = new ArrayList<>();
    final PsiReference[] psiReferences = references.toArray(new PsiReference[references.size()]);
    TextRange[] ranges = ContainerUtil.map2Array(psiReferences, TextRange.class, s -> {
        final PsiElement psiElement = s.getElement();
        final XmlAttributeValue context = PsiTreeUtil.getContextOfType(psiElement, XmlAttributeValue.class, true);
        if (psiElement instanceof XPathElement && context != null) {
            return XsltCodeInsightUtil.getRangeInsideHostingFile((XPathElement) psiElement).cutOut(s.getRangeInElement());
        }
        return psiElement.getTextRange().cutOut(s.getRangeInElement());
    });
    final Editor e = editor instanceof EditorWindow ? ((EditorWindow) editor).getDelegate() : editor;
    for (TextRange range : ranges) {
        final TextAttributes textAttributes = EditorColors.SEARCH_RESULT_ATTRIBUTES.getDefaultAttributes();
        final Color color = getScrollmarkColor(textAttributes);
        highlighter.addOccurrenceHighlight(e, range.getStartOffset(), range.getEndOffset(), textAttributes, HighlightManagerImpl.HIDE_BY_ESCAPE, highlighters, color);
    }
    highlighter.addOccurrenceHighlights(e, new PsiElement[] { ((XsltVariable) variable).getNameIdentifier() }, EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES.getDefaultAttributes(), false, highlighters);
    if (!hasExternalRefs) {
        if (!ApplicationManager.getApplication().isUnitTestMode() && Messages.showYesNoDialog(MessageFormat.format("Inline {0} ''{1}''? ({2} occurrence{3})", type, variable.getName(), String.valueOf(references.size()), references.size() > 1 ? "s" : ""), TITLE, Messages.getQuestionIcon()) != Messages.YES) {
            return;
        }
    } else {
        if (!ApplicationManager.getApplication().isUnitTestMode() && Messages.showYesNoDialog(MessageFormat.format("Inline {0} ''{1}''? ({2} local occurrence{3})\n" + "\nWarning: It is being used in external files. Its declaration will not be removed.", type, variable.getName(), String.valueOf(references.size()), references.size() > 1 ? "s" : ""), TITLE, Messages.getWarningIcon()) != Messages.YES) {
            return;
        }
    }
    final boolean hasRefs = hasExternalRefs;
    new WriteCommandAction.Simple(project, "XSLT.Inline", tag.getContainingFile()) {

        @Override
        protected void run() throws Throwable {
            try {
                for (PsiReference psiReference : references) {
                    final PsiElement element = psiReference.getElement();
                    if (element instanceof XPathElement) {
                        final XPathElement newExpr = XPathChangeUtil.createExpression(element, expression);
                        element.replace(newExpr);
                    } else {
                        assert false;
                    }
                }
                if (!hasRefs) {
                    tag.delete();
                }
            } catch (IncorrectOperationException e) {
                Logger.getInstance(VariableInlineHandler.class.getName()).error(e);
            }
        }
    }.execute();
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) XsltElement(org.intellij.lang.xpath.xslt.psi.XsltElement) ArrayList(java.util.ArrayList) RangeHighlighter(com.intellij.openapi.editor.markup.RangeHighlighter) TextAttributes(com.intellij.openapi.editor.markup.TextAttributes) PsiElement(com.intellij.psi.PsiElement) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) HighlightManager(com.intellij.codeInsight.highlighting.HighlightManager) PsiReference(com.intellij.psi.PsiReference) TextRange(com.intellij.openapi.util.TextRange) XmlAttributeValue(com.intellij.psi.xml.XmlAttributeValue) XPathElement(org.intellij.lang.xpath.psi.XPathElement) EditorWindow(com.intellij.injected.editor.EditorWindow) Project(com.intellij.openapi.project.Project) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor) XmlTag(com.intellij.psi.xml.XmlTag)

Example 4 with EditorWindow

use of com.intellij.injected.editor.EditorWindow in project intellij-community by JetBrains.

the class PythonEnterHandler method preprocessEnter.

@Override
public Result preprocessEnter(@NotNull PsiFile file, @NotNull Editor editor, @NotNull Ref<Integer> caretOffset, @NotNull Ref<Integer> caretAdvance, @NotNull DataContext dataContext, EditorActionHandler originalHandler) {
    int offset = caretOffset.get();
    if (editor instanceof EditorWindow) {
        file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
        editor = InjectedLanguageUtil.getTopLevelEditor(editor);
        offset = editor.getCaretModel().getOffset();
    }
    if (!(file instanceof PyFile)) {
        return Result.Continue;
    }
    final Boolean isSplitLine = DataManager.getInstance().loadFromDataContext(dataContext, SplitLineAction.SPLIT_LINE_KEY);
    if (isSplitLine != null) {
        return Result.Continue;
    }
    final Document doc = editor.getDocument();
    PsiDocumentManager.getInstance(file.getProject()).commitDocument(doc);
    final PsiElement element = file.findElementAt(offset);
    CodeInsightSettings codeInsightSettings = CodeInsightSettings.getInstance();
    if (codeInsightSettings.JAVADOC_STUB_ON_ENTER) {
        PsiElement comment = element;
        if (comment == null && offset != 0) {
            comment = file.findElementAt(offset - 1);
        }
        // """ or '''
        int expectedStringStart = editor.getCaretModel().getOffset() - 3;
        if (comment != null) {
            final DocstringState state = canGenerateDocstring(comment, expectedStringStart, doc);
            if (state != DocstringState.NONE) {
                insertDocStringStub(editor, comment, state);
                return Result.Continue;
            }
        }
    }
    if (element == null) {
        return Result.Continue;
    }
    PsiElement elementParent = element.getParent();
    if (element.getNode().getElementType() == PyTokenTypes.LPAR)
        elementParent = elementParent.getParent();
    if (elementParent instanceof PyParenthesizedExpression || elementParent instanceof PyGeneratorExpression)
        return Result.Continue;
    if (offset > 0 && !(PyTokenTypes.STRING_NODES.contains(element.getNode().getElementType()))) {
        final PsiElement prevElement = file.findElementAt(offset - 1);
        if (prevElement == element)
            return Result.Continue;
    }
    if (PyTokenTypes.TRIPLE_NODES.contains(element.getNode().getElementType()) || element.getNode().getElementType() == PyTokenTypes.DOCSTRING) {
        return Result.Continue;
    }
    final PsiElement prevElement = file.findElementAt(offset - 1);
    PyStringLiteralExpression string = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PyStringLiteralExpression.class, false);
    if (string != null && prevElement != null && PyTokenTypes.STRING_NODES.contains(prevElement.getNode().getElementType()) && string.getTextOffset() < offset && !(element.getNode() instanceof PsiWhiteSpace)) {
        final String stringText = element.getText();
        final int prefixLength = PyStringLiteralExpressionImpl.getPrefixLength(stringText);
        if (string.getTextOffset() + prefixLength >= offset) {
            return Result.Continue;
        }
        final String pref = element.getText().substring(0, prefixLength);
        final String quote = element.getText().substring(prefixLength, prefixLength + 1);
        final boolean nextIsBackslash = "\\".equals(doc.getText(TextRange.create(offset - 1, offset)));
        final boolean isEscapedQuote = quote.equals(doc.getText(TextRange.create(offset, offset + 1))) && nextIsBackslash;
        final boolean isEscapedBackslash = "\\".equals(doc.getText(TextRange.create(offset - 2, offset - 1))) && nextIsBackslash;
        if (nextIsBackslash && !isEscapedQuote && !isEscapedBackslash)
            return Result.Continue;
        final StringBuilder replacementString = new StringBuilder();
        myPostprocessShift = prefixLength + quote.length();
        if (PsiTreeUtil.getParentOfType(string, IMPLICIT_WRAP_CLASSES) != null) {
            replacementString.append(quote).append(pref).append(quote);
            doc.insertString(offset, replacementString);
            caretOffset.set(caretOffset.get() + 1);
            return Result.Continue;
        } else {
            if (isEscapedQuote) {
                replacementString.append(quote);
                caretOffset.set(caretOffset.get() + 1);
            }
            replacementString.append(quote).append(" \\").append(pref);
            if (!isEscapedQuote)
                replacementString.append(quote);
            doc.insertString(offset, replacementString.toString());
            caretOffset.set(caretOffset.get() + 3);
            return Result.Continue;
        }
    }
    if (!PyCodeInsightSettings.getInstance().INSERT_BACKSLASH_ON_WRAP) {
        return Result.Continue;
    }
    return checkInsertBackslash(file, caretOffset, dataContext, offset, doc);
}
Also used : PyCodeInsightSettings(com.jetbrains.python.codeInsight.PyCodeInsightSettings) CodeInsightSettings(com.intellij.codeInsight.CodeInsightSettings) Document(com.intellij.openapi.editor.Document) EditorWindow(com.intellij.injected.editor.EditorWindow)

Example 5 with EditorWindow

use of com.intellij.injected.editor.EditorWindow in project intellij-community by JetBrains.

the class EditorUtil method disposeWithEditor.

public static void disposeWithEditor(@NotNull Editor editor, @NotNull Disposable disposable) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    if (Disposer.isDisposed(disposable))
        return;
    if (editor.isDisposed()) {
        Disposer.dispose(disposable);
        return;
    }
    // for injected editors disposal will happen only when host editor is disposed,
    // but this seems to be the best we can do (there are no notifications on disposal of injected editor)
    Editor hostEditor = editor instanceof EditorWindow ? ((EditorWindow) editor).getDelegate() : editor;
    EditorFactory.getInstance().addEditorFactoryListener(new EditorFactoryAdapter() {

        @Override
        public void editorReleased(@NotNull EditorFactoryEvent event) {
            if (event.getEditor() == hostEditor) {
                Disposer.dispose(disposable);
            }
        }
    }, disposable);
}
Also used : EditorFactoryAdapter(com.intellij.openapi.editor.event.EditorFactoryAdapter) EditorFactoryEvent(com.intellij.openapi.editor.event.EditorFactoryEvent) TextEditor(com.intellij.openapi.fileEditor.TextEditor) TextComponentEditor(com.intellij.openapi.editor.textarea.TextComponentEditor) FileEditor(com.intellij.openapi.fileEditor.FileEditor) EditorWindow(com.intellij.injected.editor.EditorWindow)

Aggregations

EditorWindow (com.intellij.injected.editor.EditorWindow)44 Editor (com.intellij.openapi.editor.Editor)15 TextRange (com.intellij.openapi.util.TextRange)10 Project (com.intellij.openapi.project.Project)9 Document (com.intellij.openapi.editor.Document)8 PsiFile (com.intellij.psi.PsiFile)8 NotNull (org.jetbrains.annotations.NotNull)8 PsiElement (com.intellij.psi.PsiElement)7 com.intellij.openapi.fileEditor (com.intellij.openapi.fileEditor)5 RangeHighlighter (com.intellij.openapi.editor.markup.RangeHighlighter)4 TemplateState (com.intellij.codeInsight.template.impl.TemplateState)3 EditorEx (com.intellij.openapi.editor.ex.EditorEx)3 LexerEditorHighlighter (com.intellij.openapi.editor.ex.util.LexerEditorHighlighter)3 EditorHighlighter (com.intellij.openapi.editor.highlighter.EditorHighlighter)3 ArrayList (java.util.ArrayList)3 HighlightManager (com.intellij.codeInsight.highlighting.HighlightManager)2 DocumentWindow (com.intellij.injected.editor.DocumentWindow)2 InjectedCaret (com.intellij.injected.editor.InjectedCaret)2 SimpleDataContext (com.intellij.openapi.actionSystem.impl.SimpleDataContext)2 WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)2