3 """Utilities for dealing with "text"."""
5 from collections import defaultdict
8 from typing import List, NamedTuple, Optional
10 from ansi import fg, reset
13 class RowsColumns(NamedTuple):
18 def get_console_rows_columns() -> RowsColumns:
19 """Returns the number of rows/columns on the current console."""
21 from exec_utils import cmd
22 rows, columns = cmd("stty size").split()
23 return RowsColumns(int(rows), int(columns))
31 fgcolor=fg("school bus yellow"),
36 """Draws a progress graph."""
38 percent = current / total
39 ret = "\r" if redraw else "\n"
46 right_end = right_end)
59 fgcolor=fg("school bus yellow"),
64 """Returns a string containing a bar graph.
66 >>> bar_graph(0.5, fgcolor='', reset='')
67 '[███████████████████████████████████ ] 50.0%'
71 if percentage < 0.0 or percentage > 1.0:
72 raise ValueError(percentage)
74 text = f"{percentage*100.0:2.1f}%"
77 whole_width = math.floor(percentage * width)
78 if whole_width == width:
82 remainder_width = (percentage * width) % 1
83 part_width = math.floor(remainder_width * 8)
84 part_char = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"][part_width]
88 "█" * whole_width + part_char +
89 " " * (width - whole_width - 1) +
95 def distribute_strings(
103 Distributes strings into a line with a particular justification.
105 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40)
107 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='l')
109 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='r')
113 subwidth = math.floor(width / len(strings))
115 for string in strings:
116 string = justify_string(
117 string, width=subwidth, alignment=alignment, padding=padding
123 def justify_string_by_chunk(
124 string: str, width: int = 80, padding: str = " "
129 >>> justify_string_by_chunk("This is a test", 40)
131 >>> justify_string_by_chunk("This is a test", 20)
136 first, *rest, last = string.split()
137 w = width - (len(first) + 1 + len(last) + 1)
139 first + padding + distribute_strings(rest, width=w, padding=padding)
141 while len(retval) + len(last) < width:
148 string: str, *, width: int = 80, alignment: str = "c", padding: str = " "
152 >>> justify_string('This is another test', width=40, alignment='c')
153 ' This is another test '
154 >>> justify_string('This is another test', width=40, alignment='l')
155 'This is another test '
156 >>> justify_string('This is another test', width=40, alignment='r')
157 ' This is another test'
158 >>> justify_string('This is another test', width=40, alignment='j')
159 'This is another test'
162 alignment = alignment[0]
164 while len(string) < width:
167 elif alignment == "r":
168 string = padding + string
169 elif alignment == "j":
170 return justify_string_by_chunk(
175 elif alignment == "c":
176 if len(string) % 2 == 0:
179 string = padding + string
185 def justify_text(text: str, *, width: int = 80, alignment: str = "c") -> str:
189 >>> justify_text('This is a test of the emergency broadcast system. This is only a test.',
190 ... width=40, alignment='j') #doctest: +NORMALIZE_WHITESPACE
191 'This is a test of the emergency\\nbroadcast system. This is only a test.'
195 for word in text.split():
196 if len(line) + len(word) > width:
198 line = justify_string(line, width=width, alignment=alignment)
199 retval = retval + "\n" + line
201 line = line + " " + word
203 retval += "\n" + line[1:]
207 def generate_padded_columns(text: List[str]) -> str:
208 max_width = defaultdict(int)
210 for pos, word in enumerate(line.split()):
211 max_width[pos] = max(max_width[pos], len(word))
215 for pos, word in enumerate(line.split()):
216 width = max_width[pos]
217 word = justify_string(word, width=width, alignment='l')
222 def wrap_string(text: str, n: int) -> str:
223 chunks = text.split()
227 if width + len(chunk) > n:
231 width += len(chunk) + 1
237 with Indenter(pad_count = 8) as i:
246 pad_prefix: Optional[str] = None,
250 if pad_prefix is not None:
251 self.pad_prefix = pad_prefix
254 self.padding = pad_char * pad_count
260 def __exit__(self, exc_type, exc_value, exc_tb):
265 def print(self, *arg, **kwargs):
267 text = string_utils.sprintf(*arg, **kwargs)
268 print(self.pad_prefix + self.padding * self.level + text, end='')
271 def header(title: str, *, width: int = 80, color: str = ''):
273 Returns a nice header line with a title.
275 >>> header('title', width=60, color='')
276 '----[ title ]-----------------------------------------------'
280 w -= (len(title) + 4)
283 right = (w - 4) * '-'
284 if color != '' and color is not None:
288 return f'{left}[ {color}{title}{r} ]{right}'
293 if __name__ == '__main__':