Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Improve TeX error reporting (#2161)

kieran-pringlee3f7026d0e5c
diff --git a/manim/utils/tex_file_writing.py b/manim/utils/tex_file_writing.py
index 6493c1a3d..39c6c0e45 100644
--- a/manim/utils/tex_file_writing.py
+++ b/manim/utils/tex_file_writing.py
@@ -147,15 +147,6 @@ def insight_inputenc_error(match):
yield "See the documentation for manim.mobject.svg.tex_mobject for details on using a custom TexTemplate"
-# used by compile_tex; maps regexp to function offering additional insights
-LATEX_ERROR_INSIGHTS = [
- (
- r"inputenc Error: Unicode character (?:.*) \(U\+([0-9a-fA-F]+)\)",
- insight_inputenc_error,
- ),
-]
-
-
def compile_tex(tex_file, tex_compiler, output_format):
"""Compiles a tex_file into a .dvi or a .xdv or a .pdf
@@ -187,55 +178,7 @@ def compile_tex(tex_file, tex_compiler, output_format):
exit_code = os.system(command)
if exit_code != 0:
log_file = tex_file.replace(".tex", ".log")
- if not Path(log_file).exists():
- raise RuntimeError(
- f"{tex_compiler} failed but did not produce a log file. "
- "Check your LaTeX installation.",
- )
- with open(log_file) as f:
- log = f.readlines()
- error_pos = [
- index for index, line in enumerate(log) if line.startswith("!")
- ]
- if error_pos:
- with open(tex_file) as g:
- tex = g.readlines()
- for log_index in error_pos:
- logger.error(
- f"LaTeX compilation error: {log[log_index][2:]}",
- )
- index_line = log_index
- context = "Context for error:\n\n"
-
- # Find where the line of the error is indicated in the log file
- while not log[index_line].startswith("l."):
- index_line += 1
-
- # Find the index of the errored line in the tex file
- tex_index = (
- int(log[index_line].split(" ")[0].split(".")[1]) - 1
- )
-
- # Seek the environment scope that contains the error
- environment = tex_index
- while not tex[environment].startswith("\\begin"):
- environment -= 1
-
- # Print the entire environment including its end
- while not tex[environment - 1].startswith("\\end"):
- context += tex[environment]
- if environment == tex_index:
- context += "^ this line\n"
- environment += 1
- logger.error(context)
-
- # add insight for errors
- for prog, get_insight in LATEX_ERROR_INSIGHTS:
- match = re.search(prog, "".join(log[log_index:index_line]))
- if match is not None:
- for insight in get_insight(match):
- logger.info(insight)
-
+ print_all_tex_errors(log_file, tex_compiler, tex_file)
raise ValueError(
f"{tex_compiler} error converting to"
f" {output_format[1:]}. See log output above or"
@@ -288,3 +231,89 @@ def convert_to_svg(dvi_file, extension, page=1):
)
return result
+
+
+def print_all_tex_errors(log_file, tex_compiler, tex_file):
+ if not Path(log_file).exists():
+ raise RuntimeError(
+ f"{tex_compiler} failed but did not produce a log file. "
+ "Check your LaTeX installation.",
+ )
+ with open(log_file) as f:
+ tex_compilation_log = f.readlines()
+ error_indices = [
+ index
+ for index, line in enumerate(tex_compilation_log)
+ if line.startswith("!")
+ ]
+ if error_indices:
+ with open(tex_file) as g:
+ tex = g.readlines()
+ for error_index in error_indices:
+ print_tex_error(tex_compilation_log, error_index, tex)
+
+
+LATEX_ERROR_INSIGHTS = [
+ (
+ r"inputenc Error: Unicode character (?:.*) \(U\+([0-9a-fA-F]+)\)",
+ insight_inputenc_error,
+ ),
+]
+
+
+def print_tex_error(tex_compilation_log, error_start_index, tex_source):
+ logger.error(
+ f"LaTeX compilation error: {tex_compilation_log[error_start_index][2:]}",
+ )
+
+ # TeX errors eventually contain a line beginning 'l.xxx` where xxx is the line number that caused the compilation
+ # failure. This code finds the next such line after the error current error message
+ line_of_tex_error = (
+ int(
+ [
+ log_line
+ for log_line in tex_compilation_log[error_start_index:]
+ if log_line.startswith("l.")
+ ][0]
+ .split(" ")[0]
+ .split(".")[1],
+ )
+ - 1
+ )
+ # our tex error may be on a line outside our user input because of post-processing
+ if line_of_tex_error >= len(tex_source):
+ return None
+
+ # all lines numbers containing '\begin{' or '\end{' - except the Manim added center and document tags
+ env_markers_indices = [
+ idx
+ for idx, log_line in enumerate(tex_source)
+ if any(marker in log_line for marker in [r"\begin{", r"\end{"])
+ ][2:-2]
+
+ context = "Context of error:\n\n"
+ if line_of_tex_error in env_markers_indices:
+ context += "".join(tex_source[line_of_tex_error - 1 : line_of_tex_error + 1])
+ else:
+ marker_before_error = max(
+ idx for idx in env_markers_indices if idx < line_of_tex_error
+ )
+ marker_after_error = min(
+ idx for idx in env_markers_indices if idx > line_of_tex_error
+ )
+ context += "".join(tex_source[marker_before_error:marker_after_error])
+ logger.error(context)
+
+ for prog, get_insight in LATEX_ERROR_INSIGHTS:
+ error_end_index = [
+ idx
+ for idx, _ in enumerate(tex_compilation_log[error_start_index:])
+ if _.startswith("l.")
+ ][0]
+ match = re.search(
+ prog,
+ "".join(tex_compilation_log[error_start_index:error_end_index]),
+ )
+ if match is not None:
+ for insight in get_insight(match):
+ logger.info(insight)
diff --git a/tests/test_texmobject.py b/tests/test_texmobject.py
index 6ebb3afaa..fddb0ab6a 100644
--- a/tests/test_texmobject.py
+++ b/tests/test_texmobject.py
@@ -2,7 +2,7 @@ from pathlib import Path
import pytest
-from manim import MathTex, SingleStringMathTex, Tex, config
+from manim import MathTex, SingleStringMathTex, Tex, TexTemplate, config
def test_MathTex():
@@ -105,3 +105,60 @@ def test_changing_font_size():
num.font_size = 48
assert num.height == Tex("0", font_size=48).height
+
+
+def test_log_error_context(capsys):
+ """Test that the environment context of an error is correctly logged if it exists"""
+ invalid_tex = r"""
+ some text that is fine
+
+ \begin{unbalanced_braces}{
+ not fine
+ \end{not_even_the_right_env}
+ """
+
+ with pytest.raises(ValueError) as err:
+ Tex(invalid_tex)
+
+ # validate useful TeX error logged to user
+ assert "unbalanced_braces" in str(capsys.readouterr().out)
+ # validate useful error message raised
+ assert "See log output above or the log file" in str(err.value)
+
+
+def test_log_error_no_relevant_context(capsys):
+ """Test that an error with no environment context contains no environment context"""
+ failing_preamble = r"""\usepackage{fontspec}
+ \setmainfont[Ligatures=TeX]{not_a_font}"""
+
+ with pytest.raises(ValueError) as err:
+ Tex(
+ "The template uses a non-existent font",
+ tex_template=TexTemplate(preamble=failing_preamble),
+ )
+
+ # validate useless TeX error not logged for user
+ assert "Context" not in str(capsys.readouterr().out)
+ # validate useful error message raised
+ # this won't happen if an error is raised while formatting the message
+ assert "See log output above or the log file" in str(err.value)
+
+
+def test_error_in_nested_context(capsys):
+ """Test that displayed error context is not excessively large"""
+ invalid_tex = r"""
+ \begin{align}
+ \begin{tabular}{ c }
+ no need to display \\
+ this correct text \\
+ \end{tabular}
+ \notacontrolsequence
+ \end{align}
+ """
+
+ with pytest.raises(ValueError) as err:
+ Tex(invalid_tex)
+
+ stdout = str(capsys.readouterr().out)
+ # validate useless context is not included
+ assert r"\begin{frame}" not in stdout