|
37 | 37 | _log = logging.getLogger(__name__) |
38 | 38 |
|
39 | 39 |
|
| 40 | +def _usepackage_if_not_loaded(package, *, option=None): |
| 41 | + """ |
| 42 | + Output LaTeX code that loads a package (possibly with an option) if it |
| 43 | + hasn't been loaded yet. |
| 44 | +
|
| 45 | + LaTeX cannot load twice a package with different options, so this helper |
| 46 | + can be used to protect against users loading arbitrary packages/options in |
| 47 | + their custom preamble. |
| 48 | + """ |
| 49 | + option = f"[{option}]" if option is not None else "" |
| 50 | + return ( |
| 51 | + r"\makeatletter" |
| 52 | + r"\@ifpackageloaded{%(package)s}{}{\usepackage%(option)s{%(package)s}}" |
| 53 | + r"\makeatother" |
| 54 | + ) % {"package": package, "option": option} |
| 55 | + |
| 56 | + |
40 | 57 | class TexManager: |
41 | 58 | """ |
42 | 59 | Convert strings to dvi files using TeX, caching the results to a directory. |
@@ -176,16 +193,10 @@ def _get_preamble(self): |
176 | 193 | self.get_custom_preamble(), |
177 | 194 | # Use `underscore` package to take care of underscores in text |
178 | 195 | # The [strings] option allows to use underscores in file names |
179 | | - r"\makeatletter" |
180 | | - r"\@ifpackageloaded{underscore}{}" |
181 | | - r"{\usepackage[strings]{underscore}}" |
182 | | - r"\makeatother", |
183 | | - # textcomp is loaded last (if not already loaded by the custom |
184 | | - # preamble) in order not to clash with custom packages (e.g. |
185 | | - # newtxtext) which load it with different options. |
186 | | - r"\makeatletter" |
187 | | - r"\@ifpackageloaded{textcomp}{}{\usepackage{textcomp}}" |
188 | | - r"\makeatother", |
| 196 | + _usepackage_if_not_loaded("underscore", option="strings"), |
| 197 | + # Custom packages (e.g. newtxtext) may already have loaded textcomp |
| 198 | + # with different options. |
| 199 | + _usepackage_if_not_loaded("textcomp"), |
189 | 200 | ]) |
190 | 201 |
|
191 | 202 | def make_tex(self, tex, fontsize): |
|
0 commit comments