Search in sources :

Example 1 with XmlNamespaceHelper

use of com.intellij.xml.XmlNamespaceHelper in project intellij-community by JetBrains.

the class XmlAttributeInsertHandler method handleInsert.

@Override
public void handleInsert(final InsertionContext context, final LookupElement item) {
    final Editor editor = context.getEditor();
    final Document document = editor.getDocument();
    final int caretOffset = editor.getCaretModel().getOffset();
    final PsiFile file = context.getFile();
    final CharSequence chars = document.getCharsSequence();
    final String quote = getAttributeQuote(HtmlUtil.hasHtml(file) || HtmlUtil.supportsXmlTypedHandlers(file));
    final boolean insertQuotes = WebEditorOptions.getInstance().isInsertQuotesForAttributeValue() && StringUtil.isNotEmpty(quote);
    final boolean hasQuotes = CharArrayUtil.regionMatches(chars, caretOffset, "=\"") || CharArrayUtil.regionMatches(chars, caretOffset, "='");
    if (!hasQuotes) {
        PsiElement fileContext = file.getContext();
        String toInsert = null;
        if (fileContext != null) {
            if (fileContext.getText().startsWith("\""))
                toInsert = "=''";
            if (fileContext.getText().startsWith("\'"))
                toInsert = "=\"\"";
        }
        if (toInsert == null) {
            toInsert = "=" + quote + quote;
        }
        if (!insertQuotes)
            toInsert = "=";
        if (caretOffset >= document.getTextLength() || "/> \n\t\r".indexOf(document.getCharsSequence().charAt(caretOffset)) < 0) {
            document.insertString(caretOffset, toInsert + " ");
        } else {
            document.insertString(caretOffset, toInsert);
        }
        if ('=' == context.getCompletionChar()) {
            // IDEA-19449
            context.setAddCompletionChar(false);
        }
    }
    editor.getCaretModel().moveToOffset(caretOffset + (insertQuotes || hasQuotes ? 2 : 1));
    editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    editor.getSelectionModel().removeSelection();
    AutoPopupController.getInstance(editor.getProject()).scheduleAutoPopup(editor);
    if (myNamespaceToInsert != null && file instanceof XmlFile) {
        final PsiElement element = file.findElementAt(context.getStartOffset());
        final XmlTag tag = element != null ? PsiTreeUtil.getParentOfType(element, XmlTag.class) : null;
        if (tag != null) {
            String prefix = ExtendedTagInsertHandler.suggestPrefix((XmlFile) file, myNamespaceToInsert);
            if (prefix != null) {
                prefix = makePrefixUnique(prefix, tag);
                final XmlNamespaceHelper helper = XmlNamespaceHelper.getHelper(context.getFile());
                if (helper != null) {
                    final Project project = context.getProject();
                    PsiDocumentManager.getInstance(project).commitDocument(document);
                    qualifyWithPrefix(prefix, element);
                    helper.insertNamespaceDeclaration((XmlFile) file, editor, Collections.singleton(myNamespaceToInsert), prefix, null);
                }
            }
        }
    }
}
Also used : Project(com.intellij.openapi.project.Project) XmlFile(com.intellij.psi.xml.XmlFile) XmlNamespaceHelper(com.intellij.xml.XmlNamespaceHelper) PsiFile(com.intellij.psi.PsiFile) Editor(com.intellij.openapi.editor.Editor) Document(com.intellij.openapi.editor.Document) PsiElement(com.intellij.psi.PsiElement) XmlTag(com.intellij.psi.xml.XmlTag)

Example 2 with XmlNamespaceHelper

use of com.intellij.xml.XmlNamespaceHelper in project intellij-community by JetBrains.

the class CreateNSDeclarationIntentionFix method invoke.

@Override
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
    final PsiElement element = myElement.retrieve();
    if (element == null)
        return;
    XmlFile xmlFile = getFile();
    final String[] namespaces = ArrayUtil.toStringArray(getNamespaces(element, xmlFile));
    runActionOverSeveralAttributeValuesAfterLettingUserSelectTheNeededOne(namespaces, project, new StringToAttributeProcessor() {

        @Override
        public void doSomethingWithGivenStringToProduceXmlAttributeNowPlease(@NotNull final String namespace) throws IncorrectOperationException {
            String prefix = myNamespacePrefix;
            if (StringUtil.isEmpty(prefix)) {
                final XmlFile xmlFile = XmlExtension.getExtension(file).getContainingFile(element);
                prefix = ExtendedTagInsertHandler.getPrefixByNamespace(xmlFile, namespace);
                if (StringUtil.isNotEmpty(prefix)) {
                    // namespace already declared
                    ExtendedTagInsertHandler.qualifyWithPrefix(prefix, element);
                    return;
                } else {
                    prefix = ExtendedTagInsertHandler.suggestPrefix(xmlFile, namespace);
                    if (!StringUtil.isEmpty(prefix)) {
                        ExtendedTagInsertHandler.qualifyWithPrefix(prefix, element);
                        PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
                    }
                }
            }
            final int offset = editor.getCaretModel().getOffset();
            final RangeMarker marker = editor.getDocument().createRangeMarker(offset, offset);
            final XmlNamespaceHelper helper = XmlNamespaceHelper.getHelper(file);
            helper.insertNamespaceDeclaration((XmlFile) file, editor, Collections.singleton(namespace), prefix, new XmlNamespaceHelper.Runner<String, IncorrectOperationException>() {

                @Override
                public void run(final String param) throws IncorrectOperationException {
                    if (!namespace.isEmpty()) {
                        editor.getCaretModel().moveToOffset(marker.getStartOffset());
                    }
                }
            });
        }
    }, getTitle(), this, editor);
}
Also used : XmlNamespaceHelper(com.intellij.xml.XmlNamespaceHelper) IncorrectOperationException(com.intellij.util.IncorrectOperationException) RangeMarker(com.intellij.openapi.editor.RangeMarker) PsiElement(com.intellij.psi.PsiElement)

