-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Description
When writing a Sphinx extension or, even when using native Sphinx directives, some specific packages or commands must be declared ahead, before the \begin{document}
. From my knowledge, it is currently impossible to dynamically add LaTeX code into the header from an extension or a directive.
A usecase is for exemple the hlist
refactoring #8072. This proposal would use a new LaTeX environment \hlist
that relies on several packages (multicol
, regexpatch
...). IMHO adding them directly in sphinx.sty
isn't a good solution because you could add some unused packages if the user doesn't use any hlist
in its documentation. The same would apply for many other case.
So I propose a way for extensions or even Sphinx directives to dynamically include some LaTeX code based on the usage.
My current way of doing it is the following:
latex_preamble = r"""
%% BEGIN injection for extension <% extension_name %>
\newenvironment{foobar}
<% somevalue %>
...
%% END injection for extension <% extension_name %>
"""
def inject_latex_header(app, context):
render = LaTeXRenderer()
context['preamble'] += render.render_string(latex_preamble, extension_context)
def inject_headers(app, doctree, fromdocname):
if doctree.traverse(foobar) and hasattr(app.builder, 'context'):
inject_latex_header(app, app.builder.context)
def setup(app):
...
app.connect('doctree-resolved', inject_headers)
...
While this snippet works, I would prefer having a more convenient way of doing it with some guards that could perform some checks automatically. We could imagine a method such as:
app.add_latex_header(latex_code, context)
I am not sure though when this should be done. After the doctree
is resolved?