Code Monkey home page Code Monkey logo

plugin-xml's Introduction

Prettier Banner

Opinionated Code Formatter

JavaScript · TypeScript · Flow · JSX · JSON
CSS · SCSS · Less
HTML · Vue · Angular
GraphQL · Markdown · YAML
Your favorite language?

Github Actions Build Status Github Actions Build Status Github Actions Build Status Codecov Coverage Status Blazing Fast
npm version weekly downloads from npm code style: prettier Follow Prettier on Twitter

Intro

Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.

Input

foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());

Output

foo(
  reallyLongArg(),
  omgSoManyParameters(),
  IShouldRefactorThis(),
  isThereSeriouslyAnotherOne(),
);

Prettier can be run in your editor on-save, in a pre-commit hook, or in CI environments to ensure your codebase has a consistent style without devs ever having to post a nit-picky comment on a code review ever again!


Documentation

Install · Options · CLI · API

Playground


Badge

Show the world you're using Prettiercode style: prettier

[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)

Contributing

See CONTRIBUTING.md.

plugin-xml's People

Contributors

bweis avatar caohuilin avatar dependabot-preview[bot] avatar dependabot[bot] avatar fbartho avatar fisker avatar github-actions[bot] avatar infotexture avatar kddnewton avatar kendrickw avatar ntotten avatar petetnt avatar regseb avatar the-docta avatar thewilkybarkid avatar viceice avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

plugin-xml's Issues

Wrong spacing for opening tag with tab ident 2

Thanks for making this great addition to Prettier!

I tried to use it on my React-Native project, but for an AndroidManifest file I got a strange result:

<?xml version="1.0" encoding="utf-8" ?>
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
>

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application
    android:usesCleartextTraffic="true"
    tools:targetApi="28"
    tools:ignore="GoogleAppIndexingWarning"
  />
</manifest>

Context:

  • Prettier 2.0.5
  • Plugin 0.11.0
  • Configuration: "trailingComma": "all"

The decimal point has disappeared.

I would like to format this xml.

<?xml version="1.0" encoding="UTF-8" ?>
<ApexClass xmlns="urn:metadata.tooling.soap.sforce.com" fqn="temp">
    <apiVersion>47.0</apiVersion>
    <status>Active</status>
</ApexClass>

Expected Behavior

<?xml version="1.0" encoding="UTF-8" ?>
<ApexClass xmlns="urn:metadata.tooling.soap.sforce.com" fqn="temp">
  <apiVersion>47.0</apiVersion>
  <status>Active</status>
</ApexClass>

Actual Behavior

<?xml version="1.0" encoding="UTF-8" ?>
<ApexClass xmlns="urn:metadata.tooling.soap.sforce.com" fqn="temp">
  <apiVersion>47</apiVersion>
  <status>Active</status>
</ApexClass>

Please remain the decimal point.

Steps to Reproduce the Problem

run the command

npm init
npm install --save-dev --save-exact @prettier/plugin-xml prettier

create some files

package.json

{
  "name": "temp",
  "version": "1.0.0",
  "scripts": {
    "prettier": "prettier --write \"**/*.{json,xml}\""
  },
  "devDependencies": {
    "@prettier/plugin-xml": "0.2.0",
    "prettier": "1.19.1"
  }
}

.prettierrc

{
  "tabWidth": 2
}

force-app/main/default/classes/temp.xml

<?xml version="1.0" encoding="UTF-8" ?>
<ApexClass xmlns="urn:metadata.tooling.soap.sforce.com" fqn="temp">
    <apiVersion>47.0</apiVersion>
    <status>Active</status>
</ApexClass>

run the command

npm run prettier

Specifications

  • Version: 0.2.0
  • Platform: Windows 10 Enterprise 1809

Not converting tabs to spaces

For some reason the module is not converting tabs to spaces when using the useTabs: false option, it does work the other way though (spaces to tabs work ok).

