Various changes.
[python_utils.git] / text_utils.py
index 93e4b638ba9c840dfd05a27a83d01865643352bd..3be32ff49ec05b2d7ca0978e6cb34b65da64162e 100644 (file)
@@ -5,7 +5,7 @@
 from collections import defaultdict
 import math
 import sys
-from typing import List, NamedTuple
+from typing import List, NamedTuple, Optional
 
 from ansi import fg, reset
 
@@ -169,17 +169,39 @@ def generate_padded_columns(text: List[str]) -> str:
         yield out
 
 
+def wrap_string(text: str, n: int) -> str:
+    chunks = text.split()
+    out = ''
+    width = 0
+    for chunk in chunks:
+        if width + len(chunk) > n:
+            out += '\n'
+            width = 0
+        out += chunk + ' '
+        width += len(chunk) + 1
+    return out
+
+
 class Indenter:
     """
-    with Indenter() as i:
-      i.print('test')
-      with i:
-        i.print('-ing')
+    with Indenter(pad_count = 8) as i:
+        i.print('test')
         with i:
-          i.print('1, 2, 3')
+            i.print('-ing')
+            with i:
+                i.print('1, 2, 3')
     """
-    def __init__(self):
+    def __init__(self,
+                 *,
+                 pad_prefix: Optional[str] = None,
+                 pad_char: str = ' ',
+                 pad_count: int = 4):
         self.level = -1
+        if pad_prefix is not None:
+            self.pad_prefix = pad_prefix
+        else:
+            self.pad_prefix = ''
+        self.padding = pad_char * pad_count
 
     def __enter__(self):
         self.level += 1
@@ -193,4 +215,4 @@ class Indenter:
     def print(self, *arg, **kwargs):
         import string_utils
         text = string_utils.sprintf(*arg, **kwargs)
-        print("    " * self.level + text)
+        print(self.pad_prefix + self.padding * self.level + text, end='')