Search in sources :

Example 1 with TemplateContextType

use of com.intellij.codeInsight.template.TemplateContextType in project intellij-community by JetBrains.

the class JsonLiveTemplateTest method createJsonTemplate.

@NotNull
private Template createJsonTemplate(@NotNull String name, @NotNull String group, @NotNull String text) {
    final TemplateManager templateManager = TemplateManager.getInstance(getProject());
    final Template template = templateManager.createTemplate(name, group, text);
    final TemplateContextType context = ContainerUtil.findInstance(TemplateContextType.EP_NAME.getExtensions(), JsonContextType.class);
    assertNotNull(context);
    ((TemplateImpl) template).getTemplateContext().setEnabled(context, true);
    CodeInsightTestUtil.addTemplate(template, myFixture.getTestRootDisposable());
    return template;
}
Also used : TemplateManager(com.intellij.codeInsight.template.TemplateManager) TemplateContextType(com.intellij.codeInsight.template.TemplateContextType) Template(com.intellij.codeInsight.template.Template) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with TemplateContextType

use of com.intellij.codeInsight.template.TemplateContextType in project intellij-community by JetBrains.

the class LiveTemplateSettingsEditor method createPopupContextPanel.

static JPanel createPopupContextPanel(final Runnable onChange, final TemplateContext context) {
    JPanel panel = new JPanel(new BorderLayout());
    MultiMap<TemplateContextType, TemplateContextType> hierarchy = MultiMap.createLinked();
    for (TemplateContextType type : TemplateManagerImpl.getAllContextTypes()) {
        hierarchy.putValue(type.getBaseContextType(), type);
    }
    final CheckedTreeNode root = new CheckedTreeNode(Pair.create(null, "Hi"));
    final CheckboxTree checkboxTree = new CheckboxTree(new CheckboxTree.CheckboxTreeCellRenderer() {

        @Override
        public void customizeRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            final Object o = ((DefaultMutableTreeNode) value).getUserObject();
            if (o instanceof Pair) {
                getTextRenderer().append((String) ((Pair) o).second);
            }
        }
    }, root) {

        @Override
        protected void onNodeStateChanged(CheckedTreeNode node) {
            final TemplateContextType type = (TemplateContextType) ((Pair) node.getUserObject()).first;
            if (type != null) {
                context.setEnabled(type, node.isChecked());
            }
            onChange.run();
        }
    };
    for (TemplateContextType type : hierarchy.get(null)) {
        addContextNode(hierarchy, root, type, context);
    }
    ((DefaultTreeModel) checkboxTree.getModel()).nodeStructureChanged(root);
    TreeUtil.traverse(root, _node -> {
        final CheckedTreeNode node = (CheckedTreeNode) _node;
        if (node.isChecked()) {
            final TreeNode[] path = node.getPath();
            if (path != null) {
                checkboxTree.expandPath(new TreePath(path).getParentPath());
            }
        }
        return true;
    });
    panel.add(ScrollPaneFactory.createScrollPane(checkboxTree));
    final Dimension size = checkboxTree.getPreferredSize();
    panel.setPreferredSize(new Dimension(size.width + 30, Math.min(size.height + 10, 500)));
    return panel;
}
Also used : DefaultTreeModel(javax.swing.tree.DefaultTreeModel) RelativePoint(com.intellij.ui.awt.RelativePoint) TreePath(javax.swing.tree.TreePath) TreeNode(javax.swing.tree.TreeNode) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) TemplateContextType(com.intellij.codeInsight.template.TemplateContextType) Pair(com.intellij.openapi.util.Pair)

Example 3 with TemplateContextType

use of com.intellij.codeInsight.template.TemplateContextType in project intellij-community by JetBrains.

the class TemplateContext method isValueChanged.

/**
   * Default value for GROOVY_STATEMENT is `true` (defined in the `plugins/groovy/groovy-psi/resources/liveTemplates/Groovy.xml`).
   * Base value is `false`.
   *
   * If default value is defined (as in our example) — we must not take base value in account.
   * Because on init `setDefaultContext` will be called and we will have own value.
   * Otherwise it will be not possible to set value for `GROOVY_STATEMENT` neither to `true` (equals to default), nor to `false` (equals to base).
   * See TemplateSchemeTest.
   */