Input (it's hard to see but indentation is using tabs)

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<acl>
		<resources/>
	</acl>
</config>

Expected Result (spaces instead of tabs)

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <acl>
        <resources />
    </acl>
</config>

Actual Result (still tabs)

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<acl>
		<resources />
	</acl>
</config>

.prettierrc

{
    "printWidth": 120,
    "tabWidth": 4,
    "useTabs": false,
    "singleQuote": true
}

XML Parser

Hello.

I see this package uses a heavily modified fork of the fast-xml-parser.

I am assuming(?) the fork was done to deal with syntactic constructs which may not be represented in the output of common XML Parser (e.g Comments).

I have recently released @xml-tools/parser which produces a Concrete Syntax Tree(CST).

This means that the whole "parse tree" is available in the output (e.g comments, processing instructions, CDATA sections,...). This parser is implemented using the Chevrotain Parser Building Library which is also used in the prettier-java plugin.

Perhaps @xml-tools/parser could be useful for the implementation of prettier-plugin-xml?

Possible Pros

  • Extract Parsing concerns/maintenance from this repo.
  • Perhaps the AST Won't even be needed as the CST can be printed directly

Possible Cons

  • @xml-tools/parser is young, so expect some bugs...
  • losing direct control of the dependency (basically fork vs consume question).

Other Points to consider

  • Performance numbers (I have not benchmarked, but I doubt this would be a concern
    as the actual printing of the new text in prettier seems to be the bottleneck and Chevrotain based Parsers are pretty fast).
  • larger package size (including deps), but I doubt this is a big concern for a CLI tool.

Thoughts?

Error parsing XML

Prettier: v1.19.1
@prettier/plugin-xml: v0.6.0

The plugin throws an error on parsing the XML below:

Error: Error parsing XML
[error]     at Object.parse (PATH_TO_REPO/node_modules/@prettier/plugin-xml/src/parse.js:7:11)
[error]     at Object.parse (PATH_TO_REPO/node_modules/prettier/bin-prettier.js:9743:19)
[error]     at coreFormat (PATH_TO_REPO/node_modules/prettier/bin-prettier.js:13258:23)
[error]     at format (PATH_TO_REPO/node_modules/prettier/bin-prettier.js:13516:73)
[error]     at formatWithCursor (PATH_TO_REPO/node_modules/prettier/bin-prettier.js:13532:12)
[error]     at Object.formatWithCursor (PATH_TO_REPO/node_modules/prettier/bin-prettier.js:44213:15)
[error]     at format$1 (PATH_TO_REPO/node_modules/prettier/bin-prettier.js:45598:19)
[error]     at PATH_TO_REPO/node_modules/prettier/bin-prettier.js:45792:16
[error]     at PATH_TO_REPO/node_modules/prettier/bin-prettier.js:45731:14
[error]     at Array.forEach (<anonymous>)
<krpano>
	<events name="contextmenu"
		keep="true"
		onxmlcomplete="contextmenu_init()" />

	<contextmenu_settings />

	<!-- context menu - https://krpano.com/docu/xml/#contextmenu -->
	<contextmenu fullscreen="get:contextmenu_settings.fs"
		versioninfo="false"
		enterfs="Plein écran"
		exitfs="Quitter le plein écran">
		<item name="fs" 
			caption="FULLSCREEN"
			showif="contextmenu_settings.fs"
			separator="below" />
		<item name="cc" 
			caption="Changer mode de déplacement" 
			onclick="contextmenu_changeControlMode();" 
			separator="both"
			showif="contextmenu_settings.cc" />
		<item name="nv" 
			caption="Vue normal" 
			onclick="contextmenu_viewNormal();" 
			showif="contextmenu_settings.nv AND view.vlookatrange == 180" 
			separator="above" />
		<item name="fv" 
			caption="Vue en plongée" 
			onclick="contextmenu_viewFishEye();" 
			showif="contextmenu_settings.fv AND view.vlookatrange == 180" 
			devices="webgl" />
		<item name="sv" 
			caption="Vue stéréographique" 
			onclick="contextmenu_viewStereographic();" 
			showif="contextmenu_settings.sv AND view.vlookatrange == 180" 
			devices="webgl" />
		<item name="av" 
			caption="Vue architecturale" 
			onclick="contextmenu_viewArchitectural();" 
			showif="contextmenu_settings.av AND view.vlookatrange == 180" />
		<item name="pv" 
			caption="Vue Pannini" 
			onclick="contextmenu_viewPannini();" 
			showif="contextmenu_settings.pv AND view.vlookatrange == 180" 
			devices="flash|webgl" />
		<item name="lp" 
			caption="Vue petite planète" 
			onclick="contextmenu_viewLittlePlanet();" 
			showif="contextmenu_settings.lp AND view.vlookatrange == 180" 
			devices="flash|webgl" />
		<item name="sa" 
			caption="Démarrer l'Autotour" 
			onclick="autorotate.start();" 
			separator="both" 
			showif="contextmenu_settings.sa AND !autorotate.enabled" />
		<item name="ta" 
			caption="Arrêter l'Autotour" 
			onclick="autorotate.stop();" 
			separator="both" 
			showif="contextmenu_settings.sa AND autorotate.enabled" />
		<item name="wi" 
			separator="above"
			caption="À propos de Welcomni" 
			onclick="openurl('https://www.welcomni.com', '_blank');"
			showif="contextmenu_settings.wi" />
		<item name="kr" 
			caption="KRPANO" />
	</contextmenu>

	<action name="contextmenu_init" 
        type="Javascript"><![CDATA[
		krpano.call('theme_updateContextMenuStyle')
		krpano.set('contextmenu.customstyle', krpano.get('theme_template.contextmenu_style'))
		let menuEntries = krpano.get('setting_custom.contextmenu_entries') || krpano.get('setting_template.contextmenu_entries')
		menuEntries = menuEntries.replace(/'/g, '"')
		menuEntries = JSON.parse(menuEntries)
		for (var me in menuEntries) {
			krpano.set(`contextmenu_settings.${me}`, menuEntries[me])
		}
	]]></action>

	<action name="contextmenu_changeControlMode">
		switch(control.mouse, moveto, drag);
		switch(control.touch, moveto, drag);
	</action>

	<action name="contextmenu_viewLookStraight">
		if(view.vlookat LT -80 OR view.vlookat GT +80,
			tween(view.vlookat, 0.0, 1.0, easeInOutSine);
			tween(view.fov,     100, distance(150,0.8));
		);
	</action>

	<action name="contextmenu_viewNormal">
		contextmenu_viewLookStraight();
		tween(view.architectural, 0.0, distance(1.0,0.5));
		tween(view.pannini,       0.0, distance(1.0,0.5));
		tween(view.distortion,    0.0, distance(1.0,0.5));
	</action>

	<action name="contextmenu_viewFishEye">
		contextmenu_viewLookStraight();
		tween(view.architectural, 0.0,  distance(1.0,0.5));
		tween(view.pannini,       0.0,  distance(1.0,0.5));
		tween(view.distortion,    0.35, distance(1.0,0.5));
	</action>

	<action name="contextmenu_viewArchitectural">
		contextmenu_viewLookStraight();
		tween(view.architectural, 1.0, distance(1.0,0.5));
		tween(view.pannini,       0.0, distance(1.0,0.5));
		tween(view.distortion,    0.0, distance(1.0,0.5));
	</action>

	<action name="contextmenu_viewStereographic">
		contextmenu_viewLookStraight();
		tween(view.architectural, 0.0, distance(1.0,0.5));
		tween(view.pannini,       0.0, distance(1.0,0.5));
		tween(view.distortion,    1.0, distance(1.0,0.8));
	</action>

	<action name="contextmenu_viewPannini">
		contextmenu_viewLookStraight();
		tween(view.architectural, 0.0, distance(1.0,0.5));
		tween(view.pannini,       1.0, distance(1.0,0.8));
		if(view.distortion LT 0.1,
			tween(view.distortion, 1.0, distance(1.0,0.8));
		);
	</action>

	<action name="contextmenu_viewLittlePlanet">
		tween(view.architectural, 0.0, distance(1.0,0.5));
		tween(view.pannini,       0.0, distance(1.0,0.5));
		tween(view.distortion,    1.0, distance(1.0,0.8));
		tween(view.fov,           150, distance(150,0.8));
		tween(view.vlookat,        90, distance(100,0.8));
		tween(view.hlookat, calc(view.hlookat + 100.0 + 45.0*random), distance(100,0.8));
	</action>
	
	<action name="contextmenu_refreshTheme" 
        scope="local">
        contextmenu_init();
    </action>
	
	<action name="contextmenu_refreshTheme" 
        scope="local">
        contextmenu_init();
    </action>
</krpano>

Nested strings are broken apart

I tried this project out on some .xml test fixtures, and found that the first time I ran it, it made changes like:

image

And then if I ran it again, it would make even more changes:

image

I believe it shouldn't have made any changes at all, since double quotes don't need to be escaped if they're inside single quotes.

Multi-line comments are not preserved

Using version 0.3.0

Before

<?xml version="1.0" encoding="UTF-8" ?>
<properties>
    <!-- Dependency versions -->
    <jhipster-dependencies.version>3.0.6</jhipster-dependencies.version>
    <!-- The spring-boot version should match the one managed by
    https://mvnrepository.com/artifact/io.github.jhipster/jhipster-dependencies/${jhipster-dependencies.version} -->
    <spring-boot.version>2.1.9.RELEASE</spring-boot.version>
</properties>

After

<?xml version="1.0" encoding="UTF-8" ?>
<properties>
  <!-- Dependency versions -->
  <jhipster-dependencies.version>3.0.6</jhipster-dependencies.version>
  <spring-boot.version>2.1.9.RELEASE</spring-boot.version>
</properties>

Preserve comments

This plug-in currently strips all comments from XML files, but many projects use comments for licensing statements, documentation, or other mandatory information that must be preserved.

If the project prefers to remove comments by default, at least consider adding a configuration option that would allow users to preserve comments if necessary.

Add line breaks?

If I have an xml string like:

<xml><test myAttr="test123">Test</test></xml>

Should this plugin be adding line breaks, like:

<xml>
  <test myAttr="test123">Test</test>
</xml>

If not by default, is there an option for this..?

How to install in VScode globally

I'm using VSCode for Salesforce Dev and using Prettier for formatting.

I only seem to be able to enable this xml plugin per VSCode project not globally.

For each created VSCode project I have to:

npm init
npm install --save-dev prettier @prettier/plugin-xml

I just want to enable this plugin for all my VSCode projects. How do I do this just once?

Wrong whitespace added to csproj

editorconfig:

  • max_line_length = 120

current:

<?xml version="1.0" encoding="utf-8" ?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <ProjectTypeGuids>
      {C1CDDADD-2546-481F-9697-4EA41081F2FC};{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
    </ProjectTypeGuids>
</Project>

expected

<?xml version="1.0" encoding="utf-8" ?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <ProjectTypeGuids
        >{C1CDDADD-2546-481F-9697-4EA41081F2FC};{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</Project>

msbuild tooling has problems with the added whitespaces. 😢 Current workaround is to extend max_line_length = 160

Support SVG files as XML

SVG formatting requires renaming to *.xml before running Prettier, and renaming back to .svg afterwards.

Poorly formatted multiple lines strings

Metadata

  • @prettier/plugin-xml version: 0.1.0
  • Options:
    • xmlSelfClosingSpace: false
    • xmlWhitespaceSensitivity: "ignore"

Note - I tried all combinations. Recent log from prettier extension in vscode:

["INFO" - 1:25:52 PM] Detected local configuration (i.e. .prettierrc or .editorconfig), VS Code configuration will not be used
["INFO" - 1:25:52 PM] Prettier Options:
{
  "filepath": "/home/tbeliyah/work/proj/app/plugin/src/main/resources/spring-context.xml",
  "parser": "xml",
  "useTabs": false,
  "tabWidth": 2,
  "endOfLine": "lf",
  "xmlWhitespaceSensitivity": "ignore",
  "xmlSelfClosingSpace": false
}
["INFO" - 1:25:52 PM] Formatting completed in 18.443717ms.

Note 2 - I see that v0.1.0 is quite old, but I can't seem to find a way to install a newer version.

Input

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
  <mvc:annotation-driven>
    <mvc:message-converters>
      <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
    </mvc:message-converters>
  </mvc:annotation-driven>
</beans>

Current output

<?xml version="1.0" encoding="UTF-8"?>
<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"
>
  <mvc:annotation-driven>
    <mvc:message-converters>
      <bean
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"
      />
    </mvc:message-converters>
  </mvc:annotation-driven>
</beans>

Expected output

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
  <mvc:annotation-driven>
    <mvc:message-converters>
      <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
    </mvc:message-converters>
  </mvc:annotation-driven>
</beans>

There is a way to keep blank lines?

This file

<phpdoc>
  <title>PHPDoc-VuePress demo</title>

  <files>
    <directory>demo</directory>
    <directory>api</directory>
  </files>
</phpdoc

...get removed the black space.

<phpdoc>
  <title>PHPDoc-VuePress demo</title>
  <files>
    <directory>demo</directory>
    <directory>api</directory>
  </files>
</phpdoc

I would like to keep it to improve readability, specially in large files.

Could be nice to have a maxBlackLines-like option.

Some significant whitespace is inserted in "xmlWhitespaceSensitivity: ignore" mode

Assume the following xml file:

<test>

   <field name="report_name">event_third_party.template_event_third_party_summary</field>

   <field name="report_file">event_third_party.template_event_third_party_summary</field>

</test>

In xmlWhitespaceSensitivity: ignore mode, signficant whitespace is sometimes inserted to cut long lines, so we get:

<test>
    <field name="report_name">
        event_third_party.template_event_third_party_summary
    </field>
    <field name="report_file">
        event_third_party.template_event_third_party_summary
    </field>
</test>

For our application, the inserted space in field elements is significant.

In strict mode the issue does not occur, but then most automatic indenting is disabled.

My feeling is that, in ignore mode, the text content of an element should never be modified as soon as there is a non-whitespace character in it.

Option for closing bracket to be on the same line

Metadata

  • @prettier/plugin-xml version: '0.13.0
  • Options:

Our gradle spotless config:

        format 'xml', {
            target '**/*.xml'
            prettier(['prettier': '2.0.5', '@prettier/plugin-xml': '0.13.0']).config(['parser': 'xml', 'tabWidth': 4])
        }
  • xmlSelfClosingSpace: true
  • xmlWhitespaceSensitivity: "strict" (be 100% sure changing this to "ignore" doesn't fix your issue)
    • changing it to ignore actually throws an error: (Error while formatting: TypeError: Cannot read property 'startLine' of undefined)

Input

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    android:orientation="horizontal">

Current output

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    android:orientation="horizontal"
>

Expected output

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    android:orientation="horizontal" >

Attribute values erased

When running prettier --write .\app.config --parser=xml, the following app.config file gets transformed from:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="MassTransitConcurrencyLimit" value="1" />
    <add key="MassTransitPrefetchCount" value="8" />
  </appSettings>
</configuration>

Into:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="MassTransitConcurrencyLimit" value="" />
    <add key="MassTransitPrefetchCount" value="" />
  </appSettings>
</configuration>

Losing each of the values 1 and 8 for the two appSettings.

The expected behaviour is that the file should remain unchanged from the initial state.

[email protected]
@prettier/[email protected]

XML prettification changes content of XML tags

When the line width of a file is reached the plugin prettifies the XML as it would prettify for example HTML. But with XML it can actually lead to not only changed formatting, but also changed content.

For example we ran here into the issue that the plugin added line breaks to a boolean, which is invalid.

Incorrect indentation with closing tags

After formatting, I could see the incorrect indentation with closing tags.

Configuration option I have used:
parser: 'xml',
tabWidth: 4,
printWidth: 200,
xmlSelfClosingTags: true,
xmlWhitespaceSensitivity: 'ignore'

XML content:

<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
<edmx:Reference Uri="test">
<edmx:Include Namespace="com.sap.vocabularies.UI.v1" Alias="UI" />
</edmx:Reference>
<edmx:Reference Uri="/opu/odat/test/$metadata">
<edmx:Include Namespace="test2" Alias="test3" />
</edmx:Reference>
<edmx:DataServices>
<Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="testv2704">
<Annotations Target="test4">
<Annotation Term="UI.TextArrangement">

</Annotation>
<Annotation Term="UI.TextArrangement">
</Annotation>
<Annotation Term="Aggregation.ApplySupported">
</Annotation>
</Annotations>
</Schema>
</edmx:DataServices>
</edmx:Edmx>

After formatting:
image

Mixed content in DITA codeblocks wraps at print width

The DITA <codeblock> element is designed for code samples where line breaks are significant.

Works as expected if codeblocks don't contain other XML elements

The Prettier XML plugin seems to do the right thing here most of the time, wrapping attributes of the <codeblock> element to a new line to meet the print-width requirements, but the element content is left alone, so the result is functionally equivalent when running with the following options:

prettier
  --write "**/*.dita"
  --parser=xml
  --print-width 120
  --xml-self-closing-space false
  --xml-whitespace-sensitivity ignore

Before

<codeblock outputclass="language-xml normalize-space show-line-numbers show-whitespace">&lt;plugin id="com.example.WithSupportInfo">

After

<codeblock
  outputclass="language-xml normalize-space show-line-numbers show-whitespace"
>&lt;plugin id="com.example.WithSupportInfo">

Fails to preserve lines if codeblock contains other elements

Given a codeblock with inline elements, lines are wrapped at the print width instead of preserving the original lines.

Before

<codeblock outputclass="language-bash"><cmdname>dita uninstall</cmdname> <varname>&lt;plug-in-id&gt;</varname></codeblock>

The results differ depending on the --xml-whitespace-sensitivity setting, but neither manages to preserve the line as authored:

After --xml-whitespace-sensitivity ignore

<codeblock outputclass="language-bash">
  <cmdname>dita uninstall</cmdname>
  <varname>&lt;plug-in-id&gt;</varname>
</codeblock>

After --xml-whitespace-sensitivity strict

<codeblock outputclass="language-bash"><cmdname>dita uninstall</cmdname> <varname
  >&lt;plug-in-id&gt;</varname></codeblock>

Preserve text in mixed content elements

Mixed complex type elements can contain attributes, elements, and text.

The plug-in currently deletes all text from mixed content elements.

Before

<?xml version="1.0" encoding="UTF-8"?>
<letter>
  Dear Mr. <name>John Smith</name>.
  Your order <orderid digits="4">1032</orderid>
  will be shipped on <shipdate>2001-07-13</shipdate>.
</letter>

After

<?xml version="1.0" encoding="UTF-8" ?>
<letter>
  <name>John Smith</name>
  <orderid digits="4">1032</orderid>
  <shipdate>2001-07-13</shipdate>
</letter>

Indentation problem

I am trying to use the indentation. I have an problem :

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<foo>
<bar>
baz
</bar>
<baz>
<plop />
</baz>
</foo>

if the balise contain other things than balise xml, for example here, "baz". the indentation is bad. my output :

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<foo>
    <bar>
baz
</bar>
    <baz>
        <plop />
    </baz>
</foo>

Also recognize .wsdl files?

Hello

The plugin works pretty good with .xml files (i.e. with the .xml file extension).

Is it possible to associate other extensions like .wsdl to the xml plugin? (For info, a WSDL file is the manifest of a web service; this is a specialized XML content)

The following command will return this error [error] No parser could be inferred for file: webservice.wsdl

prettier.cmd --write "**/*.wsdl"

Thanks

Respect `max_line_length = off`

This plugin does not respect my editorconfig setting.

works

[*.{csproj,targets,props}]
max_line_length = 260

does not work

[*.{csproj,targets,props}]
max_line_length = off

0.3.0: Link-breaks inside of strings are not preserved

We use a framework that defines views as XML files. It uses a syntax for data binding inside of strings, which may become quite complex. They usually utilize line-breaks. Example:

<core:FragmentDefinition
    xmlns:core="sap.ui.core"
    xmlns:m="sap.m">
    <m:Dialog
        icon="sap-icon://message-warning"
        state="Warning"
        title="{
          parts: [ 'catalog_deletion_confirmation_title', '/EntityType' ],
          formatter: '.formatter.formatMessage'
        }"
        class="sapUiContentPadding">
        <m:content>
            <m:Text text="{
                parts: [ 'catalog_deletion_confirmation_message', 'catalog_draft_deletion_confirmation_message', '/EntityType', '/EntityTitle', '/DraftID' ],
                formatter: '.formatter.catalogDeletionMessage'
            }" />
        </m:content>
        <m:buttons>
            <m:Button text="{label_yes}" press=".onCatalogDeletionConfirmed"/>
            <m:Button text="{label_no}" press=".onCatalogDeletionRejected"/>
        </m:buttons>
    </m:Dialog>
</core:FragmentDefinition>

Result:

<core:FragmentDefinition xmlns:core="sap.ui.core" xmlns:m="sap.m">
    <m:Dialog
        icon="sap-icon://message-warning"
        state="Warning"
        title="{           parts: [ 'catalog_deletion_confirmation_title', '/EntityType' ],           formatter: '.formatter.formatMessage'         }"
        class="sapUiContentPadding"
    >
        <m:content>
            <m:Text
                text="{                 parts: [ 'catalog_deletion_confirmation_message', 'catalog_draft_deletion_confirmation_message', '/EntityType', '/EntityTitle', '/DraftID' ],                 formatter: '.formatter.catalogDeletionMessage'             }"
            />
        </m:content>
        <m:buttons>
            <m:Button text="{label_yes}" press=".onCatalogDeletionConfirmed" />
            <m:Button text="{label_no}" press=".onCatalogDeletionRejected" />
        </m:buttons>
    </m:Dialog>
</core:FragmentDefinition>

Not sure if this is in scope but it would be great to have an option to preserve line-breaks inside of strings.

Allow html tags not to be self-closed

We are using XML as our scaffold for HTML, which means we have things like

<div></div>

This gets changed to <div /> which is no longer valid HTML. It would be great to have an option to not self-close these tags

"strict" xmlWhitespaceSensitivity is not respected

<?xml version="1.0" encoding="UTF-8" ?>

<ruleset name="Default">
	<description>Coding standard configuration.</description>

	<rule ref="PSR12" />
	<rule ref="PEAR.Functions.ValidDefaultValue" />
	<rule ref="PEAR.Commenting.InlineComment" />

	<rule ref="Squiz.Operators.ValidLogicalOperators" />
	 <rule ref="Squiz.PHP.CommentedOutCode">
		  <properties>				<property name="maxPercentage" value="50" />
		    </properties>
</rule>
        </ruleset>
λ npx prettier -c phpcs.xml --xml-whitespace-sensitivity=strict
Checking formatting...
All matched files use Prettier code style!

Include this in standard prettier packages

This is more of a question than an issue: Why isn't this included in prettier by default? It seems that inferring that a file is .xml is a simple process, so why isn't this included in the standard cli?

My guess is that this package is not bug-free enough yet, but it's working well for me locally 🤷

Commented elements are uncommented

Using version 0.3.0

Before

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <mainClass>${start-class}</mainClass>
    <fork>true</fork>
    <!--
    Enable the line below to have remote debugging of your application on port 5005
    <jvmArguments>-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005</jvmArguments>
    -->
</configuration>

After

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
  <mainClass>${start-class}</mainClass>
  <fork>true</fork>
  <jvmArguments>-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005</jvmArguments>
</configuration>

How to integrate in pre-commit?

Hello, I mainly program in Python and XML, and I'd love to use prettier for the XML part, but I don't have any npm, yarn, package.json or JS thingies in my projects.

I use pre-commit. Is there a way to include prettier plugins in a .pre-commit-config.yaml file?

Weird buggy format.

Actually:

<?xml version='1.0' encoding='utf-8' ?>
<widget
  xmlns="http://www.w3.org/ns/widgets"
  xmlns:cdv="http://cordova.apache.org/ns/1.0"
>
    <content src="index.html" />
    <access origin="*" />
    <platform name="android">
        <edit-config
      file="app/src/main/AndroidManifest.xml"
      mode="merge"
      target="/manifest/application"
      xmlns:android="http://schemas.android.com/apk/res/android"
    >
            <application
        android:networkSecurityConfig="@xml/network_security_config"
      />
        </edit-config>
        <resource-file
      src="resources/android/xml/network_security_config.xml"
      target="app/src/main/res/xml/network_security_config.xml"
    />
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
</widget>

Expected:

<?xml version='1.0' encoding='utf-8' ?>
<widget
  xmlns="http://www.w3.org/ns/widgets"
  xmlns:cdv="http://cordova.apache.org/ns/1.0"
>
  <content src="index.html" />
  <access origin="*" />
  <platform name="android">
    <edit-config
      file="app/src/main/AndroidManifest.xml"
      mode="merge"
      target="/manifest/application"
      xmlns:android="http://schemas.android.com/apk/res/android"
    >
      <application
        android:networkSecurityConfig="@xml/network_security_config"
      />
    </edit-config>
    <resource-file
      src="resources/android/xml/network_security_config.xml"
      target="app/src/main/res/xml/network_security_config.xml"
    />
    <allow-intent href="market:*" />
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
  </platform>
</widget>

Editorconfig:

charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
max_line_length = 80

Versions:

vscode: 1.54.2
Chrome: 87.0.4280.141
Node.js: 12.18.3
OS: Windows_NT x64 10.0.19042
prettier: 2.2.1
@prettier/plugin-xml: 0.13.1
prettier vscode ext: 5.9.2

Testes format on VSCode with official Prettier extension and CLI only (without extension).
What's going on? Weird indent spaces. For example edit-config one level deeper and application more levels deeper. I cannot see any scheme. I'm confused. What's wrong? Sometimes the format differs. Sometimes formatting doesn't work at all. No Prettier errors. It's random...
Could someone validate this? For example by installing Ionic + Cordova, add Android and format config.xml.

0.3.0: Character '>' inside of strings causes problems

We use a framework that defines views as XML files. Example:

<core:FragmentDefinition
    xmlns:core="sap.ui.core"
    xmlns:m="sap.m">
    <m:Dialog icon="sap-icon://message-warning" state="Warning" title="{
                  parts: [ 'i18n>catalog_deletion_confirmation_title', '/EntityType' ],
                  formatter: '.formatter.formatMessage'
                }"
            class="sapUiContentPadding">
        <m:content>
            <m:Text text="{
                  parts: [ 'i18n>catalog_deletion_confirmation_message', 'i18n>catalog_draft_deletion_confirmation_message', '/EntityType', '/EntityTitle', '/DraftID' ],
                  formatter: '.formatter.catalogDeletionMessage'
                }" />
        </m:content>
        <m:buttons>
            <m:Button text="{label_yes}" press=".onCatalogDeletionConfirmed"/>
            <m:Button text="{i18n>label_no}" press=".onCatalogDeletionRejected"/>
        </m:buttons>
    </m:Dialog>
</core:FragmentDefinition>

It uses a syntax for data binding inside of strings. That may include the character ">". This causes problems. Result:

<core:FragmentDefinition xmlns:core="sap.ui.core" xmlns:m="sap.m">
    <m:Dialog icon="sap-icon://message-warning" state="Warning" title="" "{="" parts:="" [="" 'i18n="">
        <m:content>
            <m:Text text="" "{="" parts:="" [="" 'i18n="">
                catalog_deletion_confirmation_message', 'i18n>catalog_draft_deletion_confirmation_message', '/EntityType', '/EntityTitle', '/DraftID' ],
                  formatter: '.formatter.catalogDeletionMessage'
                }" />
            </m:Text>
            <m:buttons>
                <m:Button text="{label_yes}" press=".onCatalogDeletionConfirmed" />
                <m:Button text="" "{i18n="">label_no}" press=".onCatalogDeletionRejected"/></m:Button>
            </m:buttons>
        </m:content>
    </m:Dialog>
