3b1b-manim/manimlib/utils/tex.py

41 lines
1.3 KiB
Python
Raw Normal View History

from __future__ import annotations
2022-12-20 22:35:41 -08:00
import re
2022-12-29 10:37:46 -08:00
from manimlib.utils.tex_to_symbol_count import TEX_TO_SYMBOL_COUNT
2022-12-20 22:35:41 -08:00
def num_tex_symbols(tex: str) -> int:
"""
This function attempts to estimate the number of symbols that
a given string of tex would produce.
2022-12-29 10:37:46 -08:00
Warning, it may not behave perfectly
2022-12-20 22:35:41 -08:00
"""
2022-12-29 10:37:46 -08:00
# First, remove patterns like \begin{align}, \phantom{thing},
# \begin{array}{cc}, etc.
pattern = "|".join(
2022-12-29 18:52:13 -08:00
rf"(\\{s})" + r"(\{\w+\})?(\{\w+\})?(\[\w+\])?"
for s in ["begin", "end", "phantom"]
2022-12-29 10:37:46 -08:00
)
tex = re.sub(pattern, "", tex)
2022-12-29 10:37:46 -08:00
# Progressively count the symbols associated with certain tex commands,
# and remove those commands from the string, adding the number of symbols
# that command creates
total = 0
2022-12-29 10:37:46 -08:00
# Start with the special case \sqrt[number]
for substr in re.findall(r"\\sqrt\[[0-9]+\]", tex):
total += len(substr) - 5 # e.g. \sqrt[3] is 3 symbols
tex = tex.replace(substr, " ")
general_command = r"\\[a-zA-Z!,-/:;<>]+"
for substr in re.findall(general_command, tex):
total += TEX_TO_SYMBOL_COUNT.get(substr, 1)
tex = tex.replace(substr, " ")
# Count remaining characters
2022-12-29 10:37:46 -08:00
total += sum(map(lambda c: c not in "^{} \n\t_$\\&", tex))
return total