From eac142f8b894d3af34e73752ecc9cba3e31a3d76 Mon Sep 17 00:00:00 2001 From: Hong Xu Date: Sat, 19 Dec 2015 19:24:16 -0800 Subject: [PATCH] LaTeX: Support math in section titles Fix #1480 --- sphinx/ext/mathbase.py | 18 +++++++++++++++++- tests/root/math.txt | 4 ++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/sphinx/ext/mathbase.py b/sphinx/ext/mathbase.py index 1c5de3cd7..5cd157275 100644 --- a/sphinx/ext/mathbase.py +++ b/sphinx/ext/mathbase.py @@ -56,6 +56,17 @@ def eq_role(role, rawtext, text, lineno, inliner, options={}, content=[]): return [node], [] +def is_in_section_title(node): + """Determine whether the node is in a section title""" + from sphinx.util.nodes import traverse_parent + + for ancestor in traverse_parent(node): + if isinstance(ancestor, nodes.title) and \ + isinstance(ancestor.parent, nodes.section): + return True + return False + + class MathDirective(Directive): has_content = True @@ -91,7 +102,12 @@ class MathDirective(Directive): def latex_visit_math(self, node): - self.body.append('\\(' + node['latex'] + '\\)') + if is_in_section_title(node): + protect = r'\protect' + else: + protect = '' + equation = protect + r'\(' + node['latex'] + protect + r'\)' + self.body.append(equation) raise nodes.SkipNode diff --git a/tests/root/math.txt b/tests/root/math.txt index 36b244943..b252353c7 100644 --- a/tests/root/math.txt +++ b/tests/root/math.txt @@ -1,5 +1,5 @@ -Test math extensions -==================== +Test math extensions :math:`E = m c^2` +====================================== This is inline math: :math:`a^2 + b^2 = c^2`.