-
Notifications
You must be signed in to change notification settings - Fork 44
/
simple_term_menu.py
executable file
·2065 lines (1914 loc) · 89.8 KB
/
simple_term_menu.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import argparse
import copy
import ctypes
import io
import locale
import os
import platform
import re
import shlex
import signal
import string
import subprocess
import sys
from locale import getlocale
from types import FrameType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Match,
Optional,
Pattern,
Sequence,
Set,
TextIO,
Tuple,
Union,
cast,
)
try:
import termios
except ImportError as e:
raise NotImplementedError('"{}" is currently not supported.'.format(platform.system())) from e
__author__ = "Ingo Meyer"
__email__ = "i.meyer@fz-juelich.de"
__copyright__ = "Copyright © 2021 Forschungszentrum Jülich GmbH. All rights reserved."
__license__ = "MIT"
__version_info__ = (1, 6, 6)
__version__ = ".".join(map(str, __version_info__))
DEFAULT_ACCEPT_KEYS = ("enter",)
DEFAULT_CLEAR_MENU_ON_EXIT = True
DEFAULT_CLEAR_SCREEN = False
DEFAULT_CYCLE_CURSOR = True
DEFAULT_EXIT_ON_SHORTCUT = True
DEFAULT_MENU_CURSOR = "> "
DEFAULT_MENU_CURSOR_STYLE = ("fg_red", "bold")
DEFAULT_MENU_HIGHLIGHT_STYLE = ("standout",)
DEFAULT_MULTI_SELECT = False
DEFAULT_MULTI_SELECT_CURSOR = "[*] "
DEFAULT_MULTI_SELECT_CURSOR_BRACKETS_STYLE = ("fg_gray",)
DEFAULT_MULTI_SELECT_CURSOR_STYLE = ("fg_yellow", "bold")
DEFAULT_MULTI_SELECT_KEYS = (" ", "tab")
DEFAULT_MULTI_SELECT_SELECT_ON_ACCEPT = True
DEFAULT_PREVIEW_BORDER = True
DEFAULT_PREVIEW_SIZE = 0.25
DEFAULT_PREVIEW_TITLE = "preview"
DEFAULT_QUIT_KEYS = ("escape", "q", "ctrl-g")
DEFAULT_SEARCH_CASE_SENSITIVE = False
DEFAULT_SEARCH_HIGHLIGHT_STYLE = ("fg_black", "bg_yellow", "bold")
DEFAULT_SEARCH_KEY = "/"
DEFAULT_SHORTCUT_BRACKETS_HIGHLIGHT_STYLE = ("fg_gray",)
DEFAULT_SHORTCUT_KEY_HIGHLIGHT_STYLE = ("fg_blue",)
DEFAULT_SHOW_MULTI_SELECT_HINT = False
DEFAULT_SHOW_SEARCH_HINT = False
DEFAULT_SHOW_SHORTCUT_HINTS = False
DEFAULT_SHOW_SHORTCUT_HINTS_IN_STATUS_BAR = True
DEFAULT_STATUS_BAR_BELOW_PREVIEW = False
DEFAULT_STATUS_BAR_STYLE = ("fg_yellow", "bg_black")
MIN_VISIBLE_MENU_ENTRIES_COUNT = 3
class InvalidParameterCombinationError(Exception):
pass
class InvalidStyleError(Exception):
pass
class NoMenuEntriesError(Exception):
pass
class PreviewCommandFailedError(Exception):
pass
class UnknownMenuEntryError(Exception):
pass
def get_locale() -> str:
user_locale = locale.getlocale()[1]
if user_locale is None:
return "ascii"
else:
return user_locale.lower()
def wcswidth(text: str) -> int:
if not hasattr(wcswidth, "libc"):
try:
if platform.system() == "Darwin":
wcswidth.libc = ctypes.cdll.LoadLibrary("libSystem.dylib") # type: ignore
else:
wcswidth.libc = ctypes.cdll.LoadLibrary("libc.so.6") # type: ignore
except OSError:
wcswidth.libc = None # type: ignore
if wcswidth.libc is not None: # type: ignore
try:
user_locale = get_locale()
# First replace any null characters with the unicode replacement character (U+FFFD) since they cannot be
# passed in a `c_wchar_p`
encoded_text = text.replace("\0", "\uFFFD").encode(encoding=user_locale, errors="replace")
return wcswidth.libc.wcswidth( # type: ignore
ctypes.c_wchar_p(encoded_text.decode(encoding=user_locale)), len(encoded_text)
)
except AttributeError:
pass
return len(text)
def static_variables(**variables: Any) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
def decorator(f: Callable[..., Any]) -> Callable[..., Any]:
for key, value in variables.items():
setattr(f, key, value)
return f
return decorator
class BoxDrawingCharacters:
if getlocale()[1] == "UTF-8":
# Unicode box characters
horizontal = "─"
vertical = "│"
upper_left = "┌"
upper_right = "┐"
lower_left = "└"
lower_right = "┘"
else:
# ASCII box characters
horizontal = "-"
vertical = "|"
upper_left = "+"
upper_right = "+"
lower_left = "+"
lower_right = "+"
class TerminalMenu:
class Search:
def __init__(
self,
menu_entries: Iterable[str],
search_text: Optional[str] = None,
case_senitive: bool = False,
show_search_hint: bool = False,
):
self._menu_entries = menu_entries
self._case_sensitive = case_senitive
self._show_search_hint = show_search_hint
self._matches = [] # type: List[Tuple[int, Match[str]]]
self._search_regex = None # type: Optional[Pattern[str]]
self._change_callback = None # type: Optional[Callable[[], None]]
# Use the property setter since it has some more logic
self.search_text = search_text
def _update_matches(self) -> None:
if self._search_regex is None:
self._matches = []
else:
matches = []
for i, menu_entry in enumerate(self._menu_entries):
match_obj = self._search_regex.search(menu_entry)
if match_obj:
matches.append((i, match_obj))
self._matches = matches
@property
def matches(self) -> List[Tuple[int, Match[str]]]:
return list(self._matches)
@property
def search_regex(self) -> Optional[Pattern[str]]:
return self._search_regex
@property
def search_text(self) -> Optional[str]:
return self._search_text
@search_text.setter
def search_text(self, text: Optional[str]) -> None:
self._search_text = text
search_text = self._search_text
self._search_regex = None
while search_text and self._search_regex is None:
try:
self._search_regex = re.compile(search_text, flags=re.IGNORECASE if not self._case_sensitive else 0)
except re.error:
search_text = search_text[:-1]
self._update_matches()
if self._change_callback:
self._change_callback()
@property
def change_callback(self) -> Optional[Callable[[], None]]:
return self._change_callback
@change_callback.setter
def change_callback(self, callback: Optional[Callable[[], None]]) -> None:
self._change_callback = callback
@property
def occupied_lines_count(self) -> int:
if not self and not self._show_search_hint:
return 0
else:
return 1
def __bool__(self) -> bool:
return self._search_text is not None
def __contains__(self, menu_index: int) -> bool:
return any(i == menu_index for i, _ in self._matches)
def __len__(self) -> int:
return wcswidth(self._search_text) if self._search_text is not None else 0
class Selection:
def __init__(self, preselected_indices: Optional[Iterable[int]] = None):
self._selected_menu_indices = set(preselected_indices) if preselected_indices is not None else set()
def clear(self) -> None:
self._selected_menu_indices.clear()
def add(self, menu_index: int) -> None:
self[menu_index] = True
def remove(self, menu_index: int) -> None:
self[menu_index] = False
def toggle(self, menu_index: int) -> bool:
self[menu_index] = menu_index not in self._selected_menu_indices
return self[menu_index]
def __bool__(self) -> bool:
return bool(self._selected_menu_indices)
def __contains__(self, menu_index: int) -> bool:
return menu_index in self._selected_menu_indices
def __getitem__(self, menu_index: int) -> bool:
return menu_index in self._selected_menu_indices
def __setitem__(self, menu_index: int, is_selected: bool) -> None:
if is_selected:
self._selected_menu_indices.add(menu_index)
else:
self._selected_menu_indices.remove(menu_index)
def __iter__(self) -> Iterator[int]:
return iter(self._selected_menu_indices)
@property
def selected_menu_indices(self) -> Tuple[int, ...]:
return tuple(sorted(self._selected_menu_indices))
class View:
def __init__(
self,
menu_entries: Iterable[str],
search: "TerminalMenu.Search",
selection: "TerminalMenu.Selection",
viewport: "TerminalMenu.Viewport",
cycle_cursor: bool = True,
skip_indices: List[int] = [],
):
self._menu_entries = list(menu_entries)
self._search = search
self._selection = selection
self._viewport = viewport
self._cycle_cursor = cycle_cursor
self._active_displayed_index = None # type: Optional[int]
self._skip_indices = skip_indices
self.update_view()
def update_view(self) -> None:
if self._search and self._search.search_text != "":
self._displayed_index_to_menu_index = tuple(i for i, match_obj in self._search.matches)
else:
self._displayed_index_to_menu_index = tuple(range(len(self._menu_entries)))
self._menu_index_to_displayed_index = {
menu_index: displayed_index
for displayed_index, menu_index in enumerate(self._displayed_index_to_menu_index)
}
self._active_displayed_index = 0 if self._displayed_index_to_menu_index else None
self._viewport.num_displayed_menu_entries = len(self._displayed_index_to_menu_index)
self._viewport.search_lines_count = self._search.occupied_lines_count
self._viewport.keep_visible(self._active_displayed_index)
def increment_active_index(self) -> None:
if self._active_displayed_index is not None:
if self._active_displayed_index + 1 < self._viewport.num_displayed_menu_entries:
self._active_displayed_index += 1
elif self._cycle_cursor:
self._active_displayed_index = 0
self._viewport.keep_visible(self._active_displayed_index)
if self._displayed_index_to_menu_index[self._active_displayed_index] in self._skip_indices:
self.increment_active_index()
def decrement_active_index(self) -> None:
if self._active_displayed_index is not None:
if self._active_displayed_index > 0:
self._active_displayed_index -= 1
elif self._cycle_cursor:
self._active_displayed_index = self._viewport.num_displayed_menu_entries - 1
self._viewport.keep_visible(self._active_displayed_index)
if self._displayed_index_to_menu_index[self._active_displayed_index] in self._skip_indices:
self.decrement_active_index()
def page_down(self) -> None:
if self._active_displayed_index is None:
return
self._viewport.page_down()
self._active_displayed_index = min(
self._active_displayed_index + self._viewport.size, self._viewport.num_displayed_menu_entries - 1
)
def page_up(self) -> None:
if self._active_displayed_index is None:
return
self._viewport.page_up()
self._active_displayed_index = max(self._active_displayed_index - self._viewport.size, 0)
def is_visible(self, menu_index: int) -> bool:
return menu_index in self._menu_index_to_displayed_index and (
self._viewport.lower_index
<= self._menu_index_to_displayed_index[menu_index]
<= self._viewport.upper_index
)
def convert_menu_index_to_displayed_index(self, menu_index: int) -> Optional[int]:
if menu_index in self._menu_index_to_displayed_index:
return self._menu_index_to_displayed_index[menu_index]
else:
return None
def convert_displayed_index_to_menu_index(self, displayed_index: int) -> int:
return self._displayed_index_to_menu_index[displayed_index]
@property
def active_menu_index(self) -> Optional[int]:
if self._active_displayed_index is not None:
return self._displayed_index_to_menu_index[self._active_displayed_index]
else:
return None
@active_menu_index.setter
def active_menu_index(self, value: int) -> None:
self.active_displayed_index = self._menu_index_to_displayed_index[value]
@property
def active_displayed_index(self) -> Optional[int]:
return self._active_displayed_index
@active_displayed_index.setter
def active_displayed_index(self, value: int) -> None:
self._active_displayed_index = value
self._viewport.keep_visible(self._active_displayed_index)
@property
def max_displayed_index(self) -> int:
return self._viewport.num_displayed_menu_entries - 1
@property
def displayed_selected_indices(self) -> List[int]:
return [
self._menu_index_to_displayed_index[selected_index]
for selected_index in self._selection
if selected_index in self._menu_index_to_displayed_index
]
def __bool__(self) -> bool:
return self._active_displayed_index is not None
def __iter__(self) -> Iterator[Tuple[int, int, str]]:
for displayed_index, menu_index in enumerate(self._displayed_index_to_menu_index):
if self._viewport.lower_index <= displayed_index <= self._viewport.upper_index:
yield (displayed_index, menu_index, self._menu_entries[menu_index])
class Viewport:
def __init__(
self,
num_displayed_menu_entries: int,
title_lines_count: int,
status_bar_lines_count: int,
preview_lines_count: int,
search_lines_count: int,
):
self._num_displayed_menu_entries = num_displayed_menu_entries
self._title_lines_count = title_lines_count
self._status_bar_lines_count = status_bar_lines_count
# Use the property setter since it has some more logic
self.preview_lines_count = preview_lines_count
self.search_lines_count = search_lines_count
self._num_lines = self._calculate_num_lines()
self._viewport = (0, min(self._num_displayed_menu_entries, self._num_lines) - 1)
self.keep_visible(cursor_position=None, refresh_terminal_size=False)
def _calculate_num_lines(self) -> int:
return (
TerminalMenu._num_lines()
- self._title_lines_count
- self._status_bar_lines_count
- self._preview_lines_count
- self._search_lines_count
)
def keep_visible(self, cursor_position: Optional[int], refresh_terminal_size: bool = True) -> None:
# Treat `cursor_position=None` like `cursor_position=0`
if cursor_position is None:
cursor_position = 0
if refresh_terminal_size:
self.update_terminal_size()
if self._viewport[0] <= cursor_position <= self._viewport[1]:
# Cursor is already visible
return
if cursor_position < self._viewport[0]:
scroll_num = cursor_position - self._viewport[0]
else:
scroll_num = cursor_position - self._viewport[1]
self._viewport = (self._viewport[0] + scroll_num, self._viewport[1] + scroll_num)
def page_down(self) -> None:
self.scroll(self.size)
def page_up(self) -> None:
self.scroll(-self.size)
def scroll(self, number_of_lines: int) -> None:
if number_of_lines < 0:
scroll_num = max(-self._viewport[0], number_of_lines)
else:
scroll_num = min(max(0, self._num_displayed_menu_entries - self._viewport[1] - 1), number_of_lines)
self._viewport = (self._viewport[0] + scroll_num, self._viewport[1] + scroll_num)
def update_terminal_size(self) -> None:
num_lines = self._calculate_num_lines()
if num_lines != self._num_lines:
# First let the upper index grow or shrink
upper_index = min(num_lines, self._num_displayed_menu_entries) - 1
# Then, use as much space as possible for the `lower_index`
lower_index = max(0, upper_index - num_lines)
self._viewport = (lower_index, upper_index)
self._num_lines = num_lines
@property
def lower_index(self) -> int:
return self._viewport[0]
@property
def upper_index(self) -> int:
return self._viewport[1]
@property
def viewport(self) -> Tuple[int, int]:
return self._viewport
@property
def size(self) -> int:
return self._viewport[1] - self._viewport[0] + 1
@property
def num_displayed_menu_entries(self) -> int:
return self._num_displayed_menu_entries
@num_displayed_menu_entries.setter
def num_displayed_menu_entries(self, num_displayed_menu_entries: int) -> None:
self._num_displayed_menu_entries = num_displayed_menu_entries
@property
def title_lines_count(self) -> int:
return self._title_lines_count
@property
def status_bar_lines_count(self) -> int:
return self._status_bar_lines_count
@status_bar_lines_count.setter
def status_bar_lines_count(self, value: int) -> None:
self._status_bar_lines_count = value
@property
def preview_lines_count(self) -> int:
return self._preview_lines_count
@preview_lines_count.setter
def preview_lines_count(self, value: int) -> None:
self._preview_lines_count = min(
value if value >= 3 else 0,
TerminalMenu._num_lines()
- self._title_lines_count
- self._status_bar_lines_count
- MIN_VISIBLE_MENU_ENTRIES_COUNT,
)
@property
def search_lines_count(self) -> int:
return self._search_lines_count
@search_lines_count.setter
def search_lines_count(self, value: int) -> None:
self._search_lines_count = value
@property
def must_scroll(self) -> bool:
return self._num_displayed_menu_entries > self._num_lines
_codename_to_capname = {
"bg_black": "setab 0",
"bg_blue": "setab 4",
"bg_cyan": "setab 6",
"bg_gray": "setab 7",
"bg_green": "setab 2",
"bg_purple": "setab 5",
"bg_red": "setab 1",
"bg_yellow": "setab 3",
"bold": "bold",
"clear": "clear",
"colors": "colors",
"cursor_down": "cud1",
"cursor_invisible": "civis",
"cursor_left": "cub1",
"cursor_right": "cuf1",
"cursor_up": "cuu1",
"cursor_visible": "cnorm",
"delete_line": "dl1",
"down": "kcud1",
"end": "kend",
"enter_application_mode": "smkx",
"exit_application_mode": "rmkx",
"fg_black": "setaf 0",
"fg_blue": "setaf 4",
"fg_cyan": "setaf 6",
"fg_gray": "setaf 7",
"fg_green": "setaf 2",
"fg_purple": "setaf 5",
"fg_red": "setaf 1",
"fg_yellow": "setaf 3",
"home": "khome",
"italics": "sitm",
"page_down": "knp",
"page_up": "kpp",
"reset_attributes": "sgr0",
"standout": "smso",
"underline": "smul",
"up": "kcuu1",
}
_name_to_control_character = {
"backspace": "", # Is assigned later in `self._init_backspace_control_character`
"ctrl-a": "\001",
"ctrl-b": "\002",
"ctrl-e": "\005",
"ctrl-f": "\006",
"ctrl-g": "\007",
"ctrl-j": "\012",
"ctrl-k": "\013",
"ctrl-n": "\016",
"ctrl-p": "\020",
"enter": "\015",
"escape": "\033",
"tab": "\t",
}
_codenames = tuple(_codename_to_capname.keys())
_codename_to_terminal_code = None # type: Optional[Dict[str, str]]
_terminal_code_to_codename = None # type: Optional[Dict[str, str]]
def __init__(
self,
menu_entries: Iterable[str],
*,
accept_keys: Iterable[str] = DEFAULT_ACCEPT_KEYS,
clear_menu_on_exit: bool = DEFAULT_CLEAR_MENU_ON_EXIT,
clear_screen: bool = DEFAULT_CLEAR_SCREEN,
cursor_index: Optional[int] = None,
cycle_cursor: bool = DEFAULT_CYCLE_CURSOR,
exit_on_shortcut: bool = DEFAULT_EXIT_ON_SHORTCUT,
menu_cursor: Optional[str] = DEFAULT_MENU_CURSOR,
menu_cursor_style: Optional[Iterable[str]] = DEFAULT_MENU_CURSOR_STYLE,
menu_highlight_style: Optional[Iterable[str]] = DEFAULT_MENU_HIGHLIGHT_STYLE,
multi_select: bool = DEFAULT_MULTI_SELECT,
multi_select_cursor: str = DEFAULT_MULTI_SELECT_CURSOR,
multi_select_cursor_brackets_style: Optional[Iterable[str]] = DEFAULT_MULTI_SELECT_CURSOR_BRACKETS_STYLE,
multi_select_cursor_style: Optional[Iterable[str]] = DEFAULT_MULTI_SELECT_CURSOR_STYLE,
multi_select_empty_ok: bool = False,
multi_select_keys: Optional[Iterable[str]] = DEFAULT_MULTI_SELECT_KEYS,
multi_select_select_on_accept: bool = DEFAULT_MULTI_SELECT_SELECT_ON_ACCEPT,
preselected_entries: Optional[Iterable[Union[str, int]]] = None,
preview_border: bool = DEFAULT_PREVIEW_BORDER,
preview_command: Optional[Union[str, Callable[[str], str]]] = None,
preview_size: float = DEFAULT_PREVIEW_SIZE,
preview_title: str = DEFAULT_PREVIEW_TITLE,
quit_keys: Iterable[str] = DEFAULT_QUIT_KEYS,
raise_error_on_interrupt: bool = False,
search_case_sensitive: bool = DEFAULT_SEARCH_CASE_SENSITIVE,
search_highlight_style: Optional[Iterable[str]] = DEFAULT_SEARCH_HIGHLIGHT_STYLE,
search_key: Optional[str] = DEFAULT_SEARCH_KEY,
shortcut_brackets_highlight_style: Optional[Iterable[str]] = DEFAULT_SHORTCUT_BRACKETS_HIGHLIGHT_STYLE,
shortcut_key_highlight_style: Optional[Iterable[str]] = DEFAULT_SHORTCUT_KEY_HIGHLIGHT_STYLE,
show_multi_select_hint: bool = DEFAULT_SHOW_MULTI_SELECT_HINT,
show_multi_select_hint_text: Optional[str] = None,
show_search_hint: bool = DEFAULT_SHOW_SEARCH_HINT,
show_search_hint_text: Optional[str] = None,
show_shortcut_hints: bool = DEFAULT_SHOW_SHORTCUT_HINTS,
show_shortcut_hints_in_status_bar: bool = DEFAULT_SHOW_SHORTCUT_HINTS_IN_STATUS_BAR,
skip_empty_entries: bool = False,
status_bar: Optional[Union[str, Iterable[str], Callable[[str], str]]] = None,
status_bar_below_preview: bool = DEFAULT_STATUS_BAR_BELOW_PREVIEW,
status_bar_style: Optional[Iterable[str]] = DEFAULT_STATUS_BAR_STYLE,
title: Optional[Union[str, Iterable[str]]] = None
):
def check_for_terminal_environment() -> None:
if "TERM" not in os.environ or os.environ["TERM"] == "":
if "PYCHARM_HOSTED" in os.environ:
raise NotImplementedError(
"simple-term-menu does not work in the PyCharm output console. Use a terminal instead (Alt + "
'F12) or activate "Emulate terminal in output console".'
)
raise NotImplementedError("simple-term-menu can only be used in a terminal emulator")
def extract_shortcuts_menu_entries_and_preview_arguments(
entries: Iterable[str],
) -> Tuple[List[str], List[Optional[str]], List[Optional[str]], List[int]]:
separator_pattern = re.compile(r"([^\\])\|")
escaped_separator_pattern = re.compile(r"\\\|")
menu_entry_pattern = re.compile(r"^(?:\[(\S)\]\s*)?([^\x1F]+)(?:\x1F([^\x1F]*))?")
shortcut_keys = [] # type: List[Optional[str]]
menu_entries = [] # type: List[str]
preview_arguments = [] # type: List[Optional[str]]
skip_indices = [] # type: List[int]
for idx, entry in enumerate(entries):
if entry is None or (entry == "" and skip_empty_entries):
shortcut_keys.append(None)
menu_entries.append("")
preview_arguments.append(None)
skip_indices.append(idx)
else:
unit_separated_entry = escaped_separator_pattern.sub("|", separator_pattern.sub("\\1\x1F", entry))
match_obj = menu_entry_pattern.match(unit_separated_entry)
# this is none in case the entry was an emtpy string which
# will be interpreted as a separator
assert match_obj is not None
shortcut_key = match_obj.group(1)
display_text = match_obj.group(2)
preview_argument = match_obj.group(3)
shortcut_keys.append(shortcut_key)
menu_entries.append(display_text)
preview_arguments.append(preview_argument)
return menu_entries, shortcut_keys, preview_arguments, skip_indices
def convert_preselected_entries_to_indices(
preselected_indices_or_entries: Iterable[Union[str, int]]
) -> Set[int]:
menu_entry_to_indices = {} # type: Dict[str, Set[int]]
for menu_index, menu_entry in enumerate(self._menu_entries):
menu_entry_to_indices.setdefault(menu_entry, set())
menu_entry_to_indices[menu_entry].add(menu_index)
preselected_indices = set()
for item in preselected_indices_or_entries:
if isinstance(item, int):
if 0 <= item < len(self._menu_entries):
preselected_indices.add(item)
else:
raise IndexError(
"Error: {} is outside the allowable range of 0..{}.".format(
item, len(self._menu_entries) - 1
)
)
elif isinstance(item, str):
try:
preselected_indices.update(menu_entry_to_indices[item])
except KeyError as e:
raise UnknownMenuEntryError('Pre-selection "{}" is not a valid menu entry.'.format(item)) from e
else:
raise ValueError('"preselected_entries" must either contain integers or strings.')
return preselected_indices
def setup_title_or_status_bar_lines(
title_or_status_bar: Optional[Union[str, Iterable[str]]],
show_shortcut_hints: bool,
menu_entries: Iterable[str],
shortcut_keys: Iterable[Optional[str]],
shortcut_hints_in_parentheses: bool,
) -> Tuple[str, ...]:
if title_or_status_bar is None:
lines = [] # type: List[str]
elif isinstance(title_or_status_bar, str):
lines = title_or_status_bar.split("\n")
else:
lines = list(title_or_status_bar)
if show_shortcut_hints:
shortcut_hints_line = self._get_shortcut_hints_line(
menu_entries, shortcut_keys, shortcut_hints_in_parentheses
)
if shortcut_hints_line is not None:
lines.append(shortcut_hints_line)
return tuple(lines)
check_for_terminal_environment()
(
self._menu_entries,
self._shortcut_keys,
self._preview_arguments,
self._skip_indices,
) = extract_shortcuts_menu_entries_and_preview_arguments(menu_entries)
self._shortcuts_defined = any(key is not None for key in self._shortcut_keys)
self._accept_keys = tuple(accept_keys)
self._clear_menu_on_exit = clear_menu_on_exit
self._clear_screen = clear_screen
self._cycle_cursor = cycle_cursor
self._multi_select_empty_ok = multi_select_empty_ok
self._exit_on_shortcut = exit_on_shortcut
self._menu_cursor = menu_cursor if menu_cursor is not None else ""
self._menu_cursor_style = tuple(menu_cursor_style) if menu_cursor_style is not None else ()
self._menu_highlight_style = tuple(menu_highlight_style) if menu_highlight_style is not None else ()
self._multi_select = multi_select
self._multi_select_cursor = multi_select_cursor
self._multi_select_cursor_brackets_style = (
tuple(multi_select_cursor_brackets_style) if multi_select_cursor_brackets_style is not None else ()
)
self._multi_select_cursor_style = (
tuple(multi_select_cursor_style) if multi_select_cursor_style is not None else ()
)
self._multi_select_keys = tuple(multi_select_keys) if multi_select_keys is not None else ()
self._multi_select_select_on_accept = multi_select_select_on_accept
if preselected_entries and not self._multi_select:
raise InvalidParameterCombinationError(
"Multi-select mode must be enabled when preselected entries are given."
)
self._preselected_indices = (
convert_preselected_entries_to_indices(preselected_entries) if preselected_entries is not None else None
)
self._preview_border = preview_border
self._preview_command = preview_command
self._preview_size = preview_size
self._preview_title = preview_title
self._quit_keys = tuple(quit_keys)
self._raise_error_on_interrupt = raise_error_on_interrupt
self._search_case_sensitive = search_case_sensitive
self._search_highlight_style = tuple(search_highlight_style) if search_highlight_style is not None else ()
self._search_key = search_key
self._shortcut_brackets_highlight_style = (
tuple(shortcut_brackets_highlight_style) if shortcut_brackets_highlight_style is not None else ()
)
self._shortcut_key_highlight_style = (
tuple(shortcut_key_highlight_style) if shortcut_key_highlight_style is not None else ()
)
self._show_search_hint = show_search_hint
self._show_search_hint_text = show_search_hint_text
self._show_shortcut_hints = show_shortcut_hints
self._show_shortcut_hints_in_status_bar = show_shortcut_hints_in_status_bar
self._status_bar_func = None # type: Optional[Callable[[str], str]]
self._status_bar_lines = None # type: Optional[Tuple[str, ...]]
if callable(status_bar):
self._status_bar_func = status_bar
else:
self._status_bar_lines = setup_title_or_status_bar_lines(
status_bar,
show_shortcut_hints and show_shortcut_hints_in_status_bar,
self._menu_entries,
self._shortcut_keys,
False,
)
self._status_bar_below_preview = status_bar_below_preview
self._status_bar_style = tuple(status_bar_style) if status_bar_style is not None else ()
self._title_lines = setup_title_or_status_bar_lines(
title,
show_shortcut_hints and not show_shortcut_hints_in_status_bar,
self._menu_entries,
self._shortcut_keys,
True,
)
self._show_multi_select_hint = show_multi_select_hint
self._show_multi_select_hint_text = show_multi_select_hint_text
self._chosen_accept_key = None # type: Optional[str]
self._chosen_menu_index = None # type: Optional[int]
self._chosen_menu_indices = None # type: Optional[Tuple[int, ...]]
self._paint_before_next_read = False
self._previous_displayed_menu_height = None # type: Optional[int]
self._reading_next_key = False
self._search = self.Search(
self._menu_entries,
case_senitive=self._search_case_sensitive,
show_search_hint=self._show_search_hint,
)
self._selection = self.Selection(self._preselected_indices)
self._viewport = self.Viewport(
len(self._menu_entries),
len(self._title_lines),
len(self._status_bar_lines) if self._status_bar_lines is not None else 0,
0,
0,
)
self._view = self.View(
self._menu_entries, self._search, self._selection, self._viewport, self._cycle_cursor, self._skip_indices
)
if cursor_index and 0 < cursor_index < len(self._menu_entries):
self._view.active_menu_index = cursor_index
self._search.change_callback = self._view.update_view
self._old_term = None # type: Optional[List[Union[int, List[bytes]]]]
self._new_term = None # type: Optional[List[Union[int, List[bytes]]]]
self._tty_in = None # type: Optional[TextIO]
self._tty_out = None # type: Optional[TextIO]
self._user_locale = get_locale()
self._check_for_valid_styles()
# backspace can be queried from the terminal database but is unreliable, query the terminal directly instead
self._init_backspace_control_character()
self._add_missing_control_characters_for_keys(self._accept_keys)
self._add_missing_control_characters_for_keys(self._quit_keys)
self._init_terminal_codes()
@staticmethod
def _get_shortcut_hints_line(
menu_entries: Iterable[str],
shortcut_keys: Iterable[Optional[str]],
shortcut_hints_in_parentheses: bool,
) -> Optional[str]:
shortcut_hints_line = ", ".join(
"[{}]: {}".format(shortcut_key, menu_entry)
for shortcut_key, menu_entry in zip(shortcut_keys, menu_entries)
if shortcut_key is not None
)
if shortcut_hints_line != "":
if shortcut_hints_in_parentheses:
return "(" + shortcut_hints_line + ")"
else:
return shortcut_hints_line
return None
@staticmethod
def _get_keycode_for_key(key: str) -> str:
if len(key) == 1:
# One letter keys represent themselves
return key
alt_modified_regex = re.compile(r"[Aa]lt-(\S)")
ctrl_modified_regex = re.compile(r"[Cc]trl-(\S)")
match_obj = alt_modified_regex.match(key)
if match_obj:
return "\033" + match_obj.group(1)
match_obj = ctrl_modified_regex.match(key)
if match_obj:
# Ctrl + key is interpreted by terminals as the ascii code of that key minus 64
ctrl_code_ascii = ord(match_obj.group(1).upper()) - 64
if ctrl_code_ascii < 0:
# Interpret negative ascii codes as unsigned 7-Bit integers
ctrl_code_ascii = ctrl_code_ascii & 0x80 - 1
return chr(ctrl_code_ascii)
raise ValueError('Cannot interpret the given key "{}".'.format(key))
@classmethod
def _init_backspace_control_character(self) -> None:
try:
with open("/dev/tty", "r") as tty:
stty_output = subprocess.check_output(["stty", "-a"], universal_newlines=True, stdin=tty)
name_to_keycode_regex = re.compile(r"^\s*(\S+)\s*=\s*\^(\S+)\s*$")
for field in stty_output.split(";"):
match_obj = name_to_keycode_regex.match(field)
if not match_obj:
continue
name, ctrl_code = match_obj.group(1), match_obj.group(2)
if name != "erase":
continue
self._name_to_control_character["backspace"] = self._get_keycode_for_key("ctrl-" + ctrl_code)
return
except subprocess.CalledProcessError:
pass
# Backspace control character could not be queried, assume `<Ctrl-?>` (is most often used)
self._name_to_control_character["backspace"] = "\177"
@classmethod
def _add_missing_control_characters_for_keys(cls, keys: Iterable[str]) -> None:
for key in keys:
if key not in cls._name_to_control_character and key not in string.ascii_letters:
cls._name_to_control_character[key] = cls._get_keycode_for_key(key)
@classmethod
def _init_terminal_codes(cls) -> None:
if cls._codename_to_terminal_code is not None:
return
supported_colors = int(cls._query_terminfo_database("colors"))
cls._codename_to_terminal_code = {
codename: (
cls._query_terminfo_database(codename)
if not (codename.startswith("bg_") or codename.startswith("fg_")) or supported_colors >= 8
else ""
)
for codename in cls._codenames
}
cls._codename_to_terminal_code.update(cls._name_to_control_character)
cls._terminal_code_to_codename = {
terminal_code: codename for codename, terminal_code in cls._codename_to_terminal_code.items()
}
@classmethod
def _query_terminfo_database(cls, codename: str) -> str:
if codename in cls._codename_to_capname:
capname = cls._codename_to_capname[codename]
else:
capname = codename
try:
return subprocess.check_output(["tput"] + capname.split(), universal_newlines=True)
except subprocess.CalledProcessError as e:
# The return code 1 indicates a missing terminal capability
if e.returncode == 1:
return ""
raise e
@classmethod
def _num_lines(self) -> int:
return int(self._query_terminfo_database("lines"))
@classmethod
def _num_cols(self) -> int:
return int(self._query_terminfo_database("cols"))
def _check_for_valid_styles(self) -> None:
invalid_styles = []
for style_tuple in (
self._menu_cursor_style,
self._menu_highlight_style,
self._search_highlight_style,
self._shortcut_key_highlight_style,
self._shortcut_brackets_highlight_style,
self._status_bar_style,
self._multi_select_cursor_brackets_style,
self._multi_select_cursor_style,
):
for style in style_tuple:
if style not in self._codename_to_capname:
invalid_styles.append(style)
if invalid_styles:
if len(invalid_styles) == 1:
raise InvalidStyleError('The style "{}" does not exist.'.format(invalid_styles[0]))
else:
raise InvalidStyleError('The styles ("{}") do not exist.'.format('", "'.join(invalid_styles)))
def _init_term(self) -> None:
# pylint: disable=unsubscriptable-object
assert self._codename_to_terminal_code is not None
self._tty_in = open("/dev/tty", "r", encoding=self._user_locale)
self._tty_out = open("/dev/tty", "w", encoding=self._user_locale, errors="replace")
self._old_term = termios.tcgetattr(self._tty_in.fileno())
self._new_term = termios.tcgetattr(self._tty_in.fileno())
# set the terminal to: no line-buffering, no echo and no <CR> to <NL> translation (so <enter> sends <CR> instead
# of <NL, this is necessary to distinguish between <enter> and <Ctrl-j> since <Ctrl-j> generates <NL>)
self._new_term[3] = cast(int, self._new_term[3]) & ~termios.ICANON & ~termios.ECHO & ~termios.ICRNL
self._new_term[0] = cast(int, self._new_term[0]) & ~termios.ICRNL
# Set the timings for an unbuffered read: Return immediately after at least one character has arrived and don't
# wait for further characters
cast(List[bytes], self._new_term[6])[termios.VMIN] = b"\x01"
cast(List[bytes], self._new_term[6])[termios.VTIME] = b"\x00"
termios.tcsetattr(
self._tty_in.fileno(), termios.TCSAFLUSH, cast(List[Union[int, List[Union[bytes, int]]]], self._new_term)
)
# Enter terminal application mode to get expected escape codes for arrow keys
self._tty_out.write(self._codename_to_terminal_code["enter_application_mode"])
self._tty_out.write(self._codename_to_terminal_code["cursor_invisible"])
if self._clear_screen:
self._tty_out.write(self._codename_to_terminal_code["clear"])
def _reset_term(self) -> None:
# pylint: disable=unsubscriptable-object
assert self._codename_to_terminal_code is not None
assert self._tty_in is not None
assert self._tty_out is not None
assert self._old_term is not None
termios.tcsetattr(
self._tty_out.fileno(), termios.TCSAFLUSH, cast(List[Union[int, List[Union[bytes, int]]]], self._old_term)
)
self._tty_out.write(self._codename_to_terminal_code["cursor_visible"])
self._tty_out.write(self._codename_to_terminal_code["exit_application_mode"])
if self._clear_screen:
self._tty_out.write(self._codename_to_terminal_code["clear"])
self._tty_in.close()
self._tty_out.close()