</core:FragmentDefinition>

Inconsistent formatting depending on initial state

I came across those cases (not an exhaustive list though) on files where long lines and big tag attributes were exceeding the maximum line length. While formatting some of them by hand, I figured out that the formatting was actually quite different depending on the initial state.

Prettier version : 1.19.1
Pretter options :

{
  "arrowParens": "avoid",
  "bracketSpacing": true,
  "insertPragma": false,
  "printWidth": 80,
  "proseWrap": "preserve",
  "quoteProps": "as-needed",
  "requirePragma": false,
  "semi": true,
  "singleQuote": false,
  "tabWidth": 2,
  "trailingComma": "none",
  "useTabs": false,
  "parser": "xml"
}

Case 1

Before
<a>
<b>
<c xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="1" yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy="2" zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz="3"/>
</b>
</a>
After
<a>
<b>
<c
      xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="1"
      yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy="2"
      zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz="3"
    />
</b>
</a>

Here, the b tag is not indented, and the first half of c tag as well as his attributes are missing an indent.

Case 2

Before
<a>
<b>
    <c xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="1" yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy="2" zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz="3"/>
</b>
</a>
After
<a>
<b>
    <c
      xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="1"
      yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy="2"
      zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz="3"
    />
</b>
</a>

The c tag is correctly indented, b tag still isn't.