Example 3 with XmlNamespaceHelper

use of com.intellij.xml.XmlNamespaceHelper in project android by JetBrains.

the class AddMissingPrefixQuickFix method apply.

@Override
public void apply(@NotNull PsiElement startElement, @NotNull PsiElement endElement, @NotNull AndroidQuickfixContexts.Context context) {
    final XmlAttribute attribute = PsiTreeUtil.getParentOfType(startElement, XmlAttribute.class, false);
    if (attribute == null) {
        return;
    }
    final XmlTag tag = attribute.getParent();
    if (tag == null) {
        LOG.debug("tag is null");
        return;
    }
    String androidNsPrefix = tag.getPrefixByNamespace(SdkConstants.NS_RESOURCES);
    if (androidNsPrefix == null) {
        final PsiFile file = tag.getContainingFile();
        final XmlNamespaceHelper extension = XmlNamespaceHelper.getHelper(file);
        if (extension == null) {
            LOG.debug("Cannot get XmlNamespaceHelper for file + " + file);
            return;
        }
        if (!(file instanceof XmlFile)) {
            LOG.debug(file + " is not XmlFile");
            return;
        }
        final XmlFile xmlFile = (XmlFile) file;
        final String defaultPrefix = "android";
        extension.insertNamespaceDeclaration(xmlFile, null, Collections.singleton(SdkConstants.NS_RESOURCES), defaultPrefix, null);
        androidNsPrefix = defaultPrefix;
    }
    attribute.setName(androidNsPrefix + ':' + attribute.getLocalName());
}
Also used : XmlAttribute(com.intellij.psi.xml.XmlAttribute) XmlFile(com.intellij.psi.xml.XmlFile) XmlNamespaceHelper(com.intellij.xml.XmlNamespaceHelper) PsiFile(com.intellij.psi.PsiFile) XmlTag(com.intellij.psi.xml.XmlTag)

Example 4 with XmlNamespaceHelper

use of com.intellij.xml.XmlNamespaceHelper in project intellij-community by JetBrains.

the class XmlLocationCompletionContributor method completeNamespace.

private static Object[] completeNamespace(PsiElement myElement) {
    final XmlFile file = (XmlFile) myElement.getContainingFile();
    PsiElement parent = myElement.getParent();
    final Set<Object> preferred = new HashSet<>();
    if (parent instanceof XmlAttribute && "xmlns".equals(((XmlAttribute) parent).getName())) {
        XmlNamespaceHelper helper = XmlNamespaceHelper.getHelper(file);
        preferred.addAll(helper.guessUnboundNamespaces(parent.getParent(), file));
    }
    Set<String> list = new HashSet<>();
    for (XmlSchemaProvider provider : Extensions.getExtensions(XmlSchemaProvider.EP_NAME)) {
        if (provider.isAvailable(file)) {
            list.addAll(provider.getAvailableNamespaces(file, null));
        }
    }
    if (!list.isEmpty()) {
        return ArrayUtil.toObjectArray(list);
    }
    Object[] resourceUrls = ExternalResourceManagerEx.getInstanceEx().getUrlsByNamespace(myElement.getProject()).keySet().toArray();
    final XmlDocument document = file.getDocument();
    assert document != null;
    XmlTag rootTag = document.getRootTag();
    final ArrayList<String> additionalNs = new ArrayList<>();
    if (rootTag != null)
        URLReference.processWsdlSchemas(rootTag, xmlTag -> {
            final String s = xmlTag.getAttributeValue(URLReference.TARGET_NAMESPACE_ATTR_NAME);
            if (s != null) {
                additionalNs.add(s);
            }
            return true;
        });
    resourceUrls = ArrayUtil.mergeArrays(resourceUrls, ArrayUtil.toStringArray(additionalNs));
    return ContainerUtil.map2Array(resourceUrls, o -> {
        LookupElementBuilder builder = LookupElementBuilder.create(o);
        return preferred.contains(o) ? PrioritizedLookupElement.withPriority(builder, 100) : builder;
    });
}
Also used : Extensions(com.intellij.openapi.extensions.Extensions) ArrayUtil(com.intellij.util.ArrayUtil) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) PsiMultiReference(com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference) LookupElement(com.intellij.codeInsight.lookup.LookupElement) Collection(java.util.Collection) PsiReference(com.intellij.psi.PsiReference) Set(java.util.Set) ContainerUtil(com.intellij.util.containers.ContainerUtil) DependentNSReference(com.intellij.psi.impl.source.resolve.reference.impl.providers.DependentNSReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) com.intellij.psi.xml(com.intellij.psi.xml) XmlNamespaceHelper(com.intellij.xml.XmlNamespaceHelper) ExternalResourceManagerEx(com.intellij.javaee.ExternalResourceManagerEx) Function(com.intellij.util.Function) Processor(com.intellij.util.Processor) XmlSchemaProvider(com.intellij.xml.XmlSchemaProvider) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull) URLReference(com.intellij.psi.impl.source.resolve.reference.impl.providers.URLReference) MultiMap(com.intellij.util.containers.MultiMap) Condition(com.intellij.openapi.util.Condition) ArrayList(java.util.ArrayList) XmlNamespaceHelper(com.intellij.xml.XmlNamespaceHelper) XmlSchemaProvider(com.intellij.xml.XmlSchemaProvider) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) PsiElement(com.intellij.psi.PsiElement) HashSet(java.util.HashSet)

