#!/usr/bin/env python3
import re
import os
import subprocess
from bs4 import BeautifulSoup, NavigableString
import html2text
import pyperclip
D = chr(36) # Символ доллар
def get_clipboard_html() -> str:
if os.environ.get("WAYLAND_DISPLAY"):
cmd = ["wl-paste", "-n", "-t", "text/html"]
else:
cmd = ["xclip", "-o", "-selection", "clipboard", "-t", "text/html"]
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
errors="replace", # Защита от падения, если в буфере попадётся битый UTF-8 символ
)
except:
return ""
return result.stdout if result.returncode == 0 else ""
html_content = get_clipboard_html()
if html_content:
soup = BeautifulSoup(html_content, "html.parser")
math_placeholders = {}
counter = 0
# 1. Удаляем встроенные base64-картинки
for tag in soup.find_all(src=re.compile(r"^data:image/", re.I)):
tag.decompose()
# 2. Убираем визуальный слой KaTeX, чтобы формулы не дублировались (остаётся чистый LaTeX)
for katex_html in soup.find_all(class_="katex-html"):
katex_html.decompose()
# 3. Удаляем кнопки интерфейса (например, "Copy code" внутри блоков кода)
for btn in soup.find_all("button"):
btn.decompose()
# 4. Обработка формул
# 4a Извлекаем формулы в плейсхолдеры ДО html2text
def add_math(tex: str, is_block: bool) -> str:
global counter
placeholder = f"MATHPLACEHOLDER{counter}END"
counter += 1
tex = tex.strip()
if is_block:
math_placeholders[placeholder] = f"\n{D}{D}\n{tex}\n{D}{D}\n"
else:
math_placeholders[placeholder] = f"{D}{tex}{D}"
return placeholder
# 4b Текстовые формулы ... и \[...\] ТОЛЬКО вне тегов кода
open_block, close_block = re.escape(chr(92) + "["), re.escape(chr(92) + "]")
open_inline, close_inline = re.escape(chr(92) + "("), re.escape(chr(92) + ")")
no_bs = r"(?<!\\)"
block_re = re.compile(f"{no_bs}{open_block}(.*?){no_bs}{close_block}", re.DOTALL)
inline_re = re.compile(f"{no_bs}{open_inline}(.*?){no_bs}{close_inline}", re.DOTALL)
def is_isolated_on_line(node: NavigableString) -> bool:
"""Проверяет, стоит ли формула на отдельной строке внутри своего контейнера."""
# Внутри ячеек таблиц формулы НИКОГДА не должны быть блочными (иначе порвется таблица)
if node.find_parent(["td", "th"]):
return False
# Проверяем, что слева до начала блока или тега <br> нет видимого текста
curr = node.previous_sibling
while curr:
if getattr(curr, "name", None) == "br":
break
if type(curr) is NavigableString and curr.strip():
return False
if getattr(curr, "name", None) and curr.get_text(strip=True):
return False
curr = curr.previous_sibling
# Проверяем, что справа до конца блока или тега <br> нет видимого текста
curr = node.next_sibling
while curr:
if getattr(curr, "name", None) == "br":
break
if type(curr) is NavigableString and curr.strip():
return False
if getattr(curr, "name", None) and curr.get_text(strip=True):
return False
curr = curr.next_sibling
return True
for text_node in list(soup.find_all(string=True)):
if type(text_node) is not NavigableString:
continue
if text_node.find_parent(["code", "pre", "script", "style", "textarea"]):
continue
text = str(text_node)
if r"\(" not in text and r"\[" not in text:
continue
# Проверяем, занимает ли формула целиком весь текстовый узел и стоит ли она на отдельной строке
stripped = text.strip()
is_standalone = bool(inline_re.fullmatch(stripped)) and is_isolated_on_line(text_node)
new_text = block_re.sub(lambda m: add_math(m.group(1), is_block=True), text)
new_text = inline_re.sub(
lambda m: add_math(m.group(1), is_block=is_standalone), new_text
)
if new_text != text:
text_node.replace_with(NavigableString(new_text))
h = html2text.HTML2Text()
h.body_width = 0
h.ignore_links = True # Оставляет только текст ссылки, удаляя URL
h.ignore_images = True # Игнорировать все теги <img> при конвертации
h.protect_links = True # Не оборачивает длинные URL в угловые скобки <...>
h.mark_code = True # Оформляет <pre> блоки через [code]...[/code]
md = h.handle(str(soup))
md = re.sub(r"\[/?code\]", "```", md)
# 4.end Возвращаем все формулы на место плейсхолдеров
for placeholder, math_str in math_placeholders.items():
md = md.replace(placeholder, math_str)
md = re.sub(r"\n{3,}", "\n\n", md).strip()
pyperclip.copy(md.strip())
else:
print("Нет html контента!")