prompt-toolkit / python-prompt-toolkit

Library for building powerful interactive command line applications in Python
https://python-prompt-toolkit.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
9.35k stars 716 forks source link

Can't scroll TextArea using FormattedTextControl for ANSI colors #1903

Open oxysoft opened 3 months ago

oxysoft commented 3 months ago
# Repro case for prompt_toolkit issue with FormattedTextControl and scrolling in TextArea

from prompt_toolkit import Application
from prompt_toolkit.layout import Layout, HSplit, VSplit
from prompt_toolkit.widgets import TextArea
from prompt_toolkit.layout.controls import FormattedTextControl
from prompt_toolkit import ANSI
from prompt_toolkit.key_binding import KeyBindings

def create_repro_app():
    # Create a TextArea with regular text
    regular_text_area = TextArea(
        text="Regular TextArea:\n" + "\n".join([f"Line {i}" for i in range(100)]),
        scrollbar=True,
        wrap_lines=True,
    )

    # Create a TextArea with FormattedTextControl for ANSI text
    ansi_text = ANSI("\n".join([
        f"\033[1;3{i%8}mANSI Formatted Line {i}\033[0m" for i in range(100)
    ]))
    formatted_text_area = TextArea(
        scrollbar=True,
        wrap_lines=True,
    )
    formatted_text_area.window.content = FormattedTextControl(ansi_text)

    # Create the layout
    layout = Layout(
        HSplit([
            VSplit([
                regular_text_area,
                formatted_text_area,
            ]),
        ])
    )

    # Create key bindings
    kb = KeyBindings()

    @kb.add('tab')
    def _(event):
        # Toggle focus between text areas
        if event.app.layout.has_focus(regular_text_area):
            event.app.layout.focus(formatted_text_area)
        else:
            event.app.layout.focus(regular_text_area)

    @kb.add('escape', 'q')
    def _(event):
        """Quit the application when 'escape' followed by 'q' is pressed."""
        event.app.exit()

    # Create and return the application
    return Application(layout=layout, key_bindings=kb, full_screen=True)

def run_repro():
    app = create_repro_app()
    app.run()

# Run the repro case
run_repro()

# Note: This repro case demonstrates that while the regular TextArea
# scrolls normally, the TextArea with FormattedTextControl for ANSI
# text does not scroll properly for multiline content.
# Use Tab key to switch focus between the two text areas.
kumara19bara commented 2 months ago

Hi there Any news about the Issue. I failed to get both colors and scrolling using TextArea. only one of them at a time. I tried to change TextArea to Window than to Label. but they don't have mouse scrolling.

In calculator example, I was trying to get the result of output_field here in different colors while keeping the mouse scrolling feature with no success.