Files
t-deckard/deck/pager.py
T

45 lines
1.2 KiB
Python
Raw Normal View History

2025-12-21 14:05:03 +02:00
# 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)
2025-12-21 14:10:21 +02:00
TERM_COLS = os.getenv('TERM_COLS', 53)
2025-12-21 14:05:03 +02:00
try: # if running on CPython
TERM_COLS, TERM_ROWS = os.get_terminal_size()
except:
pass
# additional constants
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:TERM_COLS])
line = line[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]
2025-12-21 14:13:43 +02:00
for line in chunk: print(line, end='')
2025-12-21 14:05:03 +02:00
if i + REAL_TERM_ROWS < ll:
input(CONT_MSG)