Skip to content

Commit df37c92

Browse files
YAML frontmatter: drop block scalars so all strings round-trip
Block scalars cannot preserve newline-only strings on Python 3.12 where splitlines() yields ['']. Always emit double-quoted scalars. Widen test_escape_yaml_roundtrip to cover multiline text.
1 parent 6579447 commit df37c92

2 files changed

Lines changed: 4 additions & 15 deletions

File tree

tests/test_md_exporter_yaml.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -82,10 +82,10 @@ def test_yaml_frontmatter_roundtrip(self):
8282
assert yaml.safe_load(md.split("---")[1]) == _session_frontmatter_dict(session)
8383
assert _extract_frontmatter_dict(md) == _session_frontmatter_dict(session)
8484

85-
def test_multiline_title_uses_block_scalar(self):
85+
def test_multiline_title_uses_quoted_scalar(self):
8686
session = _base_session(title="line one\nline two")
8787
md = session_to_markdown(session)
88-
assert "title: |-" in md.split("---")[1]
88+
assert 'title: "line one\\nline two"' in md.split("---")[1]
8989
assert _extract_frontmatter_dict(md)["title"] == "line one\nline two"
9090

9191
def test_tab_and_hash_in_title(self):
@@ -97,9 +97,7 @@ def test_tab_and_hash_in_title(self):
9797
@FUZZ_SETTINGS
9898
@given(st.text())
9999
def test_escape_yaml_roundtrip(s: str) -> None:
100-
"""Double-quoted scalars round-trip for arbitrary single-line text."""
101-
if "\n" in s or "\r" in s:
102-
return
100+
"""Double-quoted scalars round-trip for arbitrary text."""
103101
loaded = yaml.safe_load(f"key: {_escape_yaml(s)}")
104102
assert loaded["key"] == s
105103

utils/md_exporter.py

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -478,7 +478,7 @@ def _yaml_mapping_key(key: str) -> str:
478478

479479

480480
def _escape_yaml(s: str) -> str:
481-
"""Return a YAML double-quoted scalar for a single-line string value."""
481+
"""Return a YAML double-quoted scalar for any string (including embedded newlines)."""
482482
parts: list[str] = []
483483
for ch in s:
484484
if ch == "\\":
@@ -522,15 +522,6 @@ def _append_yaml_value(lines: list[str], key: str, value: Any, *, indent: int =
522522
return
523523
if not isinstance(value, str):
524524
raise TypeError(f"unsupported frontmatter value type: {type(value).__name__}")
525-
if "\n" in value:
526-
content_lines = value.splitlines()
527-
if content_lines and all(ch in "\n\r\t" or ch.isprintable() for ch in value):
528-
lines.append(f"{prefix}{key}: |-")
529-
for line in content_lines:
530-
lines.append(f"{prefix} {line}")
531-
return
532-
lines.append(f"{prefix}{key}: {_escape_yaml(value)}")
533-
return
534525
lines.append(f"{prefix}{key}: {_escape_yaml(value)}")
535526

536527

0 commit comments

Comments
 (0)