Files
t-deckard/deck/pager.py
T
2025-12-21 14:20:54 +02:00

44 lines
1.2 KiB
Python

# deck.pager: Simple text pagination library for T-Deck
# Usage: from deck.pager import print_paged
# Created by Luxferre in 2025, released into public domain
import os
from deck.input import input
# detect terminal size
TERM_ROWS = os.getenv('TERM_ROWS', 24)
TERM_COLS = os.getenv('TERM_COLS', 53)
try: # if running on CPython
TERM_COLS, TERM_ROWS = os.get_terminal_size()
except:
pass
# additional constants
REAL_TERM_COLS = TERM_COLS - 1 # for the line ending character
REAL_TERM_ROWS = TERM_ROWS - 1 # for the "press Enter" message
CONT_MSG = '--- Press Enter ---'
def term_size():
"""Return the detected terminal size (rows, columns)"""
return (TERM_ROWS, TERM_COLS)
def reflow(text):
"""Split the text into lines not exceeding the terminal width"""
out = []
for line in text.split('\n'):
line = line.rstrip()
while len(line) > 0:
out.append(line[0:REAL_TERM_COLS])
line = line[REAL_TERM_COLS:]
return out
def print_paged(text):
"""Reflow and print the text in a paginated manner"""
lines = reflow(text)
ll = len(lines)
for i in range(0, ll, REAL_TERM_ROWS):
chunk = lines[i:i + REAL_TERM_ROWS]
for line in chunk: print(line)
if i + REAL_TERM_ROWS < ll:
input(CONT_MSG)