Case 3

Before
<a><b><c xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="1" yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy="2" zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz="3"/></b></a>
After
<a><b><c
      xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="1"
      yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy="2"
      zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz="3"
    /></b></a>

I don't really know what is going on on this one.

TypeError: Cannot read property 'startLine' of undefined (v0.13.0)

I get the following error if i try to update to newest version


$ prettier "{**/*,*}.*" -u --list-different
--
1183 | [error] dir\file.xml: TypeError: Cannot read property 'startLine' of undefined
1184 | [error]     at Object.element (C:\drone\src\node_modules\@prettier\plugin-xml\src\printer.js:336:34)
1185 | [error]     at Object.genericPrint [as print] (C:\drone\src\node_modules\@prettier\plugin-xml\src\printer.js:412:30)
1186 | [error]     at callPluginPrintFunction (C:\drone\src\node_modules\prettier\index.js:14718:18)
1187 | [error]     at C:\drone\src\node_modules\prettier\index.js:14649:47
1188 | [error]     at Object.printComments (C:\drone\src\node_modules\prettier\index.js:14305:19)
1189 | [error]     at printGenerically (C:\drone\src\node_modules\prettier\index.js:14649:22)
1190 | [error]     at FastPath.call (C:\drone\src\node_modules\prettier\index.js:14441:20)
1191 | [error]     at C:\drone\src\node_modules\@prettier\plugin-xml\src\printer.js:308:27
1192 | [error]     at Array.map (<anonymous>)
1193 | [error]     at Object.element (C:\drone\src\node_modules\@prettier\plugin-xml\src\printer.js:304:19)