private boolean isValueChanged(@NotNull Boolean ownValue, @NotNull TemplateContextType type, @Nullable TemplateContext defaultContext) {
    Boolean defaultValue = defaultContext == null ? null : defaultContext.getOwnValue(type);
    if (defaultValue == null) {
        TemplateContextType base = type.getBaseContextType();
        boolean baseEnabled = base != null && isEnabled(base);
        return ownValue != baseEnabled;
    }
    return !ownValue.equals(defaultValue);
}
Also used : TemplateContextType(com.intellij.codeInsight.template.TemplateContextType)

Example 4 with TemplateContextType

use of com.intellij.codeInsight.template.TemplateContextType in project intellij-community by JetBrains.

the class TemplateEditorUtil method setHighlighter.

public static void setHighlighter(Editor editor, @Nullable TemplateContext templateContext) {
    SyntaxHighlighter highlighter = null;
    if (templateContext != null) {
        for (TemplateContextType type : TemplateManagerImpl.getAllContextTypes()) {
            if (templateContext.isEnabled(type)) {
                highlighter = type.createHighlighter();
                if (highlighter != null)
                    break;
            }
        }
    }
    setHighlighter((EditorEx) editor, highlighter);
}
Also used : PlainSyntaxHighlighter(com.intellij.openapi.fileTypes.PlainSyntaxHighlighter) SyntaxHighlighter(com.intellij.openapi.fileTypes.SyntaxHighlighter) TemplateContextType(com.intellij.codeInsight.template.TemplateContextType)

Example 5 with TemplateContextType

use of com.intellij.codeInsight.template.TemplateContextType in project intellij-community by JetBrains.

