82 lines
2.3 KiB
Python
82 lines
2.3 KiB
Python
"""Less-based pager integration with mouse support and fallback."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import signal
|
|
import shutil
|
|
import subprocess
|
|
|
|
from rich.pager import Pager, SystemPager
|
|
|
|
|
|
def _mouse_capable_less() -> str | None:
|
|
"""Return a ``less`` path that likely supports ``--mouse``.
|
|
|
|
Mouse support was added in ``less`` 543. This probe is best-effort: it
|
|
checks that ``less`` exists, asks for its version string, and extracts the
|
|
version number from the leading ``less <version>`` banner. Any unexpected
|
|
output is treated as unsupported so the caller can fall back safely.
|
|
|
|
Returns:
|
|
The resolved ``less`` executable path when it appears mouse-capable,
|
|
otherwise ``None``.
|
|
"""
|
|
less = shutil.which("less")
|
|
if less is None:
|
|
return None
|
|
|
|
try:
|
|
result = subprocess.run(
|
|
[less, "--version"], capture_output=True, text=True, timeout=5
|
|
)
|
|
except (subprocess.TimeoutExpired, OSError):
|
|
return None
|
|
|
|
version_str = result.stdout or result.stderr or ""
|
|
match = re.search(r"\bless\s+(\d+)\b", version_str, re.IGNORECASE)
|
|
if match is None:
|
|
return None
|
|
|
|
if int(match.group(1)) < 543:
|
|
return None
|
|
|
|
return less
|
|
|
|
|
|
class MousePager(Pager):
|
|
"""Pager that prefers ``less -R --mouse`` for mouse scrolling.
|
|
|
|
``less`` is the prerequisite for mouse-enabled paging in this project. If
|
|
``less`` is missing, too old, cannot be launched, or exits with a non-zero
|
|
status, we fall back to Rich's ``SystemPager``. A user interrupt does not
|
|
trigger a second pager session.
|
|
"""
|
|
|
|
def show(self, content: str) -> None:
|
|
"""Display rendered content in ``less -R --mouse`` when possible.
|
|
|
|
Args:
|
|
content: Fully rendered text from Rich.
|
|
"""
|
|
less = _mouse_capable_less()
|
|
if less is None:
|
|
SystemPager().show(content)
|
|
return
|
|
|
|
try:
|
|
result = subprocess.run(
|
|
[less, "-R", "--mouse"],
|
|
input=content,
|
|
text=True,
|
|
)
|
|
except OSError:
|
|
SystemPager().show(content)
|
|
return
|
|
|
|
if result.returncode in (-signal.SIGINT, 128 + signal.SIGINT):
|
|
return
|
|
|
|
if result.returncode != 0:
|
|
SystemPager().show(content)
|