Skip to content

Stabilize XML declaration formatting on reformat#1009

Open
sarathfrancis90 wants to merge 1 commit into
prettier:mainfrom
sarathfrancis90:fix-xml-declaration-reformat
Open

Stabilize XML declaration formatting on reformat#1009
sarathfrancis90 wants to merge 1 commit into
prettier:mainfrom
sarathfrancis90:fix-xml-declaration-reformat

Conversation

@sarathfrancis90

Copy link
Copy Markdown

Running the plugin on its own output isn't stable when the XML declaration wraps. If a <?xml … ?> declaration is long enough (or printWidth small enough) to break onto multiple lines, the first pass produces

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

but a second pass inserts a blank line right after <?xml:

<?xml

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

So formatted files don't pass prettier --check.

The cause is in printProlog: the XMLDeclOpen token's image isn't just <?xml — its lexer pattern is /<\?xml[ \t\r\n]/, so it also carries the one whitespace character that follows. We print that character verbatim. On a wrapped declaration that character is a newline, and printing it ahead of the line break that begins the attributes yields the extra blank line.

I print a normalized <?xml and let the existing layout supply the spacing (the leading softline becomes a line so the single-line case keeps its space). The common single-line output is unchanged, and a wrapped declaration now round-trips. Added a test that formats a wrapped declaration twice and asserts the second pass is a no-op.

The XMLDeclOpen token ("<?xml") carries the single whitespace character
that follows it, since its lexer pattern is /<\?xml[ \t\r\n]/. Printing that
character verbatim is not stable: when the declaration wraps onto multiple
lines, the captured character is a newline, and re-formatting then renders an
extra blank line right after "<?xml". As a result prettier's own output of a
wrapped declaration is not idempotent and fails prettier --check.

Print a normalized "<?xml" and let the surrounding layout provide the
spacing, so a wrapped declaration round-trips unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant