From 34693aea8a93681985ca9b642becfbc315b98512 Mon Sep 17 00:00:00 2001 From: Vincent Gao Date: Mon, 22 Jun 2026 11:12:01 +0200 Subject: [PATCH] Preserve whitespace when replacing super tables --- tests/test_toml_document.py | 18 ++++++++++++++++++ tomlkit/container.py | 9 ++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/tests/test_toml_document.py b/tests/test_toml_document.py index 1cdfb9c5..b5727554 100644 --- a/tests/test_toml_document.py +++ b/tests/test_toml_document.py @@ -965,6 +965,24 @@ def test_replace_preserve_sep() -> None: ) +def test_replace_super_table_preserves_whitespace() -> None: + content = """\ +[env.pro1.rst] +name = "x7" + +[env2] +name = 2 + +[env3] +name = 3 +""" + doc = parse(content) + + doc["env"] = doc["env"] + + assert doc.as_string() == content + + def test_replace_with_table_of_nested() -> None: example = """\ [a] diff --git a/tomlkit/container.py b/tomlkit/container.py index 75e09018..50e476e5 100644 --- a/tomlkit/container.py +++ b/tomlkit/container.py @@ -1152,9 +1152,12 @@ def ends_with_whitespace(it: Any) -> bool: """Returns ``True`` if the given item ``it`` is a ``Table`` or ``AoT`` object ending with a ``Whitespace``. """ - return ( - isinstance(it, Table) and isinstance(it.value._previous_item(), Whitespace) - ) or (isinstance(it, AoT) and len(it) > 0 and isinstance(it[-1], Whitespace)) + if isinstance(it, Whitespace): + return True + if isinstance(it, Table): + previous = it.value._previous_item() + return previous is not None and ends_with_whitespace(previous) + return isinstance(it, AoT) and len(it) > 0 and ends_with_whitespace(it[-1]) def _equal_with_nan(left: Any, right: Any) -> bool: