From 5c4a3c1b313a566bdd5077a9d3f2df98317e8039 Mon Sep 17 00:00:00 2001 From: Abhishek Date: Fri, 13 Nov 2026 16:03:49 +0530 Subject: [PATCH] Remove backspaced characters when merging streams --- myst_nb/core/utils.py | 6 ++---- tests/test_render_outputs.py | 13 +++++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/myst_nb/core/utils.py b/myst_nb/core/utils.py index c06b11cf..20ff098f 100644 --- a/myst_nb/core/utils.py +++ b/myst_nb/core/utils.py @@ -7,7 +7,7 @@ from nbformat import NotebookNode _RGX_CARRIAGERETURN = re.compile(r".*\r(?=[^\n])") -_RGX_BACKSPACE = re.compile(r"[^\n]\b") +_RGX_BACKSPACE = re.compile(r"[^\n\x08]\x08") def coalesce_streams(outputs: list[NotebookNode]) -> list[NotebookNode]: @@ -38,9 +38,7 @@ def coalesce_streams(outputs: list[NotebookNode]) -> list[NotebookNode]: # process \r and \b characters for output in streams.values(): - old = output["text"] - while len(output["text"]) < len(old): - old = output["text"] + while _RGX_BACKSPACE.search(output["text"]): # Cancel out anything-but-newline followed by backspace output["text"] = _RGX_BACKSPACE.sub("", output["text"]) # Replace all carriage returns not followed by newline diff --git a/tests/test_render_outputs.py b/tests/test_render_outputs.py index bfd29e51..349dcbd5 100644 --- a/tests/test_render_outputs.py +++ b/tests/test_render_outputs.py @@ -3,6 +3,8 @@ import pytest from myst_nb.core.render import EntryPointError, load_renderer +from myst_nb.core.utils import coalesce_streams +from nbformat import from_dict from sphinx.util.fileutil import copy_asset_file @@ -116,6 +118,17 @@ def test_merge_streams_parallel(sphinx_run, file_regression): file_regression.check(doctree.pformat(), extension=".xml", encoding="utf-8") +def test_merge_streams_backspace(): + """Test that merging streams cancels out characters erased by backspaces.""" + outputs = [ + from_dict( + {"output_type": "stream", "name": "stdout", "text": "50%\b\b\b100%\n"} + ), + from_dict({"output_type": "stream", "name": "stderr", "text": "a\bb word\n"}), + ] + assert [o["text"] for o in coalesce_streams(outputs)] == ["100%\n", "b word\n"] + + @pytest.mark.sphinx_params( "metadata_image.ipynb", conf={"nb_execution_mode": "off", "nb_cell_metadata_key": "myst"},