Preserve explicit language in front matter (#16348)

This commit is contained in:
fisker Cheung authored and GitHub committed 2024-06-04 17:32:50 +08:00
1 parent b26f56bd31
commit 590644170e
6 files changed
+41 -10

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
#### Preserve explicit language in front matter (#16348 by @fisker)
<!-- prettier-ignore -->
```markdown
<!-- Input -->
---yaml
title: Hello
slug: home
---
<!-- Prettier stable -->
---
title: Hello
slug: home
---
<!-- Prettier main -->
---yaml
title: Hello
slug: home
---
```
+1 -1
View File
@@ -12,7 +12,7 @@ const ignoredProperties = new Set([
]);
function clean(original, cloned, parent) {
if (isFrontMatter(original) && original.lang === "yaml") {
if (isFrontMatter(original) && original.language === "yaml") {
delete cloned.value;
}
+14 -6
View File
@@ -1,7 +1,7 @@
const frontMatterRegex = new RegExp(
String.raw`^(?<startDelimiter>-{3}|\+{3})` +
// trailing spaces after delimiters are allowed
String.raw`(?<language>[^\n]*)` +
String.raw`(?<explicitLanguage>[^\n]*)` +
String.raw`\n(?:|(?<value>.*?)\n)` +
// In some markdown processors such as pandoc,
// "..." can be used as the end delimiter for YAML front-matter.
@@ -17,22 +17,30 @@ function parse(text) {
return { content: text };
}
const { startDelimiter, language, value = "", endDelimiter } = match.groups;
let {
startDelimiter,
explicitLanguage,
value = "",
endDelimiter,
} = match.groups;
let lang = language.trim() || "yaml";
explicitLanguage = explicitLanguage.trim();
let language = explicitLanguage || "yaml";
if (startDelimiter === "+++") {
lang = "toml";
language = "toml";
}
// Only allow yaml to parse with a different end delimiter
if (lang !== "yaml" && startDelimiter !== endDelimiter) {
if (language !== "yaml" && startDelimiter !== endDelimiter) {
return { content: text };
}
const [raw] = match;
const frontMatter = {
type: "front-matter",
lang,
language,
explicitLanguage: explicitLanguage || undefined,
value,
startDelimiter,
endDelimiter,
+2 -1
View File
@@ -1,11 +1,12 @@
import { hardline, markAsRoot } from "../../document/builders.js";
async function print(node, textToDoc) {
if (node.lang === "yaml") {
if (node.language === "yaml") {
const value = node.value.trim();
const doc = value ? await textToDoc(value, { parser: "yaml" }) : "";
return markAsRoot([
node.startDelimiter,
node.explicitLanguage ?? "",
hardline,
doc,
doc ? hardline : "",
@@ -106,7 +106,7 @@ slug: home
Hello world!</h1>
=====================================output=====================================
---
---yaml
title: Hello
slug: home
---
@@ -96,7 +96,7 @@ Hello world!
=====================================output=====================================
---
---yaml
title: Hello
slug: home
...