Skip to content

Python

simple_term_menu + pygments

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"""
NOTE: pygments often lives in a separate package (python3-pygments)
      but it still goes into site-packages/
NOTE: simple_term_menu is employed by some OS installers now
      (i.e. stable enough)
"""
from pygments import formatters, highlight, lexers
from pygments.util import ClassNotFound
from simple_term_menu import TerminalMenu
from .playbook.file import list as pb_list, path


def preview(name):
    fname = path(name)
    with open(fname, "rt") as f:
        text = f.read()
    try:
        lexer = lexers.get_lexer_for_filename(
            fname, stripnl=False, stripall=False
        )
    except ClassNotFound:
        lexer = lexers.get_lexer_by_name("text", stripnl=False, stripall=False)
    formatter = formatters.TerminalFormatter(bg="dark")
    return highlight(text, lexer, formatter)


def select_playbook(use_preview=None):
    lst = pb_list()
    lst.sort()
    idx = TerminalMenu(
        lst,
        preview_command=preview if use_preview else None,
        preview_size=0.7,
    ).show()
    if idx is None:
        return None
    return lst[idx]


# vim:set ft=python ai et ts=4 sts=4 sw=4 cc=80:EOF #