Skip to content

Commit ead92b0

Browse files
committed
Take the built-in pager out, to be proposed on its own
The persistent toolbar and the pager which keeps it visible while paging arrived together, but they are two decisions. The pager is about 300 of this branch's 1,050 source lines and a third of its tests, and issue #1743 itself allows the toolbar to disappear "when using a pager". Remove cmd2/pager.py, CommandToolbar.page() and the helpers only it used, the use_builtin_pager attribute, their tests and their documentation. ppaged() goes back to the configured external pager, with the toolbar suspended while it has the terminal, which is the path use_builtin_pager = False already took. The pager returns in a pull request of its own, stacked on this one.
1 parent 7747214 commit ead92b0

10 files changed

Lines changed: 17 additions & 978 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,6 @@
1212
for input, refreshing at the same `refresh_interval` as the main prompt, instead of the
1313
toolbar disappearing for the duration of the nested prompt. `Cmd.select()` is unchanged, since
1414
prompt-toolkit's `choice()` offers no way to configure a refresh interval
15-
- Added an embedded pager which `Cmd.ppaged()` uses while the bottom toolbar is running, so the
16-
toolbar stays visible and refreshing instead of the terminal being handed to an external
17-
pager. It supports vertical and horizontal scrolling, incremental search, and chopped lines on
18-
every platform, including Windows where the default external pager (`more`) always wraps.
19-
Output which already fits on the screen is printed directly rather than paged. Set
20-
`self.use_builtin_pager = False` to keep using the external `pager`/`pager_chop` commands.
2115

2216
## 4.4.2 (November 11, 2026)
2317

‎cmd2/cmd2.py‎

