diff --git a/src/parser-parse5.js b/src/parser-parse5.js index 6f15988b2..18abfaf54 100644 --- a/src/parser-parse5.js +++ b/src/parser-parse5.js @@ -6,7 +6,8 @@ function parse(text) { // Inline the require to avoid loading all the JS if we don't use it const parse5 = require("parse5"); try { - const ast = parse5.parse(text, { + const isFragment = !/^\s*<(!doctype|html|head|body)/i.test(text); + const ast = (isFragment ? parse5.parseFragment : parse5.parse)(text, { treeAdapter: parse5.treeAdapters.htmlparser2, locationInfo: true }); diff --git a/src/printer-htmlparser2.js b/src/printer-htmlparser2.js index 5044a8c27..fe6237018 100644 --- a/src/printer-htmlparser2.js +++ b/src/printer-htmlparser2.js @@ -1,5 +1,6 @@ "use strict"; +const util = require("./util"); const docBuilders = require("./doc-builders"); const concat = docBuilders.concat; const join = docBuilders.join; @@ -62,15 +63,24 @@ function genericPrint(path, options, print) { children.push(childPath.call(print)); }, "children"); + const hasNewline = util.hasNewlineInRange( + options.originalText, + util.locStart(n), + util.locEnd(n) + ); + return group( concat([ + hasNewline ? hardline : "", "<", n.name, printAttributes(n.attribs), n.children.length ? ">" : selfClose, - indent(concat(children)), + n.name.toLowerCase() === "html" + ? concat(children) + : indent(concat(children)), n.children.length ? concat([softline, "", n.name, ">"]) : "" ]) ); diff --git a/tests/html_basics/__snapshots__/jsfmt.spec.js.snap b/tests/html_basics/__snapshots__/jsfmt.spec.js.snap index 2bcd2edbd..c9d9b2683 100644 --- a/tests/html_basics/__snapshots__/jsfmt.spec.js.snap +++ b/tests/html_basics/__snapshots__/jsfmt.spec.js.snap @@ -17,13 +17,27 @@ exports[`hello-world.html 1`] = ` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + -
- - - -