dir\file.xml

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<Event>
    <Process id="XXX.Notification">

    </Process>
    <!--<Process id="XXX.Notification.Tmpl" >
        <Condition>[v:NType] == 'Tmpl'</Condition>
    </Process>-->
</Event>

Crashes while formatting NativeScript XML

NativeScript uses .xml files so I thought I would use prettier-xml for auto-formatting with VsCode.

XML file example:
Screenshot 2020-07-03 at 12 26 42

"@prettier/plugin-xml": "0.7.2",
"prettier": "1.19.1".

It throws:
"Error: Error parsing XML
at Object.parse (/Users/utukku/SnappCar Projects/frontend-app/node_modules/@prettier/plugin-xml/src/parse.js:7:11)
at Object.parse (/Users/utukku/SnappCar Projects/frontend-app/node_modules/prettier/index.js:9739:19)
at coreFormat (/Users/utukku/SnappCar Projects/frontend-app/node_modules/prettier/index.js:13252:23)
at format (/Users/utukku/SnappCar Projects/frontend-app/node_modules/prettier/index.js:13510:73)
at formatWithCursor (/Users/utukku/SnappCar Projects/frontend-app/node_modules/prettier/index.js:13526:12)
at /Users/utukku/SnappCar Projects/frontend-app/node_modules/prettier/index.js:44207:15
at Object.format (/Users/utukku/SnappCar Projects/frontend-app/node_modules/prettier/index.js:44226:12)
at t.default. (/Users/utukku/.vscode/extensions/esbenp.prettier-vscode-5.1.3/dist/extension.js:1:58387)
at Generator.next ()
at s (/Users/utukku/.vscode/extensions/esbenp.prettier-vscode-5.1.3/dist/extension.js:1:53305)"

Not formatting my xml, don't see a trace of the plugin being used/loaded in the prettier output

Using VS Code in WSL mode, prettier and @prettier/plugin-xml installed globally.

The only formatting effect that I see is in my test.xml the space added in the declaration changing it from <?xml version="1.0"?> to <?xml version="1.0" ?>.

<?xml version="1.0" ?>
<contact-info>
                <name>Tanmay Patil</name><company>TutorialsPoint</company>
   <phone>(011) 123-4567</phone>
</contact-info>
["INFO" - 10:04:46 AM] Formatting /mnt/c/Users/pietejanssens/code/career-insights/test.xml
["INFO" - 10:04:46 AM] Using ignore file (if present) at /mnt/c/Users/pietejanssens/code/.prettierignore
["INFO" - 10:04:46 AM] Loaded module '[email protected]' from '/home/pieter/.nvm/versions/node/v14.15.4/lib/node_modules/prettier'
["INFO" - 10:04:46 AM] File Info:
{
  "ignored": false,
  "inferredParser": "xml"
}
["INFO" - 10:04:46 AM] No local configuration (i.e. .prettierrc or .editorconfig) detected, falling back to VS Code configuration
["INFO" - 10:04:46 AM] Prettier Options:
{
  "arrowParens": "always",
  "bracketSpacing": true,
  "endOfLine": "lf",
  "htmlWhitespaceSensitivity": "css",
  "insertPragma": false,
  "jsxBracketSameLine": false,
  "jsxSingleQuote": false,
  "printWidth": 80,
  "proseWrap": "preserve",
  "quoteProps": "as-needed",
  "requirePragma": false,
  "semi": true,
  "singleQuote": false,
  "tabWidth": 2,
  "trailingComma": "es5",
  "useTabs": false,
  "vueIndentScriptAndStyle": false,
  "filepath": "/mnt/c/Users/pietejanssens/code/test.xml",
  "parser": "xml"
}
["INFO" - 10:04:46 AM] Formatting completed in 111.7021ms.

