Debian Codegraph @

docutils/writers/latex2e/__init__.py

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