#!/usr/bin/env python3
"""
e5_format_html.py — Форматирователь HTML: разбивает на строки по тегам,
БЕЗ добавления отступов. Просто каждый тег на новой строке.
Использование:
python e5_format_html.py input.html → выводит в stdout
python e5_format_html.py input.html output.html → сохраняет в файл
python e5_format_html.py --dir ./folder → все .html в папке (на месте)
"""
import os
import re
import sys
# Теги, после открывающего/закрывающего которых ставим перенос
BLOCK_TAGS = {
"html",
"head",
"body",
"div",
"p",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"ul",
"ol",
"li",
"table",
"tbody",
"thead",
"tfoot",
"tr",
"td",
"th",
"form",
"fieldset",
"section",
"article",
"nav",
"aside",
"header",
"footer",
"main",
"details",
"summary",
"blockquote",
"pre",
"script",
"style",
"link",
"meta",
"title",
}
# Теги, содержимое которых не трогаем
PRESERVE_TAGS = {"pre", "textarea", "script", "style"}
def format_html(html):
# Защищаем содержимое pre/textarea/script/style
preserved = []
def save_block(m):
preserved.append(m.group(0))
return f"\x00BLOCK{len(preserved) - 1}\x00"
html = re.sub(
r"(<(?:pre|textarea|script|style)\b[^>]*>)(.*?)((?:pre|textarea|script|style)>)",
save_block,
html,
flags=re.DOTALL | re.IGNORECASE,
)
# Убираем существующие переносы и лишние пробелы
html = re.sub(r"[\r\n\t]+", " ", html)
html = re.sub(r" {2,}", " ", html)
# Перенос ПЕРЕД открывающими блочными тегами
tags_pattern = "|".join(BLOCK_TAGS)
html = re.sub(
rf"(?<=>)\s*(<(?:{tags_pattern})\b)", r"\n\1", html, flags=re.IGNORECASE
)
# Перенос ПОСЛЕ закрывающих блочных тегов
html = re.sub(rf"((?:{tags_pattern})>)\s*", r"\1\n", html, flags=re.IGNORECASE)
# Перенос ПОСЛЕ самозакрывающихся тегов (meta, link, br, hr, img)
html = re.sub(r"(<(?:meta|link)\b[^>]*>)\s*", r"\1\n", html, flags=re.IGNORECASE)
# Перенос ПОСЛЕ
и