Example 5 with XmlNamespaceHelper

use of com.intellij.xml.XmlNamespaceHelper in project intellij-community by JetBrains.

the class ImportNSAction method execute.

@Override
public boolean execute() {
    final String[] strings = ArrayUtil.toStringArray(myNamespaces);
    final JList list = new JBList(strings);
    list.setCellRenderer(XmlNSRenderer.INSTANCE);
    list.setSelectedIndex(0);
    final int offset = myElement.getTextOffset();
    final RangeMarker marker = myEditor.getDocument().createRangeMarker(offset, offset);
    final Runnable runnable = () -> {
        final String namespace = (String) list.getSelectedValue();
        if (namespace != null) {
            final Project project = myFile.getProject();
            new WriteCommandAction.Simple(project, myFile) {

                @Override
                protected void run() throws Throwable {
                    final XmlNamespaceHelper extension = XmlNamespaceHelper.getHelper(myFile);
                    final String prefix = extension.getNamespacePrefix(myElement);
                    extension.insertNamespaceDeclaration(myFile, myEditor, Collections.singleton(namespace), prefix, new XmlNamespaceHelper.Runner<String, IncorrectOperationException>() {

                        @Override
                        public void run(final String s) throws IncorrectOperationException {
                            PsiDocumentManager.getInstance(myFile.getProject()).doPostponedOperationsAndUnblockDocument(myEditor.getDocument());
                            PsiElement element = myFile.findElementAt(marker.getStartOffset());
                            if (element != null) {
                                extension.qualifyWithPrefix(s, element, myEditor.getDocument());
                            }
                        }
                    });
                }
            }.execute();
        }
    };
    if (list.getModel().getSize() == 1) {
        runnable.run();
    } else {
        new PopupChooserBuilder(list).setTitle(myTitle).setItemChoosenCallback(runnable).createPopup().showInBestPositionFor(myEditor);
    }
    return true;
}
Also used : XmlNamespaceHelper(com.intellij.xml.XmlNamespaceHelper) RangeMarker(com.intellij.openapi.editor.RangeMarker) Project(com.intellij.openapi.project.Project) JBList(com.intellij.ui.components.JBList) IncorrectOperationException(com.intellij.util.IncorrectOperationException) PopupChooserBuilder(com.intellij.openapi.ui.popup.PopupChooserBuilder) PsiElement(com.intellij.psi.PsiElement)

Aggregations

XmlNamespaceHelper (com.intellij.xml.XmlNamespaceHelper)5 PsiElement (com.intellij.psi.PsiElement)4 RangeMarker (com.intellij.openapi.editor.RangeMarker)2 Project (com.intellij.openapi.project.Project)2 PsiFile (com.intellij.psi.PsiFile)2 XmlFile (com.intellij.psi.xml.XmlFile)2 XmlTag (com.intellij.psi.xml.XmlTag)2 IncorrectOperationException (com.intellij.util.IncorrectOperationException)2 LookupElement (com.intellij.codeInsight.lookup.LookupElement)1 LookupElementBuilder (com.intellij.codeInsight.lookup.LookupElementBuilder)1 ExternalResourceManagerEx (com.intellij.javaee.ExternalResourceManagerEx)1 Document (com.intellij.openapi.editor.Document)1 Editor (com.intellij.openapi.editor.Editor)1 Extensions (com.intellij.openapi.extensions.Extensions)1 PopupChooserBuilder (com.intellij.openapi.ui.popup.PopupChooserBuilder)1 Condition (com.intellij.openapi.util.Condition)1 PsiReference (com.intellij.psi.PsiReference)1 PsiMultiReference (com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference)1 DependentNSReference (com.intellij.psi.impl.source.resolve.reference.impl.providers.DependentNSReference)1 URLReference (com.intellij.psi.impl.source.resolve.reference.impl.providers.URLReference)1