public String[] knownNamespaces() { final PsiElement parentElement = getParent(); BidirectionalMap<String, String> map = initNamespaceMaps(parentElement); Set<String> known = Collections.emptySet(); if (map != null) { known = new HashSet<String>(map.values()); } if (parentElement instanceof XmlTag) { if (known.isEmpty()) return ((XmlTag) parentElement).knownNamespaces(); ContainerUtil.addAll(known, ((XmlTag) parentElement).knownNamespaces()); } else { XmlExtension xmlExtension = XmlExtension.getExtensionByElement(this); if (xmlExtension != null) { final XmlFile xmlFile = xmlExtension.getContainingFile(this); if (xmlFile != null) { final XmlTag rootTag = xmlFile.getRootTag(); if (rootTag != null && rootTag != this) { if (known.isEmpty()) return rootTag.knownNamespaces(); ContainerUtil.addAll(known, rootTag.knownNamespaces()); } } } } return ArrayUtil.toStringArray(known); }
@Nullable @NonNls public String getSubTagText(@NonNls String qname) { final XmlTag tag = findFirstSubTag(qname); if (tag == null) return null; return tag.getValue().getText(); }
public void setText(String value) { try { XmlText text = null; if (StringUtil.isNotEmpty(value)) { final XmlText[] texts = getTextElements(); if (texts.length == 0) { text = (XmlText) myTag.add( XmlElementFactory.getInstance(myTag.getProject()).createDisplayText("x")); } else { text = texts[0]; } text.setValue(value); } if (myElements.length > 0) { for (final XmlTagChild child : myElements) { if (child != text) { child.delete(); } } } } catch (IncorrectOperationException e) { LOG.error(e); } }
public XmlNSDescriptor getNSDescriptor(final String namespace, boolean strict) { final XmlTag parentTag = getParentTag(); if (parentTag == null && namespace.equals(XmlUtil.XHTML_URI)) { final XmlNSDescriptor descriptor = getDtdDescriptor(XmlUtil.getContainingFile(this)); if (descriptor != null) { return descriptor; } } Map<String, CachedValue<XmlNSDescriptor>> map = initNSDescriptorsMap(); final CachedValue<XmlNSDescriptor> descriptor = map.get(namespace); if (descriptor != null) { final XmlNSDescriptor value = descriptor.getValue(); if (value != null) { return value; } } if (parentTag == null) { final XmlDocument parentOfType = PsiTreeUtil.getParentOfType(this, XmlDocument.class); if (parentOfType == null) { return null; } return parentOfType.getDefaultNSDescriptor(namespace, strict); } return parentTag.getNSDescriptor(namespace, strict); }
@Override public void visitXmlAttributeValue(XmlAttributeValue value) { final PsiElement parent = value.getParent(); if (!(parent instanceof XmlAttribute)) { checkReferences(value); return; } XmlAttribute attribute = (XmlAttribute) parent; XmlTag tag = attribute.getParent(); XmlElementDescriptor elementDescriptor = tag.getDescriptor(); XmlAttributeDescriptor attributeDescriptor = elementDescriptor != null ? elementDescriptor.getAttributeDescriptor(attribute) : null; if (attributeDescriptor != null && !skipValidation(value)) { String error = attributeDescriptor.validateValue(value, attribute.getValue()); if (error != null) { addToResults(HighlightInfo.createHighlightInfo(getTagProblemInfoType(tag), value, error)); return; } } checkReferences(value); }
private void doFix() throws IncorrectOperationException { final XmlTag tag = PsiTreeUtil.getParentOfType(myReference.getElement(), XmlTag.class); assert tag != null; final XmlTag defineTag = tag.createChildTag("define", ApplicationLoader.RNG_NAMESPACE, "\n \n", false); defineTag.setAttribute("name", myReference.getCanonicalText()); final RngGrammar grammar = ((DefinitionReference) myReference).getScope(); if (grammar == null) return; final XmlTag root = grammar.getXmlTag(); if (root == null) return; final XmlTag[] tags = root.getSubTags(); for (XmlTag xmlTag : tags) { if (PsiTreeUtil.isAncestor(xmlTag, tag, false)) { final XmlElementFactory ef = XmlElementFactory.getInstance(tag.getProject()); final XmlText text = ef.createDisplayText(" "); final PsiElement e = root.addAfter(text, xmlTag); root.addAfter(defineTag, e); return; } } root.add(defineTag); }
static boolean checkSchemaNamespace(XmlTag context) { final String namespace = context.getNamespace(); if (namespace.length() > 0) { return checkSchemaNamespace(namespace); } return StringUtil.startsWithConcatenationOf(context.getName(), XSD_PREFIX, ":"); }
@Nullable private static String getAdditionalDocumentation(PsiElement elem) { final XmlTag xmlTag = PsiTreeUtil.getParentOfType(elem, XmlTag.class); if (xmlTag == null) { return null; } final AntDomElement antElement = AntSupport.getAntDomElement(xmlTag); if (antElement instanceof AntFilesProvider) { final List<File> list = ((AntFilesProvider) antElement).getFiles(new HashSet<AntFilesProvider>()); if (list.size() > 0) { final @NonNls StringBuilder builder = StringBuilderSpinAllocator.alloc(); try { final XmlTag tag = antElement.getXmlTag(); if (tag != null) { builder.append("<b>"); builder.append(tag.getName()); builder.append(":</b>"); } for (File file : list) { if (builder.length() > 0) { builder.append("<br>"); } builder.append(file.getPath()); } return builder.toString(); } finally { StringBuilderSpinAllocator.dispose(builder); } } } return null; }
protected void setValue(@Nullable final String value) { final XmlTag tag = ensureTagExists(); final String attributeName = getXmlElementName(); final String namespace = getXmlApiCompatibleNamespace(getParentHandler()); final String oldValue = StringUtil.unescapeXml(tag.getAttributeValue(attributeName, namespace)); final String newValue = XmlStringUtil.escapeString(value); if (Comparing.equal(oldValue, newValue, true)) return; getManager() .runChange( new Runnable() { public void run() { try { XmlAttribute attribute = tag.setAttribute(attributeName, namespace, newValue); setXmlElement(attribute); getManager() .cacheHandler( DomManagerImpl.DOM_ATTRIBUTE_HANDLER_KEY, attribute, AttributeChildInvocationHandler.this); } catch (IncorrectOperationException e) { LOG.error(e); } } }); final DomElement proxy = getProxy(); final DomElement element = proxy; getManager() .fireEvent(oldValue != null ? new DomEvent(proxy, false) : new DomEvent(element, true)); }
public static List<XmlTag> findSubTags( @NotNull final XmlTag tag, final EvaluatedXmlName name, final XmlFile file) { if (!tag.isValid()) { throw new AssertionError("Invalid tag"); } final XmlTag[] tags = tag.getSubTags(); if (tags.length == 0) { return Collections.emptyList(); } return ContainerUtil.findAll( tags, childTag -> { try { return isNameSuitable( name, childTag.getLocalName(), childTag.getName(), childTag.getNamespace(), file); } catch (PsiInvalidElementAccessException e) { if (!childTag.isValid()) { LOG.error( "tag.getSubTags() returned invalid, " + "tag=" + tag + ", " + "containing file: " + tag.getContainingFile() + "subTag.parent=" + childTag.getNode().getTreeParent()); return false; } throw e; } }); }
public String[] getEnumeratedValues(XmlElement context) { final XmlElementDescriptorImpl elementDescriptor = (XmlElementDescriptorImpl) XmlUtil.findXmlDescriptorByType( myTag, context != null ? PsiTreeUtil.getContextOfType(context, XmlTag.class, true) : null); if (elementDescriptor != null && elementDescriptor.getType() instanceof ComplexTypeDescriptor) { final EnumerationData data = getEnumeratedValuesImpl( ((ComplexTypeDescriptor) elementDescriptor.getType()).getDeclaration()); final String s = getDefaultValue(); if (s != null && s.length() > 0 && data == null) { return new String[] {s}; } return data != null ? data.enumeratedValues : ArrayUtil.EMPTY_STRING_ARRAY; } final String namespacePrefix = myTag.getNamespacePrefix(); XmlTag type = myTag.findFirstSubTag( ((namespacePrefix.length() > 0) ? namespacePrefix + ":" : "") + "simpleType"); if (type != null) { final EnumerationData data = getEnumeratedValuesImpl(type); return data != null ? data.enumeratedValues : ArrayUtil.EMPTY_STRING_ARRAY; } return ArrayUtil.EMPTY_STRING_ARRAY; }
@NotNull public XmlFile getContainingFile(@NotNull DomElement domElement) { if (domElement instanceof DomFileElement) { return ((DomFileElement) domElement).getFile(); } DomInvocationHandler handler = DomManagerImpl.getDomInvocationHandler(domElement); assert handler != null : domElement; while (handler != null && !(handler instanceof DomRootInvocationHandler) && handler.getXmlTag() == null) { handler = handler.getParentHandler(); } if (handler instanceof DomRootInvocationHandler) { return ((DomRootInvocationHandler) handler).getParent().getFile(); } assert handler != null; XmlTag tag = handler.getXmlTag(); assert tag != null; while (true) { final PsiElement parentTag = PhysicalDomParentStrategy.getParentTagCandidate(tag); if (!(parentTag instanceof XmlTag)) { return (XmlFile) tag.getContainingFile(); } tag = (XmlTag) parentTag; } }
private void reportOneTagProblem( final XmlTag tag, final String name, final String localizedMessage, final IntentionAction basicIntention, final HighlightDisplayKey key, final XmlEntitiesInspection inspection, final int type) { boolean htmlTag = false; if (tag instanceof HtmlTag) { htmlTag = true; if (isAdditionallyDeclared(inspection.getAdditionalEntries(type), name)) return; } final InspectionProfile profile = InspectionProjectProfileManager.getInstance(tag.getProject()).getInspectionProfile(); final IntentionAction intentionAction = inspection.getIntentionAction(name, type); if (htmlTag && profile.isToolEnabled(key, tag)) { addElementsForTagWithManyQuickFixes( tag, localizedMessage, isInjectedHtmlTagForWhichNoProblemsReporting((HtmlTag) tag) ? HighlightInfoType.INFORMATION : SeverityRegistrar.getInstance(tag.getProject()) .getHighlightInfoTypeBySeverity(profile.getErrorLevel(key, tag).getSeverity()), intentionAction, basicIntention); } else if (!htmlTag) { addElementsForTag(tag, localizedMessage, HighlightInfoType.ERROR, basicIntention); } }
private void checkDuplicateAttribute(XmlTag tag, final XmlAttribute attribute) { if (skipValidation(tag)) { return; } final XmlAttribute[] attributes = tag.getAttributes(); final PsiFile containingFile = tag.getContainingFile(); final XmlExtension extension = containingFile instanceof XmlFile ? XmlExtension.getExtension(containingFile) : XmlExtension.DEFAULT_EXTENSION; for (XmlAttribute tagAttribute : attributes) { ProgressManager.checkCanceled(); if (attribute != tagAttribute && Comparing.strEqual(attribute.getName(), tagAttribute.getName())) { final String localName = attribute.getLocalName(); if (extension.canBeDuplicated(tagAttribute)) continue; // multiple import attributes are allowed in jsp directive HighlightInfo highlightInfo = HighlightInfo.createHighlightInfo( getTagProblemInfoType(tag), XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild( SourceTreeToPsiMap.psiElementToTree(attribute)), XmlErrorMessages.message("duplicate.attribute", localName)); addToResults(highlightInfo); IntentionAction intentionAction = new RemoveAttributeIntentionFix(localName, attribute); QuickFixAction.registerQuickFixAction(highlightInfo, intentionAction); } } }
@Override public Extension addExtension(String name) { Extension extension = addExtension(); XmlTag tag = extension.getXmlTag(); tag.setName(name.substring(getDefaultExtensionNs().getStringValue().length() + 1)); return extension; }
public Object[] get(final PsiElement context, CompletionContext completionContext) { XmlFile containingFile = null; XmlFile descriptorFile = null; final XmlTag tag = PsiTreeUtil.getParentOfType(context, XmlTag.class); if (tag != null) { containingFile = (XmlFile) tag.getContainingFile(); descriptorFile = findDescriptorFile(tag, containingFile); } else { final XmlDocument document = PsiTreeUtil.getParentOfType(context, XmlDocument.class); if (document != null) { containingFile = (XmlFile) document.getContainingFile(); final FileType ft = containingFile.getFileType(); if (ft != StdFileTypes.XML) { final String namespace = ft == StdFileTypes.XHTML || ft == StdFileTypes.JSPX ? XmlUtil.XHTML_URI : XmlUtil.HTML_URI; final XmlNSDescriptor nsDescriptor = document.getDefaultNSDescriptor(namespace, true); if (nsDescriptor != null) { descriptorFile = nsDescriptor.getDescriptorFile(); } } } } if (descriptorFile != null) { final List<Object> results = new ArrayList<Object>(); final boolean acceptSystemEntities = containingFile.getFileType() == StdFileTypes.XML; final PsiElementProcessor processor = new PsiElementProcessor() { public boolean execute(@NotNull final PsiElement element) { if (element instanceof XmlEntityDecl) { final XmlEntityDecl xmlEntityDecl = (XmlEntityDecl) element; if (xmlEntityDecl.isInternalReference() || acceptSystemEntities) { final String name = xmlEntityDecl.getName(); final Object _item = getLookupItem(xmlEntityDecl); results.add(_item == null ? name : _item); } } return true; } }; XmlUtil.processXmlElements(descriptorFile, processor, true); if (descriptorFile != containingFile && containingFile.getFileType() == StdFileTypes.XML) { final XmlProlog element = containingFile.getDocument().getProlog(); if (element != null) XmlUtil.processXmlElements(element, processor, true); } return ArrayUtil.toObjectArray(results); } return ArrayUtil.EMPTY_OBJECT_ARRAY; }
public static String findUrl(PsiFile file, int offset, String uri) { final PsiElement currentElement = file.findElementAt(offset); final XmlAttribute attribute = PsiTreeUtil.getParentOfType(currentElement, XmlAttribute.class); if (attribute != null) { final XmlTag tag = PsiTreeUtil.getParentOfType(currentElement, XmlTag.class); if (tag != null) { final String prefix = tag.getPrefixByNamespace(XmlUtil.XML_SCHEMA_INSTANCE_URI); if (prefix != null) { final String attrValue = tag.getAttributeValue(XmlUtil.SCHEMA_LOCATION_ATT, XmlUtil.XML_SCHEMA_INSTANCE_URI); if (attrValue != null) { final StringTokenizer tokenizer = new StringTokenizer(attrValue); while (tokenizer.hasMoreElements()) { if (uri.equals(tokenizer.nextToken())) { if (!tokenizer.hasMoreElements()) return uri; final String url = tokenizer.nextToken(); return url.startsWith(HTTP_PROTOCOL) ? url : uri; } if (!tokenizer.hasMoreElements()) return uri; tokenizer.nextToken(); // skip file location } } } } } return uri; }
private static void registerProblem( @NotNull final AnnotationHolder holder, @NotNull final XmlTag tag, @Nullable final XmlToken start, @NotNull final XmlToken end) { final String tagName = (tag instanceof HtmlTag) ? tag.getName().toLowerCase() : tag.getName(); final String endTokenText = (tag instanceof HtmlTag) ? end.getText().toLowerCase() : end.getText(); final RenameTagBeginOrEndIntentionAction renameEndAction = new RenameTagBeginOrEndIntentionAction(tagName, endTokenText, false); final RenameTagBeginOrEndIntentionAction renameStartAction = new RenameTagBeginOrEndIntentionAction(endTokenText, tagName, true); if (start != null) { final Annotation annotation = holder.createErrorAnnotation( start, XmlErrorMessages.message("tag.has.wrong.closing.tag.name")); annotation.registerFix(renameEndAction); annotation.registerFix(renameStartAction); } final Annotation annotation = holder.createErrorAnnotation(end, XmlErrorMessages.message("wrong.closing.tag.name")); annotation.registerFix(new RemoveExtraClosingTagIntentionAction()); annotation.registerFix(renameEndAction); annotation.registerFix(renameStartAction); }
private static void replaceByTagContent(Project project, XmlTag tagToReplace, XmlTag tagToInline) throws AndroidRefactoringErrorException { final ASTNode node = tagToInline.getNode(); if (node == null) { throw new AndroidRefactoringErrorException(); } final ASTNode startTagEnd = XmlChildRole.START_TAG_END_FINDER.findChild(node); final ASTNode closingTagStart = XmlChildRole.CLOSING_TAG_START_FINDER.findChild(node); if (startTagEnd == null || closingTagStart == null) { throw new AndroidRefactoringErrorException(); } final int contentStart = startTagEnd.getTextRange().getEndOffset(); final int contentEnd = closingTagStart.getTextRange().getStartOffset(); if (contentStart < 0 || contentEnd < 0 || contentStart >= contentEnd) { throw new AndroidRefactoringErrorException(); } final PsiFile file = tagToInline.getContainingFile(); if (file == null) { throw new AndroidRefactoringErrorException(); } final String textToInline = file.getText().substring(contentStart, contentEnd).trim(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); final Document document = documentManager.getDocument(tagToReplace.getContainingFile()); if (document == null) { throw new AndroidRefactoringErrorException(); } final TextRange range = tagToReplace.getTextRange(); document.replaceString(range.getStartOffset(), range.getEndOffset(), textToInline); documentManager.commitDocument(document); }
@NotNull public XPathType getExpectedType(XPathExpression expr) { final XmlTag tag = PsiTreeUtil.getContextOfType(expr, XmlTag.class, true); if (tag != null && XsltSupport.isXsltTag(tag)) { final XsltElement element = XsltElementFactory.getInstance().wrapElement(tag, XsltElement.class); if (element instanceof XsltVariable) { return ((XsltVariable) element).getType(); } else { final XmlAttribute attr = PsiTreeUtil.getContextOfType(expr, XmlAttribute.class, true); if (attr != null) { if (element instanceof XsltWithParam) { final XmlAttribute nameAttr = tag.getAttribute("name", null); if (nameAttr != null) { final XmlAttributeValue valueElement = nameAttr.getValueElement(); if (valueElement != null) { final PsiReference[] references = valueElement.getReferences(); for (PsiReference reference : references) { final PsiElement psiElement = reference.resolve(); if (psiElement instanceof XsltVariable) { return ((XsltVariable) psiElement).getType(); } } } } } else { final String name = attr.getName(); return getTypeForTag(tag, name); } } } } return XPathType.UNKNOWN; }
public String getDefaultValue() { if (isFixed()) { return myTag.getAttributeValue("fixed"); } return myTag.getAttributeValue("default"); }
protected XmlElement recomputeXmlElement(@NotNull final DomInvocationHandler parent) { if (!parent.isValid()) return null; final XmlTag tag = parent.getXmlTag(); if (tag == null) return null; return tag.getAttribute(getXmlElementName(), getXmlApiCompatibleNamespace(parent)); }
private void collectPropertiesVariants(final List<Object> result) { if (myProjectDom != null) { for (XmlTag xmlTag : MavenDomProjectProcessorUtils.collectProperties(myProjectDom, myProject)) { result.add(createLookupElement(xmlTag, xmlTag.getName(), PlatformIcons.PROPERTY_ICON)); } } }
public void inline(@NotNull XmlTag layoutRootTag) throws AndroidRefactoringErrorException { final XmlTag parent = myIncludeTag.getParentTag(); if ("merge".equals(layoutRootTag.getName()) && parent != null) { inlineMultiTags(myIncludeTag, parent, layoutRootTag, myProject); } else { inlineSingleTag(myIncludeTag, parent, layoutRootTag); } }
public static XmlTag getAncestorTag(XmlTag tag, String name, String namespace) { if (tag == null) { return null; } if (tag.getLocalName().equals(name) && tag.getNamespace().equals(namespace)) { return tag; } return getAncestorTag(tag.getParentTag(), name, namespace); }
/** * @param xmlFile * @param path absolute Path * @return */ public static XmlTag findSubTag(XmlFile xmlFile, String path) { XmlTag root = xmlFile.getRootTag(); if (root != null) { String rootName = root.getName(); String relativePath = path.substring(rootName.length() + 1); return findSubTag(root, relativePath); } return null; }
private static XmlTag createTag( @NotNull XmlTag contextTag, @NotNull XmlElementDescriptor descriptor) { String namespace = getNamespace(descriptor); XmlTag tag = contextTag.createChildTag(descriptor.getName(), namespace, null, false); PsiElement lastChild = tag.getLastChild(); assert lastChild != null; lastChild.delete(); // remove XML_EMPTY_ELEMENT_END return tag; }
private static void fillFromSchema(PsiFile file, ElementNames names) { if (!(file instanceof XmlFile)) return; final XmlFile f = (XmlFile) file; final XmlDocument d = f.getDocument(); if (d == null) return; final XmlTag rootTag = d.getRootTag(); if (rootTag == null) return; //noinspection unchecked names.dependencies.add(new NSDeclTracker(rootTag)); try { final Map<String, String> namespaceDeclarations = rootTag.getLocalNamespaceDeclarations(); final Collection<String> prefixes = namespaceDeclarations.keySet(); //noinspection unchecked final Set<XmlElementDescriptor> history = new THashSet<XmlElementDescriptor>(); final XmlElementFactory ef = XmlElementFactory.getInstance(file.getProject()); int noSchemaNamespaces = 0; for (String prefix : prefixes) { final String namespace = namespaceDeclarations.get(prefix); if (isIgnoredNamespace(prefix, namespace)) continue; final XmlTag tag = ef.createTagFromText("<dummy-tag xmlns='" + namespace + "' />", XMLLanguage.INSTANCE); final XmlDocument document = PsiTreeUtil.getParentOfType(tag, XmlDocument.class); final XmlNSDescriptor rootDescriptor = tag.getNSDescriptor(tag.getNamespace(), true); if (rootDescriptor == null || (rootDescriptor instanceof XmlNSDescriptorImpl && ((XmlNSDescriptorImpl) rootDescriptor).getTag() == null) || !rootDescriptor.getDeclaration().isPhysical()) { final QName any = QNameUtil.createAnyLocalName(namespace); names.elementNames.add(any); names.attributeNames.add(any); noSchemaNamespaces++; continue; } //noinspection unchecked names.dependencies.add(rootDescriptor.getDescriptorFile()); final XmlElementDescriptor[] e = rootDescriptor.getRootElementsDescriptors(document); for (XmlElementDescriptor descriptor : e) { processElementDescriptors(descriptor, tag, names, history); } } names.validateNames = names.elementNames.size() > noSchemaNamespaces; // final QName any = QNameUtil.createAnyLocalName(""); // names.elementNames.add(any); // names.attributeNames.add(any); } catch (IncorrectOperationException e) { Logger.getInstance(XsltContextProvider.class.getName()).error(e); } }
@Override protected boolean isValidForFile( @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { if (!(file instanceof XmlFile)) return false; XmlTag contextTag = getContextTag(editor, file); return contextTag != null && isInsideTagBody(contextTag, editor) && contextTag.getDescriptor() != null; }
public boolean isAcceptable(Object element, PsiElement context) { for (XmlTag xmlTag : ((XmlTag) element).getSubTags()) { if ("filter-class".equals(xmlTag.getName()) && StripesConstants.STRIPES_FILTER_CLASS.equals( xmlTag.getValue().getText())) { return true; } } return false; }