2 Implement latex directive.
11 from docutils
import nodes
12 from docutils
.parsers
.rst
.directives
import register_directive
, flag
13 from docutils
.parsers
.rst
.roles
import register_canonical_role
17 """ Process `tex` and produce image nodes. """
18 image_names
= latex_snippet_to_png(tex
)
22 for pageno
, name
in enumerate(image_names
):
24 the_nodes
.append(nodes
.image(uri
=name
, alt
=alt
))
30 def latex_directive(name
, arguments
, options
, content
, lineno
,
31 content_offset
, block_text
, state
, state_machine
):
32 """ Latex directive. """
33 tex
= '\n'.join(content
)
35 return latex_math(tex
)
37 latex_directive
.content
= True
40 def latex_role(role
, rawtext
, text
, lineno
, inliner
,
41 options
={}, content
=[]):
46 return latex_math(tex
), []
49 register_directive('latex', latex_directive
)
50 register_canonical_role('latex', latex_role
)
54 def call_command_in_dir(app
, args
, targetdir
):
61 p
= subprocess
.Popen(app
+ ' ' + ' '.join(args
), shell
=True)
62 sts
= os
.waitpid(p
.pid
, 0)
64 # FIXME -- should we raise an exception of status is non-zero?
67 # Restore working directory
71 \documentclass[12pt]{article}
79 MAX_RUN_TIME
= 5 # seconds
80 latex_name_template
= 'latex2png_%s'
83 latex_args
= ("--interaction=nonstopmode", "%s.tex")
84 dvipng_args
= ("-bgTransparent", "-Ttight", "--noghostscript", "-l%s" % max_pages
, "%s.dvi")
86 def latex_snippet_to_png(inputtex
, prologue
=''):
87 """ Convert a latex snippet into a png. """
89 tex
= latex_template
% { 'raw': inputtex
, 'prologue': prologue
}
90 namebase
= latex_name_template
% sha
.new(tex
).hexdigest()
91 dst
= namebase
+ '%d.png'
93 tmpdir
= tempfile
.mkdtemp()
95 data
= open("%s/%s.tex" % (tmpdir
, namebase
), "w")
98 args
= list(latex_args
)
99 args
[-1] = args
[-1] % namebase
100 res
= call_command_in_dir(latex
, args
, tmpdir
)
102 # FIXME need to return some sort of error
104 args
= list(dvipng_args
)
105 args
[-1] = args
[-1] % namebase
106 res
= call_command_in_dir(dvipng
, args
, tmpdir
)
108 # FIXME need to return some sort of error
113 while os
.access("%s/%s%d.png" % (tmpdir
, namebase
, page
), os
.R_OK
):
114 pagename
= dst
% page
115 shutil
.copyfile("%s/%s%d.png" % (tmpdir
, namebase
, page
), pagename
)
117 pagenames
.append(pagename
)
119 # FIXME do some tidy up here