#!/usr/bin/env python3 """Перенос длинных строк с сохранением структуры Markdown.""" from __future__ import annotations import argparse import re import shutil import textwrap from pathlib import Path LIST_ITEM = re.compile(r"^(\s*)([-*+]|\d+[.)])\s+(.*)$") FENCE = re.compile(r"^\s*(```|~~~)") def wrap_paragraph(lines: list[str], width: int, break_words: bool) -> list[str]: text = " ".join(part.strip() for part in lines) return textwrap.wrap( text, width=width, break_long_words=break_words, break_on_hyphens=False, replace_whitespace=False, drop_whitespace=True, ) or [""] def process(text: str, width: int, break_words: bool) -> str: output: list[str] = [] paragraph: list[str] = [] in_fence = False def flush() -> None: if paragraph: output.extend(wrap_paragraph(paragraph, width, break_words)) paragraph.clear() for line in text.splitlines(): if FENCE.match(line): flush() in_fence = not in_fence output.append(line) continue if in_fence: output.append(line) continue if not line.strip(): flush() output.append("") continue if line.lstrip().startswith("#") or line.lstrip().startswith(">"): flush() output.append(line) continue match = LIST_ITEM.match(line) if match: flush() indent, marker, body = match.groups() prefix = f"{indent}{marker} " wrapped = textwrap.wrap( body, width=max(20, width - len(prefix)), break_long_words=break_words, break_on_hyphens=False, ) or [""] output.append(prefix + wrapped[0]) for continuation in wrapped[1:]: output.append(" " * len(prefix) + continuation) continue paragraph.append(line) flush() return "\n".join(output) + "\n" def main() -> int: parser = argparse.ArgumentParser(description="Перенести длинные строки") parser.add_argument("input", type=Path, help="Входной файл") parser.add_argument("--output", type=Path, help="Выходной файл") parser.add_argument("--width", type=int, default=80, help="Ширина строки") parser.add_argument("--encoding", default="utf-8", help="Кодировка") parser.add_argument("--break-long-words", action="store_true", help="Разрывать длинные слова") parser.add_argument("--in-place", action="store_true", help="Заменить исходный файл") args = parser.parse_args() if args.width < 20: parser.error("Ширина должна быть не меньше 20") source = args.input.expanduser() if not source.is_file(): parser.error(f"Файл не найден: {source}") if args.in_place and args.output: parser.error("С --in-place не указывайте --output") if args.output and args.output.expanduser().resolve() == source.resolve(): parser.error("Выходной файл совпадает с входным, используйте --in-place") text = source.read_text(encoding=args.encoding) result = process(text, args.width, args.break_long_words) if args.in_place: backup = source.with_name(source.name + ".bak") shutil.copy2(source, backup) source.write_text(result, encoding=args.encoding) print(f"Файл обновлён, копия: {backup.name}") elif args.output: target = args.output.expanduser() target.parent.mkdir(parents=True, exist_ok=True) target.write_text(result, encoding=args.encoding) print(f"Результат: {target}") else: print(result, end="") return 0 if __name__ == "__main__": raise SystemExit(main())