The plugin fails to parse XML with doctype

The XML I have (from the jhipster project defaults)

<?xml version="1.0"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
        "https://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">

    <!-- Configure checker to use UTF-8 encoding -->
    <property name="charset" value="UTF-8"/>
    <!-- Configure checker to run on files with these extensions -->
    <property name="fileExtensions" value=""/>
    <!-- For detailed checkstyle configuration, see https://github.com/spring-io/nohttp/tree/master/nohttp-checkstyle -->
    <module name="io.spring.nohttp.checkstyle.check.NoHttpCheck">
        <property name="whitelist" value="http://maven.apache.org/POM/4.0.0&#10;
            http://www.w3.org/2001/XMLSchema-instance&#10;http://maven.apache.org/maven-v4_0_0.xsd"/>
    </module>
    <!-- Allow suppression with comments
       // CHECKSTYLE:OFF
       ... ignored content ...
       // CHECKSTYLE:ON
    -->
    <module name="SuppressWithPlainTextCommentFilter"/>
</module>

The error I get

[error] checkstyle.xml: Error: Error parsing XML
[error]     at Object.parse (/home/user/node_modules/@prettier/plugin-xml/src/parse.js:7:11)
[error]     at Object.parse (/home/user/node_modules/prettier/bin-prettier.js:9743:19)
[error]     at coreFormat (/home/user/node_modules/prettier/bin-prettier.js:13258:23)
[error]     at format (/home/user/node_modules/prettier/bin-prettier.js:13516:73)
[error]     at formatWithCursor (/home/user/node_modules/prettier/bin-prettier.js:13532:12)
[error]     at Object.formatWithCursor (/home/user/node_modules/prettier/bin-prettier.js:44213:15)
[error]     at format$1 (/home/user/node_modules/prettier/bin-prettier.js:45598:19)
[error]     at /home/user/node_modules/prettier/bin-prettier.js:45792:16
[error]     at /home/user/node_modules/prettier/bin-prettier.js:45731:14
[error]     at Array.forEach (<anonymous>)

NPM modules I have

"prettier": "1.19.1",
"@prettier/plugin-xml": "^0.4.0",

If I remove the doctype then it works correctly. Not sure if it is related to #5

Preserve DOCTYPE declarations

This plug-in currently preserves the optional XML declaration on the first line of XML files:

<?xml version="1.0" encoding="UTF-8"?>

but strips any subsequent DOCTYPE declarations that are required for DTD-based validation in XML dialects, such as DocBook or DITA.

These declarations should be preserved to allow editors and parsers to validate the file content.

DocBook example

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
                         "http://docbook.org/xml/4.5/docbookx.dtd">
<article>
    <title/>
    <sect1>
        <title/>
        <para/>
    </sect1>
</article>

DITA example

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE task PUBLIC "-//OASIS//DTD DITA Task//EN" "task.dtd">
<task id="ID">
    <title></title>
    <shortdesc></shortdesc>
    <taskbody>
        <context>
            <p></p>
        </context>
        <steps>
            <step>
                <cmd></cmd>
            </step>
        </steps>
    </taskbody>
</task>

Preserve XML processing instructions

This plug-in currently preserves the optional XML declaration on the first line of XML files, but strips any subsequent processing instructions from the rest of the file.

For example, in many XML workflows, <?xml-model … ?> processing instructions are used to provide validation support via schema languages like RELAX NG, W3C XML Schema, DTD and Schematron.

<?xml version="1.0" encoding="UTF-8"?>
<?xml-model href="project.rnc" type="application/relax-ng-compact-syntax"?>
<foo />

