801c21339da0c18964ee99b9e0d764fad8e6da35
[librarian.git] / src / librarian / embeds / mathml.py
1 # -*- coding: utf-8 -*-
2 from __future__ import unicode_literals
3
4 from lxml import etree
5 import six
6 from librarian import get_resource
7 from . import TreeEmbed, create_embed, downgrades_to
8
9
10 class MathML(TreeEmbed):
11     @downgrades_to('application/x-latex')
12     def to_latex(self):
13         """
14         >>> print(MathML(etree.fromstring(
15                 '<mat>a &lt; b</mat>'
16             )).to_latex().data.strip())
17         a < b
18
19         >>> print(MathML(etree.fromstring(
20                 '<mat>&lt; &amp; &amp;lt; &#65;</mat>'
21             )).to_latex().data.strip())
22         < & &lt; A
23
24         """
25         xslt = etree.parse(get_resource('res/embeds/mathml/mathml2latex.xslt'))
26         output = self.tree.xslt(xslt)
27         text = six.text_type(output)
28         # Workaround for entities being preserved in output.
29         # But there should be a better way.
30         text = text.replace('&lt;', '<').replace('&amp;', '&')
31         return create_embed('application/x-latex', data=text)