Skip to content

Instantly share code, notes, and snippets.

@oss6
Created May 17, 2020 16:14
Show Gist options
  • Save oss6/fa61023a3ee48670bbb084ebaebd8281 to your computer and use it in GitHub Desktop.
Save oss6/fa61023a3ee48670bbb084ebaebd8281 to your computer and use it in GitHub Desktop.
Simple paging utility for reading long text in the terminal.
import curses
import math
import sys
import textwrap
def print_page(screen, pages, index):
screen.clear()
screen.addstr(0, 30, f'({index + 1})')
for i, line in enumerate(pages[index].splitlines()):
screen.addstr(2 + i, 0, line)
screen.refresh()
def main(filename):
def run(stdscr):
stdscr.clear()
stdscr.keypad(True)
curses.curs_set(0)
max_rows, max_cols = stdscr.getmaxyx()
top_pad = 2
height = max_rows - (top_pad * 2)
width = 60
container = stdscr.subwin(
height, width, top_pad, int(max_cols / 2) - int(width / 2)
)
with open(filename, 'r') as file:
text = file.read()
lines = textwrap.fill(
text, width, replace_whitespace=False).splitlines()
n_lines = len(lines)
lines_per_page = height - 2
pages = [
'\n'.join(lines[i:i + lines_per_page])
for i in range(0, n_lines, lines_per_page)
]
current_page = 0
print_page(container, pages, current_page)
while True:
c = stdscr.getch()
if c == ord('q'):
break
elif c == curses.KEY_RIGHT and current_page < len(pages) - 1:
current_page += 1
print_page(container, pages, current_page)
elif c == curses.KEY_LEFT and current_page > 0:
current_page -= 1
print_page(container, pages, current_page)
elif c == curses.KEY_NPAGE:
current_page = len(pages) - 1
print_page(container, pages, current_page)
elif c == curses.KEY_PPAGE:
current_page = 0
print_page(container, pages, current_page)
return run
if __name__ == '__main__':
filename = sys.argv[1]
curses.wrapper(main(filename))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment