diff --git a/.changeset/preserve-nbsp-html-text.md b/.changeset/preserve-nbsp-html-text.md new file mode 100644 index 000000000..88eb4a316 --- /dev/null +++ b/.changeset/preserve-nbsp-html-text.md @@ -0,0 +1,5 @@ +--- +'@shopify/prettier-plugin-liquid': patch +--- + +Preserve non-breaking spaces (U+00A0) in HTML text nodes and stop dropping borrowed closing tag markers when a text node is pure whitespace. diff --git a/packages/prettier-plugin-liquid/src/printer/printer-liquid-html.ts b/packages/prettier-plugin-liquid/src/printer/printer-liquid-html.ts index 57f4f91bf..36e1e6c2e 100644 --- a/packages/prettier-plugin-liquid/src/printer/printer-liquid-html.ts +++ b/packages/prettier-plugin-liquid/src/printer/printer-liquid-html.ts @@ -158,7 +158,19 @@ function printTextNode( if (isYamlFrontMatter(node)) return node.value; - if (node.value.match(/^\s*$/)) return ''; + // Only ASCII/HTML whitespace is collapsible. Do not treat U+00A0 (NBSP) or + // other unicode "whitespace" as collapsible, since they are meaningful + // characters in the rendered output. + const HTML_WHITESPACE_RUN = /[ \t\n\r\f]+/g; + const HTML_WHITESPACE_TRIM = /^[ \t\n\r\f]+|[ \t\n\r\f]+$/g; + + // If the text is purely collapsible whitespace we still need to emit the + // open/close prefixes so that any tag markers borrowed from the parent + // aren't lost (see needsToBorrowParentClosingTagStartMarker). + if (node.value.replace(HTML_WHITESPACE_RUN, '') === '') { + return [printOpeningTagPrefix(node, options), printClosingTagSuffix(node, options)]; + } + const text = node.value; const paragraphs = text @@ -166,7 +178,7 @@ function printTextNode( .filter(Boolean) // removes empty paragraphs (trailingWhitespace) .map((curr) => { let doc = []; - const words = curr.trim().split(/\s+/g); + const words = curr.replace(HTML_WHITESPACE_TRIM, '').split(HTML_WHITESPACE_RUN); let isFirst = true; for (let j = 0; j < words.length; j++) { const word = words[j]; diff --git a/packages/prettier-plugin-liquid/src/test/unit-paragraphs/fixed.liquid b/packages/prettier-plugin-liquid/src/test/unit-paragraphs/fixed.liquid index b3be6f0ab..8cbab6278 100644 --- a/packages/prettier-plugin-liquid/src/test/unit-paragraphs/fixed.liquid +++ b/packages/prettier-plugin-liquid/src/test/unit-paragraphs/fixed.liquid @@ -74,3 +74,8 @@ printWidth: 20 >Lorem Ipsum
+ +it should preserve non-breaking spaces (U+00A0) as text and not drop borrowed closing tags ++ +
diff --git a/packages/prettier-plugin-liquid/src/test/unit-paragraphs/index.liquid b/packages/prettier-plugin-liquid/src/test/unit-paragraphs/index.liquid index 840bb1171..680fc4fcf 100644 --- a/packages/prettier-plugin-liquid/src/test/unit-paragraphs/index.liquid +++ b/packages/prettier-plugin-liquid/src/test/unit-paragraphs/index.liquid @@ -56,3 +56,6 @@ printWidth: 20{{ drop }}Lorem Ipsum
+ +it should preserve non-breaking spaces (U+00A0) as text and not drop borrowed closing tags +\ No newline at end of file