@@ -20,18 +20,31 @@ def set_embed_author(embed: Embed, user: SimpleUser):
2020
2121_NEWLINE_PATTERN = re .compile (r"\n[ \t]*\n([ \t]*\n)+" )
2222
23- _NEWLINE_HEADING_PATTERN = re .compile (r"(\n|^)\n+(#+ +\S)" )
23+ # remove extra newlines before heading, and fix double newline after heading
24+ _NEWLINE_HEADING_PATTERN = re .compile (r"(\n|^)\n+(#+ +[^\n]+(?:\n|$))\n?" )
2425
2526
2627@overload
27- def truncate_markdown_description (text : str , limit : int = ...) -> str : ...
28+ def truncate_markdown_description (
29+ text : str ,
30+ limit : int = ...,
31+ line_limit : int | None = ...,
32+ ) -> str : ...
2833
2934
3035@overload
31- def truncate_markdown_description (text : str | None , limit : int = ...) -> str | None : ...
32-
33-
34- def truncate_markdown_description (text : str | None , limit : int = 256 ) -> str | None :
36+ def truncate_markdown_description (
37+ text : str | None ,
38+ limit : int = ...,
39+ line_limit : int | None = ...,
40+ ) -> str | None : ...
41+
42+
43+ def truncate_markdown_description (
44+ text : str | None ,
45+ limit : int = 512 ,
46+ line_limit : int | None = 16 ,
47+ ) -> str | None :
3548 if text is None :
3649 return None
3750
@@ -40,14 +53,26 @@ def truncate_markdown_description(text: str | None, limit: int = 256) -> str | N
4053 text = _NEWLINE_HEADING_PATTERN .sub (r"\1\2" , text )
4154 text = text .strip ()
4255
43- if len (text ) <= limit :
56+ if len (text ) <= limit and line_limit is None :
4457 return text
4558
46- # truncate the string at the first whitespace character after overflowing
47- # TODO: would it be better to truncate before instead?
4859 i = 0
60+ newline_count = 0
4961 for c in text :
62+ # truncate the string at the first whitespace character after overflowing
63+ # TODO: would it be better to truncate before instead?
5064 if i >= limit and c .isspace ():
5165 break
66+
67+ if line_limit is not None and c == "\n " :
68+ newline_count += 1
69+ if newline_count >= line_limit :
70+ break
71+
5272 i += 1
73+ else :
74+ # if we didn't break or run over the limit, don't truncate
75+ if i <= limit :
76+ return text
77+
5378 return text [:i ] + "..."
0 commit comments