]> asedeno.scripts.mit.edu Git - vt_decor.git/commitdiff
custom list wrapping
authorAlejandro R. Sedeño <asedeno@mit.edu>
Sun, 13 Feb 2022 22:01:26 +0000 (17:01 -0500)
committerAlejandro R. Sedeño <asedeno@mit.edu>
Mon, 14 Feb 2022 23:41:17 +0000 (18:41 -0500)
vt_decor.py

index abb3d222ad74f8bf90eed76b52b5653db7e21ecc..68719b1d0c19c7b3cf6cd8101ebed05ca47d98b9 100644 (file)
@@ -4,7 +4,6 @@ import ipaddress
 import re
 import textwrap
 import time
-import sys
 import weakref
 
 from .. import chunks, messages, roost, util, zcode
@@ -98,12 +97,14 @@ def _get_width():
 
 ## The fun part
 
-MSG_NO_WRAP_PATTERNS = [re.compile(x) for x in (
-    r'\n(?: |>)',
+MSG_NO_WRAP_PATTERNS = [re.compile(x, re.MULTILINE) for x in (
+    r'^(?: |>)',
     r'\t',
     r'[^.]  ',
 )]
 
+MSG_LIST_WRAP_PATTERN = re.compile(r'(^\s*[-*]\s+)', re.MULTILINE)
+
 REALM_MAP = {
     'ANDREW.CMU.EDU': 'AN',
     'CS.CMU.EDU': 'CS',
@@ -138,6 +139,38 @@ class RoostVTDecor(roost.RoostMessage.Decor):
         return (bool(force_wrap_tuples & msg_tuples) or
                 not any(x.search(msg.body) for x in MSG_NO_WRAP_PATTERNS))
 
+    @staticmethod
+    def list_rewrap_p(msg):
+        return len(MSG_LIST_WRAP_PATTERN.findall(msg.body)) >= 2
+
+    @classmethod
+    def partial_rewrap(cls, body, width, indent):
+        try:
+            ret = ''
+            bindent = ''
+            for m in MSG_LIST_WRAP_PATTERN.split(body):
+                if not m:
+                    continue
+                if MSG_LIST_WRAP_PATTERN.match(m):
+                    # Bullet
+                    if ret:
+                        ret += indent
+                    ret += m
+                    bindent = ' ' * util.glyphwidth(m)
+                else:
+                    # Content
+                    # collapse whitespace and wrap.
+                    ret += textwrap.fill(re.sub(r'\s+', ' ', m), width,
+                                         initial_indent=indent+bindent,
+                                         subsequent_indent=indent+bindent,
+                                         break_long_words=False,
+                                         break_on_hyphens=False).lstrip()
+                    ret += '\n'
+
+            return ret.rstrip()
+        except Exception as e:
+            return str(e)
+
 
     @classmethod
     def vt_decorate(cls, msg, decoration):
@@ -175,7 +208,9 @@ class RoostVTDecor(roost.RoostMessage.Decor):
         indent = ' ' * util.glyphwidth(prefix)
 
         body = msg.body.rstrip()
-        if cls.rewrap_p(msg):
+        if cls.list_rewrap_p(msg):
+            body = cls.partial_rewrap(body, width, indent)
+        elif cls.rewrap_p(msg):
             body = textwrap.fill(body, width,
                                  initial_indent=indent,
                                  subsequent_indent=indent,