Lines changed: 6 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -661,10 +661,6 @@ def __init__(
661661
if callargs:
662662
self._startup_commands.extend(callargs)
663663

664-
# The embedded pager shares the main toolbar. Applications can opt back
665-
# into their configured external pager by setting this to False.
666-
self.use_builtin_pager = enable_bottom_toolbar
667-
668664
# Set the pager(s) for use when displaying output using a pager
669665
if sys.platform.startswith("win"):
670666
self.pager = self.pager_chop = "more"
@@ -1956,17 +1952,15 @@ def ppaged(
19561952
fits on the screen. A pager is not used inside a script (Python or text) or when output is
19571953
redirected or piped, and in these cases, output is sent to `poutput`.
19581954
1959-
While the bottom toolbar is running, the built-in pager keeps it visible and refreshing.
1960-
Set ``use_builtin_pager=False`` to use the configured external ``pager`` or ``pager_chop``
1961-
command instead; external pagers temporarily hide the toolbar. Where no toolbar is
1962-
running, such as outside the command loop, the external pager is used regardless.
1955+
The pager takes over the terminal, so the bottom toolbar is hidden while it is open and
1956+
comes back when it exits.
19631957
19641958
:param chop: True -> causes lines longer than the screen width to be chopped (truncated) rather than wrapped
19651959
- truncated text is still accessible by scrolling with the right & left arrow keys
19661960
- chopping is ideal for displaying wide tabular data as is done in utilities like pgcli
19671961
False -> causes lines longer than the screen width to wrap to the next line
19681962
- wrapping is ideal when you want to keep users from having to use horizontal scrolling
1969-
WARNING: The default external pager on Windows always wraps; the built-in pager supports chopping.
1963+
WARNING: On Windows, the text always wraps regardless of what the chop argument is set to
19701964
:param soft_wrap: Enable soft wrap mode. If True, lines of text will not be word-wrapped or cropped to
19711965
fit the terminal width. Defaults to True.
19721966
@@ -2009,17 +2003,8 @@ def ppaged(
20092003
soft_wrap=soft_wrap,
20102004
**(rich_print_kwargs if rich_print_kwargs is not None else {}),
20112005
)
2012-
output = capture.get()
2013-
2014-
# Page inside the toolbar's display only when the command loop is already
2015-
# running one. Starting one here would seize the terminal for commands run
2016-
# outside that loop, which the toolbar is documented not to do.
2017-
if self.use_builtin_pager and self._command_toolbar is not None and self._command_toolbar.is_active:
2018-
self._command_toolbar.page(output, chop=chop)
2019-
return
2020-
20212006
# As for a pipe: the pager gets UTF-8, and on Windows the console is UTF-8 while it runs.
2022-
output_bytes = output.encode("utf-8", "replace")
2007+
output_bytes = capture.get().encode("utf-8", "replace")
20232008

20242009
# Prevent KeyboardInterrupts while in the pager. The pager application will
20252010
# still receive the SIGINT since it is in the same process group as us.
@@ -2131,8 +2116,8 @@ def get_bottom_toolbar(self) -> AnyFormattedText:
21312116
During command execution this callback runs in a background UI thread. Protect shared
21322117
state with a lock when necessary, but never hold that lock in a command while it prompts
21332118
for input, pages output, runs a shell command, or otherwise pauses the toolbar: pausing
2134-
waits for this callback to return. The built-in pager shares this toolbar. It is suspended
2135-
while another prompt, external pager, or interactive shell owns the terminal.
2119+
waits for this callback to return. The toolbar is suspended while another prompt, a
2120+
pager, or an interactive shell owns the terminal.
21362121
21372122
If this callback raises an exception during a command, the error is reported once and the
21382123
command carries on without the toolbar.

‎cmd2/command_toolbar.py‎

Lines changed: 1 addition & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,9 @@
1212
import threading
1313
import time
1414
from collections.abc import Callable, Generator
15-
from concurrent.futures import Future
16-
from concurrent.futures import TimeoutError as FutureTimeoutError
1715
from typing import TYPE_CHECKING, Any, TextIO, TypeVar, cast
1816

1917
from prompt_toolkit.application import Application, create_app_session, run_in_terminal
20-
from prompt_toolkit.enums import EditingMode
2118
from prompt_toolkit.filters import Condition, to_filter
2219
from prompt_toolkit.input.typeahead import get_typeahead, store_typeahead
2320
from prompt_toolkit.key_binding import KeyBindings
@@ -27,8 +24,6 @@
2724
from prompt_toolkit.patch_stdout import StdoutProxy
2825
from prompt_toolkit.utils import get_cwidth, suspend_to_background_supported
2926

30-
from .pager import Pager, output_fits
31-
3227
if TYPE_CHECKING:
3328
from .cmd2 import Cmd
3429

@@ -37,7 +32,6 @@
3732
_ESCAPE_RE = re.compile(r"\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])")
3833

3934
_F = TypeVar("_F", bound=Callable[..., Any])
40-
_R = TypeVar("_R")
4135

4236

4337
def suspend_process_group(suspend_group: bool = True) -> None:
@@ -347,7 +341,6 @@ def suspend(event: KeyPressEvent) -> None:
347341
event.app.suspend_to_background()
348342

349343
self._bindings = bindings
350-
self._suspend_binding = suspend
351344

352345
@staticmethod
353346
def _suspend_to_background(suspend_group: bool = True) -> None:
@@ -405,7 +398,7 @@ def _resume(self) -> None:
405398
# has not seen with other bindings. It caches the bindings it merges for each focused
406399
# window, application bindings included, and does not notice this attribute being
407400
# reassigned, so reusing a window with different bindings would keep the old ones.
408-
# This layout, the main prompt's, and each pager's all have windows of their own.
401+
# This layout and the main prompt's have windows of their own.
409402
for name, value in (("layout", self._layout), ("key_bindings", self._bindings), ("erase_when_done", True)):
410403
stack.callback(setattr, self.app, name, getattr(self.app, name))
411404
setattr(self.app, name, value)
@@ -560,103 +553,6 @@ def is_active(self) -> bool:
560553
"""Whether the display currently owns the terminal."""
561554
return self._proxy is not None and self.app.is_running
562555

563-
def _call_in_ui(self, func: Callable[[], _R]) -> _R:
564-
"""Change UI state on its event loop, propagating failures to the command."""
565-
result: Future[_R] = Future()
566-
567-
def call() -> None:
568-
try:
569-
value = func()
570-
except BaseException as exc: # noqa: BLE001
571-
result.set_exception(exc)
572-
else:
573-
result.set_result(value)
574-
575-
if self.app.loop is None:
576-
raise RuntimeError("Toolbar is not running")
577-
self.app.loop.call_soon_threadsafe(call)
578-
while True:
579-
try:
580-
value = result.result(timeout=0.1)
581-
except FutureTimeoutError:
582-
if result.done():
583-
# The callback finished while this poll was expiring, or raised a
584-
# TimeoutError of its own -- indistinguishable here, because
585-
# concurrent.futures.TimeoutError is TimeoutError on Python 3.11+.
586-
# Ask the future for its outcome rather than re-raising this poll's
587-
# timeout, which would report a failure for a call that succeeded.
588-
return result.result()
589-
self._check_running()
590-
else:
591-
return value
592-
593-
def _check_running(self) -> None:
594-
if self._thread is None or not self._thread.is_alive():
595-
if self._error is not None:
596-
raise self._error
597-
raise EOFError
598-
599-
def page(self, text: str, *, chop: bool) -> None:
600-
"""Show a pager above the same toolbar without starting another input reader."""
601-
size = self.app.output.get_size()
602-
# Measuring the toolbar can invoke its callback; keep that work on the
603-
# UI thread along with rendering and layout changes.
604-
toolbar_height = self._call_in_ui(lambda: self.toolbar.preferred_height(size.columns, size.rows).preferred)
605-
if output_fits(text, size.columns, max(0, size.rows - toolbar_height), chop=chop):
606-
self.cmd.stdout.write(text)
607-
self.cmd.stdout.flush()
608-
return
609-
610-
pager = Pager(text, chop=chop)
611-
pager.bindings.add(
612-
"c-z",
613-
filter=Condition(lambda: suspend_to_background_supported() and to_filter(self.cmd.main_session.enable_suspend)()),
614-
)(self._suspend_binding)
615-
layout = Layout(HSplit([pager.container, self.toolbar]), focused_element=pager.text)
616-
previous = (self.app.layout, self.app.key_bindings, self.app.editing_mode, self.app.full_screen)
617-
entered = False
618-
619-
def enter() -> None:
620-
nonlocal entered
621-
entered = True
622-
self.app.renderer.erase()
623-
self.app.layout = layout
624-
self.app.key_bindings = pager.bindings
625-
self.app.editing_mode = EditingMode.EMACS
626-
self.app.full_screen = self.app.renderer.full_screen = True
627-
self.app.invalidate()
628-
629-
def leave() -> None:
630-
nonlocal entered
631-
if not entered:
632-
return
633-
entered = False
634-
self.app.renderer.erase()
635-
self.app.layout, self.app.key_bindings, self.app.editing_mode, self.app.full_screen = previous
636-
self.app.renderer.full_screen = self.app.full_screen
637-
self.app.renderer.request_absolute_cursor_position()
638-
self.app.invalidate()
639-
640-
def close() -> None:
641-
# Switch bindings before the next key is processed, preserving
642-
# typeahead sent in the same terminal read as the pager's quit key.
643-
leave()
644-
pager.closed.set()
645-
646-
pager.on_close = close
647-
648-
try:
649-
self._call_in_ui(enter)
650-
while not pager.closed.wait(0.1):
651-
self._check_running()
652-
finally:
653-
if self._thread is not None and self._thread.is_alive():
654-
self._call_in_ui(leave)
655-
else:
656-
# The application's shutdown already reset the renderer.
657-
self.app.layout, self.app.key_bindings, self.app.editing_mode, self.app.full_screen = previous
658-
self.app.renderer.full_screen = self.app.full_screen
659-
660556
@contextlib.contextmanager
661557
def suspend(self) -> Generator[None]:
662558
"""Temporarily restore ordinary terminal access, including nested suspensions."""

0 commit comments

Comments
 (0)