下面列出了怎么用com.intellij.psi.xml.XmlTag的API类实例代码及写法,或者点击链接到github查看源代码。
private static void loadFilters(XmlTag customFilters, LatteXmlFileData data) {
for (XmlTag filterData : customFilters.findSubTags("filter")) {
XmlAttribute name = filterData.getAttribute("name");
if (name == null) {
continue;
}
LatteFilterSettings filter = new LatteFilterSettings(
name.getValue(),
getTextValue(filterData, "description"),
getTextValue(filterData, "arguments"),
getTextValue(filterData, "insertColons")
);
data.addFilter(filter);
}
}
private String decideFillColor(XmlTag group, XmlTag self) {
String result = Configuration.getDefaultTint();
XmlAttribute groupFill;
if ((groupFill = group.getAttribute("fill")) != null) {
result = StdColorUtil.formatColor(groupFill.getValue());
}
XmlAttribute selfFill;
if ((selfFill = self.getAttribute("fill")) != null) {
result = StdColorUtil.formatColor(selfFill.getValue());
}
XmlAttribute id = self.getAttribute("class");
String colorFromStyle;
if (id != null && id.getValue() != null && (colorFromStyle = styleParser.getFillColor(id.getValue())) != null) {
result = colorFromStyle;
}
return result;
}
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
PsiElement psiElement = completionParameters.getOriginalPosition();
if(psiElement == null || !ShopwareProjectComponent.isValidForProject(psiElement)) {
return;
}
PsiElement parent = psiElement.getParent();
if(!(parent instanceof XmlTag)) {
return;
}
String controllerName = getControllerOnScope((XmlTag) parent);
if (controllerName == null) {
return;
}
ShopwareUtil.collectControllerAction(psiElement.getProject(), controllerName, (method, methodStripped, moduleName, controllerName1) -> {
LookupElementBuilder lookupElement = LookupElementBuilder.create(methodStripped)
.withIcon(method.getIcon())
.withTypeText(method.getName(), true);
completionResultSet.addElement(lookupElement);
}, "Backend");
}
/**
* @see XmlHelper#getArgumentIndex
*/
public void testGetArgumentIndexOnIndex() {
myFixture.configureByText(XmlFileType.INSTANCE, "" +
"<service class=\"Foo\\Bar\">\n" +
" <argum<caret>ent index=\"2\" />\n" +
"</service>"
);
PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
assertEquals(2, XmlHelper.getArgumentIndex((XmlTag) psiElement.getParent()));
myFixture.configureByText(XmlFileType.INSTANCE, "" +
"<service class=\"Foo\\Bar\">\n" +
" <argum<caret>ent index=\"foobar\" />\n" +
"</service>"
);
psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
assertEquals(-1, XmlHelper.getArgumentIndex((XmlTag) psiElement.getParent()));
}
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement psiElement) throws IncorrectOperationException {
XmlTag xmlTag = getServiceTagValid(psiElement);
if(xmlTag == null) {
return;
}
final List<String> args = ServiceActionUtil.getXmlMissingArgumentTypes(xmlTag, true, new ContainerCollectionResolver.LazyServiceCollector(project));
if (args.size() == 0) {
return;
}
ServiceActionUtil.fixServiceArgument(args, xmlTag);
}
private @NotNull
String extractDocumentation(XmlTag attributeTag) {
StringBuilder attributeDocumentation = new StringBuilder();
XmlTag attributeAnnotation = attributeTag.findFirstSubTag("xsd:annotation");
if (attributeAnnotation != null) {
XmlTag attributeDoc = attributeAnnotation.findFirstSubTag("xsd:documentation");
if (attributeDoc != null) {
for (XmlText textElement : attributeDoc.getValue().getTextElements()) {
attributeDocumentation.append(textElement.getValue());
}
}
}
return attributeDocumentation.toString();
}
private static void loadTags(XmlTag customTags, LatteXmlFileData data) {
for (XmlTag tag : customTags.findSubTags("tag")) {
XmlAttribute name = tag.getAttribute("name");
XmlAttribute type = tag.getAttribute("type");
if (name == null || type == null || !LatteTagSettings.isValidType(type.getValue())) {
continue;
}
LatteTagSettings macro = new LatteTagSettings(
name.getValue(),
LatteTagSettings.Type.valueOf(type.getValue()),
isTrue(tag, "allowedFilters"),
getTextValue(tag, "arguments"),
isTrue(tag, "multiLine"),
getTextValue(tag, "deprecatedMessage").trim(),
getArguments(tag)
);
data.addTag(macro);
}
}
@Nullable
private static Collection<ServiceTagInterface> create(@NotNull String serviceId, @NotNull XmlTag xmlTag) {
final Collection<ServiceTagInterface> tags = new ArrayList<>();
for (XmlTag tag : xmlTag.findSubTags("tag")) {
String name = tag.getAttributeValue("name");
if(name == null) {
continue;
}
ServiceTagInterface serviceTagInterface = XmlServiceTag.create(serviceId, tag);
if(serviceTagInterface == null) {
continue;
}
tags.add(serviceTagInterface);
}
return tags;
}
public void testGetTargetForXlfAsXmlFileInVersion12() {
PsiFile fileFromText = PsiFileFactory.getInstance(getProject()).createFileFromText(XMLLanguage.INSTANCE, "" +
"<?xml version=\"1.0\"?>\n" +
"<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\">\n" +
" <file source-language=\"en\" datatype=\"plaintext\" original=\"file.ext\">\n" +
" <body>\n" +
" <trans-unit id=\"1\">\n" +
" <source>This value should be false.</source>\n" +
" </trans-unit>\n" +
" </body>\n" +
" </file>\n" +
"</xliff>\n"
);
Collection<PsiElement> files = TranslationUtil.getTargetForXlfAsXmlFile((XmlFile) fileFromText, "This value should be false.");
assertNotNull(ContainerUtil.find(files, psiElement ->
psiElement instanceof XmlTag && "This value should be false.".equals(((XmlTag) psiElement).getValue().getText()))
);
}
@Override
public XmlAttributeDescriptor[] getAttributeDescriptors(XmlTag xmlTag) {
if (!WeexFileUtil.isOnWeexFile(xmlTag)) {
return new XmlAttributeDescriptor[0];
}
final Map<String, XmlAttributeDescriptor> result = new LinkedHashMap<String, XmlAttributeDescriptor>();
WeexTag tag = DirectiveLint.getWeexTag(xmlTag.getName());
if (tag == null) {
return new XmlAttributeDescriptor[0];
}
for (String attributeName : tag.getExtAttrs()) {
result.put(attributeName, new WeexAttrDescriptor(attributeName,
tag.getAttribute(attributeName).valueEnum,
null));
}
return result.values().toArray(new XmlAttributeDescriptor[result.size()]);
}
/**
* <route controller="Foo"/>
* <route>
* <default key="_controller">Foo</default>
* </route>
*/
@Nullable
public static String getXmlController(@NotNull XmlTag serviceTag) {
for(XmlTag subTag :serviceTag.getSubTags()) {
if("default".equalsIgnoreCase(subTag.getName())) {
String keyValue = subTag.getAttributeValue("key");
if(keyValue != null && "_controller".equals(keyValue)) {
String actionName = subTag.getValue().getTrimmedText();
if(StringUtils.isNotBlank(actionName)) {
return actionName;
}
}
}
}
String controller = serviceTag.getAttributeValue("controller");
if(controller != null && StringUtils.isNotBlank(controller)) {
return controller;
}
return null;
}
private static XmlTag findChildMessageProcessorByPath(MessageProcessorPath messageProcessorPath, XmlTag xmlTag) {
final List<MessageProcessorPathNode> nodes = messageProcessorPath.getNodes();
for (MessageProcessorPathNode node : nodes) {
final String elementName = node.getElementName();
final int i = Integer.parseInt(elementName);
final XmlTag[] subTags = xmlTag.getSubTags();
int index = -1;
for (XmlTag subTag : subTags) {
final MuleElementType muleElementType = getMuleElementTypeFromXmlElement(subTag);
if (muleElementType == MuleElementType.MESSAGE_PROCESSOR) {
xmlTag = subTag;
index = index + 1;
}
if (index == i) {
break;
}
}
}
return xmlTag;
}
@Override
public void collectSlowLineMarkers(@NotNull List<PsiElement> psiElements, @NotNull Collection<LineMarkerInfo> result) {
if(psiElements.size() == 0 || !Symfony2ProjectComponent.isEnabled(psiElements.get(0))) {
return;
}
LazyDecoratedParentServiceValues lazyDecoratedParentServiceValues = null;
for (PsiElement psiElement : psiElements) {
if(!XmlHelper.getXmlTagNameLeafStartPattern().accepts(psiElement)) {
continue;
}
PsiElement xmlTag = psiElement.getParent();
if(!(xmlTag instanceof XmlTag) || !getServiceIdPattern().accepts(xmlTag)) {
continue;
}
if(lazyDecoratedParentServiceValues == null) {
lazyDecoratedParentServiceValues = new LazyDecoratedParentServiceValues(psiElement.getProject());
}
// <services><service id="foo"/></services>
visitServiceId(psiElement, (XmlTag) xmlTag, result, lazyDecoratedParentServiceValues);
}
}
private static void loadFunctions(XmlTag customFunctions, LatteXmlFileData data) {
for (XmlTag filter : customFunctions.findSubTags("function")) {
XmlAttribute name = filter.getAttribute("name");
if (name == null) {
continue;
}
String returnType = getTextValue(filter, "returnType");
LatteFunctionSettings instance = new LatteFunctionSettings(
name.getValue(),
returnType.length() == 0 ? "mixed" : returnType,
getTextValue(filter, "arguments"),
getTextValue(filter, "description")
);
data.addFunction(instance);
}
}
/**
* Get documentation html for the given StringTable key XmlTag (this should be one returned from {@link #getIDXmlTag()})
*
* @param element key's tag
* @return html showing all languages' values, or null if element was null, or null if element wasn't a key tag
*/
@Nullable
public static String getKeyDoc(@Nullable XmlTag element) {
if (element == null) {
return null;
}
if (!element.getName().equalsIgnoreCase("key")) {
return null;
}
final String format = "<div><b>%s</b> : <pre>%s</pre></div>";
StringBuilder doc = new StringBuilder();
for (XmlTag childTag : element.getSubTags()) {
doc.append(String.format(format, childTag.getName(), childTag.getText()));
}
return doc.toString();
}
protected void doAction() {
LOG.assertTrue(this.myElement.isValid());
CommandProcessor.getInstance().executeCommand(this.myProject, () -> {
ApplicationManager.getApplication().runWriteAction(() -> {
try {
final List<XmlTag> refs = MuleConfigUtils.findFlowRefsForFlow(this.myTag);
this.myTag.getAttribute(MuleConfigConstants.NAME_ATTRIBUTE).setValue(this.getNewName());
for (XmlTag ref : refs) {
ref.getAttribute(MuleConfigConstants.NAME_ATTRIBUTE).setValue(this.getNewName());
}
} catch (IncorrectOperationException var2) {
LOG.error(var2);
}
});
}, RefactoringBundle.message("rename.title"), (Object)null);
this.close(0);
}
public void testGetTargetForXlfAsXmlFileInVersion20() {
PsiFile fileFromText = PsiFileFactory.getInstance(getProject()).createFileFromText(XMLLanguage.INSTANCE, "" +
"<?xml version=\"1.0\"?>\n" +
"<xliff xmlns=\"urn:oasis:names:tc:xliff:document:2.0\"\n" +
" version=\"2.0\" srcLang=\"en-US\" trgLang=\"ja-JP\">\n" +
" <file id=\"f1\" original=\"Graphic Example.psd\">\n" +
" <skeleton href=\"Graphic Example.psd.skl\"/>\n" +
" <group id=\"1\">\n" +
" <unit id=\"1\">\n" +
" <segment>\n" +
" <source>foo</source>\n" +
" </segment>\n" +
" </unit>\n" +
" </group>\n" +
" </file>\n" +
"</xliff>"
);
Collection<PsiElement> files = TranslationUtil.getTargetForXlfAsXmlFile((XmlFile) fileFromText, "foo");
assertNotNull(ContainerUtil.find(files, psiElement ->
psiElement instanceof XmlTag && "foo".equals(((XmlTag) psiElement).getValue().getText()))
);
}
private static XmlTag findXmlTag(XSourcePosition sourcePosition, XmlTag rootTag) {
final XmlTag[] subTags = rootTag.getSubTags();
for (int i = 0; i < subTags.length; i++) {
XmlTag subTag = subTags[i];
final int subTagLineNumber = getLineNumber(sourcePosition.getFile(), subTag);
if (subTagLineNumber == sourcePosition.getLine()) {
return subTag;
} else if (subTagLineNumber > sourcePosition.getLine() && i > 0 && subTags[i - 1].getSubTags().length > 0) {
return findXmlTag(sourcePosition, subTags[i - 1]);
}
}
if (subTags.length > 0) {
final XmlTag lastElement = subTags[subTags.length - 1];
return findXmlTag(sourcePosition, lastElement);
} else {
return null;
}
}
@Nullable
private static XmlTag findFlowInFile(Project project, String flowName, VirtualFile file) {
final DomManager manager = DomManager.getDomManager(project);
final PsiFile xmlFile = PsiManager.getInstance(project).findFile(file);
if (isMuleFile(xmlFile)) {
final DomFileElement<Mule> fileElement = manager.getFileElement((XmlFile) xmlFile, Mule.class);
if (fileElement != null) {
final Mule rootElement = fileElement.getRootElement();
final List<Flow> flows = rootElement.getFlows();
for (Flow flow : flows) {
if (flowName.equals(flow.getName().getValue())) {
return flow.getXmlTag();
}
}
final List<SubFlow> subFlows = rootElement.getSubFlows();
for (SubFlow subFlow : subFlows) {
if (flowName.equals(subFlow.getName().getValue())) {
return subFlow.getXmlTag();
}
}
}
}
return null;
}
public boolean isReferenceTo(PsiElement element) {
if (element == null)
return false;
PsiElement parent = PsiTreeUtil.getParentOfType(element, XmlTag.class);
if (parent != null && parent instanceof XmlTag &&
(MuleConfigConstants.FLOW_TAG_NAME.equals(((XmlTag)parent).getName()) ||
MuleConfigConstants.SUB_FLOW_TAG_NAME.equals(((XmlTag)parent).getName()))) { //It's a <flow> tag or <sub-flow> tag
if (element instanceof XmlAttributeValue && ((XmlAttributeValue)element).getValue().equals(getFlowName())) {
return true;
}
}
return false;
}
/**
* Get documentation html for the given StringTable key XmlTag (this should be one returned from {@link #getIDXmlTag()})
*
* @param element key's tag
* @return html showing all languages' values, or null if element was null, or null if element wasn't a key tag
*/
@Nullable
public static String getKeyDoc(@Nullable XmlTag element) {
if (element == null) {
return null;
}
if (!element.getName().equalsIgnoreCase("key")) {
return null;
}
final String format = "<div><b>%s</b> : <pre>%s</pre></div>";
StringBuilder doc = new StringBuilder();
for (XmlTag childTag : element.getSubTags()) {
doc.append(String.format(format, childTag.getName(), childTag.getText()));
}
return doc.toString();
}
@Override
public boolean shouldHighlightErrorElement(@NotNull PsiErrorElement error) {
final Project project = error.getProject();
final Language language = error.getLanguage();
// if ("CSS".equals(language.getID()) && PsiTreeUtil.getParentOfType(error, XmlAttribute.class) != null &&
// AngularIndexUtil.hasAngularJS(project)) {
// final PsiFile file = error.getContainingFile();
//
// PsiErrorElement nextError = error;
// while (nextError != null) {
// if (hasAngularInjectionAt(project, file, nextError.getTextOffset())) return false;
// nextError = PsiTreeUtil.getNextSiblingOfType(nextError, PsiErrorElement.class);
// }
// }
if (HTMLLanguage.INSTANCE.is(language) && error.getErrorDescription().endsWith("not closed")) {
System.out.println(error.getErrorDescription());
final PsiElement parent = error.getParent();
final XmlElementDescriptor descriptor = parent instanceof XmlTag ? ((XmlTag) parent).getDescriptor() : null;
return !(descriptor instanceof RTRequireTagDescriptor);
}
return true;
}
private static int getIdForNewXlfUnit(@NotNull XmlTag body, @NotNull String subTag) {
int lastId = 0;
for (XmlTag transUnit : body.findSubTags(subTag)) {
String id = transUnit.getAttributeValue("id");
if(id == null) {
continue;
}
Integer integer;
try {
integer = Integer.valueOf(id);
} catch (NumberFormatException e) {
continue;
}
// next safe id
if(integer >= lastId) {
lastId = integer + 1;
}
}
return lastId;
}
@Nullable
public static XmlTag getServiceTagValid(@NotNull PsiElement psiElement) {
XmlTag xmlTag = PsiTreeUtil.getParentOfType(psiElement, XmlTag.class);
if(xmlTag == null) {
return null;
}
if("service".equals(xmlTag.getName())) {
return xmlTag;
}
xmlTag = PsiTreeUtil.getParentOfType(xmlTag, XmlTag.class);
if(xmlTag != null && "service".equals(xmlTag.getName())) {
return xmlTag;
}
return null;
}
public static void insertSchemaLocationLookup(XmlFile xmlFile, String namespace, String locationLookup) {
final XmlTag rootTag = xmlFile.getRootTag();
if (rootTag == null)
return;
final XmlAttribute attribute = rootTag.getAttribute("xsi:schemaLocation", HTTP_WWW_W3_ORG_2001_XMLSCHEMA);
if (attribute != null) {
final String value = attribute.getValue();
attribute.setValue(value + "\n\t\t\t" + namespace + " " + locationLookup);
} else {
final XmlElementFactory elementFactory = XmlElementFactory.getInstance(xmlFile.getProject());
final XmlAttribute schemaLocation = elementFactory.createXmlAttribute("xsi:schemaLocation", XmlUtil.XML_SCHEMA_INSTANCE_URI);
schemaLocation.setValue(namespace + " " + locationLookup);
rootTag.add(schemaLocation);
}
}
/**
* @see XmlHelper#getArgumentIndex
*/
public void testGetArgumentIndexCallOnNamedArgument() {
myFixture.configureByText(XmlFileType.INSTANCE, "" +
"<service class=\"Foo\\Bar\">\n" +
" <call method=\"setBar\">\n" +
" <arg<caret>ument type=\"service\" key=\"$arg2\" id=\"args_bar\"/>\n" +
" </call>\n" +
"</service>"
);
PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
assertEquals(1, XmlHelper.getArgumentIndex((XmlTag) psiElement.getParent()));
}
@Override
public boolean isProducerEndpoint(PsiElement element) {
XmlTag xml = PsiTreeUtil.getParentOfType(element, XmlTag.class);
if (xml != null) {
return getIdeaUtils().hasParentXmlTag(xml, "enrich")
|| getIdeaUtils().isFromXmlTag(xml, "to", "interceptSendToEndpoint", "wireTap", "deadLetterChannel");
}
return false;
}
private boolean isCamelRouteTag(PsiElement element) {
if (element instanceof XmlTag) {
XmlTag routeTag = (XmlTag) element;
return routeTag.getLocalName().equals("route");
} else {
return false;
}
}
private void processSubGroups(XmlTag svgTag, XmlTag parent) {
Map<String, String> trans = AttrMapper.getTranslateAttrs(svgTag.getAttributeValue("transform"));
Logger.debug("Translate for sub groups:" + trans.toString());
XmlTag merged = AttrMergeUtil.mergeAttrs((XmlTag) svgTag.copy(), trans);
for (XmlTag tag : svgParser.getSubGroups(merged)) {
parseGroup(tag, parent);
}
}
@Override
public XmlAttributeDescriptor[] getAttributesDescriptors(@Nullable XmlTag context) {
// final Project project = xmlTag.getProject();
final Map<String, XmlAttributeDescriptor> result = new LinkedHashMap<String, XmlAttributeDescriptor>();
result.put(RTTagDescriptorsProvider.NAME, new RTXmlAttributeDescriptor2(RTTagDescriptorsProvider.NAME));
result.put(RTTagDescriptorsProvider.AS, new RTXmlAttributeDescriptor2(RTTagDescriptorsProvider.AS));
result.put(RTTagDescriptorsProvider.FROM, new RTXmlAttributeDescriptor2(RTTagDescriptorsProvider.FROM));
// <rt-require dependency="./CodeMirrorEditor" as="CodeEditor"/>
return result.values().toArray(new XmlAttributeDescriptor[result.size()]);
// return new XmlAttributeDescriptor[0];
}