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

47 lines
1.3 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', 19)
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()
if len(line) == 0: # also handle effectively empty lines
out.append('')
else:
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)
while True:
chunk = lines[0:REAL_TERM_ROWS]
for line in chunk: print(line)
lines = lines[REAL_TERM_ROWS:]
if len(lines) > 0: input(CONT_MSG)
else: break