For more information, see http://www.w3.org/TR/xml-model/ and http://xml-model.info.

Other use cases may depend heavily on other (proprietary) processing instructions, so it would be best to provide an option to handle all processing instructions, regardless of their content.

If the project prefers to remove processing instructions by default, at least consider adding a configuration option that would allow users to preserve them if necessary.

Support for '.inx' files

This is similar to #89:

Is it possible to add .inx files to be recognized by your plugin? .inx is an .xml file used by Inkscape and Adobe InDesign.

Thanks in advance!

PS: Is there maybe a CLI option or a config file (don't think prettier supports any, right?) that would accept a list of extensions?

Error parsing XML with attributes starting with an underscore

Hi,

I am trying to run prettier on an XML file like this:

<?xml version="1.0" encoding="utf-8" ?>
<a _test="5" />

When executing prettier test.xml (test.xml being the file listed above), it fails with:

test.xml[error] test.xml: Error: Error parsing XML
[error]     at Object.parse (C:\Temp\node_modules\@prettier\plugin-xml\src\parse.js:7:11)
[error]     at Object.parse (C:\Temp\node_modules\prettier\bin-prettier.js:9743:19)
[error]     at coreFormat (C:\Temp\node_modules\prettier\bin-prettier.js:13258:23)
[error]     at format (C:\Temp\node_modules\prettier\bin-prettier.js:13516:73)
[error]     at formatWithCursor (C:\Temp\node_modules\prettier\bin-prettier.js:13532:12)
[error]     at Object.formatWithCursor (C:\Temp\node_modules\prettier\bin-prettier.js:44213:15)
[error]     at format$1 (C:\Temp\node_modules\prettier\bin-prettier.js:45598:19)
[error]     at C:\Temp\node_modules\prettier\bin-prettier.js:45792:16
[error]     at C:\Temp\node_modules\prettier\bin-prettier.js:45731:14
[error]     at Array.forEach (<anonymous>)

This is on prettier 1.19.1 and @prettier/plugin-xml 0.7.1

Thanks and regards,
Dirk

Drop space before slash in empty elements

Currently, the plug-in enforces a space before the closing slash in empty elements when xmlSelfClosingTags is true, normalizing <foo></foo> and <foo/> to <foo />.

Some projects prefer the tighter <foo/> syntax, so if an option already exists to configure empty tag handling, perhaps a third value could be added to support this convention, like:

  • true (no space) – <foo/>
  • false<foo></foo>
  • space (current behavior) – <foo />

If so, this setting could also be applied to the XML declaration, to permit

<?xml version="1.0" encoding="UTF-8"?>

instead of rewriting to insert an extra space before the closing ?> as noted in #3:

<?xml version="1.0" encoding="UTF-8" ?>

Changes Content

When running this on an attribute like:

<apiVersion>47.0</apiVersion>

The output is:

<apiVersion>47</apiVersion>

This specifically is used for Salesforce metadata in which case this is a breaking change. Not sure if this is considered a valid XML optimization, but if so, i think we need an option to disable this. My opinion though is that contents are never modified.

Thanks! Great project so far. :)

0.4.0: indentation issues

Using 0.4.0 I tested one of our XML files.

Settings:

tabWidth: 4
printWidth: 120

Before:

<core:FragmentDefinition
  xmlns:core="sap.ui.core"
  xmlns:m="sap.m"
  xmlns:dev="sap.ead.c4s.ui.view.control"
  xmlns:devEl="sap.ead.c4s.ui.view.element"
  xmlns="http://www.w3.org/1999/xhtml">
  <m:VBox
    renderType="Bare"
    items="{
        path: 'contextMenu>/Info/Context',
        templateShareable: false
      }">
    <dev:SmallBreadcrumbs
      items="{
          path: 'contextMenu>',
          templateShareable: false
        }">
      <dev:items>
        <devEl:SmallBreadcrumbItem depth="{contextMenu>depth}">
          <m:HBox renderType="Bare">
            <m:HBox renderType="Bare">
              <dev:DataExplorerIcon
                explorerType="{contextMenu>DataExplorerType}"
                explorerSubType="{contextMenu>DataExplorerSubType}"/>
              <m:Label
                text="{
                    path: 'contextMenu>',
                    formatter: '._navigationPathTitleFormatter'
                  }"
                class="c4sSmallTileHeaderTitle"/>
            </m:HBox>
          </m:HBox>
        </devEl:SmallBreadcrumbItem>
      </dev:items>
    </dev:SmallBreadcrumbs>
  </m:VBox>
</core:FragmentDefinition>

After:

<core:FragmentDefinition
    xmlns:core="sap.ui.core"
    xmlns:m="sap.m"
    xmlns:dev="sap.ead.c4s.ui.view.control"
    xmlns:devEl="sap.ead.c4s.ui.view.element"
    xmlns="http://www.w3.org/1999/xhtml"
>
  <m:VBox renderType="Bare" items="{
        path: 'contextMenu>/Info/Context',
        templateShareable: false
      }">
    <dev:SmallBreadcrumbs items="{
          path: 'contextMenu>',
          templateShareable: false
        }">
      <dev:items>
        <devEl:SmallBreadcrumbItem depth="{contextMenu>depth}">
          <m:HBox renderType="Bare">
            <m:HBox renderType="Bare">
              <dev:DataExplorerIcon
                                explorerType="{contextMenu>DataExplorerType}"
                                explorerSubType="{contextMenu>DataExplorerSubType}"
                            />
              <m:Label
                                text="{
                    path: 'contextMenu>',
                    formatter: '._navigationPathTitleFormatter'
                  }"
                                class="c4sSmallTileHeaderTitle"
                            />
            </m:HBox>
          </m:HBox>
        </devEl:SmallBreadcrumbItem>
      </dev:items>
    </dev:SmallBreadcrumbs>
  </m:VBox>
</core:FragmentDefinition>

Perceived issues:

  1. Starting in line 8, a tabWidth of 2 seems to be used.
  2. Surprisingly high indentations in lines 21 - 23, 25, 29, 30.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.