root / tools / trunk / LatexEquationMacro / LatexEquation.py

Revision 53, 2.5 kB (checked in by phil, 15 months ago)

Initial import of LatexEquation as a trac plugin

Line 
1"""LatexEquation Macro."""
2import md5
3import os
4import tempfile
5from trac.wiki.macros import WikiMacroBase
6
7# Include your favourite LaTeX preamble
8tex_preamble = r'''
9\documentclass{article}
10\usepackage{amsmath}
11\usepackage{amsthm}
12\usepackage{amssymb}
13\pagestyle{empty}
14\begin{document}
15\begin{equation*}
16'''
17
18class LatexEquationMacro(WikiMacroBase):
19    """Simple LatexEquation macro.
20
21    Can be called with either `[[LatexEquation(E=Mc^x)]]` or
22    {{{
23    {{{
24    #!LatexEquation
25    E=Mc^2
26    }}}
27    }}}
28    This Macro:
29
30     * Uses latex and dvipng executables to do it's work
31     * Uses the  the `\\begin{equation*}` latex environment
32     * Caches the images in the `images/latex` subdir in the trac environment
33   
34    """
35
36    def expand_macro(self, formatter, name, text):
37        """Return some output that will be displayed in the Wiki content.
38
39        `name` is the actual name of the macro (no surprise, here it'll be
40        `'LatexEquation'`),
41        `text` is the text enclosed in parenthesis at the call of the macro.
42        """
43        md5sum = md5.new(text).hexdigest()
44        images_url = '../chrome/site/images/latex'
45        images_folder = os.path.join(formatter.env.get_htdocs_dir(),"images")
46        if not os.path.exists(images_folder):
47            os.mkdir(images_folder)
48        images_folder = os.path.join(images_folder, "latex")
49        if not os.path.exists(images_folder):
50            os.mkdir(images_folder)
51
52        if not os.access('%s/%s.png' % (images_folder, md5sum), os.F_OK):
53            cwd = os.getcwd()
54            os.chdir("/tmp")
55            fd, texfn = tempfile.mkstemp(suffix='.tex', prefix='eq')
56            f = os.fdopen(fd, 'w+')
57            f.write(tex_preamble)
58            f.write(text)
59            f.write(' \end{equation*}\end{document}')
60            f.close()
61
62            # compile LaTeX document. A DVI file is created
63            ret = os.system('latex \\\\nonstopmode\\\\input{%s} >/dev/null 2>/dev/null' % texfn)
64            tex_base = os.path.basename(texfn.replace('.tex', ''))
65            tex_path = os.path.dirname(texfn)
66            cmd = "dvipng -T tight -x 1200 -z 6 -bg Transparent " \
67                     + "-o %s/%s.png %s 2>/dev/null 1>/dev/null" \
68                     % (images_folder, md5sum, tex_base)
69            ret = os.system(cmd)
70            # lets clean up the crud a little
71            ret = os.system('rm %s.*'%(tex_base,))
72            os.chdir(cwd)
73        return '<img src="%s/%s.png" alt="%s" />' % (images_url, md5sum,text)
Note: See TracBrowser for help on using the browser.