scripts/md_table_align.py
10.2 KB| 1 | #!/usr/bin/env python3 |
| 2 | # -*- coding: utf-8 -*- |
| 3 | """Markdown 表格对齐美化(离线,仅用标准库)。 |
| 4 | |
| 5 | 把 Markdown 里不齐的表格重排成列宽一致、竖线对齐的排版,中文按两个字符宽度计算。 |
| 6 | 默认输出到屏幕,--in-place 才写回文件;--check 只检查不修改。 |
| 7 | """ |
| 8 | |
| 9 | import sys |
| 10 | import os |
| 11 | import argparse |
| 12 | import unicodedata |
| 13 | |
| 14 | EXIT_OK = 0 |
| 15 | EXIT_UNAGINED = 1 |
| 16 | EXIT_BAD_INPUT = 2 |
| 17 | EXIT_BAD_TABLE = 3 |
| 18 | |
| 19 | FENCE_MARKS = ("```", "~~~") |
| 20 | |
| 21 | |
| 22 | def force_utf8_stdout(): |
| 23 | for stream in (sys.stdout, sys.stderr): |
| 24 | if hasattr(stream, "reconfigure"): |
| 25 | try: |
| 26 | stream.reconfigure(encoding="utf-8", errors="replace") |
| 27 | except Exception: |
| 28 | pass |
| 29 | |
| 30 | |
| 31 | def display_width(text): |
| 32 | """按终端显示宽度计算:全角/宽字符计 2,组合字符计 0,其余计 1。""" |
| 33 | width = 0 |
| 34 | for ch in text: |
| 35 | if unicodedata.combining(ch): |
| 36 | continue |
| 37 | east = unicodedata.east_asian_width(ch) |
| 38 | if east in ("W", "F"): |
| 39 | width += 2 |
| 40 | else: |
| 41 | width += 1 |
| 42 | return width |
| 43 | |
| 44 | |
| 45 | def pad_to(text, width): |
| 46 | """右侧补空格到指定显示宽度。""" |
| 47 | gap = width - display_width(text) |
| 48 | return text + (" " * gap if gap > 0 else "") |
| 49 | |
| 50 | |
| 51 | def split_cells(line): |
| 52 | """按未被反斜杠转义的竖线切分单元格,返回 (单元格列表, 是否以竖线开头, 是否以竖线结尾)。""" |
| 53 | cells = [] |
| 54 | current = [] |
| 55 | leading = line.startswith("|") |
| 56 | trailing = False |
| 57 | escaped = False |
| 58 | index = 0 |
| 59 | length = len(line) |
| 60 | if leading: |
| 61 | index = 1 |
| 62 | while index < length: |
| 63 | ch = line[index] |
| 64 | if escaped: |
| 65 | current.append(ch) |
| 66 | escaped = False |
| 67 | elif ch == "\\": |
| 68 | current.append(ch) |
| 69 | escaped = True |
| 70 | elif ch == "|": |
| 71 | cells.append("".join(current)) |
| 72 | current = [] |
| 73 | trailing = index == length - 1 |
| 74 | else: |
| 75 | current.append(ch) |
| 76 | index += 1 |
| 77 | if not trailing: |
| 78 | cells.append("".join(current)) |
| 79 | return [cell.strip() for cell in cells], leading, trailing |
| 80 | |
| 81 | |
| 82 | def is_separator_row(cells): |
| 83 | """判断是否为表头分隔行,如 ---、:---、---:、:---:。""" |
| 84 | if not cells: |
| 85 | return False |
| 86 | for cell in cells: |
| 87 | body = cell.strip() |
| 88 | if not body: |
| 89 | return False |
| 90 | left_colon = body.startswith(":") |
| 91 | right_colon = body.endswith(":") |
| 92 | middle = body[1 if left_colon else 0:len(body) - 1 if right_colon else len(body)] |
| 93 | if not middle or set(middle) != {"-"}: |
| 94 | return False |
| 95 | return True |
| 96 | |
| 97 | |
| 98 | def separator_style(cell): |
| 99 | body = cell.strip() |
| 100 | left = body.startswith(":") |
| 101 | right = body.endswith(":") |
| 102 | if left and right: |
| 103 | return "both" |
| 104 | if left: |
| 105 | return "left" |
| 106 | if right: |
| 107 | return "right" |
| 108 | return "none" |
| 109 | |
| 110 | |
| 111 | def render_separator(style, width): |
| 112 | if width < 3: |
| 113 | width = 3 |
| 114 | if style == "both": |
| 115 | return ":" + "-" * (width - 2) + ":" |
| 116 | if style == "left": |
| 117 | return ":" + "-" * (width - 1) |
| 118 | if style == "right": |
| 119 | return "-" * (width - 1) + ":" |
| 120 | return "-" * width |
| 121 | |
| 122 | |
| 123 | def collect_table(lines, start): |
| 124 | """从 start 行起收集连续的表格行,返回 (行列表, 结束索引)。""" |
| 125 | block = [] |
| 126 | index = start |
| 127 | while index < len(lines): |
| 128 | stripped = lines[index].strip() |
| 129 | if not stripped.startswith("|"): |
| 130 | break |
| 131 | block.append((index, lines[index])) |
| 132 | index += 1 |
| 133 | return block, index |
| 134 | |
| 135 | |
| 136 | def align_table(block, outer_pipes=True): |
| 137 | """把一组表格行重排,返回对齐后的行列表。出错抛 ValueError。""" |
| 138 | parsed = [] |
| 139 | for lineno, line in block: |
| 140 | cells, _, _ = split_cells(line.strip()) |
| 141 | parsed.append((lineno, cells)) |
| 142 | |
| 143 | header = parsed[0] |
| 144 | if len(parsed) < 2 or not is_separator_row(parsed[1][1]): |
| 145 | raise ValueError("第 %d 行开始的表格缺少表头分隔行(如 | --- | --- |)" % (header[0] + 1)) |
| 146 | |
| 147 | column_count = len(header[1]) |
| 148 | if is_separator_row(header[1]): |
| 149 | raise ValueError("第 %d 行是分隔行,前面缺少表头" % (header[0] + 1)) |
| 150 | if len(parsed[1][1]) != column_count: |
| 151 | raise ValueError( |
| 152 | "第 %d 行分隔行的列数(%d)与表头列数(%d)不一致" |
| 153 | % (parsed[1][0] + 1, len(parsed[1][1]), column_count) |
| 154 | ) |
| 155 | |
| 156 | rows = [(header[0], header[1], False)] |
| 157 | styles = [separator_style(cell) for cell in parsed[1][1]] |
| 158 | rows.append((parsed[1][0], parsed[1][1], True)) |
| 159 | for lineno, cells in parsed[2:]: |
| 160 | if len(cells) != column_count: |
| 161 | raise ValueError( |
| 162 | "第 %d 行的列数(%d)与表头列数(%d)不一致,请先补齐或删除多余的单元格" |
| 163 | % (lineno + 1, len(cells), column_count) |
| 164 | ) |
| 165 | rows.append((lineno, cells, False)) |
| 166 | |
| 167 | widths = [3] * column_count |
| 168 | for _, cells, is_sep in rows: |
| 169 | if is_sep: |
| 170 | continue |
| 171 | for col, cell in enumerate(cells): |
| 172 | widths[col] = max(widths[col], display_width(cell)) |
| 173 | |
| 174 | rendered = [] |
| 175 | for _, cells, is_sep in rows: |
| 176 | if is_sep: |
| 177 | pieces = [render_separator(styles[col], widths[col]) for col in range(column_count)] |
| 178 | else: |
| 179 | pieces = [pad_to(cells[col], widths[col]) for col in range(column_count)] |
| 180 | body = " | ".join(pieces) |
| 181 | rendered.append(("| " + body + " |") if outer_pipes else (body.strip())) |
| 182 | return rendered |
| 183 | |
| 184 | |
| 185 | def process(text, align_all=True): |
| 186 | """处理全文,返回 (新文本, 未对齐数量)。保持原文件的换行风格(LF / CRLF)。""" |
| 187 | newline = "\r\n" if "\r\n" in text else "\n" |
| 188 | lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n") |
| 189 | output = [] |
| 190 | unaligned = 0 |
| 191 | index = 0 |
| 192 | in_fence = False |
| 193 | fence_marker = "" |
| 194 | while index < len(lines): |
| 195 | line = lines[index] |
| 196 | stripped = line.strip() |
| 197 | for mark in FENCE_MARKS: |
| 198 | if stripped.startswith(mark): |
| 199 | if not in_fence: |
| 200 | in_fence = True |
| 201 | fence_marker = mark |
| 202 | elif mark == fence_marker: |
| 203 | in_fence = False |
| 204 | break |
| 205 | if in_fence: |
| 206 | output.append(line) |
| 207 | index += 1 |
| 208 | continue |
| 209 | if stripped.startswith("|"): |
| 210 | block, next_index = collect_table(lines, index) |
| 211 | aligned = align_table(block, outer_pipes=True) |
| 212 | original = [item[1] for item in block] |
| 213 | if aligned != original: |
| 214 | unaligned += 1 |
| 215 | output.extend(aligned if align_all else original) |
| 216 | index = next_index |
| 217 | continue |
| 218 | output.append(line) |
| 219 | index += 1 |
| 220 | return newline.join(output), unaligned |
| 221 | |
| 222 | |
| 223 | def build_parser(): |
| 224 | parser = argparse.ArgumentParser( |
| 225 | prog="md_table_align.py", |
| 226 | description="把 Markdown 表格重排成竖线对齐的整齐格式,中文按两字符宽度计算。", |
| 227 | ) |
| 228 | parser.add_argument("file", help="Markdown 文件,- 表示从标准输入读取") |
| 229 | parser.add_argument("--in-place", action="store_true", help="把结果写回原文件(默认只打印)") |
| 230 | parser.add_argument("--check", action="store_true", help="只检查,不对齐;有未对齐表格时退出码 1") |
| 231 | parser.add_argument("--output", metavar="FILE", help="把结果写到另一个文件,原文件不动") |
| 232 | return parser |
| 233 | |
| 234 | |
| 235 | def read_input(path): |
| 236 | """返回 (文本, 是否带 BOM)。""" |
| 237 | if path == "-": |
| 238 | text = sys.stdin.read() |
| 239 | return text, False |
| 240 | if not os.path.isfile(path): |
| 241 | raise IOError("找不到文件:%s" % path) |
| 242 | with open(path, "rb") as handle: |
| 243 | raw = handle.read() |
| 244 | try: |
| 245 | text = raw.decode("utf-8") |
| 246 | except UnicodeDecodeError: |
| 247 | raise IOError("文件不是 UTF-8 编码,请先转成 UTF-8 再处理") |
| 248 | has_bom = text.startswith("\ufeff") |
| 249 | if has_bom: |
| 250 | text = text[1:] |
| 251 | return text, has_bom |
| 252 | |
| 253 | |
| 254 | def write_output(path, text, has_bom): |
| 255 | payload = (("\ufeff" if has_bom else "") + text).encode("utf-8") |
| 256 | with open(path, "wb") as handle: |
| 257 | handle.write(payload) |
| 258 | |
| 259 | |
| 260 | def main(argv=None): |
| 261 | force_utf8_stdout() |
| 262 | parser = build_parser() |
| 263 | args = parser.parse_args(argv) |
| 264 | |
| 265 | if args.in_place and args.check: |
| 266 | print("参数冲突:--check 只检查,不能与 --in-place 同时使用", file=sys.stderr) |
| 267 | return EXIT_BAD_INPUT |
| 268 | if args.in_place and args.output: |
| 269 | print("参数冲突:--in-place 与 --output 只能二选一", file=sys.stderr) |
| 270 | return EXIT_BAD_INPUT |
| 271 | if args.in_place and args.file == "-": |
| 272 | print("参数错误:从标准输入读取时不能用 --in-place", file=sys.stderr) |
| 273 | return EXIT_BAD_INPUT |
| 274 | |
| 275 | try: |
| 276 | text, has_bom = read_input(args.file) |
| 277 | except (IOError, OSError) as exc: |
| 278 | print("读取失败:%s" % exc, file=sys.stderr) |
| 279 | return EXIT_BAD_INPUT |
| 280 | |
| 281 | try: |
| 282 | new_text, unaligned = process(text, align_all=not args.check) |
| 283 | except ValueError as exc: |
| 284 | print("表格格式错误:%s" % exc, file=sys.stderr) |
| 285 | return EXIT_BAD_TABLE |
| 286 | |
| 287 | if args.check: |
| 288 | if unaligned: |
| 289 | print("发现 %d 处未对齐的表格,建议运行本工具重排。" % unaligned, file=sys.stderr) |
| 290 | return EXIT_UNAGINED |
| 291 | print("全部表格已对齐。") |
| 292 | return EXIT_OK |
| 293 | |
| 294 | if args.in_place: |
| 295 | try: |
| 296 | write_output(args.file, new_text, has_bom) |
| 297 | except (IOError, OSError) as exc: |
| 298 | print("写入失败:%s" % exc, file=sys.stderr) |
| 299 | return EXIT_BAD_INPUT |
| 300 | print("已重排 %d 处表格并写回:%s" % (unaligned, os.path.basename(args.file))) |
| 301 | return EXIT_OK |
| 302 | |
| 303 | if args.output: |
| 304 | try: |
| 305 | write_output(args.output, new_text, has_bom) |
| 306 | except (IOError, OSError) as exc: |
| 307 | print("写入失败:%s" % exc, file=sys.stderr) |
| 308 | return EXIT_BAD_INPUT |
| 309 | print("已重排 %d 处表格,结果写入:%s" % (unaligned, os.path.basename(args.output))) |
| 310 | return EXIT_OK |
| 311 | |
| 312 | sys.stdout.write(new_text) |
| 313 | if not new_text.endswith("\n"): |
| 314 | sys.stdout.write("\n") |
| 315 | if unaligned: |
| 316 | print("已重排 %d 处表格。" % unaligned, file=sys.stderr) |
| 317 | return EXIT_OK |
| 318 | |
| 319 | |
| 320 | if __name__ == "__main__": |
| 321 | sys.exit(main()) |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

