| 1 |
# $Id: __init__.py 10331 2026-05-08 14:57:28Z milde $ |
| 2 |
# Author: Engelbert Gruber, Günter Milde |
| 3 |
# Maintainer: [email protected] |
| 4 |
# Copyright: This module has been placed in the public domain. |
| 5 |
|
| 6 |
"""LaTeX2e document tree Writer.""" |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
__docformat__ = 'reStructuredText' |
| 11 |
|
| 12 |
# code contributions from several people included, thanks to all. |
| 13 |
# some named: David Abrahams, Julien Letessier, Lele Gaifax, and others. |
| 14 |
# |
| 15 |
# convention deactivate code by two # i.e. ##. |
| 16 |
|
| 17 |
import re |
| 18 |
import string |
| 19 |
import warnings |
| 20 |
from pathlib import Path |
| 21 |
|
| 22 |
from docutils import frontend, nodes, languages, writers, utils |
| 23 |
from docutils.transforms import references, writer_aux |
| 24 |
from docutils.utils._roman_numerals import RomanNumeral |
| 25 |
from docutils.utils.math import pick_math_environment, unichar2tex |
| 26 |
|
| 27 |
LATEX_WRITER_DIR = Path(__file__).parent |
| 28 |
|
| 29 |
|
| 30 |
class Writer(writers.Writer): |
| 31 |
|
| 32 |
supported = ('latex', 'latex2e') |
| 33 |
"""Formats this writer supports.""" |
| 34 |
|
| 35 |
default_template = 'default.tex' |
| 36 |
default_template_path = LATEX_WRITER_DIR |
| 37 |
default_preamble = ('% PDF Standard Fonts\n' |
| 38 |
'\\usepackage{mathptmx} % Times\n' |
| 39 |
'\\usepackage[scaled=.90]{helvet}\n' |
| 40 |
'\\usepackage{courier}') |
| 41 |
table_style_values = [ # TODO: align-left, align-center, align-right, ?? |
| 42 |
'booktabs', 'borderless', 'colwidths-auto', |
| 43 |
'nolines', 'standard'] |
| 44 |
|
| 45 |
settings_spec = ( |
| 46 |
'LaTeX-Specific Options', |
| 47 |
None, |
| 48 |
(('Specify LaTeX documentclass. Default: "article".', |
| 49 |
['--documentclass'], |
| 50 |
{'metavar': '<documentclass>', 'default': 'article'}), |
| 51 |
('Specify document options. Multiple options can be given, ' |
| 52 |
'separated by commas. Default: "a4paper".', |
| 53 |
['--documentoptions'], |
| 54 |
{'metavar': '<options>', 'default': 'a4paper'}), |
| 55 |
('Format for footnote references: one of "superscript" or ' |
| 56 |
'"brackets". Default: "superscript".', |
| 57 |
['--footnote-references'], |
| 58 |
{'choices': ['superscript', 'brackets'], 'default': 'superscript', |
| 59 |
'metavar': '<format>', |
| 60 |
'overrides': 'trim_footnote_reference_space'}), |
| 61 |
('Use \\cite command for citations. (future default)', |
| 62 |
['--use-latex-citations'], |
| 63 |
{'default': None, 'action': 'store_true', |
| 64 |
'validator': frontend.validate_boolean}), |
| 65 |
('Use figure floats for citations ' |
| 66 |
'(might get mixed with real figures). (provisional default)', |
| 67 |
['--figure-citations'], |
| 68 |
{'dest': 'use_latex_citations', 'action': 'store_false', |
| 69 |
'validator': frontend.validate_boolean}), |
| 70 |
('Format for block quote attributions: one of "dash" (em-dash ' |
| 71 |
'prefix), "parentheses"/"parens", or "none". Default: "dash".', |
| 72 |
['--attribution'], |
| 73 |
{'choices': ['dash', 'parentheses', 'parens', 'none'], |
| 74 |
'default': 'dash', 'metavar': '<format>'}), |
| 75 |
('Specify LaTeX packages/stylesheets. ' |
| 76 |
'A style is referenced with "\\usepackage" if extension is ' |
| 77 |
'".sty" or omitted and with "\\input" else. ' |
| 78 |
' Overrides previous --stylesheet and --stylesheet-path settings.', |
| 79 |
['--stylesheet'], |
| 80 |
{'default': '', 'metavar': '<file[,file,...]>', |
| 81 |
'overrides': 'stylesheet_path', |
| 82 |
'validator': frontend.validate_comma_separated_list}), |
| 83 |
('Comma separated list of LaTeX packages/stylesheets. ' |
| 84 |
'Relative paths are expanded if a matching file is found in ' |
| 85 |
'the --stylesheet-dirs. With --link-stylesheet, ' |
| 86 |
'the path is rewritten relative to the output *.tex file. ', |
| 87 |
['--stylesheet-path'], |
| 88 |
{'metavar': '<file[,file,...]>', 'overrides': 'stylesheet', |
| 89 |
'validator': frontend.validate_comma_separated_list}), |
| 90 |
('Link to the stylesheet(s) in the output file. (default)', |
| 91 |
['--link-stylesheet'], |
| 92 |
{'dest': 'embed_stylesheet', 'action': 'store_false'}), |
| 93 |
('Embed the stylesheet(s) in the output file. ' |
| 94 |
'Stylesheets must be accessible during processing. ', |
| 95 |
['--embed-stylesheet'], |
| 96 |
{'default': False, 'action': 'store_true', |
| 97 |
'validator': frontend.validate_boolean}), |
| 98 |
('Comma-separated list of directories where stylesheets are found. ' |
| 99 |
'Used by --stylesheet-path when expanding relative path arguments. ' |
| 100 |
'Default: ".".', |
| 101 |
['--stylesheet-dirs'], |
| 102 |
{'metavar': '<dir[,dir,...]>', |
| 103 |
'validator': frontend.validate_comma_separated_list, |
| 104 |
'default': ['.']}), |
| 105 |
('Customization by LaTeX code in the preamble. ' |
| 106 |
'Default: select PDF standard fonts (Times, Helvetica, Courier).', |
| 107 |
['--latex-preamble'], |
| 108 |
{'metavar': '<preamble>', 'default': default_preamble}), |
| 109 |
('Specify the template file. Default: "%s".' % default_template, |
| 110 |
['--template'], |
| 111 |
{'default': default_template, 'metavar': '<file>'}), |
| 112 |
('Table of contents by LaTeX. (default)', |
| 113 |
['--use-latex-toc'], |
| 114 |
{'default': True, 'action': 'store_true', |
| 115 |
'validator': frontend.validate_boolean}), |
| 116 |
('Table of contents by Docutils (without page numbers).', |
| 117 |
['--use-docutils-toc'], |
| 118 |
{'dest': 'use_latex_toc', 'action': 'store_false', |
| 119 |
'validator': frontend.validate_boolean}), |
| 120 |
('Add parts on top of the section hierarchy.', |
| 121 |
['--use-part-section'], |
| 122 |
{'default': False, 'action': 'store_true', |
| 123 |
'validator': frontend.validate_boolean}), |
| 124 |
('Attach author and date to the document info table. (default)', |
| 125 |
['--use-docutils-docinfo'], |
| 126 |
{'dest': 'use_latex_docinfo', 'action': 'store_false', |
| 127 |
'validator': frontend.validate_boolean}), |
| 128 |
('Attach author and date to the document title.', |
| 129 |
['--use-latex-docinfo'], |
| 130 |
{'default': False, 'action': 'store_true', |
| 131 |
'validator': frontend.validate_boolean}), |
| 132 |
("Typeset abstract as topic. (default)", |
| 133 |
['--topic-abstract'], |
| 134 |
{'dest': 'use_latex_abstract', 'action': 'store_false', |
| 135 |
'validator': frontend.validate_boolean}), |
| 136 |
("Use LaTeX abstract environment for the document's abstract.", |
| 137 |
['--use-latex-abstract'], |
| 138 |
{'default': False, 'action': 'store_true', |
| 139 |
'validator': frontend.validate_boolean}), |
| 140 |
('Color of any hyperlinks embedded in text. ' |
| 141 |
'Default: "blue" (use "false" to disable).', |
| 142 |
['--hyperlink-color'], |
| 143 |
{'metavar': '<color>', 'default': 'blue'}), |
| 144 |
('Additional options to the "hyperref" package.', |
| 145 |
['--hyperref-options'], |
| 146 |
{'metavar': '<options>', 'default': ''}), |
| 147 |
('Enable compound enumerators for nested enumerated lists ' |
| 148 |
'(e.g. "1.2.a.ii").', |
| 149 |
['--compound-enumerators'], |
| 150 |
{'default': False, 'action': 'store_true', |
| 151 |
'validator': frontend.validate_boolean}), |
| 152 |
('Disable compound enumerators for nested enumerated lists. ' |
| 153 |
'(default)', |
| 154 |
['--no-compound-enumerators'], |
| 155 |
{'action': 'store_false', 'dest': 'compound_enumerators'}), |
| 156 |
('Enable section ("." subsection ...) prefixes for compound ' |
| 157 |
'enumerators. This has no effect without --compound-enumerators.', |
| 158 |
['--section-prefix-for-enumerators'], |
| 159 |
{'default': None, 'action': 'store_true', |
| 160 |
'validator': frontend.validate_boolean}), |
| 161 |
('Disable section prefixes for compound enumerators. (default)', |
| 162 |
['--no-section-prefix-for-enumerators'], |
| 163 |
{'action': 'store_false', 'dest': 'section_prefix_for_enumerators'}), |
| 164 |
('Set the separator between section number and enumerator ' |
| 165 |
'for compound enumerated lists. Default: "-".', |
| 166 |
['--section-enumerator-separator'], |
| 167 |
{'default': '-', 'metavar': '<char>'}), |
| 168 |
('When possible, use the specified environment for literal-blocks. ' |
| 169 |
'Default: "" (fall back to "alltt").', |
| 170 |
['--literal-block-env'], |
| 171 |
{'metavar': '<environment>', 'default': ''}), |
| 172 |
(frontend.SUPPRESS_HELP, # deprecated legacy option |
| 173 |
['--use-verbatim-when-possible'], |
| 174 |
{'action': 'store_true', |
| 175 |
'validator': frontend.validate_boolean}), |
| 176 |
('Table style. "standard" with horizontal and vertical lines, ' |
| 177 |
'"booktabs" (LaTeX booktabs style) only horizontal lines ' |
| 178 |
'above and below the table and below the header, or "borderless". ' |
| 179 |
'Default: "standard"', |
| 180 |
['--table-style'], |
| 181 |
{'default': ['standard'], |
| 182 |
'metavar': '<format>', |
| 183 |
'action': 'append', |
| 184 |
'validator': frontend.validate_comma_separated_list, |
| 185 |
'choices': table_style_values}), |
| 186 |
('LaTeX graphicx package option. Default: "".', |
| 187 |
['--graphicx-option'], |
| 188 |
{'metavar': '<option>', 'default': ''}), |
| 189 |
('LaTeX font encoding. ' |
| 190 |
'Possible values are "", "T1" (default), "OT1", "LGR,T1" or ' |
| 191 |
'any other combination of options to the `fontenc` package. ', |
| 192 |
['--font-encoding'], |
| 193 |
{'metavar': '<encoding>', 'default': 'T1'}), |
| 194 |
('Per default the latex-writer puts the reference title into ' |
| 195 |
'hyperreferences. Specify "ref" or "pageref" to get the section ' |
| 196 |
'number or the page number.', |
| 197 |
['--reference-label'], |
| 198 |
{'metavar': '<command name>', 'default': ''}), |
| 199 |
('Specify style and database(s) for bibtex, for example ' |
| 200 |
'"--use-bibtex=unsrt,mydb1,mydb2". Provisional!', |
| 201 |
['--use-bibtex'], |
| 202 |
{'default': '', |
| 203 |
'metavar': '<style,bibfile[,bibfile,...]>', |
| 204 |
'validator': frontend.validate_comma_separated_list}), |
| 205 |
('Use legacy functions with class value list for ' |
| 206 |
'\\DUtitle and \\DUadmonition.', |
| 207 |
['--legacy-class-functions'], |
| 208 |
{'default': False, |
| 209 |
'action': 'store_true', |
| 210 |
'validator': frontend.validate_boolean}), |
| 211 |
('Use \\DUrole and "DUclass" wrappers for class values. ' |
| 212 |
'Place admonition content in an environment. (default)', |
| 213 |
['--new-class-functions'], |
| 214 |
{'dest': 'legacy_class_functions', |
| 215 |
'action': 'store_false', |
| 216 |
'validator': frontend.validate_boolean}), |
| 217 |
('Use legacy algorithm to determine table column widths. ' |
| 218 |
'(provisional default)', |
| 219 |
['--legacy-column-widths'], |
| 220 |
{'default': None, |
| 221 |
'action': 'store_true', |
| 222 |
'validator': frontend.validate_boolean}), |
| 223 |
('Use new algorithm to determine table column widths. ' |
| 224 |
'(future default)', |
| 225 |
['--new-column-widths'], |
| 226 |
{'dest': 'legacy_column_widths', |
| 227 |
'action': 'store_false', |
| 228 |
'validator': frontend.validate_boolean}), |
| 229 |
('Footnotes with numbers/symbols by Docutils. (default)', |
| 230 |
['--docutils-footnotes'], |
| 231 |
{'dest': 'latex_footnotes', |
| 232 |
'action': 'store_false', |
| 233 |
'validator': frontend.validate_boolean}), |
| 234 |
('Footnotes with numbers by LaTeX.', |
| 235 |
['--latex-footnotes'], |
| 236 |
{'action': 'store_true', |
| 237 |
'default': False, |
| 238 |
'validator': frontend.validate_boolean}), |
| 239 |
), |
| 240 |
) |
| 241 |
|
| 242 |
relative_path_settings = ('template',) |
| 243 |
settings_defaults = {} |
| 244 |
config_section = 'latex2e writer' |
| 245 |
config_section_dependencies = ('writers', 'latex writers') |
| 246 |
|
| 247 |
head_parts = ('head_prefix', 'requirements', 'latex_preamble', |
| 248 |
'stylesheet', 'fallbacks', 'pdfsetup', 'titledata') |
| 249 |
visitor_attributes = head_parts + ('title', 'subtitle', |
| 250 |
'body_pre_docinfo', 'docinfo', |
| 251 |
'dedication', 'abstract', 'body') |
| 252 |
|
| 253 |
output = None |
| 254 |
"""Final translated form of `document`.""" |
| 255 |
|
| 256 |
def __init__(self) -> None: |
| 257 |
writers.Writer.__init__(self) |
| 258 |
self.translator_class = LaTeXTranslator |
| 259 |
|
| 260 |
def get_transforms(self): |
| 261 |
# Override parent method to add latex-specific transforms |
| 262 |
return super().get_transforms() + [ |
| 263 |
# Convert specific admonitions to generic one |
| 264 |
writer_aux.Admonitions, |
| 265 |
references.CitationReferences, |
| 266 |
] |
| 267 |
|
| 268 |
def translate(self) -> None: |
| 269 |
visitor = self.translator_class(self.document) |
| 270 |
self.document.walkabout(visitor) |
| 271 |
# copy parts |
| 272 |
for part in self.visitor_attributes: |
| 273 |
setattr(self, part, getattr(visitor, part)) |
| 274 |
# fill template |
| 275 |
self.assemble_parts() # create dictionary of parts |
| 276 |
self.output = string.Template(self.parts['template'] |
| 277 |
).substitute(self.parts) |
| 278 |
|
| 279 |
def assemble_parts(self) -> None: |
| 280 |
"""Assemble the `self.parts` dictionary of output fragments.""" |
| 281 |
super().assemble_parts() |
| 282 |
for part in self.visitor_attributes: |
| 283 |
if part in self.parts: |
| 284 |
continue # make the function idempotent |
| 285 |
lines = getattr(self, part) |
| 286 |
if part in self.head_parts: |
| 287 |
if lines: |
| 288 |
lines.append('') # to get a trailing newline |
| 289 |
self.parts[part] = '\n'.join(lines) |
| 290 |
else: |
| 291 |
# body contains inline elements, so join without newline |
| 292 |
self.parts[part] = ''.join(lines) |
| 293 |
# get template string from file |
| 294 |
templatepath = Path(self.document.settings.template) |
| 295 |
if not templatepath.exists(): |
| 296 |
templatepath = self.default_template_path / templatepath.name |
| 297 |
self.parts['template'] = templatepath.read_text(encoding='utf-8') |
| 298 |
|
| 299 |
|
| 300 |
class Babel: |
| 301 |
"""Language specifics for LaTeX.""" |
| 302 |
|
| 303 |
# TeX (babel) language names: |
| 304 |
# ! not all of these are supported by Docutils! |
| 305 |
# |
| 306 |
# based on LyX' languages file with adaptions to `BCP 47`_ |
| 307 |
# (https://www.rfc-editor.org/rfc/bcp/bcp47.txt) and |
| 308 |
# http://www.tug.org/TUGboat/Articles/tb29-3/tb93miklavec.pdf |
| 309 |
# * the key without subtags is the default |
| 310 |
# * case is ignored |
| 311 |
# cf. https://docutils.sourceforge.io/docs/howto/i18n.html |
| 312 |
# https://www.w3.org/International/articles/language-tags/ |
| 313 |
# and http://www.iana.org/assignments/language-subtag-registry |
| 314 |
language_codes = { |
| 315 |
# code TeX/Babel-name comment |
| 316 |
'af': 'afrikaans', |
| 317 |
'ar': 'arabic', |
| 318 |
# 'be': 'belarusian', |
| 319 |
'bg': 'bulgarian', |
| 320 |
'br': 'breton', |
| 321 |
'ca': 'catalan', |
| 322 |
# 'cop': 'coptic', |
| 323 |
'cs': 'czech', |
| 324 |
'cy': 'welsh', |
| 325 |
'da': 'danish', |
| 326 |
'de': 'ngerman', # new spelling (de_1996) |
| 327 |
'de-1901': 'german', # old spelling |
| 328 |
'de-AT': 'naustrian', |
| 329 |
'de-AT-1901': 'austrian', |
| 330 |
'dsb': 'lowersorbian', |
| 331 |
'el': 'greek', # monotonic (el-monoton) |
| 332 |
'el-polyton': 'polutonikogreek', |
| 333 |
'en': 'english', # TeX' default language |
| 334 |
'en-AU': 'australian', |
| 335 |
'en-CA': 'canadian', |
| 336 |
'en-GB': 'british', |
| 337 |
'en-NZ': 'newzealand', |
| 338 |
'en-US': 'american', |
| 339 |
'eo': 'esperanto', |
| 340 |
'es': 'spanish', |
| 341 |
'et': 'estonian', |
| 342 |
'eu': 'basque', |
| 343 |
# 'fa': 'farsi', |
| 344 |
'fi': 'finnish', |
| 345 |
'fr': 'french', |
| 346 |
'fr-CA': 'canadien', |
| 347 |
'ga': 'irish', # Irish Gaelic |
| 348 |
# 'grc': # Ancient Greek |
| 349 |
'grc-ibycus': 'ibycus', # Ibycus encoding |
| 350 |
'gl': 'galician', |
| 351 |
'he': 'hebrew', |
| 352 |
'hr': 'croatian', |
| 353 |
'hsb': 'uppersorbian', |
| 354 |
'hu': 'magyar', |
| 355 |
'ia': 'interlingua', |
| 356 |
'id': 'bahasai', # Bahasa (Indonesian) |
| 357 |
'is': 'icelandic', |
| 358 |
'it': 'italian', |
| 359 |
'ja': 'japanese', |
| 360 |
'kk': 'kazakh', |
| 361 |
'la': 'latin', |
| 362 |
'lt': 'lithuanian', |
| 363 |
'lv': 'latvian', |
| 364 |
'mn': 'mongolian', # Mongolian, Cyrillic (mn-cyrl) |
| 365 |
'ms': 'bahasam', # Bahasa (Malay) |
| 366 |
'nb': 'norsk', # Norwegian Bokmal |
| 367 |
'nl': 'dutch', |
| 368 |
'nn': 'nynorsk', # Norwegian Nynorsk |
| 369 |
'no': 'norsk', # Norwegian (Bokmal) |
| 370 |
'pl': 'polish', |
| 371 |
'pt': 'portuges', |
| 372 |
'pt-BR': 'brazil', |
| 373 |
'ro': 'romanian', |
| 374 |
'ru': 'russian', |
| 375 |
'se': 'samin', # North Sami |
| 376 |
'sh-Cyrl': 'serbianc', # Serbo-Croatian, Cyrillic |
| 377 |
'sh-Latn': 'serbian', # Serbo-Croatian, Latin (cf. 'hr') |
| 378 |
'sk': 'slovak', |
| 379 |
'sl': 'slovene', |
| 380 |
'sq': 'albanian', |
| 381 |
'sr': 'serbianc', # Serbian, Cyrillic (contributed) |
| 382 |
'sr-Latn': 'serbian', # Serbian, Latin script |
| 383 |
'sv': 'swedish', |
| 384 |
# 'th': 'thai', |
| 385 |
'tr': 'turkish', |
| 386 |
'uk': 'ukrainian', |
| 387 |
'vi': 'vietnam', |
| 388 |
# zh-Latn: Chinese Pinyin |
| 389 |
} |
| 390 |
# normalize (downcase) keys |
| 391 |
language_codes = {k.lower(): v for k, v in language_codes.items()} |
| 392 |
|
| 393 |
warn_msg = 'Language "%s" not supported by LaTeX (babel)' |
| 394 |
|
| 395 |
# "Active characters" are shortcuts that start a LaTeX macro and may need |
| 396 |
# escaping for literals use. Characters that prevent literal use (e.g. |
| 397 |
# starting accent macros like "a -> ä) will be deactivated if one of the |
| 398 |
# defining languages is used in the document. |
| 399 |
# Special cases: |
| 400 |
# ~ (tilde) -- used in estonian, basque, galician, and old versions of |
| 401 |
# spanish -- cannot be deactivated as it denotes a no-break space macro, |
| 402 |
# " (straight quote) -- used in albanian, austrian, basque |
| 403 |
# brazil, bulgarian, catalan, czech, danish, dutch, estonian, |
| 404 |
# finnish, galician, german, icelandic, italian, latin, naustrian, |
| 405 |
# ngerman, norsk, nynorsk, polish, portuges, russian, serbian, slovak, |
| 406 |
# slovene, spanish, swedish, ukrainian, and uppersorbian -- |
| 407 |
# is escaped as ``\textquotedbl``. |
| 408 |
active_chars = { |
| 409 |
# TeX/Babel-name: active characters to deactivate |
| 410 |
# 'breton': ':;!?' # ensure whitespace |
| 411 |
# 'esperanto': '^', |
| 412 |
# 'estonian': '~"`', |
| 413 |
# 'french': ':;!?' # ensure whitespace |
| 414 |
'galician': '.<>', # also '~"' |
| 415 |
# 'magyar': '`', # for special hyphenation cases |
| 416 |
'spanish': '.<>', # old versions also '~' |
| 417 |
# 'turkish': ':!=' # ensure whitespace |
| 418 |
} |
| 419 |
|
| 420 |
def __init__(self, language_code, reporter=None) -> None: |
| 421 |
self.reporter = reporter |
| 422 |
self.language = self.language_name(language_code) |
| 423 |
self.otherlanguages = {} |
| 424 |
|
| 425 |
def __call__(self): |
| 426 |
"""Return the babel call with correct options and settings""" |
| 427 |
languages = sorted(self.otherlanguages.keys()) |
| 428 |
if languages: |
| 429 |
languages.append(f'main={self.language or "english"}') |
| 430 |
else: |
| 431 |
languages.append(self.language or 'english') |
| 432 |
self.setup = [r'\usepackage[%s]{babel}' % ','.join(languages)] |
| 433 |
# Deactivate "active characters" |
| 434 |
shorthands = [] |
| 435 |
for c in ''.join(self.active_chars.get(lng, '') for lng in languages): |
| 436 |
if c not in shorthands: |
| 437 |
shorthands.append(c) |
| 438 |
if shorthands: |
| 439 |
self.setup.append(r'\AtBeginDocument{\shorthandoff{%s}}' |
| 440 |
% ''.join(shorthands)) |
| 441 |
# Including '~' in shorthandoff prevents its use as no-break space |
| 442 |
if 'galician' in languages: |
| 443 |
self.setup.append(r'\deactivatetilden % restore ~ in Galician') |
| 444 |
if 'estonian' in languages: |
| 445 |
self.setup.extend([r'\makeatletter', |
| 446 |
r' \addto\extrasestonian{\bbl@deactivate{~}}', |
| 447 |
r'\makeatother']) |
| 448 |
if 'basque' in languages: |
| 449 |
self.setup.extend([r'\makeatletter', |
| 450 |
r' \addto\extrasbasque{\bbl@deactivate{~}}', |
| 451 |
r'\makeatother']) |
| 452 |
if (languages[-1] == 'main=english' |
| 453 |
and 'french' in self.otherlanguages.keys()): |
| 454 |
self.setup += ['% Prevent side-effects if French hyphenation ' |
| 455 |
'patterns are not loaded:', |
| 456 |
r'\frenchbsetup{StandardLayout}', |
| 457 |
r'\AtBeginDocument{\selectlanguage{%s}' |
| 458 |
r'\noextrasfrench}' % self.language] |
| 459 |
return '\n'.join(self.setup) |
| 460 |
|
| 461 |
def language_name(self, language_code): |
| 462 |
"""Return TeX language name for `language_code`""" |
| 463 |
for tag in utils.normalize_language_tag(language_code): |
| 464 |
try: |
| 465 |
return self.language_codes[tag] |
| 466 |
except KeyError: |
| 467 |
pass |
| 468 |
if self.reporter is not None: |
| 469 |
self.reporter.warning(self.warn_msg % language_code) |
| 470 |
return '' |
| 471 |
|
| 472 |
def get_language(self): |
| 473 |
# Obsolete, kept for backwards compatibility with Sphinx |
| 474 |
return self.language |
| 475 |
|
| 476 |
|
| 477 |
# Building blocks for the latex preamble |
| 478 |
# -------------------------------------- |
| 479 |
|
| 480 |
class SortableDict(dict): # NoQA: FURB189 |
| 481 |
"""Dictionary with additional sorting methods |
| 482 |
|
| 483 |
Deprecated. Will be removed in Docutils 0.24. |
| 484 |
""" |
| 485 |
|
| 486 |
def __init__(self, *args, **kwargs): |
| 487 |
warnings.warn('`writers.latex2e.SortableDict` is obsolete' |
| 488 |
' and will be removed in Docutils 0.24.', |
| 489 |
DeprecationWarning, stacklevel=2) |
| 490 |
super().__init__(*args, **kwargs) |
| 491 |
|
| 492 |
def sortedkeys(self): |
| 493 |
"""Return sorted list of keys""" |
| 494 |
return sorted(self.keys()) |
| 495 |
|
| 496 |
def sortedvalues(self): |
| 497 |
"""Return list of values sorted by keys""" |
| 498 |
return [self[key] for key in self.sortedkeys()] |
| 499 |
|
| 500 |
|
| 501 |
# PreambleCmds |
| 502 |
# ````````````` |
| 503 |
# A container for LaTeX code snippets that can be |
| 504 |
# inserted into the preamble if required in the document. |
| 505 |
# |
| 506 |
# .. The package 'makecmds' would enable shorter definitions using the |
| 507 |
# \providelength and \provideenvironment commands. |
| 508 |
# However, it is pretty non-standard (texlive-latex-extra). |
| 509 |
|
| 510 |
class PreambleCmds: |
| 511 |
"""Building blocks for the latex preamble.""" |
| 512 |
|
| 513 |
|
| 514 |
# Requirements and Setup |
| 515 |
|
| 516 |
# Not in docutils.sty because of the overhead for every font change: |
| 517 |
PreambleCmds.ch = r""" |
| 518 |
\ifdefined\DUchdimen % lengh unit "ch": width of a zero char |
| 519 |
\else |
| 520 |
\newlength{\DUchdimen} |
| 521 |
\AtBeginDocument{\settowidth\DUchdimen{0}} % set after font setup, |
| 522 |
% update with font changes (requires LaTeX > 2021-06-01, see lthooks-doc.pdf) |
| 523 |
\AddToHook{cmd/selectfont/after}{\settowidth\DUchdimen{0}} |
| 524 |
\fi""" |
| 525 |
|
| 526 |
PreambleCmds.color = r"""\usepackage{color}""" |
| 527 |
|
| 528 |
PreambleCmds.float = r"""\usepackage{float} % extended float configuration |
| 529 |
\floatplacement{figure}{H} % place figures here definitely""" |
| 530 |
|
| 531 |
PreambleCmds.linking = r"""%% hyperlinks: |
| 532 |
\ifdefined\hypersetup |
| 533 |
\else |
| 534 |
\usepackage[%s]{hyperref} |
| 535 |
\usepackage{bookmark} |
| 536 |
\urlstyle{same} %% normal text font (alternatives: tt, rm, sf) |
| 537 |
\fi""" |
| 538 |
|
| 539 |
PreambleCmds.minitoc = r"""%% local table of contents |
| 540 |
\usepackage{minitoc}""" |
| 541 |
|
| 542 |
PreambleCmds.table = r"""\usepackage{longtable,ltcaption,array} |
| 543 |
\setlength{\extrarowheight}{2pt} |
| 544 |
\newlength{\DUtablewidth} % internal use in tables""" |
| 545 |
|
| 546 |
PreambleCmds.table_columnwidth = ( |
| 547 |
r'\newcommand{\DUcolumnwidth}[1]' |
| 548 |
r'{\dimexpr#1\DUtablewidth-2\tabcolsep\relax}') |
| 549 |
|
| 550 |
PreambleCmds.textcomp = r"""\usepackage{textcomp} % text symbol macros""" |
| 551 |
# TODO? Options [force,almostfull] prevent spurious error messages, |
| 552 |
# see de.comp.text.tex/2005-12/msg01855 |
| 553 |
|
| 554 |
# backwards compatibility definitions |
| 555 |
|
| 556 |
PreambleCmds.abstract_legacy = r""" |
| 557 |
% abstract title |
| 558 |
\providecommand*{\DUtitleabstract}[1]{\centerline{\textbf{#1}}}""" |
| 559 |
|
| 560 |
# see https://sourceforge.net/p/docutils/bugs/339/ |
| 561 |
PreambleCmds.admonition_legacy = r""" |
| 562 |
% admonition (specially marked topic) |
| 563 |
\providecommand{\DUadmonition}[2][class-arg]{% |
| 564 |
% try \DUadmonition#1{#2}: |
| 565 |
\ifcsname DUadmonition#1\endcsname% |
| 566 |
\csname DUadmonition#1\endcsname{#2}% |
| 567 |
\else |
| 568 |
\begin{center} |
| 569 |
\fbox{\parbox{0.9\linewidth}{#2}} |
| 570 |
\end{center} |
| 571 |
\fi |
| 572 |
}""" |
| 573 |
|
| 574 |
PreambleCmds.error_legacy = r""" |
| 575 |
% error admonition title |
| 576 |
\providecommand*{\DUtitleerror}[1]{\DUtitle{\color{red}#1}}""" |
| 577 |
|
| 578 |
PreambleCmds.title_legacy = r""" |
| 579 |
% title for topics, admonitions, unsupported section levels, and sidebar |
| 580 |
\providecommand*{\DUtitle}[2][class-arg]{% |
| 581 |
% call \DUtitle#1{#2} if it exists: |
| 582 |
\ifcsname DUtitle#1\endcsname% |
| 583 |
\csname DUtitle#1\endcsname{#2}% |
| 584 |
\else |
| 585 |
\smallskip\noindent\textbf{#2}\smallskip% |
| 586 |
\fi |
| 587 |
}""" |
| 588 |
|
| 589 |
PreambleCmds.toc_list = r""" |
| 590 |
\providecommand*{\DUCLASScontents}{% |
| 591 |
\renewenvironment{itemize}% |
| 592 |
{\begin{list}{}{\setlength{\partopsep}{0pt} |
| 593 |
\setlength{\parsep}{0pt}} |
| 594 |
}% |
| 595 |
{\end{list}}% |
| 596 |
}""" |
| 597 |
|
| 598 |
PreambleCmds.ttem = r""" |
| 599 |
% character width in monospaced font |
| 600 |
\newlength{\ttemwidth} |
| 601 |
\settowidth{\ttemwidth}{\ttfamily M}""" |
| 602 |
|
| 603 |
## PreambleCmds.caption = r"""% configure caption layout |
| 604 |
## \usepackage{caption} |
| 605 |
## \captionsetup{singlelinecheck=false}% no exceptions for one-liners""" |
| 606 |
|
| 607 |
|
| 608 |
# Definitions from docutils.sty:: |
| 609 |
|
| 610 |
def _read_block(fp): |
| 611 |
block = [next(fp)] # first line (empty) |
| 612 |
for line in fp: |
| 613 |
if not line.strip(): |
| 614 |
break |
| 615 |
block.append(line) |
| 616 |
return ''.join(block).rstrip() |
| 617 |
|
| 618 |
|
| 619 |
with open(LATEX_WRITER_DIR/'docutils.sty', encoding='utf-8') as fp: |
| 620 |
for line in fp: |
| 621 |
line = line.strip('% \n') |
| 622 |
if not line.endswith('::'): |
| 623 |
continue |
| 624 |
block_name = line.rstrip(':') |
| 625 |
if not block_name: |
| 626 |
continue |
| 627 |
definitions = _read_block(fp) # all lines up to the next empty one |
| 628 |
if block_name in ('color', 'float', 'table', 'textcomp'): |
| 629 |
definitions = definitions.strip() |
| 630 |
# print('Block: `%s`'% block_name) |
| 631 |
# print(definitions) |
| 632 |
setattr(PreambleCmds, block_name, definitions) |
| 633 |
|
| 634 |
|
| 635 |
# LaTeX encoding maps |
| 636 |
# ------------------- |
| 637 |
# :: |
| 638 |
|
| 639 |
class CharMaps: |
| 640 |
"""LaTeX representations for active and Unicode characters.""" |
| 641 |
|
| 642 |
# characters that need escaping even in `alltt` environments: |
| 643 |
alltt = { |
| 644 |
ord('\\'): '\\textbackslash{}', |
| 645 |
ord('{'): '\\{', |
| 646 |
ord('}'): '\\}', |
| 647 |
} |
| 648 |
# characters that normally need escaping: |
| 649 |
special = { |
| 650 |
ord('#'): '\\#', |
| 651 |
ord('$'): '\\$', |
| 652 |
ord('%'): '\\%', |
| 653 |
ord('&'): '\\&', |
| 654 |
ord('~'): '\\textasciitilde{}', |
| 655 |
ord('_'): '\\_', |
| 656 |
ord('^'): '\\textasciicircum{}', |
| 657 |
# straight double quotes are 'active' in many languages |
| 658 |
ord('"'): '\\textquotedbl{}', |
| 659 |
# Square brackets are ordinary chars and cannot be escaped with '\', |
| 660 |
# so we put them in a group '{[}'. (Alternative: ensure that all |
| 661 |
# macros with optional arguments are terminated with {} and text |
| 662 |
# inside any optional argument is put in a group ``[{text}]``). |
| 663 |
# Commands with optional args inside an optional arg must be put in a |
| 664 |
# group, e.g. ``\item[{\hyperref[label]{text}}]``. |
| 665 |
ord('['): '{[}', |
| 666 |
ord(']'): '{]}', |
| 667 |
# the soft hyphen is unknown in 8-bit text |
| 668 |
# and not properly handled by XeTeX |
| 669 |
0x00AD: '\\-', # SOFT HYPHEN |
| 670 |
} |
| 671 |
# Unicode chars that are not recognized by LaTeX's utf8 encoding |
| 672 |
unsupported_unicode = { |
| 673 |
# TODO: ensure white space also at the beginning of a line? |
| 674 |
# 0x00A0: '\\leavevmode\\nobreak\\vadjust{}~' |
| 675 |
0x2000: '\\enskip', # EN QUAD |
| 676 |
0x2001: '\\quad', # EM QUAD |
| 677 |
0x2002: '\\enskip', # EN SPACE |
| 678 |
0x2003: '\\quad', # EM SPACE |
| 679 |
0x2008: '\\,', # PUNCTUATION SPACE |
| 680 |
0x200b: '\\hspace{0pt}', # ZERO WIDTH SPACE |
| 681 |
0x202F: '\\,', # NARROW NO-BREAK SPACE |
| 682 |
# 0x02d8: '\\\u{ }', # BREVE |
| 683 |
0x2011: '\\hbox{-}', # NON-BREAKING HYPHEN |
| 684 |
0x212b: '\\AA', # ANGSTROM SIGN |
| 685 |
0x21d4: '\\ensuremath{\\Leftrightarrow}', # LEFT RIGHT DOUBLE ARROW |
| 686 |
0x2260: '\\ensuremath{\\neq}', # NOT EQUAL TO |
| 687 |
0x2261: '\\ensuremath{\\equiv}', # IDENTICAL TO |
| 688 |
0x2264: '\\ensuremath{\\le}', # LESS-THAN OR EQUAL TO |
| 689 |
0x2265: '\\ensuremath{\\ge}', # GREATER-THAN OR EQUAL TO |
| 690 |
# Docutils footnote symbols: |
| 691 |
0x2660: '\\ensuremath{\\spadesuit}', |
| 692 |
0x2663: '\\ensuremath{\\clubsuit}', |
| 693 |
0xfb00: 'ff', # LATIN SMALL LIGATURE FF |
| 694 |
0xfb01: 'fi', # LATIN SMALL LIGATURE FI |
| 695 |
0xfb02: 'fl', # LATIN SMALL LIGATURE FL |
| 696 |
0xfb03: 'ffi', # LATIN SMALL LIGATURE FFI |
| 697 |
0xfb04: 'ffl', # LATIN SMALL LIGATURE FFL |
| 698 |
} |
| 699 |
# Unicode chars that are recognized by LaTeX's utf8 encoding |
| 700 |
utf8_supported_unicode = { |
| 701 |
0x00A0: '~', # NO-BREAK SPACE |
| 702 |
0x00AB: '\\guillemotleft{}', # LEFT-POINTING DOUBLE ANGLE QUOTATION |
| 703 |
0x00bb: '\\guillemotright{}', # RIGHT-POINTING DOUBLE ANGLE QUOTATION |
| 704 |
0x200C: '\\textcompwordmark{}', # ZERO WIDTH NON-JOINER |
| 705 |
0x2013: '\\textendash{}', |
| 706 |
0x2014: '\\textemdash{}', |
| 707 |
0x2018: '\\textquoteleft{}', |
| 708 |
0x2019: '\\textquoteright{}', |
| 709 |
0x201A: '\\quotesinglbase{}', # SINGLE LOW-9 QUOTATION MARK |
| 710 |
0x201C: '\\textquotedblleft{}', |
| 711 |
0x201D: '\\textquotedblright{}', |
| 712 |
0x201E: '\\quotedblbase{}', # DOUBLE LOW-9 QUOTATION MARK |
| 713 |
0x2030: '\\textperthousand{}', # PER MILLE SIGN |
| 714 |
0x2031: '\\textpertenthousand{}', # PER TEN THOUSAND SIGN |
| 715 |
0x2039: '\\guilsinglleft{}', |
| 716 |
0x203A: '\\guilsinglright{}', |
| 717 |
0x2423: '\\textvisiblespace{}', # OPEN BOX |
| 718 |
0x2020: '\\dag{}', |
| 719 |
0x2021: '\\ddag{}', |
| 720 |
0x2026: '\\dots{}', |
| 721 |
0x2122: '\\texttrademark{}', |
| 722 |
} |
| 723 |
# recognized with 'utf8', if textcomp is loaded |
| 724 |
textcomp = { |
| 725 |
# Latin-1 Supplement |
| 726 |
0x00a2: '\\textcent{}', # ¢ CENT SIGN |
| 727 |
0x00a4: '\\textcurrency{}', # ¤ CURRENCY SYMBOL |
| 728 |
0x00a5: '\\textyen{}', # ¥ YEN SIGN |
| 729 |
0x00a6: '\\textbrokenbar{}', # ¦ BROKEN BAR |
| 730 |
0x00a7: '\\textsection{}', # § SECTION SIGN |
| 731 |
0x00a8: '\\textasciidieresis{}', # ¨ DIAERESIS |
| 732 |
0x00a9: '\\textcopyright{}', # © COPYRIGHT SIGN |
| 733 |
0x00aa: '\\textordfeminine{}', # ª FEMININE ORDINAL INDICATOR |
| 734 |
0x00ac: '\\textlnot{}', # ¬ NOT SIGN |
| 735 |
0x00ae: '\\textregistered{}', # ® REGISTERED SIGN |
| 736 |
0x00af: '\\textasciimacron{}', # ¯ MACRON |
| 737 |
0x00b0: '\\textdegree{}', # ° DEGREE SIGN |
| 738 |
0x00b1: '\\textpm{}', # ± PLUS-MINUS SIGN |
| 739 |
0x00b2: '\\texttwosuperior{}', # ² SUPERSCRIPT TWO |
| 740 |
0x00b3: '\\textthreesuperior{}', # ³ SUPERSCRIPT THREE |
| 741 |
0x00b4: '\\textasciiacute{}', # ´ ACUTE ACCENT |
| 742 |
0x00b5: '\\textmu{}', # µ MICRO SIGN |
| 743 |
0x00b6: '\\textparagraph{}', # ¶ PILCROW SIGN # != \textpilcrow |
| 744 |
0x00b9: '\\textonesuperior{}', # ¹ SUPERSCRIPT ONE |
| 745 |
0x00ba: '\\textordmasculine{}', # º MASCULINE ORDINAL INDICATOR |
| 746 |
0x00bc: '\\textonequarter{}', # 1/4 FRACTION |
| 747 |
0x00bd: '\\textonehalf{}', # 1/2 FRACTION |
| 748 |
0x00be: '\\textthreequarters{}', # 3/4 FRACTION |
| 749 |
0x00d7: '\\texttimes{}', # × MULTIPLICATION SIGN |
| 750 |
0x00f7: '\\textdiv{}', # ÷ DIVISION SIGN |
| 751 |
# others |
| 752 |
0x0192: '\\textflorin{}', # LATIN SMALL LETTER F WITH HOOK |
| 753 |
0x02b9: '\\textasciiacute{}', # MODIFIER LETTER PRIME |
| 754 |
0x02ba: '\\textacutedbl{}', # MODIFIER LETTER DOUBLE PRIME |
| 755 |
0x2016: '\\textbardbl{}', # DOUBLE VERTICAL LINE |
| 756 |
0x2022: '\\textbullet{}', # BULLET |
| 757 |
0x2032: '\\textasciiacute{}', # PRIME |
| 758 |
0x2033: '\\textacutedbl{}', # DOUBLE PRIME |
| 759 |
0x2035: '\\textasciigrave{}', # REVERSED PRIME |
| 760 |
0x2036: '\\textgravedbl{}', # REVERSED DOUBLE PRIME |
| 761 |
0x203b: '\\textreferencemark{}', # REFERENCE MARK |
| 762 |
0x203d: '\\textinterrobang{}', # INTERROBANG |
| 763 |
0x2044: '\\textfractionsolidus{}', # FRACTION SLASH |
| 764 |
0x2045: '\\textlquill{}', # LEFT SQUARE BRACKET WITH QUILL |
| 765 |
0x2046: '\\textrquill{}', # RIGHT SQUARE BRACKET WITH QUILL |
| 766 |
0x2052: '\\textdiscount{}', # COMMERCIAL MINUS SIGN |
| 767 |
0x20a1: '\\textcolonmonetary{}', # COLON SIGN |
| 768 |
0x20a3: '\\textfrenchfranc{}', # FRENCH FRANC SIGN |
| 769 |
0x20a4: '\\textlira{}', # LIRA SIGN |
| 770 |
0x20a6: '\\textnaira{}', # NAIRA SIGN |
| 771 |
0x20a9: '\\textwon{}', # WON SIGN |
| 772 |
0x20ab: '\\textdong{}', # DONG SIGN |
| 773 |
0x20ac: '\\texteuro{}', # EURO SIGN |
| 774 |
0x20b1: '\\textpeso{}', # PESO SIGN |
| 775 |
0x20b2: '\\textguarani{}', # GUARANI SIGN |
| 776 |
0x2103: '\\textcelsius{}', # DEGREE CELSIUS |
| 777 |
0x2116: '\\textnumero{}', # NUMERO SIGN |
| 778 |
0x2117: '\\textcircledP{}', # SOUND RECORDING COPYRIGHT |
| 779 |
0x211e: '\\textrecipe{}', # PRESCRIPTION TAKE |
| 780 |
0x2120: '\\textservicemark{}', # SERVICE MARK |
| 781 |
0x2122: '\\texttrademark{}', # TRADE MARK SIGN |
| 782 |
0x2126: '\\textohm{}', # OHM SIGN |
| 783 |
0x2127: '\\textmho{}', # INVERTED OHM SIGN |
| 784 |
0x212e: '\\textestimated{}', # ESTIMATED SYMBOL |
| 785 |
0x2190: '\\textleftarrow{}', # LEFTWARDS ARROW |
| 786 |
0x2191: '\\textuparrow{}', # UPWARDS ARROW |
| 787 |
0x2192: '\\textrightarrow{}', # RIGHTWARDS ARROW |
| 788 |
0x2193: '\\textdownarrow{}', # DOWNWARDS ARROW |
| 789 |
0x2212: '\\textminus{}', # MINUS SIGN |
| 790 |
0x2217: '\\textasteriskcentered{}', # ASTERISK OPERATOR |
| 791 |
0x221a: '\\textsurd{}', # SQUARE ROOT |
| 792 |
0x2422: '\\textblank{}', # BLANK SYMBOL |
| 793 |
0x25e6: '\\textopenbullet{}', # WHITE BULLET |
| 794 |
0x25ef: '\\textbigcircle{}', # LARGE CIRCLE |
| 795 |
0x266a: '\\textmusicalnote{}', # EIGHTH NOTE |
| 796 |
0x26ad: '\\textmarried{}', # MARRIAGE SYMBOL |
| 797 |
0x26ae: '\\textdivorced{}', # DIVORCE SYMBOL |
| 798 |
0x27e8: '\\textlangle{}', # MATHEMATICAL LEFT ANGLE BRACKET |
| 799 |
0x27e9: '\\textrangle{}', # MATHEMATICAL RIGHT ANGLE BRACKET |
| 800 |
} |
| 801 |
# Unicode chars that require a feature/package to render |
| 802 |
pifont = { |
| 803 |
0x2665: '\\ding{170}', # black heartsuit |
| 804 |
0x2666: '\\ding{169}', # black diamondsuit |
| 805 |
0x2713: '\\ding{51}', # check mark |
| 806 |
0x2717: '\\ding{55}', # check mark |
| 807 |
} |
| 808 |
# TODO: greek alphabet ... ? |
| 809 |
# see also LaTeX codec |
| 810 |
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252124 |
| 811 |
# and unimap.py from TeXML |
| 812 |
|
| 813 |
|
| 814 |
class DocumentClass: |
| 815 |
"""Details of a LaTeX document class.""" |
| 816 |
|
| 817 |
def __init__(self, document_class, with_part=False) -> None: |
| 818 |
self.document_class = document_class |
| 819 |
self._with_part = with_part |
| 820 |
self.sections = ['section', 'subsection', 'subsubsection', |
| 821 |
'paragraph', 'subparagraph'] |
| 822 |
if (self.document_class.endswith('book') |
| 823 |
or self.document_class.endswith('report') |
| 824 |
or self.document_class in ('ctexrep', 'memoir', 'mwbk', |
| 825 |
'mwrep', 'scrreprt')): |
| 826 |
self.sections.insert(0, 'chapter') |
| 827 |
if self._with_part: |
| 828 |
self.sections.insert(0, 'part') |
| 829 |
|
| 830 |
def section(self, level): |
| 831 |
"""Return the LaTeX section name for section `level`. |
| 832 |
|
| 833 |
The name depends on the specific document class. |
| 834 |
Level is 1,2,3..., as level 0 is the title. |
| 835 |
""" |
| 836 |
if level <= len(self.sections): |
| 837 |
return self.sections[level-1] |
| 838 |
# unsupported levels |
| 839 |
return 'DUtitle' |
| 840 |
|
| 841 |
def latex_section_depth(self, depth: int) -> int: |
| 842 |
""" |
| 843 |
Return LaTeX equivalent of Docutils section level `depth`. |
| 844 |
|
| 845 |
Given the value of the ``:depth:`` option of the "contents" or |
| 846 |
"sectnum" directive, return the corresponding value for the |
| 847 |
LaTeX ``tocdepth`` or ``secnumdepth`` counters. |
| 848 |
|
| 849 |
LaTeX section depth values: |
| 850 |
:-1|0: part (optional, 0 with "article"-like document classes) |
| 851 |
:0: chapter (missing in "article"-like document classes) |
| 852 |
:1: section |
| 853 |
:2: subsection |
| 854 |
:3: subsubsection |
| 855 |
:4: paragraph |
| 856 |
:5: subparagraph |
| 857 |
""" |
| 858 |
depth = min(depth, len(self.sections)) # limit to supported levels |
| 859 |
if 'chapter' in self.sections: |
| 860 |
depth -= 1 |
| 861 |
if self.sections[0] == 'part': |
| 862 |
depth -= 1 |
| 863 |
return depth |
| 864 |
|
| 865 |
|
| 866 |
class Table: |
| 867 |
"""Manage a table while traversing. |
| 868 |
|
| 869 |
Table style might be |
| 870 |
|
| 871 |
:standard: horizontal and vertical lines |
| 872 |
:booktabs: only horizontal lines (requires "booktabs" LaTeX package) |
| 873 |
:borderless: no borders around table cells |
| 874 |
:nolines: alias for borderless |
| 875 |
|
| 876 |
:colwidths-auto: column widths determined by LaTeX |
| 877 |
""" |
| 878 |
def __init__(self, translator, latex_type) -> None: |
| 879 |
self._translator = translator |
| 880 |
self._latex_type = latex_type |
| 881 |
self.legacy_column_widths = False |
| 882 |
|
| 883 |
self.close() |
| 884 |
self._colwidths = [] |
| 885 |
self._rowspan = [] |
| 886 |
self._in_thead = 0 |
| 887 |
|
| 888 |
def open(self) -> None: |
| 889 |
self._open = True |
| 890 |
self._col_specs = [] |
| 891 |
self.caption = [] |
| 892 |
self._attrs = {} |
| 893 |
self._in_head = False # maybe context with search |
| 894 |
|
| 895 |
def close(self) -> None: |
| 896 |
self._open = False |
| 897 |
self._col_specs = None |
| 898 |
self.caption = [] |
| 899 |
self._attrs = {} |
| 900 |
self.stubs = [] |
| 901 |
self.colwidths_auto = False |
| 902 |
|
| 903 |
def is_open(self): |
| 904 |
return self._open |
| 905 |
|
| 906 |
def set_table_style(self, node, settings) -> None: |
| 907 |
self.legacy_column_widths = settings.legacy_column_widths |
| 908 |
if 'align' in node: |
| 909 |
self.set('align', node['align']) |
| 910 |
# TODO: elif 'align' in classes/settings.table-style: |
| 911 |
# self.set('align', ...) |
| 912 |
borders = [cls.replace('nolines', 'borderless') |
| 913 |
for cls in (['standard'] |
| 914 |
+ settings.table_style |
| 915 |
+ node['classes']) |
| 916 |
if cls in ('standard', 'booktabs', 'borderless', 'nolines')] |
| 917 |
self.borders = borders[-1] |
| 918 |
self.colwidths_auto = (('colwidths-auto' in node['classes'] |
| 919 |
or 'colwidths-auto' in settings.table_style) |
| 920 |
and 'colwidths-given' not in node['classes'] |
| 921 |
and 'width' not in node) |
| 922 |
|
| 923 |
def get_latex_type(self): |
| 924 |
if self._latex_type == 'longtable' and not self.caption: |
| 925 |
# do not advance the "table" counter (requires "ltcaption" package) |
| 926 |
return 'longtable*' |
| 927 |
return self._latex_type |
| 928 |
|
| 929 |
def set(self, attr, value) -> None: |
| 930 |
self._attrs[attr] = value |
| 931 |
|
| 932 |
def get(self, attr): |
| 933 |
if attr in self._attrs: |
| 934 |
return self._attrs[attr] |
| 935 |
return None |
| 936 |
|
| 937 |
def get_vertical_bar(self) -> str: |
| 938 |
if self.borders == 'standard': |
| 939 |
return '|' |
| 940 |
return '' |
| 941 |
|
| 942 |
def get_opening(self, width=r'\linewidth'): |
| 943 |
opening = [] |
| 944 |
nr_of_cols = len(self._col_specs) |
| 945 |
align_map = {'left': '[l]', |
| 946 |
'center': '[c]', |
| 947 |
'right': '[r]', |
| 948 |
None: ''} |
| 949 |
align = align_map.get(self.get('align')) |
| 950 |
latex_type = self.get_latex_type() |
| 951 |
if align and not latex_type.startswith("longtable"): |
| 952 |
opening.append(r'\noindent\makebox[\linewidth]%s{%%' % align) |
| 953 |
align = '' |
| 954 |
if not self.colwidths_auto: |
| 955 |
if self.borders == 'standard' and not self.legacy_column_widths: |
| 956 |
opening.append(r'\setlength{\DUtablewidth}' |
| 957 |
r'{\dimexpr%s-%i\arrayrulewidth\relax}%%' |
| 958 |
% (width, nr_of_cols+1)) |
| 959 |
else: |
| 960 |
opening.append(r'\setlength{\DUtablewidth}{%s}%%' % width) |
| 961 |
opening.append(r'\begin{%s}%s' % (latex_type, align)) |
| 962 |
return '\n'.join(opening) |
| 963 |
|
| 964 |
def get_closing(self): |
| 965 |
closing = [] |
| 966 |
if self.borders == 'booktabs': |
| 967 |
closing.append(r'\bottomrule') |
| 968 |
# elif self.borders == 'standard': |
| 969 |
# closing.append(r'\hline') |
| 970 |
closing.append(r'\end{%s}' % self.get_latex_type()) |
| 971 |
if (self.get('align') |
| 972 |
and not self.get_latex_type().startswith("longtable")): |
| 973 |
closing.append('}') |
| 974 |
return '\n'.join(closing) |
| 975 |
|
| 976 |
def visit_colspec(self, node) -> None: |
| 977 |
self._col_specs.append(node) |
| 978 |
# "stubs" list is an attribute of the tgroup element: |
| 979 |
self.stubs.append(node.attributes.get('stub')) |
| 980 |
|
| 981 |
def get_colspecs(self, node): |
| 982 |
"""Return column specification for longtable. |
| 983 |
""" |
| 984 |
bar = self.get_vertical_bar() |
| 985 |
self._rowspan = [0] * len(self._col_specs) |
| 986 |
if self.colwidths_auto: |
| 987 |
self._colwidths = [] |
| 988 |
latex_colspecs = ['l'] * len(self._col_specs) |
| 989 |
elif self.legacy_column_widths: |
| 990 |
# use old algorithm for backwards compatibility |
| 991 |
width = 80 # assumed standard line length |
| 992 |
factor = 0.93 # do not make it full linewidth |
| 993 |
# first see if we get too wide. |
| 994 |
total_width = sum(node.propwidth()+1 for node in self._col_specs) |
| 995 |
if total_width > width: |
| 996 |
factor *= width / total_width |
| 997 |
self._colwidths = [(factor * (node.propwidth()+1)/width) + 0.005 |
| 998 |
for node in self._col_specs] |
| 999 |
latex_colspecs = ['p{%.3f\\DUtablewidth}' % colwidth |
| 1000 |
for colwidth in self._colwidths] |
| 1001 |
else: |
| 1002 |
# No of characters corresponding to table width = 100% |
| 1003 |
# Characters/line with LaTeX article, A4, Times, default margins |
| 1004 |
# depends on character: M: 40, A: 50, x: 70, i: 120. |
| 1005 |
norm_length = 40 |
| 1006 |
# Allowance to prevent unpadded columns like |
| 1007 |
# === == |
| 1008 |
# ABC DE |
| 1009 |
# === == |
| 1010 |
# getting too narrow: |
| 1011 |
if 'colwidths-given' not in node.parent.parent['classes']: |
| 1012 |
allowance = 1 |
| 1013 |
else: |
| 1014 |
allowance = 0 # "widths" option specified, use exact ratio |
| 1015 |
self._colwidths = [(node.propwidth()+allowance)/norm_length |
| 1016 |
for node in self._col_specs] |
| 1017 |
total_width = sum(self._colwidths) |
| 1018 |
# Limit to 100%, force 100% if table width is specified: |
| 1019 |
if total_width > 1 or 'width' in node.parent.parent.attributes: |
| 1020 |
self._colwidths = [colwidth/total_width |
| 1021 |
for colwidth in self._colwidths] |
| 1022 |
latex_colspecs = ['p{\\DUcolumnwidth{%.3f}}' % colwidth |
| 1023 |
for colwidth in self._colwidths] |
| 1024 |
return bar + bar.join(latex_colspecs) + bar |
| 1025 |
|
| 1026 |
def get_column_width(self) -> str: |
| 1027 |
"""Return columnwidth for current cell (not multicell).""" |
| 1028 |
try: |
| 1029 |
if self.legacy_column_widths: |
| 1030 |
return '%.2f\\DUtablewidth'%self._colwidths[self._cell_in_row] |
| 1031 |
return '\\DUcolumnwidth{%.2f}'%self._colwidths[self._cell_in_row] |
| 1032 |
except IndexError: |
| 1033 |
return '*' |
| 1034 |
|
| 1035 |
def get_multicolumn_width(self, start, len_) -> str: |
| 1036 |
"""Return sum of columnwidths for multicell.""" |
| 1037 |
try: |
| 1038 |
multicol_width = sum(self._colwidths[start + co] |
| 1039 |
for co in range(len_)) |
| 1040 |
if self.legacy_column_widths: |
| 1041 |
return 'p{%.2f\\DUtablewidth}' % multicol_width |
| 1042 |
return 'p{\\DUcolumnwidth{%.3f}}' % multicol_width |
| 1043 |
except IndexError: |
| 1044 |
return 'l' |
| 1045 |
|
| 1046 |
def need_recurse(self): |
| 1047 |
if self._latex_type == 'longtable': |
| 1048 |
return 1 == self._translator.thead_depth() |
| 1049 |
return 0 |
| 1050 |
|
| 1051 |
def visit_thead(self): |
| 1052 |
self._in_thead += 1 |
| 1053 |
if self.borders == 'standard': |
| 1054 |
return ['\\hline\n'] |
| 1055 |
elif self.borders == 'booktabs': |
| 1056 |
return ['\\toprule\n'] |
| 1057 |
return [] |
| 1058 |
|
| 1059 |
def depart_thead(self): |
| 1060 |
a = [] |
| 1061 |
## if self.borders == 'standard': |
| 1062 |
## a.append('\\hline\n') |
| 1063 |
if self.borders == 'booktabs': |
| 1064 |
a.append('\\midrule\n') |
| 1065 |
if self._latex_type == 'longtable': |
| 1066 |
if 1 == self._translator.thead_depth(): |
| 1067 |
a.append('\\endfirsthead\n') |
| 1068 |
else: |
| 1069 |
n_c = len(self._col_specs) |
| 1070 |
a.append('\\endhead\n') |
| 1071 |
# footer on all but last page (if it fits): |
| 1072 |
t_width = sum(node.propwidth()+2 for node in self._col_specs) |
| 1073 |
if t_width > 30 or (t_width > 12 and not self.colwidths_auto): |
| 1074 |
a.append(r'\multicolumn{%d}{%s}' |
| 1075 |
% (n_c, self.get_multicolumn_width(0, n_c)) |
| 1076 |
+ r'{\raggedleft\ldots continued on next page}\\' |
| 1077 |
+ '\n') |
| 1078 |
a.append('\\endfoot\n\\endlastfoot\n') |
| 1079 |
# for longtable one could add firsthead, foot and lastfoot |
| 1080 |
self._in_thead -= 1 |
| 1081 |
return a |
| 1082 |
|
| 1083 |
def visit_row(self) -> None: |
| 1084 |
self._cell_in_row = 0 |
| 1085 |
|
| 1086 |
def depart_row(self): |
| 1087 |
res = [' \\\\\n'] |
| 1088 |
self._cell_in_row = None # remove cell counter |
| 1089 |
for i in range(len(self._rowspan)): |
| 1090 |
if self._rowspan[i] > 0: |
| 1091 |
self._rowspan[i] -= 1 |
| 1092 |
|
| 1093 |
if self.borders == 'standard': |
| 1094 |
rowspans = [i+1 for i in range(len(self._rowspan)) |
| 1095 |
if self._rowspan[i] <= 0] |
| 1096 |
if len(rowspans) == len(self._rowspan): |
| 1097 |
res.append('\\hline\n') |
| 1098 |
else: |
| 1099 |
cline = '' |
| 1100 |
rowspans.reverse() |
| 1101 |
# TODO merge clines |
| 1102 |
while True: |
| 1103 |
try: |
| 1104 |
c_start = rowspans.pop() |
| 1105 |
except IndexError: |
| 1106 |
break |
| 1107 |
cline += '\\cline{%d-%d}\n' % (c_start, c_start) |
| 1108 |
res.append(cline) |
| 1109 |
return res |
| 1110 |
|
| 1111 |
def set_rowspan(self, cell, value) -> None: |
| 1112 |
try: |
| 1113 |
self._rowspan[cell] = value |
| 1114 |
except IndexError: |
| 1115 |
pass |
| 1116 |
|
| 1117 |
def get_rowspan(self, cell): |
| 1118 |
try: |
| 1119 |
return self._rowspan[cell] |
| 1120 |
except IndexError: |
| 1121 |
return 0 |
| 1122 |
|
| 1123 |
def get_entry_number(self): |
| 1124 |
return self._cell_in_row |
| 1125 |
|
| 1126 |
def visit_entry(self) -> None: |
| 1127 |
self._cell_in_row += 1 |
| 1128 |
|
| 1129 |
def is_stub_column(self): |
| 1130 |
if len(self.stubs) >= self._cell_in_row: |
| 1131 |
return self.stubs[self._cell_in_row] |
| 1132 |
return False |
| 1133 |
|
| 1134 |
|
| 1135 |
class LaTeXTranslator(writers.DoctreeTranslator): |
| 1136 |
""" |
| 1137 |
Generate code for 8-bit LaTeX from a Docutils document tree. |
| 1138 |
|
| 1139 |
See the docstring of docutils.writers._html_base.HTMLTranslator for |
| 1140 |
notes on and examples of safe subclassing. |
| 1141 |
""" |
| 1142 |
|
| 1143 |
# When options are given to the documentclass, latex will pass them |
| 1144 |
# to other packages, as done with babel. |
| 1145 |
# Dummy settings might be taken from document settings |
| 1146 |
|
| 1147 |
# Generate code for typesetting with 8-bit latex/pdflatex vs. |
| 1148 |
# xelatex/lualatex engine. Overwritten by the XeTeX writer |
| 1149 |
is_xetex = False |
| 1150 |
|
| 1151 |
# Config setting defaults |
| 1152 |
# ----------------------- |
| 1153 |
|
| 1154 |
# TODO: use mixins for different implementations. |
| 1155 |
# list environment for docinfo. else tabularx |
| 1156 |
## use_optionlist_for_docinfo = False # TODO: NOT YET IN USE |
| 1157 |
|
| 1158 |
# Use compound enumerations (1.A.1.) |
| 1159 |
compound_enumerators = False |
| 1160 |
|
| 1161 |
# If using compound enumerations, include section information. |
| 1162 |
section_prefix_for_enumerators = False |
| 1163 |
|
| 1164 |
# This is the character that separates the section ("." subsection ...) |
| 1165 |
# prefix from the regular list enumerator. |
| 1166 |
section_enumerator_separator = '-' |
| 1167 |
|
| 1168 |
# Auxiliary variables |
| 1169 |
# ------------------- |
| 1170 |
|
| 1171 |
has_latex_toc = False # is there a toc in the doc? (needed by minitoc) |
| 1172 |
section_level = 0 |
| 1173 |
|
| 1174 |
# Flags to encode(): |
| 1175 |
# inside citation reference labels underscores dont need to be escaped |
| 1176 |
inside_citation_reference_label = False |
| 1177 |
verbatim = False # do not encode |
| 1178 |
insert_non_breaking_blanks = False # replace blanks by "~" |
| 1179 |
insert_newline = False # add latex newline commands |
| 1180 |
literal = False # literal text (block or inline) |
| 1181 |
alltt = False # inside `alltt` environment |
| 1182 |
|
| 1183 |
# Nodes to be stored in the "titledata" part if "use_latex_docinfo" is true |
| 1184 |
TITLEDATA_NODES = (nodes.address, nodes.author, nodes.authors, |
| 1185 |
nodes.contact, nodes.date, nodes.organization) |
| 1186 |
|
| 1187 |
def __init__(self, document, babel_class=Babel) -> None: |
| 1188 |
super().__init__(document) |
| 1189 |
# Reporter |
| 1190 |
# ~~~~~~~~ |
| 1191 |
self.warn = self.document.reporter.warning |
| 1192 |
self.error = self.document.reporter.error |
| 1193 |
|
| 1194 |
# Set of IDs that are actually used in <reference>'s "refid" attribute |
| 1195 |
# (see `ids_to_labels()`): |
| 1196 |
self.refids = set() |
| 1197 |
for node in document.findall(nodes.reference): |
| 1198 |
if 'refid' in node: |
| 1199 |
self.refids.add(node['refid']) |
| 1200 |
|
| 1201 |
# Settings |
| 1202 |
# ~~~~~~~~ |
| 1203 |
settings = self.settings |
| 1204 |
# warn of deprecated settings and changing defaults: |
| 1205 |
if settings.use_latex_citations is None and not settings.use_bibtex: |
| 1206 |
settings.use_latex_citations = False |
| 1207 |
warnings.warn('The default for the setting "use_latex_citations" ' |
| 1208 |
'will change to "True" in Docutils 1.0.', |
| 1209 |
FutureWarning, stacklevel=7) |
| 1210 |
if settings.legacy_column_widths is None: |
| 1211 |
settings.legacy_column_widths = True |
| 1212 |
warnings.warn('The default for the setting "legacy_column_widths" ' |
| 1213 |
'will change to "False" in Docutils 1.0.)', |
| 1214 |
FutureWarning, stacklevel=7) |
| 1215 |
if settings.use_verbatim_when_possible is not None: |
| 1216 |
warnings.warn( |
| 1217 |
'The configuration setting "use_verbatim_when_possible" ' |
| 1218 |
'will be removed in Docutils 2.0. ' |
| 1219 |
'Use "literal_block_env: verbatim".', |
| 1220 |
FutureWarning, stacklevel=7) |
| 1221 |
|
| 1222 |
self.latex_encoding = self.to_latex_encoding(settings.output_encoding) |
| 1223 |
self.use_latex_toc = settings.use_latex_toc |
| 1224 |
self.use_latex_docinfo = settings.use_latex_docinfo |
| 1225 |
self.use_latex_citations = settings.use_latex_citations |
| 1226 |
self.reference_label = settings.reference_label |
| 1227 |
self.hyperlink_color = settings.hyperlink_color |
| 1228 |
self.compound_enumerators = settings.compound_enumerators |
| 1229 |
self.font_encoding = getattr(settings, 'font_encoding', '') |
| 1230 |
self.section_prefix_for_enumerators = ( |
| 1231 |
settings.section_prefix_for_enumerators) |
| 1232 |
self.section_enumerator_separator = ( |
| 1233 |
settings.section_enumerator_separator.replace('_', r'\_')) |
| 1234 |
# literal blocks: |
| 1235 |
self.literal_block_env = '' |
| 1236 |
self.literal_block_options = '' |
| 1237 |
if settings.literal_block_env: |
| 1238 |
(_none, |
| 1239 |
self.literal_block_env, |
| 1240 |
self.literal_block_options, |
| 1241 |
_none) = re.split(r'(\w+)(.*)', settings.literal_block_env) |
| 1242 |
elif settings.use_verbatim_when_possible: |
| 1243 |
self.literal_block_env = 'verbatim' |
| 1244 |
|
| 1245 |
if settings.use_bibtex: |
| 1246 |
self.use_latex_citations = True |
| 1247 |
self.bibtex = settings.use_bibtex |
| 1248 |
# language module for Docutils-generated text |
| 1249 |
# (labels, bibliographic_fields, and author_separators) |
| 1250 |
self.language_module = languages.get_language(settings.language_code, |
| 1251 |
document.reporter) |
| 1252 |
self.babel = babel_class(settings.language_code, document.reporter) |
| 1253 |
self.author_separator = self.language_module.author_separators[0] |
| 1254 |
d_options = [settings.documentoptions] |
| 1255 |
if self.babel.language not in ('english', ''): |
| 1256 |
d_options.append(self.babel.language) |
| 1257 |
self.documentoptions = ','.join(filter(None, d_options)) |
| 1258 |
self.d_class = DocumentClass(settings.documentclass, |
| 1259 |
settings.use_part_section) |
| 1260 |
# graphic package options: |
| 1261 |
if settings.graphicx_option == '': |
| 1262 |
self.graphicx_package = r'\usepackage{graphicx}' |
| 1263 |
else: |
| 1264 |
self.graphicx_package = (r'\usepackage[%s]{graphicx}' % |
| 1265 |
settings.graphicx_option) |
| 1266 |
self.latex_footnotes = settings.latex_footnotes |
| 1267 |
|
| 1268 |
# Output collection stacks |
| 1269 |
# ~~~~~~~~~~~~~~~~~~~~~~~~ |
| 1270 |
# Document parts |
| 1271 |
self.head_prefix = [f'\\documentclass[{self.documentoptions}]' |
| 1272 |
f'{{{settings.documentclass}}}'] |
| 1273 |
self.requirements = {} # converted to a list in depart_document() |
| 1274 |
self.latex_preamble = [settings.latex_preamble] |
| 1275 |
self.fallbacks = {} # converted to a list in depart_document() |
| 1276 |
self.pdfsetup = [] # PDF properties (hyperref package) |
| 1277 |
self.title = [] |
| 1278 |
self.subtitle = [] |
| 1279 |
self.titledata = [] # \title, \author, \date |
| 1280 |
## self.body_prefix = ['\\begin{document}\n'] |
| 1281 |
self.body_pre_docinfo = [] # \maketitle |
| 1282 |
self.docinfo = [] |
| 1283 |
self.dedication = [] |
| 1284 |
self.abstract = [] |
| 1285 |
self.body = [] |
| 1286 |
## self.body_suffix = ['\\end{document}\n'] |
| 1287 |
|
| 1288 |
self.context = [] |
| 1289 |
"""Heterogeneous stack. |
| 1290 |
|
| 1291 |
Used by visit_* and depart_* functions in conjunction with the tree |
| 1292 |
traversal. Make sure that the pops correspond to the pushes.""" |
| 1293 |
|
| 1294 |
# Title metadata: |
| 1295 |
self.title_labels = [] |
| 1296 |
self.subtitle_labels = [] |
| 1297 |
# with "use_latex_docinfo", we also need |
| 1298 |
self.author_stack = [['']] # first item reserved for author name |
| 1299 |
self.date = [] |
| 1300 |
|
| 1301 |
# PDF properties: |
| 1302 |
self.pdfauthor = [] |
| 1303 |
self.pdfinfo = [] |
| 1304 |
if settings.language_code != 'en': |
| 1305 |
self.pdfinfo.append(' pdflang={%s},'%settings.language_code) |
| 1306 |
|
| 1307 |
# Stack of section counters so that we don't have to use_latex_toc. |
| 1308 |
# This will grow and shrink as processing occurs. |
| 1309 |
# Initialized for potential first-level sections. |
| 1310 |
self._section_number = [0] |
| 1311 |
|
| 1312 |
# The current stack of enumerations so that we can expand |
| 1313 |
# them into a compound enumeration. |
| 1314 |
self._enumeration_counters = [] |
| 1315 |
# The maximum number of enumeration counters we've used. |
| 1316 |
# If we go beyond this number, we need to create a new |
| 1317 |
# counter; otherwise, just reuse an old one. |
| 1318 |
self._max_enumeration_counters = 0 |
| 1319 |
|
| 1320 |
self._bibitems = [] |
| 1321 |
|
| 1322 |
# object for a table while processing. |
| 1323 |
self.table_stack = [] |
| 1324 |
self.active_table = Table(self, 'longtable') |
| 1325 |
|
| 1326 |
# Where to collect the output of visitor methods (default: body) |
| 1327 |
self.out = self.body |
| 1328 |
self.out_stack = [] # stack of output collectors |
| 1329 |
|
| 1330 |
# LaTeX footnotes (see `visit_footnote_reference()`) |
| 1331 |
self.footnote_queue = [] # FIFO queue of footnote IDs |
| 1332 |
self.processed_footnotes = set() # IDs of already set footnotes |
| 1333 |
|
| 1334 |
# Process settings |
| 1335 |
# ~~~~~~~~~~~~~~~~ |
| 1336 |
# Encodings: |
| 1337 |
# Docutils' output-encoding => TeX input encoding |
| 1338 |
if self.latex_encoding not in ('ascii', 'unicode', 'utf8'): |
| 1339 |
self.requirements['_inputenc'] = (r'\usepackage[%s]{inputenc}' |
| 1340 |
% self.latex_encoding) |
| 1341 |
# TeX font encoding |
| 1342 |
if not self.is_xetex: |
| 1343 |
if self.font_encoding: |
| 1344 |
self.requirements['_fontenc'] = (r'\usepackage[%s]{fontenc}' % |
| 1345 |
self.font_encoding) |
| 1346 |
# ensure \textquotedbl is defined: |
| 1347 |
for enc in self.font_encoding.split(','): |
| 1348 |
enc = enc.strip() |
| 1349 |
if enc == 'OT1': |
| 1350 |
self.requirements['_textquotedblOT1'] = ( |
| 1351 |
r'\DeclareTextSymbol{\textquotedbl}{OT1}{`\"}') |
| 1352 |
elif enc not in ('T1', 'T2A', 'T2B', 'T2C', 'T4', 'T5'): |
| 1353 |
self.requirements['_textquotedbl'] = ( |
| 1354 |
r'\DeclareTextSymbolDefault{\textquotedbl}{T1}') |
| 1355 |
# page layout with typearea (if there are relevant document options) |
| 1356 |
if (not settings.documentclass.startswith('scr') |
| 1357 |
and ('DIV' in self.documentoptions |
| 1358 |
or 'BCOR' in self.documentoptions)): |
| 1359 |
self.requirements['typearea'] = r'\usepackage{typearea}' |
| 1360 |
|
| 1361 |
# Stylesheets |
| 1362 |
# (the name `self.stylesheet` is singular because only one |
| 1363 |
# stylesheet was supported before Docutils 0.6). |
| 1364 |
stylesheet_list = utils.get_stylesheet_list(settings) |
| 1365 |
self.fallback_stylesheet = 'docutils' in stylesheet_list |
| 1366 |
if self.fallback_stylesheet: |
| 1367 |
stylesheet_list.remove('docutils') |
| 1368 |
if settings.legacy_class_functions: |
| 1369 |
# docutils.sty is incompatible with legacy class functions |
| 1370 |
self.fallback_stylesheet = False |
| 1371 |
else: |
| 1372 |
# require a minimal version: |
| 1373 |
self.fallbacks['_docutils.sty'] = ( |
| 1374 |
r'\usepackage{docutils}[2026-05-06]') |
| 1375 |
|
| 1376 |
self.stylesheet = [self.stylesheet_call(path) |
| 1377 |
for path in stylesheet_list] |
| 1378 |
|
| 1379 |
# PDF setup |
| 1380 |
self.hyperref_options = [] |
| 1381 |
# avoid warnings about empty anchors with \DUfootnotetext: |
| 1382 |
if not self.latex_footnotes: |
| 1383 |
self.hyperref_options = ['hyperfootnotes=false'] |
| 1384 |
# link color (default is "blue"): |
| 1385 |
if self.hyperlink_color.lower() not in ('0', 'off', 'no', 'false', ''): |
| 1386 |
self.hyperref_options.append('colorlinks=true,' |
| 1387 |
f'linkcolor={self.hyperlink_color},' |
| 1388 |
f'urlcolor={self.hyperlink_color}') |
| 1389 |
if settings.hyperref_options: |
| 1390 |
self.hyperref_options.append(settings.hyperref_options) |
| 1391 |
# wrap and align (cf. PreambleCmds.linking): |
| 1392 |
self.hyperref_options = ',\n '.join(self.hyperref_options) |
| 1393 |
|
| 1394 |
# Auxiliary Methods |
| 1395 |
# ----------------- |
| 1396 |
|
| 1397 |
def stylesheet_call(self, path): |
| 1398 |
"""Return code to reference or embed stylesheet file `path`.""" |
| 1399 |
|
| 1400 |
path = Path(path) |
| 1401 |
# is it a package (no extension or *.sty) or "normal" tex code: |
| 1402 |
is_package = path.suffix in ('.sty', '') |
| 1403 |
# Embed content of style file: |
| 1404 |
if self.settings.embed_stylesheet: |
| 1405 |
if is_package: |
| 1406 |
path = path.with_suffix('.sty') # ensure extension |
| 1407 |
try: |
| 1408 |
content = path.read_text(encoding='utf-8') |
| 1409 |
except OSError as err: |
| 1410 |
msg = f'Cannot embed stylesheet:\n {err}'.replace('\\\\', '/') |
| 1411 |
self.document.reporter.error(msg) |
| 1412 |
return '% ' + msg.replace('\n', '\n% ') |
| 1413 |
else: |
| 1414 |
self.settings.record_dependencies.add(path.as_posix()) |
| 1415 |
if is_package: |
| 1416 |
# allow '@' in macro names: |
| 1417 |
content = (f'\\makeatletter\n{content}\n\\makeatother') |
| 1418 |
return (f'% embedded stylesheet: {path.as_posix()}\n' |
| 1419 |
f'{content}') |
| 1420 |
# Link to style file: |
| 1421 |
if is_package: |
| 1422 |
path = path.parent / path.stem # drop extension |
| 1423 |
cmd = r'\usepackage{%s}' |
| 1424 |
else: |
| 1425 |
cmd = r'\input{%s}' |
| 1426 |
if self.settings.stylesheet_path: |
| 1427 |
# adapt path relative to output (cf. config.html#stylesheet-path) |
| 1428 |
return cmd % utils.relative_path(self.settings.output_path, path) |
| 1429 |
return cmd % path.as_posix() |
| 1430 |
|
| 1431 |
def to_latex_encoding(self, docutils_encoding): |
| 1432 |
"""Translate docutils encoding name into LaTeX's. |
| 1433 |
|
| 1434 |
Default method is remove "-" and "_" chars from docutils_encoding. |
| 1435 |
""" |
| 1436 |
tr = {'iso-8859-1': 'latin1', # west european |
| 1437 |
'iso-8859-2': 'latin2', # east european |
| 1438 |
'iso-8859-3': 'latin3', # esperanto, maltese |
| 1439 |
'iso-8859-4': 'latin4', # north european |
| 1440 |
'iso-8859-5': 'iso88595', # cyrillic (ISO) |
| 1441 |
'iso-8859-9': 'latin5', # turkish |
| 1442 |
'iso-8859-15': 'latin9', # latin9, update to latin1. |
| 1443 |
'mac_cyrillic': 'maccyr', # cyrillic (on Mac) |
| 1444 |
'windows-1251': 'cp1251', # cyrillic (on Windows) |
| 1445 |
'koi8-r': 'koi8-r', # cyrillic (Russian) |
| 1446 |
'koi8-u': 'koi8-u', # cyrillic (Ukrainian) |
| 1447 |
'windows-1250': 'cp1250', # |
| 1448 |
'windows-1252': 'cp1252', # |
| 1449 |
'us-ascii': 'ascii', # ASCII (US) |
| 1450 |
# unmatched encodings |
| 1451 |
# '': 'applemac', |
| 1452 |
# '': 'ansinew', # windows 3.1 ansi |
| 1453 |
# '': 'ascii', # ASCII encoding for the range 32--127. |
| 1454 |
# '': 'cp437', # dos latin us |
| 1455 |
# '': 'cp850', # dos latin 1 |
| 1456 |
# '': 'cp852', # dos latin 2 |
| 1457 |
# '': 'decmulti', |
| 1458 |
# '': 'latin10', |
| 1459 |
# 'iso-8859-6': '' # arabic |
| 1460 |
# 'iso-8859-7': '' # greek |
| 1461 |
# 'iso-8859-8': '' # hebrew |
| 1462 |
# 'iso-8859-10': '' # latin6, more complete iso-8859-4 |
| 1463 |
} |
| 1464 |
encoding = docutils_encoding.lower() # normalize case |
| 1465 |
encoding = encoding.split(':')[0] # strip the error handler |
| 1466 |
if encoding in tr: |
| 1467 |
return tr[encoding] |
| 1468 |
# drop HYPHEN or LOW LINE from "latin_1", "utf-8" and similar |
| 1469 |
return encoding.replace('_', '').replace('-', '') |
| 1470 |
|
| 1471 |
def language_label(self, docutil_label): |
| 1472 |
return self.language_module.labels[docutil_label] |
| 1473 |
|
| 1474 |
def encode(self, text): |
| 1475 |
"""Return text with 'problematic' characters escaped. |
| 1476 |
|
| 1477 |
* Escape the special printing characters ``# $ % & ~ _ ^ \\ { }``, |
| 1478 |
square brackets ``[ ]``, double quotes and (in OT1) ``< | >``. |
| 1479 |
* Translate non-supported Unicode characters. |
| 1480 |
* Separate ``-`` (and more in literal text) to prevent input ligatures. |
| 1481 |
""" |
| 1482 |
if self.verbatim: |
| 1483 |
return text |
| 1484 |
# Set up the translation table: |
| 1485 |
table = CharMaps.alltt.copy() |
| 1486 |
if not self.alltt: |
| 1487 |
table.update(CharMaps.special) |
| 1488 |
# keep the underscore in citation references |
| 1489 |
if self.inside_citation_reference_label and not self.alltt: |
| 1490 |
del table[ord('_')] |
| 1491 |
# Workarounds for OT1 font-encoding |
| 1492 |
if self.font_encoding in ['OT1', ''] and not self.is_xetex: |
| 1493 |
# * out-of-order characters in cmtt |
| 1494 |
if self.literal: |
| 1495 |
# replace underscore by underlined blank, |
| 1496 |
# because this has correct width. |
| 1497 |
table[ord('_')] = '\\underline{~}' |
| 1498 |
# the backslash doesn't work, so we use a mirrored slash. |
| 1499 |
# \reflectbox is provided by graphicx: |
| 1500 |
self.requirements['graphicx'] = self.graphicx_package |
| 1501 |
table[ord('\\')] = '\\reflectbox{/}' |
| 1502 |
# * ``< | >`` come out as different chars (except for cmtt): |
| 1503 |
else: |
| 1504 |
table[ord('|')] = '\\textbar{}' |
| 1505 |
table[ord('<')] = '\\textless{}' |
| 1506 |
table[ord('>')] = '\\textgreater{}' |
| 1507 |
if self.insert_non_breaking_blanks: |
| 1508 |
table[ord(' ')] = '~' |
| 1509 |
# tab chars may occur in included files (literal or code) |
| 1510 |
# quick-and-dirty replacement with spaces |
| 1511 |
# (for better results use `--literal-block-env=lstlisting`) |
| 1512 |
table[ord('\t')] = '~' * self.settings.tab_width |
| 1513 |
# Unicode replacements for 8-bit tex engines (not required with XeTeX) |
| 1514 |
if not self.is_xetex: |
| 1515 |
if not self.latex_encoding.startswith('utf8'): |
| 1516 |
table.update(CharMaps.unsupported_unicode) |
| 1517 |
table.update(CharMaps.utf8_supported_unicode) |
| 1518 |
table.update(CharMaps.textcomp) |
| 1519 |
table.update(CharMaps.pifont) |
| 1520 |
# Characters that require a feature/package to render |
| 1521 |
for ch in text: |
| 1522 |
cp = ord(ch) |
| 1523 |
if cp in CharMaps.textcomp and not self.fallback_stylesheet: |
| 1524 |
self.requirements['textcomp'] = PreambleCmds.textcomp |
| 1525 |
elif cp in CharMaps.pifont: |
| 1526 |
self.requirements['pifont'] = '\\usepackage{pifont}' |
| 1527 |
# preamble-definitions for unsupported Unicode characters |
| 1528 |
elif (self.latex_encoding == 'utf8' |
| 1529 |
and cp in CharMaps.unsupported_unicode): |
| 1530 |
self.requirements['_inputenc'+str(cp)] = ( |
| 1531 |
'\\DeclareUnicodeCharacter{%04X}{%s}' |
| 1532 |
% (cp, CharMaps.unsupported_unicode[cp])) |
| 1533 |
text = text.translate(table) |
| 1534 |
|
| 1535 |
# Break up input ligatures e.g. '--' to '-{}-'. |
| 1536 |
if not self.is_xetex: # Not required with xetex/luatex |
| 1537 |
separate_chars = '-' |
| 1538 |
# In monospace-font, we also separate ',,', '``' and "''" and some |
| 1539 |
# other characters which can't occur in non-literal text. |
| 1540 |
if self.literal: |
| 1541 |
separate_chars += ',`\'"<>' |
| 1542 |
for char in separate_chars * 2: |
| 1543 |
# Do it twice ("* 2") because otherwise we would replace |
| 1544 |
# '---' by '-{}--'. |
| 1545 |
text = text.replace(char + char, char + '{}' + char) |
| 1546 |
|
| 1547 |
# Literal line breaks (in address or literal blocks): |
| 1548 |
if self.insert_newline: |
| 1549 |
lines = text.split('\n') |
| 1550 |
# Add a protected space to blank lines (except the last) |
| 1551 |
# to avoid ``! LaTeX Error: There's no line here to end.`` |
| 1552 |
for i, line in enumerate(lines[:-1]): |
| 1553 |
if not line.lstrip(): |
| 1554 |
lines[i] += '~' |
| 1555 |
text = (r'\\' + '\n').join(lines) |
| 1556 |
if self.literal and not self.insert_non_breaking_blanks: |
| 1557 |
# preserve runs of spaces but allow wrapping |
| 1558 |
text = text.replace(' ', ' ~') |
| 1559 |
return text |
| 1560 |
|
| 1561 |
def attval(self, text, |
| 1562 |
whitespace=re.compile('[\n\r\t\v\f]')): |
| 1563 |
"""Cleanse, encode, and return attribute value text.""" |
| 1564 |
return self.encode(whitespace.sub(' ', text)) |
| 1565 |
|
| 1566 |
def is_inline(self, node): |
| 1567 |
"""Check whether a node represents an inline or block-level element""" |
| 1568 |
return isinstance(node.parent, nodes.TextElement) |
| 1569 |
|
| 1570 |
def append_hypertargets(self, node) -> None: |
| 1571 |
"""Append hypertargets for all ids of `node`""" |
| 1572 |
# hypertarget places the anchor at the target's baseline, |
| 1573 |
# so we raise it explicitly |
| 1574 |
self.out.append('%\n'.join('\\raisebox{1em}{\\hypertarget{%s}{}}' % |
| 1575 |
id for id in node['ids'])) |
| 1576 |
|
| 1577 |
def ids_to_labels(self, node, set_anchor=True, protect=False, |
| 1578 |
newline=False, pre_nl=False) -> list[str]: |
| 1579 |
"""Return label definitions for IDs of `node`. |
| 1580 |
|
| 1581 |
Make labels for all IDs that are either explicit or referenced in |
| 1582 |
the document (i.e. not for section headings that are not referenced). |
| 1583 |
|
| 1584 |
If `set_anchor` is True, an anchor is set with \\phantomsection. |
| 1585 |
If `protect` is True, the \\label cmd is made robust. |
| 1586 |
If `newline` is True, a newline is added if there are labels. |
| 1587 |
If `pre_nl` is True, a newline is prepended if there are labels. |
| 1588 |
|
| 1589 |
Provisional. |
| 1590 |
""" |
| 1591 |
explicit_IDs = set(self.document.nameids[name] |
| 1592 |
for name in node['names'] |
| 1593 |
if self.document.nametypes[name]) |
| 1594 |
prefix = '\\protect' if protect else '' |
| 1595 |
labels = [f'{prefix}\\label{{{ID}}}' for ID in node['ids'] |
| 1596 |
if ID in explicit_IDs.union(self.refids)] |
| 1597 |
if labels: |
| 1598 |
if set_anchor: |
| 1599 |
labels.insert(0, '\\phantomsection') |
| 1600 |
if newline: |
| 1601 |
labels.append('\n') |
| 1602 |
if pre_nl: |
| 1603 |
labels.insert(0, '\n') |
| 1604 |
return labels |
| 1605 |
|
| 1606 |
def set_align_from_classes(self, node) -> None: |
| 1607 |
"""Convert ``align-*`` class arguments into alignment args.""" |
| 1608 |
# separate: |
| 1609 |
align = [cls for cls in node['classes'] if cls.startswith('align-')] |
| 1610 |
if align: |
| 1611 |
node['align'] = align[-1].removeprefix('align-') |
| 1612 |
node['classes'] = [cls for cls in node['classes'] |
| 1613 |
if not cls.startswith('align-')] |
| 1614 |
|
| 1615 |
def insert_align_declaration(self, node, default=None) -> None: |
| 1616 |
align = node.get('align', default) |
| 1617 |
if align == 'left': |
| 1618 |
self.out.append('\\raggedright\n') |
| 1619 |
elif align == 'center': |
| 1620 |
self.out.append('\\centering\n') |
| 1621 |
elif align == 'right': |
| 1622 |
self.out.append('\\raggedleft\n') |
| 1623 |
|
| 1624 |
def provide_fallback(self, feature, key=None) -> None: |
| 1625 |
if key is None: |
| 1626 |
key = feature |
| 1627 |
if self.fallback_stylesheet: |
| 1628 |
return # provided by the included style sheet |
| 1629 |
self.fallbacks[key] = getattr(PreambleCmds, feature) |
| 1630 |
|
| 1631 |
def duclass_open(self, node) -> None: |
| 1632 |
"""Open a group and insert declarations for class values.""" |
| 1633 |
if not isinstance(node.parent, nodes.compound): |
| 1634 |
self.out.append('\n') |
| 1635 |
for cls in node['classes']: |
| 1636 |
if cls.startswith('language-'): |
| 1637 |
language = self.babel.language_name(cls[9:]) |
| 1638 |
if language: |
| 1639 |
self.babel.otherlanguages[language] = True |
| 1640 |
self.out.append('\\begin{selectlanguage}{%s}\n' % language) |
| 1641 |
elif (isinstance(node, nodes.table) |
| 1642 |
and cls in Writer.table_style_values + ['colwidths-given']): |
| 1643 |
pass |
| 1644 |
else: |
| 1645 |
self.provide_fallback('duclass', 'DUclass') |
| 1646 |
self.out.append('\\begin{DUclass}{%s}\n' % cls) |
| 1647 |
|
| 1648 |
def duclass_close(self, node) -> None: |
| 1649 |
"""Close a group of class declarations.""" |
| 1650 |
for cls in reversed(node['classes']): |
| 1651 |
if cls.startswith('language-'): |
| 1652 |
language = self.babel.language_name(cls[9:]) |
| 1653 |
if language: |
| 1654 |
self.out.append('\\end{selectlanguage}\n') |
| 1655 |
elif (isinstance(node, nodes.table) |
| 1656 |
and cls in Writer.table_style_values + ['colwidths-given']): |
| 1657 |
pass |
| 1658 |
else: |
| 1659 |
self.provide_fallback('duclass', 'DUclass') |
| 1660 |
self.out.append('\\end{DUclass}\n') |
| 1661 |
|
| 1662 |
def push_output_collector(self, new_out: list) -> None: |
| 1663 |
self.out_stack.append(self.out) |
| 1664 |
self.out = new_out |
| 1665 |
|
| 1666 |
def pop_output_collector(self) -> list: |
| 1667 |
old_out = self.out |
| 1668 |
self.out = self.out_stack.pop() |
| 1669 |
return old_out |
| 1670 |
|
| 1671 |
def term_postfix(self, node): |
| 1672 |
""" |
| 1673 |
Return LaTeX code required between term or field name and content. |
| 1674 |
|
| 1675 |
In a LaTeX "description" environment (used for definition |
| 1676 |
lists and non-docinfo field lists), a ``\\leavevmode`` |
| 1677 |
between an item's label and content ensures the correct |
| 1678 |
placement of certain block constructs. |
| 1679 |
""" |
| 1680 |
for child in node: |
| 1681 |
if not isinstance(child, (nodes.Invisible, nodes.footnote, |
| 1682 |
nodes.citation)): |
| 1683 |
break |
| 1684 |
else: |
| 1685 |
return '' |
| 1686 |
if isinstance(child, (nodes.container, nodes.compound)): |
| 1687 |
return self.term_postfix(child) |
| 1688 |
if isinstance(child, nodes.image): |
| 1689 |
return '\\leavevmode\n' # Images get an additional newline. |
| 1690 |
if not isinstance(child, (nodes.paragraph, nodes.math_block)): |
| 1691 |
return '\\leavevmode' |
| 1692 |
return '' |
| 1693 |
|
| 1694 |
# Visitor methods |
| 1695 |
# --------------- |
| 1696 |
|
| 1697 |
def visit_Text(self, node) -> None: |
| 1698 |
self.out.append(self.encode(node.astext())) |
| 1699 |
|
| 1700 |
def depart_Text(self, node) -> None: |
| 1701 |
pass |
| 1702 |
|
| 1703 |
def visit_abbreviation(self, node) -> None: |
| 1704 |
node['classes'].insert(0, 'abbreviation') |
| 1705 |
self.visit_inline(node) |
| 1706 |
|
| 1707 |
def depart_abbreviation(self, node) -> None: |
| 1708 |
self.depart_inline(node) |
| 1709 |
|
| 1710 |
def visit_acronym(self, node) -> None: |
| 1711 |
node['classes'].insert(0, 'acronym') |
| 1712 |
self.visit_inline(node) |
| 1713 |
|
| 1714 |
def depart_acronym(self, node) -> None: |
| 1715 |
self.depart_inline(node) |
| 1716 |
|
| 1717 |
def visit_address(self, node) -> None: |
| 1718 |
self.insert_newline = True # preserve newlines |
| 1719 |
self.visit_docinfo_item(node) |
| 1720 |
|
| 1721 |
def depart_address(self, node) -> None: |
| 1722 |
self.depart_docinfo_item(node) |
| 1723 |
self.insert_newline = False |
| 1724 |
|
| 1725 |
def visit_admonition(self, node) -> None: |
| 1726 |
# strip the generic 'admonition' from the list of classes |
| 1727 |
node['classes'] = [cls for cls in node['classes'] |
| 1728 |
if cls != 'admonition'] |
| 1729 |
if self.settings.legacy_class_functions: |
| 1730 |
self.fallbacks['admonition'] = PreambleCmds.admonition_legacy |
| 1731 |
if 'error' in node['classes']: |
| 1732 |
self.fallbacks['error'] = PreambleCmds.error_legacy |
| 1733 |
self.out.append('\n\\DUadmonition[%s]{'%','.join(node['classes'])) |
| 1734 |
return |
| 1735 |
self.provide_fallback('admonition') |
| 1736 |
if 'error' in node['classes']: |
| 1737 |
self.provide_fallback('error') |
| 1738 |
if not isinstance(node, nodes.system_message): |
| 1739 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 1740 |
self.duclass_open(node) |
| 1741 |
self.out.append('\\begin{DUadmonition}') |
| 1742 |
|
| 1743 |
def depart_admonition(self, node) -> None: |
| 1744 |
if self.settings.legacy_class_functions: |
| 1745 |
self.out.append('}\n') |
| 1746 |
return |
| 1747 |
self.out.append('\\end{DUadmonition}\n') |
| 1748 |
self.duclass_close(node) |
| 1749 |
|
| 1750 |
def visit_author(self, node) -> None: |
| 1751 |
self.pdfauthor.append(self.attval(node.astext())) |
| 1752 |
if isinstance(node.parent, nodes.authors): |
| 1753 |
# ensure output is one item per <author> element (see depart…) |
| 1754 |
self.push_output_collector([]) |
| 1755 |
else: |
| 1756 |
self.visit_docinfo_item(node) |
| 1757 |
|
| 1758 |
def depart_author(self, node) -> None: |
| 1759 |
if isinstance(node.parent, nodes.authors): |
| 1760 |
author_name = self.pop_output_collector() |
| 1761 |
self.out.append(''.join(author_name)) |
| 1762 |
else: |
| 1763 |
self.depart_docinfo_item(node) |
| 1764 |
|
| 1765 |
def visit_authors(self, node) -> None: |
| 1766 |
self.visit_docinfo_item(node) |
| 1767 |
|
| 1768 |
def depart_authors(self, node) -> None: |
| 1769 |
self.depart_docinfo_item(node) |
| 1770 |
|
| 1771 |
def visit_block_quote(self, node) -> None: |
| 1772 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 1773 |
self.duclass_open(node) |
| 1774 |
self.out.append('\\begin{quote}') |
| 1775 |
|
| 1776 |
def depart_block_quote(self, node) -> None: |
| 1777 |
self.out.append('\\end{quote}\n') |
| 1778 |
self.duclass_close(node) |
| 1779 |
|
| 1780 |
def visit_bullet_list(self, node) -> None: |
| 1781 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 1782 |
self.duclass_open(node) |
| 1783 |
self.out.append('\\begin{itemize}') |
| 1784 |
|
| 1785 |
def depart_bullet_list(self, node) -> None: |
| 1786 |
self.out.append('\\end{itemize}\n') |
| 1787 |
self.duclass_close(node) |
| 1788 |
|
| 1789 |
def visit_superscript(self, node) -> None: |
| 1790 |
self.out.append(r'\textsuperscript{') |
| 1791 |
self.visit_inline(node) |
| 1792 |
|
| 1793 |
def depart_superscript(self, node) -> None: |
| 1794 |
self.depart_inline(node) |
| 1795 |
self.out.append('}') |
| 1796 |
|
| 1797 |
def visit_subscript(self, node) -> None: |
| 1798 |
self.out.append(r'\textsubscript{') |
| 1799 |
self.visit_inline(node) |
| 1800 |
|
| 1801 |
def depart_subscript(self, node) -> None: |
| 1802 |
self.depart_inline(node) |
| 1803 |
self.out.append('}') |
| 1804 |
|
| 1805 |
def visit_caption(self, node) -> None: |
| 1806 |
self.out.append('\\caption{') |
| 1807 |
self.visit_inline(node) |
| 1808 |
|
| 1809 |
def depart_caption(self, node) -> None: |
| 1810 |
self.depart_inline(node) |
| 1811 |
self.out.append('}\n') |
| 1812 |
|
| 1813 |
def visit_title_reference(self, node) -> None: |
| 1814 |
self.provide_fallback('titlereference') |
| 1815 |
self.out.append(r'\DUroletitlereference{') |
| 1816 |
self.visit_inline(node) |
| 1817 |
|
| 1818 |
def depart_title_reference(self, node) -> None: |
| 1819 |
self.depart_inline(node) |
| 1820 |
self.out.append('}') |
| 1821 |
|
| 1822 |
def visit_citation(self, node) -> None: |
| 1823 |
if self.use_latex_citations: |
| 1824 |
self.push_output_collector([]) |
| 1825 |
else: |
| 1826 |
self.out.append(r'\begin{figure}[b]') |
| 1827 |
self.append_hypertargets(node) |
| 1828 |
|
| 1829 |
def depart_citation(self, node) -> None: |
| 1830 |
if self.use_latex_citations: |
| 1831 |
# TODO: normalize label |
| 1832 |
label = self.out[0] |
| 1833 |
text = ''.join(self.out[1:]) |
| 1834 |
self._bibitems.append([label, text]) |
| 1835 |
self.pop_output_collector() |
| 1836 |
else: |
| 1837 |
self.out.append('\\end{figure}\n') |
| 1838 |
|
| 1839 |
def visit_citation_reference(self, node) -> None: |
| 1840 |
if self.bibtex: |
| 1841 |
self._bibitems.append([node.astext()]) |
| 1842 |
if self.use_latex_citations: |
| 1843 |
if not self.inside_citation_reference_label: |
| 1844 |
self.out.append(r'\cite{') |
| 1845 |
self.inside_citation_reference_label = True |
| 1846 |
else: |
| 1847 |
assert self.out[-1] in (' ', '\n'), \ |
| 1848 |
'unexpected non-whitespace while in reference label' |
| 1849 |
del self.out[-1] |
| 1850 |
else: |
| 1851 |
href = '' |
| 1852 |
if 'refid' in node: |
| 1853 |
href = node['refid'] |
| 1854 |
elif 'refname' in node: |
| 1855 |
href = self.document.nameids[node['refname']] |
| 1856 |
self.out.append('\\hyperlink{%s}{[' % href) |
| 1857 |
|
| 1858 |
def depart_citation_reference(self, node) -> None: |
| 1859 |
# TODO: normalize labels |
| 1860 |
if self.use_latex_citations: |
| 1861 |
followup_citation = False |
| 1862 |
# check for a following citation separated by a space or newline |
| 1863 |
sibling = node.next_node(descend=False, siblings=True) |
| 1864 |
if (isinstance(sibling, nodes.Text) |
| 1865 |
and sibling.astext() in (' ', '\n')): |
| 1866 |
sibling2 = sibling.next_node(descend=False, siblings=True) |
| 1867 |
if isinstance(sibling2, nodes.citation_reference): |
| 1868 |
followup_citation = True |
| 1869 |
if followup_citation: |
| 1870 |
self.out.append(',') |
| 1871 |
else: |
| 1872 |
self.out.append('}') |
| 1873 |
self.inside_citation_reference_label = False |
| 1874 |
else: |
| 1875 |
self.out.append(']}') |
| 1876 |
|
| 1877 |
def visit_classifier(self, node) -> None: |
| 1878 |
self.out.append('(\\textbf{') |
| 1879 |
|
| 1880 |
def depart_classifier(self, node) -> None: |
| 1881 |
self.out.append('})') |
| 1882 |
if node.next_node(nodes.term, descend=False, siblings=True): |
| 1883 |
self.out.append('\n') |
| 1884 |
|
| 1885 |
def visit_colspec(self, node) -> None: |
| 1886 |
self.active_table.visit_colspec(node) |
| 1887 |
|
| 1888 |
def depart_colspec(self, node) -> None: |
| 1889 |
pass |
| 1890 |
|
| 1891 |
def visit_comment(self, node): |
| 1892 |
if not isinstance(node.parent, nodes.compound): |
| 1893 |
self.out.append('\n') |
| 1894 |
# Precede every line with a comment sign, wrap in newlines |
| 1895 |
self.out.append('%% %s\n' % node.astext().replace('\n', '\n% ')) |
| 1896 |
raise nodes.SkipNode |
| 1897 |
|
| 1898 |
def depart_comment(self, node) -> None: |
| 1899 |
pass |
| 1900 |
|
| 1901 |
def visit_compound(self, node) -> None: |
| 1902 |
if isinstance(node.parent, nodes.compound): |
| 1903 |
self.out.append('\n') |
| 1904 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 1905 |
node['classes'].insert(0, 'compound') |
| 1906 |
self.duclass_open(node) |
| 1907 |
|
| 1908 |
def depart_compound(self, node) -> None: |
| 1909 |
self.duclass_close(node) |
| 1910 |
|
| 1911 |
def visit_contact(self, node) -> None: |
| 1912 |
self.visit_docinfo_item(node) |
| 1913 |
|
| 1914 |
def depart_contact(self, node) -> None: |
| 1915 |
self.depart_docinfo_item(node) |
| 1916 |
|
| 1917 |
def visit_container(self, node) -> None: |
| 1918 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 1919 |
self.duclass_open(node) |
| 1920 |
|
| 1921 |
def depart_container(self, node) -> None: |
| 1922 |
self.duclass_close(node) |
| 1923 |
|
| 1924 |
def visit_copyright(self, node) -> None: |
| 1925 |
self.visit_docinfo_item(node) |
| 1926 |
|
| 1927 |
def depart_copyright(self, node) -> None: |
| 1928 |
self.depart_docinfo_item(node) |
| 1929 |
|
| 1930 |
def visit_date(self, node) -> None: |
| 1931 |
self.visit_docinfo_item(node) |
| 1932 |
|
| 1933 |
def depart_date(self, node) -> None: |
| 1934 |
self.depart_docinfo_item(node) |
| 1935 |
|
| 1936 |
def visit_decoration(self, node) -> None: |
| 1937 |
# header and footer |
| 1938 |
pass |
| 1939 |
|
| 1940 |
def depart_decoration(self, node) -> None: |
| 1941 |
pass |
| 1942 |
|
| 1943 |
def visit_definition(self, node) -> None: |
| 1944 |
pass |
| 1945 |
|
| 1946 |
def depart_definition(self, node) -> None: |
| 1947 |
pass |
| 1948 |
|
| 1949 |
def visit_definition_list(self, node) -> None: |
| 1950 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 1951 |
self.duclass_open(node) |
| 1952 |
self.out.append('\\begin{description}\n') |
| 1953 |
|
| 1954 |
def depart_definition_list(self, node) -> None: |
| 1955 |
self.out.append('\\end{description}\n') |
| 1956 |
self.duclass_close(node) |
| 1957 |
|
| 1958 |
def visit_definition_list_item(self, node) -> None: |
| 1959 |
self.out += self.ids_to_labels(node, newline=True) |
| 1960 |
|
| 1961 |
def depart_definition_list_item(self, node) -> None: |
| 1962 |
if node.next_node(descend=False, siblings=True) is not None: |
| 1963 |
self.out.append('\n') # TODO: just pass? |
| 1964 |
|
| 1965 |
def visit_description(self, node) -> None: |
| 1966 |
self.out.append(' ') |
| 1967 |
|
| 1968 |
def depart_description(self, node) -> None: |
| 1969 |
pass |
| 1970 |
|
| 1971 |
def visit_docinfo(self, node) -> None: |
| 1972 |
self.push_output_collector(self.docinfo) |
| 1973 |
|
| 1974 |
def depart_docinfo(self, node) -> None: |
| 1975 |
self.pop_output_collector() |
| 1976 |
# Some itmes (e.g. author) end up at other places |
| 1977 |
if self.docinfo: |
| 1978 |
# tabularx: automatic width of columns, no page breaks allowed. |
| 1979 |
self.requirements['tabularx'] = r'\usepackage{tabularx}' |
| 1980 |
self.provide_fallback('providelength', '_providelength') |
| 1981 |
self.provide_fallback('docinfo') |
| 1982 |
# |
| 1983 |
self.docinfo.insert(0, '\n% Docinfo\n' |
| 1984 |
'\\begin{center}\n' |
| 1985 |
'\\begin{tabularx}{\\DUdocinfowidth}{lX}\n') |
| 1986 |
self.docinfo.append('\\end{tabularx}\n' |
| 1987 |
'\\end{center}\n') |
| 1988 |
|
| 1989 |
def visit_docinfo_item(self, node, name=None) -> None: |
| 1990 |
# auxiliary method, called by the visitors of "bibliographic elements" |
| 1991 |
if name is not None: |
| 1992 |
warnings.warn('visit_docinfo_item(): argument "name" is obsolete' |
| 1993 |
' and will be removed in Docutils 0.24', |
| 1994 |
DeprecationWarning, stacklevel=2) |
| 1995 |
if self.use_latex_docinfo and isinstance(node, self.TITLEDATA_NODES): |
| 1996 |
self.push_output_collector([]) # see depart_docinfo_item() |
| 1997 |
else: |
| 1998 |
label = self.language_label(node.tagname) |
| 1999 |
self.out.append('\\textbf{%s}: &' % label) |
| 2000 |
if isinstance(node, nodes.address): |
| 2001 |
self.out.append(' {\\raggedright\n') |
| 2002 |
elif len(label) + len(node.astext()) > 64: |
| 2003 |
self.out.append('\n ') |
| 2004 |
else: |
| 2005 |
self.out.append(' ') |
| 2006 |
if isinstance(node, nodes.authors): |
| 2007 |
self.push_output_collector([]) # collect author names |
| 2008 |
|
| 2009 |
def depart_docinfo_item(self, node) -> None: |
| 2010 |
if self.use_latex_docinfo and isinstance(node, self.TITLEDATA_NODES): |
| 2011 |
# Prepare data for use in `self.make_title()` |
| 2012 |
if isinstance(node, nodes.authors): |
| 2013 |
# join author names with "\and" or, |
| 2014 |
# if there is shared author info, with "\quad" |
| 2015 |
# (cf. https://tex.stackexchange.com/a/11656/288060) |
| 2016 |
s = r' \and ' |
| 2017 |
for nn in node.findall(include_self=False, descend=False, |
| 2018 |
siblings=True): |
| 2019 |
if isinstance(nn, (nodes.author, nodes.authors)): |
| 2020 |
break |
| 2021 |
if isinstance(nn, (nodes.address, nodes.contact, |
| 2022 |
nodes.organization)): |
| 2023 |
s = r' \quad ' |
| 2024 |
else: |
| 2025 |
s = '' |
| 2026 |
text = s.join(self.pop_output_collector()) |
| 2027 |
|
| 2028 |
if isinstance(node, nodes.date): |
| 2029 |
self.date.append(text) |
| 2030 |
elif isinstance(node, (nodes.author, nodes.authors)): |
| 2031 |
# Insert author name(s) as first item of an "author info" list, |
| 2032 |
# starting a new list if author name already set: |
| 2033 |
if self.author_stack[-1][0]: |
| 2034 |
self.author_stack.append([text]) |
| 2035 |
else: |
| 2036 |
self.author_stack[-1][0] = text |
| 2037 |
else: |
| 2038 |
# Append affiliation & contact info to current "author info". |
| 2039 |
self.author_stack[-1].append(text) |
| 2040 |
else: |
| 2041 |
if isinstance(node, nodes.address): |
| 2042 |
self.out.append('}') |
| 2043 |
elif isinstance(node, nodes.authors): |
| 2044 |
author_names = self.pop_output_collector() |
| 2045 |
# get last "author separator" that is not in any author name |
| 2046 |
for sep in reversed(self.language_module.author_separators): |
| 2047 |
if not any(sep in name for name in author_names): |
| 2048 |
break |
| 2049 |
self.out.append((sep+' ').join(author_names)) |
| 2050 |
self.out.append(' \\\\\n') |
| 2051 |
|
| 2052 |
def visit_doctest_block(self, node) -> None: |
| 2053 |
self.visit_literal_block(node) |
| 2054 |
|
| 2055 |
def depart_doctest_block(self, node) -> None: |
| 2056 |
self.depart_literal_block(node) |
| 2057 |
|
| 2058 |
def visit_document(self, node) -> None: |
| 2059 |
# titled document? |
| 2060 |
if self.use_latex_docinfo or isinstance(node.next_node(), nodes.title): |
| 2061 |
protect = (self.settings.documentclass == 'memoir') |
| 2062 |
self.title_labels += self.ids_to_labels(node, set_anchor=False, |
| 2063 |
protect=protect) |
| 2064 |
|
| 2065 |
def depart_document(self, node) -> None: |
| 2066 |
# Complete "parts" with information gained from walkabout |
| 2067 |
# * language setup |
| 2068 |
if (self.babel.otherlanguages |
| 2069 |
or self.babel.language not in ('', 'english')): |
| 2070 |
self.requirements['babel'] = self.babel() |
| 2071 |
# * PDF properties |
| 2072 |
self.pdfsetup.append(PreambleCmds.linking % self.hyperref_options) |
| 2073 |
if self.document.get('title', ''): |
| 2074 |
self.pdfinfo.insert(0, ' pdftitle={%s},' % |
| 2075 |
self.encode(self.document.get('title', ''))) |
| 2076 |
if self.pdfauthor: |
| 2077 |
authors = (self.author_separator + ' ').join(self.pdfauthor) |
| 2078 |
self.pdfinfo.append(' pdfauthor={%s}' % authors) |
| 2079 |
if self.pdfinfo: |
| 2080 |
self.pdfsetup += [r'\hypersetup{'] + self.pdfinfo + ['}'] |
| 2081 |
# * title (including author(s) and date if using "latex_docinfo") |
| 2082 |
if self.title or self.date or self.author_stack != [['']]: |
| 2083 |
self.make_title() # see below |
| 2084 |
# * bibliography |
| 2085 |
if self._bibitems: |
| 2086 |
self.append_bibliogaphy() # see below |
| 2087 |
# * make sure to generate a toc file if needed for local contents: |
| 2088 |
if 'minitoc' in self.requirements and not self.has_latex_toc: |
| 2089 |
self.out.append('\n\\faketableofcontents % for local ToCs\n') |
| 2090 |
# * conditional requirements (before style sheet) |
| 2091 |
self.requirements = [self.requirements[key] |
| 2092 |
for key in sorted(self.requirements.keys())] |
| 2093 |
# * coditional fallback definitions (after style sheet) |
| 2094 |
self.fallbacks = [self.fallbacks[key] |
| 2095 |
for key in sorted(self.fallbacks.keys())] |
| 2096 |
|
| 2097 |
def make_title(self) -> None: |
| 2098 |
# Auxiliary function called by `self.depart_document()`. |
| 2099 |
# |
| 2100 |
# The document title is stored in the "titledata" document part. |
| 2101 |
# Date and author info is included with "use_latex_docinfo". |
| 2102 |
# However, we need the ``\title``, ``\author``, and ``\date`` |
| 2103 |
# macros even if empty, to prevent errors and/or automatic |
| 2104 |
# display of the current date by ``\maketitle``. |
| 2105 |
|
| 2106 |
# \title |
| 2107 |
title_arg = [''.join(self.title)] # ensure len == 1 |
| 2108 |
if self.title: |
| 2109 |
title_arg += self.title_labels |
| 2110 |
if self.subtitle: |
| 2111 |
title_arg += [r'\\', |
| 2112 |
r'\DUdocumentsubtitle{%s}' % ''.join(self.subtitle), |
| 2113 |
] + self.subtitle_labels |
| 2114 |
self.titledata.append(r'\title{%s}' % '%\n '.join(title_arg)) |
| 2115 |
# \author |
| 2116 |
# author name(s) and optional affiliation and contact info |
| 2117 |
# cf. https://tex.stackexchange.com/a/377030/288060. |
| 2118 |
authors = ['\\\\\n'.join(filter(None, author_entry)) |
| 2119 |
for author_entry in self.author_stack] |
| 2120 |
self.titledata.append(r'\author{%s}' % ' \\and\n'.join(authors)) |
| 2121 |
# \date |
| 2122 |
self.titledata.append(r'\date{%s}' % ', '.join(self.date)) |
| 2123 |
# \maketitle |
| 2124 |
# Must be in the document body. Append to "body_pre_docinfo" part |
| 2125 |
# so templates may use the "titledata" part in the document preamble. |
| 2126 |
self.body_pre_docinfo.append('\\maketitle\n') |
| 2127 |
|
| 2128 |
def append_bibliogaphy(self) -> None: |
| 2129 |
# Add bibliography at end of document. |
| 2130 |
# TODO insertion point should be configurable. |
| 2131 |
# Auxiliary function called by `depart_document`. |
| 2132 |
if self.bibtex: |
| 2133 |
self.out.append('\n\\bibliographystyle{%s}\n' % self.bibtex[0]) |
| 2134 |
self.out.append('\\bibliography{%s}\n' % ','.join(self.bibtex[1:])) |
| 2135 |
elif self.use_latex_citations: |
| 2136 |
# TODO: insert citations at point of definition. |
| 2137 |
widest_label = '' |
| 2138 |
for bibitem in self._bibitems: |
| 2139 |
if len(widest_label) < len(bibitem[0]): |
| 2140 |
widest_label = bibitem[0] |
| 2141 |
self.out.append('\n\\begin{thebibliography}{%s}\n' % |
| 2142 |
widest_label) |
| 2143 |
for bibitem in self._bibitems: |
| 2144 |
# cite_key: underscores must not be escaped |
| 2145 |
cite_key = bibitem[0].replace(r'\_', '_') |
| 2146 |
self.out.append('\\bibitem[%s]{%s}{%s}\n' % |
| 2147 |
(bibitem[0], cite_key, bibitem[1])) |
| 2148 |
self.out.append('\\end{thebibliography}\n') |
| 2149 |
|
| 2150 |
def visit_emphasis(self, node) -> None: |
| 2151 |
self.out.append('\\emph{') |
| 2152 |
self.visit_inline(node) |
| 2153 |
|
| 2154 |
def depart_emphasis(self, node) -> None: |
| 2155 |
self.depart_inline(node) |
| 2156 |
self.out.append('}') |
| 2157 |
|
| 2158 |
# Append column delimiters and advance column counter, |
| 2159 |
# if the current cell is a multi-row continuation.""" |
| 2160 |
def insert_additional_table_colum_delimiters(self) -> None: |
| 2161 |
while self.active_table.get_rowspan( |
| 2162 |
self.active_table.get_entry_number()): |
| 2163 |
self.out.append(' & ') |
| 2164 |
self.active_table.visit_entry() # increment cell count |
| 2165 |
|
| 2166 |
def visit_entry(self, node): |
| 2167 |
# cell separation |
| 2168 |
if self.active_table.get_entry_number() == 0: |
| 2169 |
self.insert_additional_table_colum_delimiters() |
| 2170 |
else: |
| 2171 |
self.out.append(' & ') |
| 2172 |
|
| 2173 |
# multirow, multicolumn |
| 2174 |
if 'morerows' in node and 'morecols' in node: |
| 2175 |
raise NotImplementedError('Cells that span multiple rows *and* ' |
| 2176 |
'columns currently not supported ' |
| 2177 |
'by the LaTeX writer') |
| 2178 |
# TODO: should be possible with LaTeX, see e.g. |
| 2179 |
# http://texblog.org/2012/12/21/multi-column-and-multi-row-cells-in-latex-tables/ |
| 2180 |
# multirow in LaTeX simply will enlarge the cell over several rows |
| 2181 |
# (the following n if n is positive, the former if negative). |
| 2182 |
if 'morerows' in node: |
| 2183 |
self.requirements['multirow'] = r'\usepackage{multirow}' |
| 2184 |
mrows = node['morerows'] + 1 |
| 2185 |
self.active_table.set_rowspan( |
| 2186 |
self.active_table.get_entry_number(), mrows) |
| 2187 |
self.out.append('\\multirow{%d}{%s}{' % |
| 2188 |
(mrows, self.active_table.get_column_width())) |
| 2189 |
self.context.append('}') |
| 2190 |
elif 'morecols' in node: |
| 2191 |
# the vertical bar before column is missing if it is the first |
| 2192 |
# column. the one after always. |
| 2193 |
if self.active_table.get_entry_number() == 0: |
| 2194 |
bar1 = self.active_table.get_vertical_bar() |
| 2195 |
else: |
| 2196 |
bar1 = '' |
| 2197 |
mcols = node['morecols'] + 1 |
| 2198 |
self.out.append('\\multicolumn{%d}{%s%s%s}{' % |
| 2199 |
(mcols, |
| 2200 |
bar1, |
| 2201 |
self.active_table.get_multicolumn_width( |
| 2202 |
self.active_table.get_entry_number(), mcols), |
| 2203 |
self.active_table.get_vertical_bar())) |
| 2204 |
self.context.append('}') |
| 2205 |
else: |
| 2206 |
self.context.append('') |
| 2207 |
|
| 2208 |
# bold header/stub-column |
| 2209 |
if len(node) and (isinstance(node.parent.parent, nodes.thead) |
| 2210 |
or self.active_table.is_stub_column()): |
| 2211 |
self.out.append('\\textbf{') |
| 2212 |
self.context.append('}') |
| 2213 |
else: |
| 2214 |
self.context.append('') |
| 2215 |
|
| 2216 |
# if line ends with '{', mask line break |
| 2217 |
if (not self.active_table.colwidths_auto |
| 2218 |
and self.out[-1].endswith("{") |
| 2219 |
and node.astext()): |
| 2220 |
self.out.append("%") |
| 2221 |
|
| 2222 |
self.active_table.visit_entry() # increment cell count |
| 2223 |
|
| 2224 |
def depart_entry(self, node) -> None: |
| 2225 |
self.out.append(self.context.pop()) # header / not header |
| 2226 |
self.out.append(self.context.pop()) # multirow/column |
| 2227 |
# insert extra "&"s, if following rows are spanned from above: |
| 2228 |
self.insert_additional_table_colum_delimiters() |
| 2229 |
|
| 2230 |
def visit_row(self, node) -> None: |
| 2231 |
self.active_table.visit_row() |
| 2232 |
|
| 2233 |
def depart_row(self, node) -> None: |
| 2234 |
self.out.extend(self.active_table.depart_row()) |
| 2235 |
|
| 2236 |
def visit_enumerated_list(self, node) -> None: |
| 2237 |
# enumeration styles: |
| 2238 |
types = {'': '', |
| 2239 |
'arabic': 'arabic', |
| 2240 |
'loweralpha': 'alph', |
| 2241 |
'upperalpha': 'Alph', |
| 2242 |
'lowerroman': 'roman', |
| 2243 |
'upperroman': 'Roman'} |
| 2244 |
# default LaTeX enumeration labels: |
| 2245 |
default_labels = [ |
| 2246 |
# (präfix, enumtype, suffix) |
| 2247 |
('', 'arabic', '.'), # 1. |
| 2248 |
('(', 'alph', ')'), # (a) |
| 2249 |
('', 'roman', '.'), # i. |
| 2250 |
('', 'Alph', '.')] # A. |
| 2251 |
|
| 2252 |
prefix = '' |
| 2253 |
if self.compound_enumerators: |
| 2254 |
if (self.section_prefix_for_enumerators and self.section_level |
| 2255 |
and not self._enumeration_counters): |
| 2256 |
prefix = '.'.join(str(n) for n in |
| 2257 |
self._section_number[:self.section_level] |
| 2258 |
) + self.section_enumerator_separator |
| 2259 |
if self._enumeration_counters: |
| 2260 |
prefix += self._enumeration_counters[-1] |
| 2261 |
prefix += node.get('prefix', '') |
| 2262 |
enumtype = types[node.get('enumtype', 'arabic')] |
| 2263 |
suffix = node.get('suffix', '.') |
| 2264 |
|
| 2265 |
enum_level = len(self._enumeration_counters)+1 |
| 2266 |
counter_name = 'enum' + RomanNumeral(enum_level).to_lowercase() |
| 2267 |
label = r'%s\%s{%s}%s' % (prefix, enumtype, counter_name, suffix) |
| 2268 |
self._enumeration_counters.append(label) |
| 2269 |
|
| 2270 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 2271 |
self.duclass_open(node) |
| 2272 |
if enum_level <= 4: |
| 2273 |
self.out.append('\\begin{enumerate}') |
| 2274 |
if (prefix, enumtype, suffix) != default_labels[enum_level-1]: |
| 2275 |
self.out.append('\n\\renewcommand{\\label%s}{%s}' % |
| 2276 |
(counter_name, label)) |
| 2277 |
else: |
| 2278 |
self.fallbacks[counter_name] = '\\newcounter{%s}' % counter_name |
| 2279 |
self.out.append('\\begin{list}') |
| 2280 |
self.out.append('{%s}' % label) |
| 2281 |
self.out.append('{\\usecounter{%s}}' % counter_name) |
| 2282 |
if 'start' in node: |
| 2283 |
self.out.append('\n\\setcounter{%s}{%d}' % |
| 2284 |
(counter_name, node['start']-1)) |
| 2285 |
|
| 2286 |
def depart_enumerated_list(self, node) -> None: |
| 2287 |
if len(self._enumeration_counters) <= 4: |
| 2288 |
self.out.append('\\end{enumerate}\n') |
| 2289 |
else: |
| 2290 |
self.out.append('\\end{list}\n') |
| 2291 |
self.duclass_close(node) |
| 2292 |
self._enumeration_counters.pop() |
| 2293 |
|
| 2294 |
def visit_field(self, node) -> None: |
| 2295 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 2296 |
# output is done in field_body, field_name |
| 2297 |
|
| 2298 |
def depart_field(self, node) -> None: |
| 2299 |
pass |
| 2300 |
|
| 2301 |
def visit_field_body(self, node) -> None: |
| 2302 |
if not isinstance(node.parent.parent, nodes.docinfo): |
| 2303 |
self.out.append(self.term_postfix(node)) |
| 2304 |
|
| 2305 |
def depart_field_body(self, node) -> None: |
| 2306 |
if self.out is self.docinfo: |
| 2307 |
self.out.append(r'\\'+'\n') |
| 2308 |
|
| 2309 |
def visit_field_list(self, node) -> None: |
| 2310 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 2311 |
self.duclass_open(node) |
| 2312 |
if self.out is not self.docinfo: |
| 2313 |
self.provide_fallback('fieldlist') |
| 2314 |
self.out.append('\\begin{DUfieldlist}') |
| 2315 |
|
| 2316 |
def depart_field_list(self, node) -> None: |
| 2317 |
if self.out is not self.docinfo: |
| 2318 |
self.out.append('\\end{DUfieldlist}\n') |
| 2319 |
self.duclass_close(node) |
| 2320 |
|
| 2321 |
def visit_field_name(self, node) -> None: |
| 2322 |
if self.out is self.docinfo: |
| 2323 |
self.out.append('\\textbf{') |
| 2324 |
else: |
| 2325 |
# Commands with optional args inside an optional arg must be put |
| 2326 |
# in a group, e.g. ``\item[{\hyperref[label]{text}}]``. |
| 2327 |
self.out.append('\n\\item[{') |
| 2328 |
|
| 2329 |
def depart_field_name(self, node) -> None: |
| 2330 |
if self.out is self.docinfo: |
| 2331 |
self.out.append('}: &') |
| 2332 |
else: |
| 2333 |
self.out.append(':}]') |
| 2334 |
|
| 2335 |
def visit_figure(self, node) -> None: |
| 2336 |
self.requirements['float'] = PreambleCmds.float |
| 2337 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 2338 |
self.duclass_open(node) |
| 2339 |
# The 'align' attribute sets the "outer alignment", |
| 2340 |
# for "inner alignment" use LaTeX default alignment (similar to HTML) |
| 2341 |
alignment = node.attributes.get('align', 'center') |
| 2342 |
if alignment != 'center': |
| 2343 |
# The LaTeX "figure" environment always uses the full linewidth, |
| 2344 |
# so "outer alignment" is ignored. Just write a comment. |
| 2345 |
# TODO: use the wrapfigure environment? |
| 2346 |
self.out.append('\\begin{figure} %% align = "%s"' % alignment) |
| 2347 |
else: |
| 2348 |
self.out.append('\\begin{figure}') |
| 2349 |
|
| 2350 |
def depart_figure(self, node) -> None: |
| 2351 |
self.out.append('\\end{figure}\n') |
| 2352 |
self.duclass_close(node) |
| 2353 |
|
| 2354 |
def visit_footer(self, node) -> None: |
| 2355 |
self.push_output_collector([]) |
| 2356 |
self.out.append(r'\newcommand{\DUfooter}{') |
| 2357 |
|
| 2358 |
def depart_footer(self, node) -> None: |
| 2359 |
self.out.append('}') |
| 2360 |
self.requirements['~footer'] = ''.join(self.out) |
| 2361 |
self.pop_output_collector() |
| 2362 |
|
| 2363 |
def visit_footnote(self, node) -> None: |
| 2364 |
if not self.latex_footnotes: |
| 2365 |
try: |
| 2366 |
backref = node['backrefs'][0] |
| 2367 |
except IndexError: |
| 2368 |
backref = '' # no backref, keep empty |
| 2369 |
self.provide_fallback('footnotes') |
| 2370 |
label = self.encode(node[0].astext()) |
| 2371 |
if self.settings.footnote_references == 'brackets': |
| 2372 |
label = '[%s]' % label |
| 2373 |
self.out.append('%%\n\\DUfootnotetext{%s}{%s}{%s}{%%' % |
| 2374 |
(node['ids'][0], backref, label)) |
| 2375 |
elif not self.footnote_queue: |
| 2376 |
# latex-footnotes: set only scheduled footnotes |
| 2377 |
# (see `visit_footnote_reference()`) |
| 2378 |
raise nodes.SkipNode |
| 2379 |
|
| 2380 |
def depart_footnote(self, node) -> None: |
| 2381 |
# prevent overlap with next note if footnote ends with "admonition": |
| 2382 |
if isinstance(node[-1], nodes.Admonition): |
| 2383 |
self.out.append('\\smallskip') |
| 2384 |
if not self.latex_footnotes: |
| 2385 |
self.out.append('}\n') |
| 2386 |
|
| 2387 |
def visit_footnote_reference(self, node) -> None: |
| 2388 |
href = node['refid'] |
| 2389 |
if not self.latex_footnotes: |
| 2390 |
if isinstance(node.parent, nodes.title): |
| 2391 |
if isinstance(node.parent.parent, nodes.section): |
| 2392 |
self.out.append('\\texorpdfstring{') |
| 2393 |
self.out.append('\\protect') |
| 2394 |
if self.settings.footnote_references == 'brackets': |
| 2395 |
self.provide_fallback('bracket_footnoterefs') |
| 2396 |
cmd = r'\DUbracketfootnotemark' |
| 2397 |
else: |
| 2398 |
self.provide_fallback('footnotes') |
| 2399 |
cmd = r'\DUfootnotemark' |
| 2400 |
self.out.append(r'%s{%s}{%s}{' % (cmd, node['ids'][0], href)) |
| 2401 |
else: # latex-footnotes |
| 2402 |
target = self.document.ids[href] |
| 2403 |
if not isinstance(target, nodes.footnote): |
| 2404 |
self.out.append(r'\textsuperscript{') |
| 2405 |
self.visit_reference(node) |
| 2406 |
return |
| 2407 |
if href in self.processed_footnotes: |
| 2408 |
# footnote is already set, just insert a reference: |
| 2409 |
self.out.append(r'\footref{%s}' % href) |
| 2410 |
raise nodes.SkipNode |
| 2411 |
if self.footnote_queue: |
| 2412 |
# nested footnote: insert reference now and text later |
| 2413 |
self.out.append(r'\footref{%s}' % href) |
| 2414 |
self.footnote_queue.append(href) |
| 2415 |
raise nodes.SkipNode |
| 2416 |
# `target` is a new top-level footnote: |
| 2417 |
self.footnote_queue.append(href) |
| 2418 |
footnote_cmd = '%\n\\footnote' |
| 2419 |
if isinstance(node.parent, nodes.title): |
| 2420 |
if isinstance(node.parent.parent, nodes.section): |
| 2421 |
self.out.append('%\n\\texorpdfstring{') |
| 2422 |
footnote_cmd = '%\n \\protect\\footnote' |
| 2423 |
add_label = target['names'] and self.document.refnames.get( |
| 2424 |
target['names'][0], []) |
| 2425 |
while self.footnote_queue: |
| 2426 |
ID = self.footnote_queue[0] |
| 2427 |
footnote = self.document.ids[ID] |
| 2428 |
self.processed_footnotes.add(ID) # keep ID for re-references |
| 2429 |
self.out += [footnote_cmd, '{'] |
| 2430 |
if add_label: |
| 2431 |
self.out += [r'\label{', ID, '}'] |
| 2432 |
self.out.append('%') |
| 2433 |
# get footnote content |
| 2434 |
self.push_output_collector([]) |
| 2435 |
footnote.walkabout(self) # visit/depart footnote & content |
| 2436 |
note = ''.join(self.pop_output_collector()) |
| 2437 |
# indent lines |
| 2438 |
note = '\n '.join(note.splitlines()) |
| 2439 |
self.out.append(note) |
| 2440 |
self.out.append('\n}') |
| 2441 |
self.footnote_queue.pop(0) |
| 2442 |
# subsequent items have their reference already set: |
| 2443 |
footnote_cmd = '%\n\\refstepcounter{footnote}\\footnotetext' |
| 2444 |
add_label = True |
| 2445 |
raise nodes.SkipChildren # ignore content (footnote number/symbol) |
| 2446 |
|
| 2447 |
def depart_footnote_reference(self, node) -> None: |
| 2448 |
if not self.latex_footnotes: |
| 2449 |
self.out.append('}') |
| 2450 |
elif not isinstance(self.document.ids[node['refid']], nodes.footnote): |
| 2451 |
self.depart_reference(node) |
| 2452 |
self.out.append('}') |
| 2453 |
return |
| 2454 |
if isinstance(node.parent.parent, nodes.section |
| 2455 |
) and isinstance(node.parent, nodes.title): |
| 2456 |
self.out.append('}{}') |
| 2457 |
|
| 2458 |
# footnote/citation label |
| 2459 |
def label_delim(self, node, bracket, superscript): |
| 2460 |
if isinstance(node.parent, nodes.footnote): |
| 2461 |
raise nodes.SkipNode |
| 2462 |
else: |
| 2463 |
assert isinstance(node.parent, nodes.citation) |
| 2464 |
if not self.use_latex_citations: |
| 2465 |
self.out.append(bracket) |
| 2466 |
|
| 2467 |
def visit_label(self, node) -> None: |
| 2468 |
"""footnote or citation label: in brackets or as superscript""" |
| 2469 |
self.label_delim(node, '[', '\\textsuperscript{') |
| 2470 |
|
| 2471 |
def depart_label(self, node) -> None: |
| 2472 |
self.label_delim(node, ']', '}') |
| 2473 |
|
| 2474 |
# elements generated by the framework e.g. section numbers. |
| 2475 |
def visit_generated(self, node) -> None: |
| 2476 |
pass |
| 2477 |
|
| 2478 |
def depart_generated(self, node) -> None: |
| 2479 |
pass |
| 2480 |
|
| 2481 |
def visit_header(self, node) -> None: |
| 2482 |
self.push_output_collector([]) |
| 2483 |
self.out.append(r'\newcommand{\DUheader}{') |
| 2484 |
|
| 2485 |
def depart_header(self, node) -> None: |
| 2486 |
self.out.append('}') |
| 2487 |
self.requirements['~header'] = ''.join(self.out) |
| 2488 |
self.pop_output_collector() |
| 2489 |
|
| 2490 |
def to_latex_length(self, length_str, node=None) -> str: |
| 2491 |
"""Convert "measure" `length_str` to LaTeX length specification. |
| 2492 |
|
| 2493 |
Note: the default length unit will change from "bp" |
| 2494 |
(Postscript point) to "px" in Docutils 1.0. |
| 2495 |
""" |
| 2496 |
value, unit = nodes.parse_measure(length_str) |
| 2497 |
if unit in ('em', 'ex', 'cm', 'mm', 'in', 'pc', 'px', |
| 2498 |
'bp', 'cc', 'dd', 'sp', 'mu'): # TeX unit == CSS unit |
| 2499 |
return length_str |
| 2500 |
if unit in ('', 'pt'): # no unit or "Postscript points" |
| 2501 |
return f'{value}bp' # LaTeX uses symbol "bp" |
| 2502 |
if unit == 'Q': |
| 2503 |
return f'{value/4}mm' |
| 2504 |
if unit == '%': # percentage: relate to current line width |
| 2505 |
return f'{value/100:g}\\linewidth' |
| 2506 |
if unit == 'vw': # viewport width: relate to page width |
| 2507 |
return f'{value/100:g}\\paperwidth' |
| 2508 |
if unit == 'vh': # viewport height: relate to page height |
| 2509 |
return f'{value/100:g}\\paperheight' |
| 2510 |
# emulate with macro modelled on pdfLaTeX's \pdfpxdimen |
| 2511 |
if not hasattr(PreambleCmds, unit): |
| 2512 |
self.warn(f'Unit "{unit}" not supported by LaTeX.\n' |
| 2513 |
f' Define lenght "\\DU{unit}dimen" in preamble,' |
| 2514 |
' raw LaTeX, or custom stylesheet.', |
| 2515 |
base_node=node) |
| 2516 |
elif unit == 'ch': |
| 2517 |
self.fallbacks['ch'] = PreambleCmds.ch |
| 2518 |
else: |
| 2519 |
self.provide_fallback('providelength', '_providelength') |
| 2520 |
self.provide_fallback(unit) |
| 2521 |
return f'{value}\\DU{unit}dimen' |
| 2522 |
|
| 2523 |
def visit_image(self, node) -> None: |
| 2524 |
# <image> can be inline element, body element, or nested in a <figure> |
| 2525 |
# in all three cases the <image> may also be nested in a <reference> |
| 2526 |
# TODO: "classes" attribute currently ignored! |
| 2527 |
self.requirements['graphicx'] = self.graphicx_package |
| 2528 |
attrs = node.attributes |
| 2529 |
# convert image URI to filesystem path, do not adjust relative path: |
| 2530 |
imagepath = self.uri2path(attrs['uri'], output_path='') |
| 2531 |
# alignment defaults: |
| 2532 |
if 'align' not in attrs: |
| 2533 |
# Set default align of image in a figure to 'center' |
| 2534 |
if (isinstance(node.parent, nodes.figure) |
| 2535 |
or isinstance(node.parent, nodes.reference) |
| 2536 |
and isinstance(node.parent.parent, nodes.figure)): |
| 2537 |
attrs['align'] = 'center' |
| 2538 |
self.set_align_from_classes(node) |
| 2539 |
# pre- and postfix (prefix inserted in reverse order) |
| 2540 |
pre = [] |
| 2541 |
post = [] |
| 2542 |
include_graphics_options = [] |
| 2543 |
if isinstance(node.parent, nodes.reference): |
| 2544 |
pre.append(self.out.pop()) # move \href behind alignment code |
| 2545 |
align_codes = { |
| 2546 |
# inline images: by default latex aligns the bottom. |
| 2547 |
'bottom': ('', ''), |
| 2548 |
'middle': (r'\raisebox{-0.5\height}{', '}'), |
| 2549 |
'top': (r'\raisebox{-\height}{', '}'), |
| 2550 |
# block level images: |
| 2551 |
'center': (r'\noindent\makebox[\linewidth][c]{', '}'), |
| 2552 |
'left': (r'\noindent{', r'\hfill}'), |
| 2553 |
'right': (r'\noindent{\hfill', '}'), |
| 2554 |
} |
| 2555 |
if 'align' in attrs: |
| 2556 |
# TODO: warn or ignore non-applicable alignment settings? |
| 2557 |
try: |
| 2558 |
align_code = align_codes[attrs['align']] |
| 2559 |
pre.append(align_code[0]) |
| 2560 |
post.append(align_code[1]) |
| 2561 |
except KeyError: |
| 2562 |
pass # TODO: warn? |
| 2563 |
if 'height' in attrs: |
| 2564 |
include_graphics_options.append( |
| 2565 |
f"height={self.to_latex_length(attrs['height'], node)}") |
| 2566 |
if 'scale' in attrs: |
| 2567 |
include_graphics_options.append(f"scale={attrs['scale']/100:g}") |
| 2568 |
if 'width' in attrs: |
| 2569 |
include_graphics_options.append( |
| 2570 |
f"width={self.to_latex_length(attrs['width'], node)}") |
| 2571 |
pre.append(''.join(self.ids_to_labels(node, newline=True))) |
| 2572 |
if not (self.is_inline(node) |
| 2573 |
or isinstance(node.parent, nodes.compound)): |
| 2574 |
pre.append('\n') |
| 2575 |
if not self.is_inline(node): |
| 2576 |
post.append('\n') |
| 2577 |
pre.reverse() |
| 2578 |
# now insert image code |
| 2579 |
self.out.extend(pre) |
| 2580 |
if imagepath.suffix == '.svg' and 'svg' in self.settings.stylesheet: |
| 2581 |
cmd = 'includesvg' |
| 2582 |
else: |
| 2583 |
cmd = 'includegraphics' |
| 2584 |
options = '' |
| 2585 |
if include_graphics_options: |
| 2586 |
options = f"[{','.join(include_graphics_options)}]" |
| 2587 |
self.out.append(f'\\{cmd}{options}{{{imagepath.as_posix()}}}') |
| 2588 |
self.out.extend(post) |
| 2589 |
|
| 2590 |
def depart_image(self, node) -> None: |
| 2591 |
pass |
| 2592 |
|
| 2593 |
def visit_inline(self, node) -> None: |
| 2594 |
# This function is also called by the visiting functions for |
| 2595 |
# specific inline elements, <caption>, and <paragraph>. |
| 2596 |
|
| 2597 |
# Handle "ids" attribute: |
| 2598 |
# do we need a \phantomsection? |
| 2599 |
anchor_nodes = (nodes.caption, nodes.subtitle, nodes.title) |
| 2600 |
set_anchor = not (isinstance(node.parent, anchor_nodes) |
| 2601 |
or isinstance(node, anchor_nodes)) |
| 2602 |
add_newline = isinstance(node, nodes.paragraph) |
| 2603 |
self.out += self.ids_to_labels(node, set_anchor, newline=add_newline) |
| 2604 |
# Handle "classes" attribute: |
| 2605 |
for cls in node['classes']: |
| 2606 |
if cls.startswith('language-'): |
| 2607 |
language = self.babel.language_name(cls[9:]) |
| 2608 |
if language: |
| 2609 |
self.babel.otherlanguages[language] = True |
| 2610 |
self.out.append(r'\foreignlanguage{%s}{' % language) |
| 2611 |
else: |
| 2612 |
self.provide_fallback('inline') |
| 2613 |
if hasattr(PreambleCmds, f'inline role {cls}'): |
| 2614 |
self.provide_fallback(f'inline role {cls}') |
| 2615 |
if cls in ('del', 'ins', 'mark', 's', 'u'): |
| 2616 |
self.requirements['soul'] = r'\usepackage{soul}' |
| 2617 |
if cls == 'mark': |
| 2618 |
self.requirements['color'] = PreambleCmds.color |
| 2619 |
self.out.append(r'\DUrole{%s}{' % cls) |
| 2620 |
|
| 2621 |
def depart_inline(self, node) -> None: |
| 2622 |
self.out.append('}' * len(node['classes'])) |
| 2623 |
|
| 2624 |
def visit_legend(self, node) -> None: |
| 2625 |
self.provide_fallback('legend') |
| 2626 |
self.out.append('\\begin{DUlegend}') |
| 2627 |
|
| 2628 |
def depart_legend(self, node) -> None: |
| 2629 |
self.out.append('\\end{DUlegend}\n') |
| 2630 |
|
| 2631 |
def visit_line(self, node) -> None: |
| 2632 |
self.out.append(r'\item[] ') |
| 2633 |
|
| 2634 |
def depart_line(self, node) -> None: |
| 2635 |
self.out.append('\n') |
| 2636 |
|
| 2637 |
def visit_line_block(self, node) -> None: |
| 2638 |
self.provide_fallback('providelength', '_providelength') |
| 2639 |
self.provide_fallback('lineblock') |
| 2640 |
self.set_align_from_classes(node) |
| 2641 |
if isinstance(node.parent, nodes.line_block): |
| 2642 |
self.out.append('\\item[]\n' |
| 2643 |
'\\begin{DUlineblock}{\\DUlineblockindent}\n') |
| 2644 |
# In rST, nested line-blocks cannot be given class arguments |
| 2645 |
else: |
| 2646 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 2647 |
self.duclass_open(node) |
| 2648 |
self.out.append('\\begin{DUlineblock}{0em}\n') |
| 2649 |
self.insert_align_declaration(node) |
| 2650 |
|
| 2651 |
def depart_line_block(self, node) -> None: |
| 2652 |
self.out.append('\\end{DUlineblock}\n') |
| 2653 |
self.duclass_close(node) |
| 2654 |
|
| 2655 |
def visit_list_item(self, node) -> None: |
| 2656 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 2657 |
self.out.append('\n\\item ') |
| 2658 |
|
| 2659 |
def depart_list_item(self, node) -> None: |
| 2660 |
pass |
| 2661 |
|
| 2662 |
def visit_literal(self, node) -> None: |
| 2663 |
self.literal = True |
| 2664 |
if ('code' in node['classes'] |
| 2665 |
and self.settings.syntax_highlight != 'none'): |
| 2666 |
self.requirements['color'] = PreambleCmds.color |
| 2667 |
self.provide_fallback('highlight_rules', 'code') |
| 2668 |
self.out.append('\\texttt{') |
| 2669 |
self.visit_inline(node) |
| 2670 |
|
| 2671 |
def depart_literal(self, node) -> None: |
| 2672 |
self.literal = False |
| 2673 |
self.depart_inline(node) |
| 2674 |
self.out.append('}') |
| 2675 |
|
| 2676 |
# <literal_block> elements are used |
| 2677 |
# for literal blocks (where content is not parsed), |
| 2678 |
# for the "code" directive (where content may be parsed by Pygments), and |
| 2679 |
# for the "parsed-literal" directive (where rST inline markup is parsed). |
| 2680 |
# |
| 2681 |
# In all cases, we want to use a monospaced typeface. |
| 2682 |
# If the <literal_block> contains only text, we can use a "verbatim-like" |
| 2683 |
# environment, for mixed content we must use \ttfamily and \raggedright. |
| 2684 |
# |
| 2685 |
# We can distinguish between the use cases looking at the element's |
| 2686 |
# children: if there is a single <Text> child, it is either |
| 2687 |
# * a "real" literal block or |
| 2688 |
# * a parsed-literal that does not contain any markup. |
| 2689 |
def is_plaintext(self, node): |
| 2690 |
"""Check whether `node` contains only text""" |
| 2691 |
return (len(node) == 1) and isinstance(node[0], nodes.Text) |
| 2692 |
|
| 2693 |
def visit_literal_block(self, node) -> None: |
| 2694 |
"""Render a literal block. |
| 2695 |
|
| 2696 |
Corresponding rST elements: literal block, parsed-literal, code. |
| 2697 |
""" |
| 2698 |
packages = {'lstlisting': '\\usepackage{listings}\n' |
| 2699 |
'\\lstset{xleftmargin=\\leftmargin}', |
| 2700 |
'listing': r'\usepackage{moreverb}', |
| 2701 |
'Verbatim': r'\usepackage{fancyvrb}', |
| 2702 |
'verbatimtab': r'\usepackage{moreverb}', |
| 2703 |
} |
| 2704 |
|
| 2705 |
literal_env = self.literal_block_env |
| 2706 |
|
| 2707 |
# Check, if it is possible to use a literal-block environment |
| 2708 |
_plaintext = self.is_plaintext(node) |
| 2709 |
_in_table = self.active_table.is_open() |
| 2710 |
# TODO: fails if normal text precedes the literal block. |
| 2711 |
# Check parent node instead? |
| 2712 |
_autowidth_table = _in_table and self.active_table.colwidths_auto |
| 2713 |
_no_env_nodes = (nodes.footnote, nodes.sidebar) |
| 2714 |
if self.settings.legacy_class_functions: |
| 2715 |
_no_env_nodes += (nodes.admonition, nodes.system_message) |
| 2716 |
_use_env = _plaintext and not isinstance(node.parent, _no_env_nodes) |
| 2717 |
_use_listings = (literal_env == 'lstlisting') and _use_env |
| 2718 |
|
| 2719 |
# Labels and classes: |
| 2720 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 2721 |
self.duclass_open(node) |
| 2722 |
# Highlight code? |
| 2723 |
if (not _plaintext |
| 2724 |
and 'code' in node['classes'] |
| 2725 |
and self.settings.syntax_highlight != 'none'): |
| 2726 |
self.requirements['color'] = PreambleCmds.color |
| 2727 |
self.provide_fallback('highlight_rules', 'code') |
| 2728 |
# Wrap? |
| 2729 |
if _in_table and _use_env and not _autowidth_table: |
| 2730 |
# Wrap in minipage to prevent extra vertical space |
| 2731 |
# with alltt and verbatim-like environments: |
| 2732 |
self.fallbacks['ttem'] = PreambleCmds.ttem |
| 2733 |
self.out.append( |
| 2734 |
'\\begin{minipage}{%d\\ttemwidth}\n' % |
| 2735 |
(max(len(line) for line in node.astext().split('\n')))) |
| 2736 |
self.context.append('\n\\end{minipage}\n') |
| 2737 |
elif not _in_table and not _use_listings: |
| 2738 |
# Wrap in quote to set off vertically and indent |
| 2739 |
self.out.append('\\begin{quote}\n') |
| 2740 |
self.context.append('\n\\end{quote}\n') |
| 2741 |
else: |
| 2742 |
self.context.append('\n') |
| 2743 |
|
| 2744 |
# Use verbatim-like environment, if defined and possible |
| 2745 |
# (in an auto-width table, only listings works): |
| 2746 |
if literal_env and _use_env and (not _autowidth_table |
| 2747 |
or _use_listings): |
| 2748 |
try: |
| 2749 |
self.requirements['literal_block'] = packages[literal_env] |
| 2750 |
except KeyError: |
| 2751 |
pass |
| 2752 |
self.verbatim = True |
| 2753 |
if _in_table and _use_listings: |
| 2754 |
self.out.append('\\lstset{xleftmargin=0pt}\n') |
| 2755 |
self.out.append('\\begin{%s}%s\n' % |
| 2756 |
(literal_env, self.literal_block_options)) |
| 2757 |
self.context.append('\n\\end{%s}' % literal_env) |
| 2758 |
elif _use_env and not _autowidth_table: |
| 2759 |
self.alltt = True |
| 2760 |
self.requirements['alltt'] = r'\usepackage{alltt}' |
| 2761 |
self.out.append('\\begin{alltt}\n') |
| 2762 |
self.context.append('\n\\end{alltt}') |
| 2763 |
else: |
| 2764 |
self.literal = True |
| 2765 |
self.insert_newline = True |
| 2766 |
self.insert_non_breaking_blanks = True |
| 2767 |
# \raggedright ensures leading blanks are respected but |
| 2768 |
# leads to additional leading vspace if the first line |
| 2769 |
# of the block is overfull :-( |
| 2770 |
self.out.append('\\ttfamily\\raggedright\n') |
| 2771 |
self.context.append('') |
| 2772 |
|
| 2773 |
def depart_literal_block(self, node) -> None: |
| 2774 |
self.insert_non_breaking_blanks = False |
| 2775 |
self.insert_newline = False |
| 2776 |
self.literal = False |
| 2777 |
self.verbatim = False |
| 2778 |
self.alltt = False |
| 2779 |
self.out.append(self.context.pop()) |
| 2780 |
self.out.append(self.context.pop()) |
| 2781 |
self.duclass_close(node) |
| 2782 |
|
| 2783 |
def visit_meta(self, node) -> None: |
| 2784 |
if 'name' not in node or 'content' not in node: |
| 2785 |
raise nodes.SkipNode # HTML specific or empty metadata |
| 2786 |
# TODO: Filter nodes with additional fields ("lang", "http-equiv", …)? |
| 2787 |
# They are HTML-specific and may override equally named keys. |
| 2788 |
# Only if name already present? See also ODT writer. |
| 2789 |
name = node['name'] |
| 2790 |
content = self.encode(node['content']) |
| 2791 |
if name in ('author', 'keywords', 'producer', 'subject', 'title'): |
| 2792 |
# fields with dedicated hyperref options: |
| 2793 |
self.pdfinfo.append(' pdf%s={%s},'%(name, content)) |
| 2794 |
elif name == 'creator': |
| 2795 |
self.pdfinfo.append(' addtopdfcreator={%s},'%content) |
| 2796 |
else: |
| 2797 |
# generic interface (case sensitive!) |
| 2798 |
self.pdfinfo.append(' pdfinfo={%s={%s}},'%(name, content)) |
| 2799 |
|
| 2800 |
def depart_meta(self, node) -> None: |
| 2801 |
pass |
| 2802 |
|
| 2803 |
def visit_math(self, node, math_env='$') -> None: |
| 2804 |
""" |
| 2805 |
Provisional: the `math_env` argument will be dropped in Docutils 2.0. |
| 2806 |
""" |
| 2807 |
self.requirements['amsmath'] = r'\usepackage{amsmath}' |
| 2808 |
self.visit_inline(node) |
| 2809 |
math_code = node.astext().translate(unichar2tex.uni2tex_table) |
| 2810 |
if self.alltt: |
| 2811 |
self.out += ['\\(', math_code, '\\)'] |
| 2812 |
else: |
| 2813 |
self.out += ['$', math_code, '$'] |
| 2814 |
self.depart_inline(node) |
| 2815 |
raise nodes.SkipNode # content already processed |
| 2816 |
|
| 2817 |
def depart_math(self, node) -> None: |
| 2818 |
pass # never reached |
| 2819 |
|
| 2820 |
def visit_math_block(self, node) -> None: |
| 2821 |
self.requirements['amsmath'] = r'\usepackage{amsmath}' |
| 2822 |
math_env = pick_math_environment(node.astext()) |
| 2823 |
self.out.append('%\n') |
| 2824 |
if node['ids'] and math_env.endswith('*'): # non-numbered equation |
| 2825 |
self.out.append('\\phantomsection\n') |
| 2826 |
for cls in node['classes']: |
| 2827 |
self.provide_fallback('inline') |
| 2828 |
self.out.append(f'\\DUrole{{{cls}}}{{%\n') |
| 2829 |
self.out += [f'\\begin{{{math_env}}}\n', |
| 2830 |
node.astext().translate(unichar2tex.uni2tex_table), |
| 2831 |
'\n', |
| 2832 |
*self.ids_to_labels(node, set_anchor=False, newline=True), |
| 2833 |
f'\\end{{{math_env}}}'] |
| 2834 |
if node['classes']: |
| 2835 |
self.out.append('\n' + '}' * len(node['classes'])) |
| 2836 |
raise nodes.SkipNode # content already processed |
| 2837 |
|
| 2838 |
def depart_math_block(self, node) -> None: |
| 2839 |
pass # never reached |
| 2840 |
|
| 2841 |
def visit_option(self, node) -> None: |
| 2842 |
if self.context[-1]: |
| 2843 |
# this is not the first option |
| 2844 |
self.out.append(', ') |
| 2845 |
|
| 2846 |
def depart_option(self, node) -> None: |
| 2847 |
# flag that the first option is done. |
| 2848 |
self.context[-1] += 1 |
| 2849 |
|
| 2850 |
def visit_option_argument(self, node) -> None: |
| 2851 |
"""Append the delimiter between an option and its argument to body.""" |
| 2852 |
self.out.append(node.get('delimiter', ' ')) |
| 2853 |
|
| 2854 |
def depart_option_argument(self, node) -> None: |
| 2855 |
pass |
| 2856 |
|
| 2857 |
def visit_option_group(self, node) -> None: |
| 2858 |
self.out.append('\\item[') |
| 2859 |
# flag for first option |
| 2860 |
self.context.append(0) |
| 2861 |
|
| 2862 |
def depart_option_group(self, node) -> None: |
| 2863 |
self.context.pop() # the flag |
| 2864 |
self.out.append('] ') |
| 2865 |
|
| 2866 |
def visit_option_list(self, node) -> None: |
| 2867 |
self.provide_fallback('providelength', '_providelength') |
| 2868 |
self.provide_fallback('optionlist') |
| 2869 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 2870 |
self.duclass_open(node) |
| 2871 |
self.out.append('\\begin{DUoptionlist}\n') |
| 2872 |
|
| 2873 |
def depart_option_list(self, node) -> None: |
| 2874 |
self.out.append('\\end{DUoptionlist}\n') |
| 2875 |
self.duclass_close(node) |
| 2876 |
|
| 2877 |
def visit_option_list_item(self, node) -> None: |
| 2878 |
self.out += self.ids_to_labels(node, newline=True) |
| 2879 |
|
| 2880 |
def depart_option_list_item(self, node) -> None: |
| 2881 |
pass |
| 2882 |
|
| 2883 |
def visit_option_string(self, node) -> None: |
| 2884 |
## self.out.append(self.starttag(node, 'span', '', CLASS='option')) |
| 2885 |
pass |
| 2886 |
|
| 2887 |
def depart_option_string(self, node) -> None: |
| 2888 |
## self.out.append('</span>') |
| 2889 |
pass |
| 2890 |
|
| 2891 |
def visit_organization(self, node) -> None: |
| 2892 |
self.visit_docinfo_item(node) |
| 2893 |
|
| 2894 |
def depart_organization(self, node) -> None: |
| 2895 |
self.depart_docinfo_item(node) |
| 2896 |
|
| 2897 |
def visit_paragraph(self, node) -> None: |
| 2898 |
# insert blank line, unless |
| 2899 |
# * the paragraph is first in a list item, compound, or container |
| 2900 |
# * follows a non-paragraph node in a compound, |
| 2901 |
# * is in a table with auto-width columns |
| 2902 |
index = node.parent.index(node) |
| 2903 |
if index == 0 and isinstance(node.parent, |
| 2904 |
(nodes.list_item, nodes.description, |
| 2905 |
nodes.compound, nodes.container)): |
| 2906 |
pass |
| 2907 |
elif (index > 0 |
| 2908 |
and isinstance(node.parent, nodes.compound) |
| 2909 |
and not isinstance(node.parent[index - 1], |
| 2910 |
(nodes.paragraph, nodes.compound))): |
| 2911 |
pass |
| 2912 |
elif self.active_table.colwidths_auto: |
| 2913 |
if index == 1: # second paragraph |
| 2914 |
self.warn('LaTeX merges paragraphs in tables ' |
| 2915 |
'with auto-sized columns!', base_node=node) |
| 2916 |
if index > 0: |
| 2917 |
self.out.append('\n') |
| 2918 |
else: |
| 2919 |
self.out.append('\n') |
| 2920 |
self.visit_inline(node) |
| 2921 |
|
| 2922 |
def depart_paragraph(self, node) -> None: |
| 2923 |
self.depart_inline(node) |
| 2924 |
if not self.active_table.colwidths_auto: |
| 2925 |
self.out.append('\n') |
| 2926 |
|
| 2927 |
def visit_problematic(self, node) -> None: |
| 2928 |
self.requirements['color'] = PreambleCmds.color |
| 2929 |
self.out.append('%\n') |
| 2930 |
self.append_hypertargets(node) |
| 2931 |
self.out.append(r'\hyperlink{%s}{\textbf{\color{red}' % node['refid']) |
| 2932 |
|
| 2933 |
def depart_problematic(self, node) -> None: |
| 2934 |
self.out.append('}}') |
| 2935 |
|
| 2936 |
def visit_raw(self, node): |
| 2937 |
if 'latex' not in node.get('format', '').split(): |
| 2938 |
raise nodes.SkipNode |
| 2939 |
if not (self.is_inline(node) |
| 2940 |
or isinstance(node.parent, nodes.compound)): |
| 2941 |
self.out.append('\n') |
| 2942 |
self.visit_inline(node) |
| 2943 |
# append "as-is" skipping any LaTeX-encoding |
| 2944 |
self.verbatim = True |
| 2945 |
|
| 2946 |
def depart_raw(self, node) -> None: |
| 2947 |
self.verbatim = False |
| 2948 |
self.depart_inline(node) |
| 2949 |
if not self.is_inline(node): |
| 2950 |
self.out.append('\n') |
| 2951 |
|
| 2952 |
def has_unbalanced_braces(self, string): |
| 2953 |
"""Test whether there are unmatched '{' or '}' characters.""" |
| 2954 |
level = 0 |
| 2955 |
for ch in string: |
| 2956 |
if ch == '{': |
| 2957 |
level += 1 |
| 2958 |
if ch == '}': |
| 2959 |
level -= 1 |
| 2960 |
if level < 0: |
| 2961 |
return True |
| 2962 |
return level != 0 |
| 2963 |
|
| 2964 |
def visit_reference(self, node): |
| 2965 |
# We need to escape #, \, and % if we use the URL in a command. |
| 2966 |
special_chars = {ord('#'): '\\#', |
| 2967 |
ord('%'): '\\%', |
| 2968 |
ord('\\'): '\\\\', |
| 2969 |
} |
| 2970 |
if not self.is_inline(node): |
| 2971 |
self.out.append('\n') |
| 2972 |
# external reference (URL) |
| 2973 |
if 'refuri' in node: |
| 2974 |
href = str(node['refuri']).translate(special_chars) |
| 2975 |
# problematic chars double caret and unbalanced braces: |
| 2976 |
if '^^' in href or self.has_unbalanced_braces(href): |
| 2977 |
self.error( |
| 2978 |
f'External link "{href}" not supported by LaTeX.\n' |
| 2979 |
' (Must not contain "^^" or unbalanced braces.)') |
| 2980 |
if node['refuri'] == node.astext(): |
| 2981 |
self.out.append(r'\url{%s}' % href) |
| 2982 |
raise nodes.SkipNode |
| 2983 |
self.out.append(r'\href{%s}{' % href) |
| 2984 |
return |
| 2985 |
# internal reference |
| 2986 |
if 'refid' in node: |
| 2987 |
href = node['refid'] |
| 2988 |
elif 'refname' in node: |
| 2989 |
href = self.document.nameids[node['refname']] |
| 2990 |
else: |
| 2991 |
raise AssertionError('Unknown reference.') |
| 2992 |
if self.reference_label: |
| 2993 |
self.out.append('\\%s{%s}' % |
| 2994 |
(self.reference_label, href.replace('#', ''))) |
| 2995 |
raise nodes.SkipNode |
| 2996 |
self.out.append('\\hyperref[%s]{' % href) |
| 2997 |
|
| 2998 |
def depart_reference(self, node) -> None: |
| 2999 |
self.out.append('}') |
| 3000 |
if not self.is_inline(node): |
| 3001 |
self.out.append('\n') |
| 3002 |
|
| 3003 |
def visit_revision(self, node) -> None: |
| 3004 |
self.visit_docinfo_item(node) |
| 3005 |
|
| 3006 |
def depart_revision(self, node) -> None: |
| 3007 |
self.depart_docinfo_item(node) |
| 3008 |
|
| 3009 |
def visit_rubric(self, node) -> None: |
| 3010 |
self.provide_fallback('rubric') |
| 3011 |
# class wrapper would interfere with ``\section*"`` type commands |
| 3012 |
# (spacing/indent of first paragraph) |
| 3013 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 3014 |
self.duclass_open(node) |
| 3015 |
self.out.append('\\DUrubric{') |
| 3016 |
|
| 3017 |
def depart_rubric(self, node) -> None: |
| 3018 |
self.out.append('}\n') |
| 3019 |
self.duclass_close(node) |
| 3020 |
|
| 3021 |
def visit_section(self, node) -> None: |
| 3022 |
# Update counter-prefix for compound enumerators |
| 3023 |
self.section_level += 1 |
| 3024 |
# initialize counter for potential subsections |
| 3025 |
self._section_number.append(0) |
| 3026 |
# counter for this section's level (initialized by parent section) |
| 3027 |
self._section_number[self.section_level - 1] += 1 |
| 3028 |
|
| 3029 |
# Section numbering configuration |
| 3030 |
if 'sectnum' in self.requirements: |
| 3031 |
return # already done |
| 3032 |
# sectnum_depth values: |
| 3033 |
# 0 no section numbering or section numbering by Docutils |
| 3034 |
# >0 value of "sectnum"'s :depth: option (1 = top level section) |
| 3035 |
# None "sectnum" directive without depth arg -> keep default |
| 3036 |
if self.settings.sectnum_xform: # section numbering by Docutils |
| 3037 |
sectnum_depth = 0 # suppress LaTeX section numbers |
| 3038 |
else: |
| 3039 |
sectnum_depth = getattr(self.settings, 'sectnum_depth', 0) |
| 3040 |
if isinstance(sectnum_depth, str): |
| 3041 |
sectnum_depth = 0 # ignore values from config files |
| 3042 |
sectnum_start = getattr(self.settings, 'sectnum_start', 1) |
| 3043 |
if isinstance(sectnum_start, str): |
| 3044 |
sectnum_start = 1 # ignore values from config files |
| 3045 |
if sectnum_start != 1: |
| 3046 |
self.requirements['sectnum_start'] = r'\setcounter{%s}{%d}' % ( |
| 3047 |
self.d_class.sections[0], sectnum_start-1) |
| 3048 |
# TODO: currently ignored (configure in a stylesheet): |
| 3049 |
# settings.sectnum_prefix |
| 3050 |
# settings.sectnum_suffix |
| 3051 |
if sectnum_depth is not None: |
| 3052 |
self.requirements['sectnum'] = r'\setcounter{secnumdepth}{%d}' % ( |
| 3053 |
self.d_class.latex_section_depth(sectnum_depth)) |
| 3054 |
|
| 3055 |
def depart_section(self, node) -> None: |
| 3056 |
# Remove counter for potential subsections: |
| 3057 |
self._section_number.pop() |
| 3058 |
self.section_level -= 1 |
| 3059 |
|
| 3060 |
def visit_sidebar(self, node) -> None: |
| 3061 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 3062 |
self.duclass_open(node) |
| 3063 |
self.requirements['color'] = PreambleCmds.color |
| 3064 |
self.provide_fallback('sidebar') |
| 3065 |
self.out.append('\\DUsidebar{') |
| 3066 |
|
| 3067 |
def depart_sidebar(self, node) -> None: |
| 3068 |
self.out.append('}\n') |
| 3069 |
self.duclass_close(node) |
| 3070 |
|
| 3071 |
attribution_formats = {'dash': ('—', ''), # EM DASH |
| 3072 |
'parentheses': ('(', ')'), |
| 3073 |
'parens': ('(', ')'), |
| 3074 |
'none': ('', '')} |
| 3075 |
|
| 3076 |
def visit_attribution(self, node) -> None: |
| 3077 |
prefix, suffix = self.attribution_formats[self.settings.attribution] |
| 3078 |
self.out.append('\\nopagebreak\n') |
| 3079 |
self.out += self.ids_to_labels(node, pre_nl=True) |
| 3080 |
self.duclass_open(node) |
| 3081 |
self.out.append(f'\\raggedleft {prefix}') |
| 3082 |
self.context.append(suffix) |
| 3083 |
|
| 3084 |
def depart_attribution(self, node) -> None: |
| 3085 |
self.out.append(self.context.pop() + '\n') |
| 3086 |
self.duclass_close(node) |
| 3087 |
|
| 3088 |
def visit_status(self, node) -> None: |
| 3089 |
self.visit_docinfo_item(node) |
| 3090 |
|
| 3091 |
def depart_status(self, node) -> None: |
| 3092 |
self.depart_docinfo_item(node) |
| 3093 |
|
| 3094 |
def visit_strong(self, node) -> None: |
| 3095 |
self.out.append('\\textbf{') |
| 3096 |
self.visit_inline(node) |
| 3097 |
|
| 3098 |
def depart_strong(self, node) -> None: |
| 3099 |
self.depart_inline(node) |
| 3100 |
self.out.append('}') |
| 3101 |
|
| 3102 |
def visit_substitution_definition(self, node): |
| 3103 |
raise nodes.SkipNode |
| 3104 |
|
| 3105 |
def visit_substitution_reference(self, node) -> None: |
| 3106 |
self.unimplemented_visit(node) |
| 3107 |
|
| 3108 |
def visit_subtitle(self, node) -> None: |
| 3109 |
if isinstance(node.parent, nodes.document): |
| 3110 |
self.push_output_collector(self.subtitle) |
| 3111 |
self.provide_fallback('documentsubtitle') |
| 3112 |
protect = (self.settings.documentclass == 'memoir') |
| 3113 |
self.subtitle_labels += self.ids_to_labels(node, set_anchor=False, |
| 3114 |
protect=protect) |
| 3115 |
# section subtitle: "starred" (no number, not in ToC) |
| 3116 |
elif isinstance(node.parent, nodes.section): |
| 3117 |
self.out.append(r'\%s*{' % |
| 3118 |
self.d_class.section(self.section_level + 1)) |
| 3119 |
else: |
| 3120 |
self.provide_fallback('subtitle') |
| 3121 |
self.out.append('\n\\DUsubtitle{') |
| 3122 |
|
| 3123 |
def depart_subtitle(self, node) -> None: |
| 3124 |
if isinstance(node.parent, nodes.document): |
| 3125 |
self.pop_output_collector() |
| 3126 |
else: |
| 3127 |
self.out.append('}\n') |
| 3128 |
|
| 3129 |
def visit_system_message(self, node) -> None: |
| 3130 |
self.requirements['color'] = PreambleCmds.color |
| 3131 |
self.provide_fallback('title') |
| 3132 |
if self.settings.legacy_class_functions: |
| 3133 |
self.fallbacks['title'] = PreambleCmds.title_legacy |
| 3134 |
node['classes'] = ['system-message'] |
| 3135 |
self.out.append('\n') |
| 3136 |
self.append_hypertargets(node) |
| 3137 |
self.visit_admonition(node) |
| 3138 |
if self.settings.legacy_class_functions: |
| 3139 |
self.out.append('\n\\DUtitle[system-message]' |
| 3140 |
'{\\color{red}System Message}\n') |
| 3141 |
else: |
| 3142 |
self.out.append('\n\\DUtitle{\\color{red}System Message}\n') |
| 3143 |
try: |
| 3144 |
line = f", line~{node['line']}" |
| 3145 |
except KeyError: |
| 3146 |
line = '' |
| 3147 |
self.out.append(f"\n{node['type']}/{node['level']} in " |
| 3148 |
f"\\texttt{{{self.encode(node['source'])}}}{line}\n") |
| 3149 |
if len(node['backrefs']) == 1: |
| 3150 |
self.out.append(f"\n\\hyperlink{{{node['backrefs'][0]}}}{{") |
| 3151 |
self.context.append('}\n') |
| 3152 |
else: |
| 3153 |
backrefs = [f'\\hyperlink{{{href}}}{{{i+1}}}\n' |
| 3154 |
for (i, href) in enumerate(node['backrefs'])] |
| 3155 |
self.context.append('backrefs: ' + ' '.join(backrefs)) |
| 3156 |
|
| 3157 |
def depart_system_message(self, node) -> None: |
| 3158 |
self.out.append(self.context.pop()) |
| 3159 |
self.depart_admonition(node) |
| 3160 |
|
| 3161 |
def visit_table(self, node) -> None: |
| 3162 |
self.requirements['table'] = PreambleCmds.table |
| 3163 |
if not self.settings.legacy_column_widths: |
| 3164 |
self.requirements['table1'] = PreambleCmds.table_columnwidth |
| 3165 |
if self.active_table.is_open(): |
| 3166 |
self.table_stack.append(self.active_table) |
| 3167 |
# nesting longtable does not work (e.g. 2007-04-18) |
| 3168 |
self.active_table = Table(self, 'tabular') |
| 3169 |
# A longtable moves before \paragraph and \subparagraph |
| 3170 |
# section titles if it immediately follows them: |
| 3171 |
if (self.active_table._latex_type == 'longtable' |
| 3172 |
and isinstance(node.parent, nodes.section) |
| 3173 |
and node.parent.index(node) == 1 |
| 3174 |
and 'paragraph' in self.d_class.section(self.section_level)): |
| 3175 |
self.out.append('\\leavevmode') |
| 3176 |
self.active_table.open() |
| 3177 |
self.active_table.set_table_style(node, self.settings) |
| 3178 |
if self.active_table.borders == 'booktabs': |
| 3179 |
self.requirements['booktabs'] = r'\usepackage{booktabs}' |
| 3180 |
self.push_output_collector([]) |
| 3181 |
|
| 3182 |
def depart_table(self, node) -> None: |
| 3183 |
# complete and write the table |
| 3184 |
content = self.pop_output_collector() |
| 3185 |
try: |
| 3186 |
width = self.to_latex_length(node['width'], node) |
| 3187 |
except KeyError: |
| 3188 |
width = r'\linewidth' |
| 3189 |
# Insert hyperlabel and anchor before the table |
| 3190 |
# if it has no caption/title. |
| 3191 |
# See visit_thead() for tables with caption. |
| 3192 |
if not self.active_table.caption: |
| 3193 |
set_anchor = (len(self.table_stack) != 1) |
| 3194 |
self.out += self.ids_to_labels(node, set_anchor, pre_nl=True) |
| 3195 |
self.duclass_open(node) |
| 3196 |
# TODO: Don't use a longtable or add \noindent before |
| 3197 |
# the next paragraph, when in a "compound paragraph". |
| 3198 |
# Start a new line or a new paragraph? |
| 3199 |
# if (isinstance(node.parent, nodes.compound) |
| 3200 |
# and self._latex_type != 'longtable')? |
| 3201 |
self.out.append(self.active_table.get_opening(width)) |
| 3202 |
self.out += content |
| 3203 |
self.out.append(self.active_table.get_closing() + '\n') |
| 3204 |
self.active_table.close() |
| 3205 |
if len(self.table_stack) > 0: |
| 3206 |
self.active_table = self.table_stack.pop() |
| 3207 |
self.duclass_close(node) |
| 3208 |
|
| 3209 |
def visit_target(self, node) -> None: |
| 3210 |
# Skip indirect targets: |
| 3211 |
if ('refuri' in node # external hyperlink |
| 3212 |
or 'refid' in node # resolved internal link |
| 3213 |
or 'refname' in node): # unresolved internal link |
| 3214 |
## self.out.append('%% %s\n' % node) # for debugging |
| 3215 |
return |
| 3216 |
if self.is_inline(node): |
| 3217 |
self.out.append('%') |
| 3218 |
self.out.append('\n') |
| 3219 |
self.visit_inline(node) |
| 3220 |
|
| 3221 |
def depart_target(self, node) -> None: |
| 3222 |
self.depart_inline(node) |
| 3223 |
|
| 3224 |
def visit_tbody(self, node) -> None: |
| 3225 |
# BUG write preamble if not yet done (colspecs not []) |
| 3226 |
# for tables without heads. |
| 3227 |
if not self.active_table.get('preamble written'): |
| 3228 |
self.visit_thead(node) |
| 3229 |
self.depart_thead(None) |
| 3230 |
|
| 3231 |
def depart_tbody(self, node) -> None: |
| 3232 |
pass |
| 3233 |
|
| 3234 |
def visit_term(self, node) -> None: |
| 3235 |
"""definition list term""" |
| 3236 |
# Commands with optional args inside an optional arg must be put |
| 3237 |
# in a group, e.g. ``\item[{\hyperref[label]{text}}]``. |
| 3238 |
self.out.append('\\item[{') |
| 3239 |
|
| 3240 |
def depart_term(self, node) -> None: |
| 3241 |
self.out.append('}] ') |
| 3242 |
# Do we need a \leavevmode (line break if the field body begins |
| 3243 |
# with a list or environment)? |
| 3244 |
next_node = node.next_node(descend=False, siblings=True) |
| 3245 |
if isinstance(next_node, nodes.term): |
| 3246 |
self.out.append('\n') |
| 3247 |
elif not isinstance(next_node, nodes.classifier): |
| 3248 |
self.out.append(self.term_postfix(next_node)) |
| 3249 |
|
| 3250 |
def visit_tgroup(self, node) -> None: |
| 3251 |
pass |
| 3252 |
|
| 3253 |
def depart_tgroup(self, node) -> None: |
| 3254 |
pass |
| 3255 |
|
| 3256 |
_thead_depth = 0 |
| 3257 |
|
| 3258 |
def thead_depth(self): |
| 3259 |
return self._thead_depth |
| 3260 |
|
| 3261 |
def visit_thead(self, node) -> None: |
| 3262 |
self._thead_depth += 1 |
| 3263 |
if 1 == self.thead_depth(): |
| 3264 |
self.out.append('{%s}\n' % self.active_table.get_colspecs(node)) |
| 3265 |
self.active_table.set('preamble written', 1) |
| 3266 |
if self.active_table.caption: |
| 3267 |
if self._thead_depth == 1: |
| 3268 |
pre = [r'\caption{'] |
| 3269 |
post = self.ids_to_labels(node.parent.parent, False) + [r'}\\'] |
| 3270 |
else: |
| 3271 |
pre = [r'\caption[]{'] |
| 3272 |
post = [r' (... continued)}\\'] |
| 3273 |
self.out.extend(pre + self.active_table.caption + post + ['\n']) |
| 3274 |
self.out.extend(self.active_table.visit_thead()) |
| 3275 |
|
| 3276 |
def depart_thead(self, node) -> None: |
| 3277 |
if node is not None: |
| 3278 |
self.out.extend(self.active_table.depart_thead()) |
| 3279 |
if self.active_table.need_recurse(): |
| 3280 |
node.walkabout(self) |
| 3281 |
self._thead_depth -= 1 |
| 3282 |
|
| 3283 |
def visit_title(self, node) -> None: |
| 3284 |
"""Append section and other titles.""" |
| 3285 |
# Document title |
| 3286 |
if isinstance(node.parent, nodes.document): |
| 3287 |
self.push_output_collector(self.title) |
| 3288 |
self.context.append('') |
| 3289 |
# Topic titles (topic, admonition, sidebar) |
| 3290 |
elif (isinstance(node.parent, nodes.topic) |
| 3291 |
or isinstance(node.parent, nodes.admonition) |
| 3292 |
or isinstance(node.parent, nodes.sidebar)): |
| 3293 |
classes = node.parent['classes'] or [node.parent.tagname] |
| 3294 |
if self.settings.legacy_class_functions: |
| 3295 |
self.fallbacks['title'] = PreambleCmds.title_legacy |
| 3296 |
self.out.append('\n\\DUtitle[%s]{' % ','.join(classes)) |
| 3297 |
else: |
| 3298 |
self.provide_fallback('title') |
| 3299 |
self.out.append('\n\\DUtitle{') |
| 3300 |
self.context.append('}\n') |
| 3301 |
# Table caption |
| 3302 |
elif isinstance(node.parent, nodes.table): |
| 3303 |
self.push_output_collector(self.active_table.caption) |
| 3304 |
self.context.append('') |
| 3305 |
# Section title |
| 3306 |
else: |
| 3307 |
level = self.section_level |
| 3308 |
section_name = self.d_class.section(level) |
| 3309 |
self.out.append('\n\n') |
| 3310 |
if level > len(self.d_class.sections): |
| 3311 |
# section level not supported by LaTeX |
| 3312 |
if self.settings.legacy_class_functions: |
| 3313 |
self.fallbacks['title'] = PreambleCmds.title_legacy |
| 3314 |
section_name += '[section%s]' % RomanNumeral(level) |
| 3315 |
else: |
| 3316 |
self.provide_fallback('title') |
| 3317 |
self.provide_fallback('duclass', 'DUclass') |
| 3318 |
self.out.append('\\begin{DUclass}{section%s}\n' |
| 3319 |
% RomanNumeral(level)) |
| 3320 |
|
| 3321 |
# System messages heading in red: |
| 3322 |
if 'system-messages' in node.parent['classes']: |
| 3323 |
self.requirements['color'] = PreambleCmds.color |
| 3324 |
section_title = self.encode(node.astext()) |
| 3325 |
self.out.append(r'\%s[%s]{\color{red}' % ( |
| 3326 |
section_name, section_title)) |
| 3327 |
else: |
| 3328 |
self.out.append(r'\%s{' % section_name) |
| 3329 |
|
| 3330 |
# label(s) and ToC entry: |
| 3331 |
labels = self.ids_to_labels(node.parent, set_anchor=False) |
| 3332 |
if labels: |
| 3333 |
self.context.append('%\n '.join(('', *labels)) + '%\n}\n') |
| 3334 |
else: |
| 3335 |
self.context.append('}\n') |
| 3336 |
if (level > len(self.d_class.sections) |
| 3337 |
and not self.settings.legacy_class_functions): |
| 3338 |
self.context[-1] += '\\end{DUclass}\n' |
| 3339 |
# MAYBE postfix paragraph and subparagraph with \leavevmode to |
| 3340 |
# ensure floats stay in the section and text starts on a new line. |
| 3341 |
|
| 3342 |
def depart_title(self, node) -> None: |
| 3343 |
self.out.append(self.context.pop()) |
| 3344 |
if isinstance(node.parent, (nodes.table, nodes.document)): |
| 3345 |
self.pop_output_collector() |
| 3346 |
|
| 3347 |
def visit_contents(self, node): |
| 3348 |
"""Write the table of contents. |
| 3349 |
|
| 3350 |
Called from visit_topic() for "contents" topics. |
| 3351 |
""" |
| 3352 |
# requirements/setup for local ToC with package "minitoc", |
| 3353 |
if self.use_latex_toc and 'local' in node['classes']: |
| 3354 |
section_name = self.d_class.section(self.section_level) |
| 3355 |
# minitoc only supports "part" and toplevel sections |
| 3356 |
minitoc_names = {'part': 'part', |
| 3357 |
'chapter': 'mini', |
| 3358 |
'section': 'sect'} |
| 3359 |
if 'chapter' in self.d_class.sections: |
| 3360 |
del minitoc_names['section'] |
| 3361 |
try: |
| 3362 |
mtc_name = minitoc_names[section_name] |
| 3363 |
except KeyError: |
| 3364 |
self.warn('Skipping local ToC at "%s" level.\n' |
| 3365 |
' Feature not supported with option "use-latex-toc"' |
| 3366 |
% section_name, base_node=node) |
| 3367 |
raise nodes.SkipNode |
| 3368 |
|
| 3369 |
# labels and PDF bookmark (sidebar entry) |
| 3370 |
self.out.append('\n') # start new paragraph |
| 3371 |
self.out += self.ids_to_labels(node, newline=True) |
| 3372 |
if (isinstance(node.next_node(), nodes.title) |
| 3373 |
and 'local' not in node['classes'] |
| 3374 |
and self.settings.documentclass != 'memoir'): |
| 3375 |
self.out.append('\\pdfbookmark[%d]{%s}{%s}\n' % |
| 3376 |
(self.section_level+1, |
| 3377 |
node.next_node().astext(), |
| 3378 |
node.get('ids', ['contents'])[0])) |
| 3379 |
|
| 3380 |
# Docutils generated contents list (no page numbers) |
| 3381 |
if not self.use_latex_toc: |
| 3382 |
self.fallbacks['toc-list'] = PreambleCmds.toc_list |
| 3383 |
self.duclass_open(node) |
| 3384 |
return |
| 3385 |
|
| 3386 |
# ToC by LaTeX |
| 3387 |
try: |
| 3388 |
details = node.next_node(nodes.pending).details |
| 3389 |
except AttributeError: |
| 3390 |
self.warn('Setting "use_latex_toc" is True but "contents" details ' |
| 3391 |
'are missing. Directive option values may be lost.') |
| 3392 |
details = {} |
| 3393 |
depth = details.get('depth', 0) |
| 3394 |
maxdepth = len(self.d_class.sections) |
| 3395 |
if isinstance(node.next_node(), nodes.title): |
| 3396 |
title = self.encode(node[0].astext()) |
| 3397 |
else: |
| 3398 |
title = '' |
| 3399 |
if 'local' in node['classes']: |
| 3400 |
# use the "minitoc" package |
| 3401 |
self.requirements['minitoc'] = PreambleCmds.minitoc |
| 3402 |
self.requirements['minitoc-'+mtc_name] = r'\do%stoc'%mtc_name |
| 3403 |
self.requirements['minitoc-%s-depth' % mtc_name] = ( |
| 3404 |
r'\mtcsetdepth{%stoc}{%d}' % (mtc_name, maxdepth)) |
| 3405 |
# "depth" option: Docutils stores a relative depth while |
| 3406 |
# minitoc expects an absolute depth!: |
| 3407 |
offset = {'sect': 1, 'mini': 0, 'part': 0} |
| 3408 |
if 'chapter' in self.d_class.sections: |
| 3409 |
offset['part'] = -1 |
| 3410 |
if depth: |
| 3411 |
self.out.append('\\setcounter{%stocdepth}{%d}' % |
| 3412 |
(mtc_name, depth + offset[mtc_name])) |
| 3413 |
# title: |
| 3414 |
self.out.append('\\mtcsettitle{%stoc}{%s}\n' % (mtc_name, title)) |
| 3415 |
# the toc-generating command: |
| 3416 |
self.out.append('\\%stoc\n' % mtc_name) |
| 3417 |
else: |
| 3418 |
if depth: |
| 3419 |
self.out.append('\\setcounter{tocdepth}{%d}\n' |
| 3420 |
% self.d_class.latex_section_depth(depth)) |
| 3421 |
if title != 'Contents': |
| 3422 |
self.out.append('\\renewcommand{\\contentsname}{%s}\n' % title) |
| 3423 |
self.out.append('\\tableofcontents\n') |
| 3424 |
self.has_latex_toc = True |
| 3425 |
# ignore rest of node content |
| 3426 |
raise nodes.SkipNode |
| 3427 |
|
| 3428 |
def visit_topic(self, node) -> None: |
| 3429 |
# Topic nodes can be generic topic, abstract, dedication, or ToC. |
| 3430 |
# table of contents: |
| 3431 |
if 'contents' in node['classes']: |
| 3432 |
self.visit_contents(node) |
| 3433 |
elif ('abstract' in node['classes'] |
| 3434 |
and self.settings.use_latex_abstract): |
| 3435 |
self.push_output_collector(self.abstract) |
| 3436 |
self.out.append('\\begin{abstract}') |
| 3437 |
if isinstance(node.next_node(), nodes.title): |
| 3438 |
node.pop(0) # LaTeX provides its own title |
| 3439 |
else: |
| 3440 |
# special topics: |
| 3441 |
if 'abstract' in node['classes']: |
| 3442 |
self.provide_fallback('abstract') |
| 3443 |
if self.settings.legacy_class_functions: |
| 3444 |
self.fallbacks['abstract'] = PreambleCmds.abstract_legacy |
| 3445 |
self.push_output_collector(self.abstract) |
| 3446 |
elif 'dedication' in node['classes']: |
| 3447 |
self.provide_fallback('dedication') |
| 3448 |
self.push_output_collector(self.dedication) |
| 3449 |
else: |
| 3450 |
node['classes'].insert(0, 'topic') |
| 3451 |
self.visit_block_quote(node) |
| 3452 |
|
| 3453 |
def depart_topic(self, node) -> None: |
| 3454 |
if ('abstract' in node['classes'] |
| 3455 |
and self.settings.use_latex_abstract): |
| 3456 |
self.out.append('\\end{abstract}\n') |
| 3457 |
elif 'contents' in node['classes']: |
| 3458 |
self.duclass_close(node) |
| 3459 |
else: |
| 3460 |
self.depart_block_quote(node) |
| 3461 |
if ('abstract' in node['classes'] |
| 3462 |
or 'dedication' in node['classes']): |
| 3463 |
self.pop_output_collector() |
| 3464 |
|
| 3465 |
def visit_transition(self, node) -> None: |
| 3466 |
self.provide_fallback('transition') |
| 3467 |
self.out.append('\n%' + '_' * 75 + '\n') |
| 3468 |
self.out.append('\\DUtransition\n') |
| 3469 |
|
| 3470 |
def depart_transition(self, node) -> None: |
| 3471 |
pass |
| 3472 |
|
| 3473 |
def visit_version(self, node) -> None: |
| 3474 |
self.visit_docinfo_item(node) |
| 3475 |
|
| 3476 |
def depart_version(self, node) -> None: |
| 3477 |
self.depart_docinfo_item(node) |
| 3478 |
|
| 3479 |
def unimplemented_visit(self, node): |
| 3480 |
raise NotImplementedError('visiting unimplemented node type: %s' % |
| 3481 |
node.__class__.__name__) |
| 3482 |
|
| 3483 |
# def unknown_visit(self, node): |
| 3484 |
# def default_visit(self, node): |
| 3485 |
|
| 3486 |
# vim: set ts=4 et ai : |