44from markdown_it import MarkdownIt
55from mdformat .renderer import RenderContext , RenderTreeNode
66from mdformat .renderer .typing import Postprocess , Render
7+ from wcwidth import wcswidth
78
89_COMPACT_TABLES = False
910"""user-specified flag for toggling compact tables."""
@@ -26,6 +27,22 @@ def update_mdit(mdit: MarkdownIt) -> None:
2627 _COMPACT_TABLES = mdit .options ["mdformat" ].get ("compact_tables" , False )
2728
2829
30+ def _lpad (text : str , width : int ) -> str :
31+ indent = width - wcswidth (text )
32+ return " " * max (0 , indent ) + text
33+
34+
35+ def _rpad (text : str , width : int ) -> str :
36+ outdent = width - wcswidth (text )
37+ return text + " " * max (0 , outdent )
38+
39+
40+ def _center (text : str , width : int ) -> str :
41+ text_len = wcswidth (text )
42+ indent = (width - text_len ) // 2 + text_len
43+ return _rpad (_lpad (text , indent ), width )
44+
45+
2946def _to_string (
3047 rows : Sequence [Sequence [str ]], align : Sequence [Sequence [str ]], widths : Sequence [int ]
3148) -> List [str ]:
@@ -40,19 +57,19 @@ def format_delimiter_cell(index: int, align: str) -> str:
4057 )
4158 return ":-:" if delim == "::" else delim
4259
60+ pad = {"" : _rpad , "<" : _rpad , ">" : _lpad , "^" : _center }
61+
4362 header = join_row (
44- f"{{:{ al or '<' } { widths [i ]} }}" .format (text )
45- for i , (text , al ) in enumerate (zip (rows [0 ], align [0 ]))
63+ pad [al ](text , widths [i ]) for i , (text , al ) in enumerate (zip (rows [0 ], align [0 ]))
4664 )
4765 delimiter = join_row (
4866 (format_delimiter_cell (i , al ) for i , al in enumerate (align [0 ]))
4967 )
5068 rows = [
5169 join_row (
52- f"{{:{ al or '<' } { widths [i ]} }}" .format (text )
53- for i , (text , al ) in enumerate (zip (row , als ))
70+ pad [_al ](text , widths [i ]) for i , (text , _al ) in enumerate (zip (row , aligns ))
5471 )
55- for row , als in zip (rows [1 :], align [1 :])
72+ for row , aligns in zip (rows [1 :], align [1 :])
5673 ]
5774 return [header , delimiter , * rows ]
5875
@@ -83,7 +100,7 @@ def _calculate_width(col_idx: int) -> int:
83100 """Work out the widths for each column."""
84101 if _COMPACT_TABLES :
85102 return 0
86- return max (3 , * (len (row [col_idx ]) for row in rows ))
103+ return max (3 , * (wcswidth (row [col_idx ]) for row in rows ))
87104
88105 widths = [_calculate_width (col_idx ) for col_idx in range (len (rows [0 ]))]
89106
0 commit comments