2 # -*- coding: utf-8 -*-
4 # © Copyright 2021-2022, Scott Gasch
7 Utilities for dealing with and creating text chunks. For example:
9 - Make a bar graph / progress graph,
11 - left, right, center, justify text,
13 - indent / dedent text,
14 - create a header line,
15 - draw a box around some text.
26 from collections import defaultdict
27 from dataclasses import dataclass
28 from typing import Dict, Generator, List, Literal, Optional, Tuple, Union
30 from pyutils import string_utils
31 from pyutils.ansi import fg, reset
33 logger = logging.getLogger(__file__)
44 """Number of columns"""
47 def get_console_rows_columns() -> RowsColumns:
50 The number of rows/columns on the current console or None
51 if we can't tell or an error occurred.
53 from pyutils.exec_utils import cmd
55 rows: Union[Optional[str], int] = os.environ.get('LINES', None)
56 cols: Union[Optional[str], int] = os.environ.get('COLUMNS', None)
57 if not rows or not cols:
58 logger.debug('Rows: %s, cols: %s, trying stty.', rows, cols)
68 if not rows or not cols:
69 size = os.get_terminal_size()
73 if not rows or not cols:
74 raise Exception('Can\'t determine console size?!')
75 return RowsColumns(int(rows), int(cols))
78 class BarGraphText(enum.Enum):
79 """What kind of text to include at the end of the bar graph?"""
82 """None, leave it blank."""
96 text: BarGraphText = BarGraphText.PERCENTAGE,
97 fgcolor=fg("school bus yellow"),
102 """Draws a progress graph at the current cursor position.
105 current: how many have we done so far?
106 total: how many are there to do total?
107 text: how should we render the text at the end?
108 width: how many columns wide should be progress graph be?
109 fgcolor: what color should "done" part of the graph be?
110 left_end: the character at the left side of the graph
111 right_end: the character at the right side of the graph
112 redraw: if True, omit a line feed after the carriage return
113 so that subsequent calls to this method redraw the graph
116 See also :meth:`bar_graph_string`, :meth:`sparkline`.
120 '[███████████████████████████████████ ] 0.5'
123 ret = "\r" if redraw else "\n"
124 bar = bar_graph_string(
133 print(bar, end=ret, flush=True, file=sys.stderr)
136 def _make_bar_graph_text(
137 text: BarGraphText, current: int, total: int, percentage: float
139 if text == BarGraphText.NONE:
141 elif text == BarGraphText.PERCENTAGE:
142 return f'{percentage:.1f}'
143 elif text == BarGraphText.FRACTION:
144 return f'{current} / {total}'
145 raise ValueError(text)
148 def bar_graph_string(
152 text: BarGraphText = BarGraphText.PERCENTAGE,
154 fgcolor=fg("school bus yellow"),
159 """Returns a string containing a bar graph.
162 current: how many have we done so far?
163 total: how many are there to do total?
164 text: how should we render the text at the end?
165 width: how many columns wide should be progress graph be?
166 fgcolor: what color should "done" part of the graph be?
167 reset_seq: sequence to use to turn off color
168 left_end: the character at the left side of the graph
169 right_end: the character at the right side of the graph
171 See also :meth:`bar_graph`, :meth:`sparkline`.
173 >>> bar_graph_string(5, 10, fgcolor='', reset_seq='')
174 '[███████████████████████████████████ ] 0.5'
179 percentage = float(current) / float(total)
182 if percentage < 0.0 or percentage > 1.0:
183 raise ValueError(percentage)
184 text = _make_bar_graph_text(text, current, total, percentage)
185 whole_width = math.floor(percentage * width)
186 if whole_width == width:
189 elif whole_width == 0 and percentage > 0.0:
192 remainder_width = (percentage * width) % 1
193 part_width = math.floor(remainder_width * 8)
194 part_char = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"][part_width]
200 + " " * (width - whole_width - 1)
208 def sparkline(numbers: List[float]) -> Tuple[float, float, str]:
210 Makes a "sparkline" little inline histogram graph. Auto scales.
213 numbers: the population over which to create the sparkline
216 a three tuple containing:
218 * the minimum number in the population
219 * the maximum number in the population
220 * a string representation of the population in a concise format
222 See also :meth:`bar_graph`, :meth:`bar_graph_string`.
224 >>> sparkline([1, 2, 3, 5, 10, 3, 5, 7])
227 >>> sparkline([104, 99, 93, 96, 82, 77, 85, 73])
228 (73, 104, '█▇▆▆▃▂▄▁')
231 _bar = '▁▂▃▄▅▆▇█' # Unicode: 9601, 9602, 9603, 9604, 9605, 9606, 9607, 9608
234 min_num, max_num = min(numbers), max(numbers)
235 span = max_num - min_num
237 _bar[min([barcount - 1, int((n - min_num) / span * barcount)])] for n in numbers
239 return min_num, max_num, sline
242 def distribute_strings(
249 Distributes strings into a line for justified text.
252 strings: a list of string tokens to distribute
253 width: the width of the line to create
254 padding: the padding character to place between string chunks
257 The distributed, justified string.
259 See also :meth:`justify_string`, :meth:`justify_text`.
261 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40)
264 ret = ' ' + ' '.join(strings) + ' '
265 assert len(string_utils.strip_ansi_sequences(ret)) < width
267 while len(string_utils.strip_ansi_sequences(ret)) < width:
268 spaces = [m.start() for m in re.finditer(r' ([^ ]|$)', ret)]
272 ret = before + padding + after
279 def _justify_string_by_chunk(string: str, width: int = 80, padding: str = " ") -> str:
281 Justifies a string chunk by chunk.
284 string: the string to be justified
285 width: how wide to make the output
286 padding: what padding character to use between chunks
291 >>> _justify_string_by_chunk("This is a test", 40)
293 >>> _justify_string_by_chunk("This is a test", 20)
297 assert len(string_utils.strip_ansi_sequences(string)) <= width
299 first, *rest, last = string.split()
301 len(string_utils.strip_ansi_sequences(first))
302 + len(string_utils.strip_ansi_sequences(last))
304 ret = first + distribute_strings(rest, width=w, padding=padding) + last
309 string: str, *, width: int = 80, alignment: str = "c", padding: str = " "
311 """Justify a string to width with left, right, center of justified
315 string: the string to justify
316 width: the width to justify the string to
317 alignment: a single character indicating the desired alignment:
318 * 'c' = centered within the width
319 * 'j' = justified at width
320 * 'l' = left alignment
321 * 'r' = right alignment
322 padding: the padding character to use while justifying
324 >>> justify_string('This is another test', width=40, alignment='c')
325 ' This is another test '
326 >>> justify_string('This is another test', width=40, alignment='l')
327 'This is another test '
328 >>> justify_string('This is another test', width=40, alignment='r')
329 ' This is another test'
330 >>> justify_string('This is another test', width=40, alignment='j')
331 'This is another test'
333 alignment = alignment[0]
335 while len(string_utils.strip_ansi_sequences(string)) < width:
338 elif alignment == "r":
339 string = padding + string
340 elif alignment == "j":
341 return _justify_string_by_chunk(string, width=width, padding=padding)
342 elif alignment == "c":
343 if len(string) % 2 == 0:
346 string = padding + string
353 text: str, *, width: int = 80, alignment: str = "c", indent_by: int = 0
355 """Justifies text with left, right, centered or justified alignment
356 and optionally with initial indentation.
359 text: the text to be justified
360 width: the width at which to justify text
361 alignment: a single character indicating the desired alignment:
362 * 'c' = centered within the width
363 * 'j' = justified at width
364 * 'l' = left alignment
365 * 'r' = right alignment
366 indent_by: if non-zero, adds n prefix spaces to indent the text.
371 See also :meth:`justify_text`.
373 >>> justify_text('This is a test of the emergency broadcast system. This is only a test.',
374 ... width=40, alignment='j') #doctest: +NORMALIZE_WHITESPACE
375 'This is a test of the emergency\\nbroadcast system. This is only a test.'
381 indent += ' ' * indent_by
384 for word in text.split():
386 len(string_utils.strip_ansi_sequences(line))
387 + len(string_utils.strip_ansi_sequences(word))
390 line = justify_string(line, width=width, alignment=alignment)
391 retval = retval + '\n' + line
393 line = line + ' ' + word
394 if len(string_utils.strip_ansi_sequences(line)) > 0:
396 retval += "\n" + justify_string(line[1:], width=width, alignment=alignment)
398 retval += "\n" + line[1:]
402 def generate_padded_columns(text: List[str]) -> Generator:
403 """Given a list of strings, break them into columns using :meth:`split`
404 and then compute the maximum width of each column. Finally,
405 distribute the columular chunks into the output padding each to
409 text: a list of strings to chunk into padded columns
412 padded columns based on text.split()
414 >>> for x in generate_padded_columns(
415 ... [ 'reading writing arithmetic',
416 ... 'mathematics psychology physics',
417 ... 'communications sociology anthropology' ]):
419 reading writing arithmetic
420 mathematics psychology physics
421 communications sociology anthropology
423 max_width: Dict[int, int] = defaultdict(int)
425 for pos, word in enumerate(line.split()):
426 max_width[pos] = max(
427 max_width[pos], len(string_utils.strip_ansi_sequences(word))
432 for pos, word in enumerate(line.split()):
433 width = max_width[pos]
434 word = justify_string(word, width=width, alignment='l')
439 def wrap_string(text: str, n: int) -> str:
442 text: the string to be wrapped
443 n: the width after which to wrap text
446 The wrapped form of text
448 chunks = text.split()
452 if width + len(string_utils.strip_ansi_sequences(chunk)) > n:
456 width += len(string_utils.strip_ansi_sequences(chunk)) + 1
460 class Indenter(contextlib.AbstractContextManager):
462 Context manager that indents stuff (even recursively). e.g.::
464 with Indenter(pad_count = 8) as i:
481 pad_prefix: Optional[str] = None,
485 """Construct an Indenter.
488 pad_prefix: an optional prefix to prepend to each line
489 pad_char: the character used to indent
490 pad_count: the number of pad_chars to use to indent
493 if pad_prefix is not None:
494 self.pad_prefix = pad_prefix
497 self.padding = pad_char * pad_count
503 def __exit__(self, exc_type, exc_value, exc_tb) -> Literal[False]:
509 def print(self, *arg, **kwargs):
510 text = string_utils.sprintf(*arg, **kwargs)
511 print(self.pad_prefix + self.padding * self.level + text, end='')
517 width: Optional[int] = None,
518 align: Optional[str] = None,
519 style: Optional[str] = 'solid',
520 color: Optional[str] = None,
523 Creates a nice header line with a title.
527 width: how wide to make the header
528 align: "left" or "right"
529 style: "ascii", "solid" or "dashed"
532 The header as a string.
534 >>> header('title', width=60, style='ascii')
535 '----[ title ]-----------------------------------------------'
539 width = get_console_rows_columns().columns
547 text_len = len(string_utils.strip_ansi_sequences(title))
550 right = width - (left + text_len + 4)
551 elif align == 'right':
553 left = width - (right + text_len + 4)
555 left = int((width - (text_len + 4)) / 2)
557 while left + text_len + 4 + right < width:
564 elif style == 'dashed':
592 title: Optional[str] = None,
593 text: Optional[str] = None,
599 Make a nice unicode box (optionally with color) around some text.
602 title: the title of the box
603 text: the text in the box
604 width: the box's width
605 color: the box's color
610 See also :meth:`print_box`, :meth:`preformatted_box`.
612 >>> print(box('title', 'this is some text', width=20).strip())
622 text = justify_text(text, width=width - 4, alignment='l')
623 return preformatted_box(title, text, width=width, color=color)
626 def preformatted_box(
627 title: Optional[str] = None,
628 text: Optional[str] = None,
633 """Creates a nice box with rounded corners and returns it as a string.
636 title: the title of the box
637 text: the text inside the box
638 width: the width of the box
639 color: the box's color
644 See also :meth:`print_box`, :meth:`box`.
646 >>> print(preformatted_box('title', 'this\\nis\\nsome\\ntext', width=20).strip())
663 ret += color + '╭' + '─' * w + '╮' + rset + '\n'
664 if title is not None:
669 + justify_string(title, width=w, alignment='c')
675 ret += color + '│' + ' ' * w + '│' + rset + '\n'
677 for line in text.split('\n'):
678 tw = len(string_utils.strip_ansi_sequences(line))
691 ret += color + '╰' + '─' * w + '╯' + rset + '\n'
696 title: Optional[str] = None,
697 text: Optional[str] = None,
702 """Draws a box with nice rounded corners.
705 title: the title of the box
706 text: the text inside the box
707 width: the width of the box
708 color: the box's color
714 Prints a box with your text on the console to sys.stdout.
716 See also :meth:`preformatted_box`, :meth:`box`.
718 >>> print_box('Title', 'This is text', width=30)
719 ╭────────────────────────────╮
723 ╰────────────────────────────╯
725 >>> print_box(None, 'OK', width=6)
730 print(preformatted_box(title, text, width=width, color=color), end='')
733 if __name__ == '__main__':