the class SaveAsTemplateAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent e) {
    DataContext dataContext = e.getDataContext();
    Editor editor = Objects.requireNonNull(CommonDataKeys.EDITOR.getData(dataContext));
    PsiFile file = Objects.requireNonNull(CommonDataKeys.PSI_FILE.getData(dataContext));
    final Project project = file.getProject();
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    final TextRange selection = new TextRange(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd());
    PsiElement current = file.findElementAt(selection.getStartOffset());
    int startOffset = selection.getStartOffset();
    while (current instanceof PsiWhiteSpace) {
        current = current.getNextSibling();
        if (current == null)
            break;
        startOffset = current.getTextRange().getStartOffset();
    }
    if (startOffset >= selection.getEndOffset())
        startOffset = selection.getStartOffset();
    final PsiElement[] psiElements = PsiTreeUtil.collectElements(file, new PsiElementFilter() {

        @Override
        public boolean isAccepted(PsiElement element) {
            return selection.contains(element.getTextRange()) && element.getReferences().length > 0;
        }
    });
    final Document document = EditorFactory.getInstance().createDocument(editor.getDocument().getText().substring(startOffset, selection.getEndOffset()));
    final boolean isXml = file.getLanguage().is(StdLanguages.XML);
    final int offsetDelta = startOffset;
    new WriteCommandAction.Simple(project, (String) null) {

        @Override
        protected void run() throws Throwable {
            Map<RangeMarker, String> rangeToText = new HashMap<>();
            for (PsiElement element : psiElements) {
                for (PsiReference reference : element.getReferences()) {
                    if (!(reference instanceof PsiQualifiedReference) || ((PsiQualifiedReference) reference).getQualifier() == null) {
                        String canonicalText = reference.getCanonicalText();
                        TextRange referenceRange = reference.getRangeInElement();
                        final TextRange elementTextRange = element.getTextRange();
                        LOG.assertTrue(elementTextRange != null, elementTextRange);
                        final TextRange range = elementTextRange.cutOut(referenceRange).shiftRight(-offsetDelta);
                        final String oldText = document.getText(range);
                        // workaround for Java references: canonicalText contains generics, and we need to cut them off because otherwise
                        // they will be duplicated
                        int pos = canonicalText.indexOf('<');
                        if (pos > 0 && !oldText.contains("<")) {
                            canonicalText = canonicalText.substring(0, pos);
                        }
                        if (isXml) {
                            //strip namespace prefixes
                            pos = canonicalText.lastIndexOf(':');
                            if (pos >= 0 && pos < canonicalText.length() - 1 && !oldText.contains(":")) {
                                canonicalText = canonicalText.substring(pos + 1);
                            }
                        }
                        if (!canonicalText.equals(oldText)) {
                            rangeToText.put(document.createRangeMarker(range), canonicalText);
                        }
                    }
                }
            }
            List<RangeMarker> markers = new ArrayList<>();
            for (RangeMarker m1 : rangeToText.keySet()) {
                boolean nested = false;
                for (RangeMarker m2 : rangeToText.keySet()) {
                    if (m1 != m2 && m2.getStartOffset() <= m1.getStartOffset() && m1.getEndOffset() <= m2.getEndOffset()) {
                        nested = true;
                        break;
                    }
                }
                if (!nested) {
                    markers.add(m1);
                }
            }
            for (RangeMarker marker : markers) {
                final String value = rangeToText.get(marker);
                document.replaceString(marker.getStartOffset(), marker.getEndOffset(), value);
            }
        }
    }.execute();
    final TemplateImpl template = new TemplateImpl(TemplateListPanel.ABBREVIATION, document.getText(), TemplateSettings.USER_GROUP_NAME);
    template.setToReformat(true);
    OffsetKey startKey = OffsetKey.create("pivot");
    OffsetsInFile offsets = new OffsetsInFile(file);
    offsets.getOffsets().addOffset(startKey, startOffset);
    OffsetsInFile copy = TemplateManagerImpl.copyWithDummyIdentifier(offsets, editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd(), CompletionUtil.DUMMY_IDENTIFIER_TRIMMED);
    Set<TemplateContextType> applicable = TemplateManagerImpl.getApplicableContextTypes(copy.getFile(), copy.getOffsets().getOffset(startKey));
    for (TemplateContextType contextType : TemplateManagerImpl.getAllContextTypes()) {
        template.getTemplateContext().setEnabled(contextType, applicable.contains(contextType));
    }
    final LiveTemplatesConfigurable configurable = new LiveTemplatesConfigurable();
    ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> configurable.getTemplateListPanel().addTemplate(template));
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) OffsetsInFile(com.intellij.codeInsight.completion.OffsetsInFile) Document(com.intellij.openapi.editor.Document) DataContext(com.intellij.openapi.actionSystem.DataContext) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) PsiElementFilter(com.intellij.psi.util.PsiElementFilter) Project(com.intellij.openapi.project.Project) OffsetKey(com.intellij.codeInsight.completion.OffsetKey) Editor(com.intellij.openapi.editor.Editor) HashMap(com.intellij.util.containers.HashMap) TemplateContextType(com.intellij.codeInsight.template.TemplateContextType)

Aggregations

TemplateContextType (com.intellij.codeInsight.template.TemplateContextType)8 RelativePoint (com.intellij.ui.awt.RelativePoint)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 OffsetKey (com.intellij.codeInsight.completion.OffsetKey)1 OffsetsInFile (com.intellij.codeInsight.completion.OffsetsInFile)1 EverywhereContextType (com.intellij.codeInsight.template.EverywhereContextType)1 Template (com.intellij.codeInsight.template.Template)1 TemplateManager (com.intellij.codeInsight.template.TemplateManager)1 DataContext (com.intellij.openapi.actionSystem.DataContext)1 WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)1 Document (com.intellij.openapi.editor.Document)1 Editor (com.intellij.openapi.editor.Editor)1 RangeMarker (com.intellij.openapi.editor.RangeMarker)1 PlainSyntaxHighlighter (com.intellij.openapi.fileTypes.PlainSyntaxHighlighter)1 SyntaxHighlighter (com.intellij.openapi.fileTypes.SyntaxHighlighter)1 Project (com.intellij.openapi.project.Project)1 JBPopupAdapter (com.intellij.openapi.ui.popup.JBPopupAdapter)1 LightweightWindowEvent (com.intellij.openapi.ui.popup.LightweightWindowEvent)1 Pair (com.intellij.openapi.util.Pair)1 TextRange (com.intellij.openapi.util.TextRange)1