Текст и документы

Перенести длинные строки

Разбивает абзацы по ширине, сохраняя списки, заголовки и блоки кода без изменений.

Python Windows macOS Linux Средний
Скачать wrap_lines.py
Описание

Что делает скрипт

Скрипт собирает соседние строки в абзацы и переносит их по словам до заданной ширины. Списки получают висячий отступ, а содержимое блоков кода и заголовки остаются как были. По умолчанию результат идёт в новый файл или на экран.

Перед запуском
  • С --in-place исходный файл заменяется, рядом остаётся копия .bak.
Запуск

Быстрый старт

python wrap_lines.py article.md --width 80 --output wrapped.md

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python wrap_lines.py article.md --width 72
  • python wrap_lines.py article.md --width 90 --output article-wrapped.md
  • python wrap_lines.py notes.txt --width 60 --break-long-words --in-place
Зависимости

Что понадобится

Python 3.10+ Только стандартная библиотека
Windows winget install Python.Python.3.12
macOS brew install python
Linux sudo apt install python3
Исходник

wrap_lines.py

#!/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())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get text-wrap-lines
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Текст и документы

Поиск, замена, кодировки, Markdown, CSV и работа с большими текстами.