Spelling fixes
[docutils.git] / docutils / writers / latex2e / __init__.py
blobc1584c1f1adf0bc631161069067c906b4f7bd1f8
1 # .. coding: utf-8
2 # $Id$
3 # Author: Engelbert Gruber, Günter Milde
4 # Maintainer: docutils-develop@lists.sourceforge.net
5 # Copyright: This module has been placed in the public domain.
7 """LaTeX2e document tree Writer."""
9 __docformat__ = 'reStructuredText'
11 # code contributions from several people included, thanks to all.
12 # some named: David Abrahams, Julien Letessier, Lele Gaifax, and others.
14 # convention deactivate code by two # i.e. ##.
16 import sys
17 import os
18 import time
19 import re
20 import string
21 import urllib
22 try:
23 import roman
24 except ImportError:
25 import docutils.utils.roman as roman
26 from docutils import frontend, nodes, languages, writers, utils, io
27 from docutils.utils.error_reporting import SafeString
28 from docutils.transforms import writer_aux
29 from docutils.utils.math import pick_math_environment, unichar2tex
31 class Writer(writers.Writer):
33 supported = ('latex','latex2e')
34 """Formats this writer supports."""
36 default_template = 'default.tex'
37 default_template_path = os.path.dirname(os.path.abspath(__file__))
38 default_preamble = '\n'.join([r'% PDF Standard Fonts',
39 r'\usepackage{mathptmx} % Times',
40 r'\usepackage[scaled=.90]{helvet}',
41 r'\usepackage{courier}'])
42 table_style_values = ('standard', 'booktabs','nolines', 'borderless',
43 'colwidths-auto', 'colwidths-given')
45 settings_spec = (
46 'LaTeX-Specific Options',
47 None,
48 (('Specify documentclass. Default is "article".',
49 ['--documentclass'],
50 {'default': 'article', }),
51 ('Specify document options. Multiple options can be given, '
52 'separated by commas. Default is "a4paper".',
53 ['--documentoptions'],
54 {'default': 'a4paper', }),
55 ('Footnotes with numbers/symbols by Docutils. (default)',
56 ['--docutils-footnotes'],
57 {'default': True, 'action': 'store_true',
58 'validator': frontend.validate_boolean}),
59 ('Format for footnote references: one of "superscript" or '
60 '"brackets". Default is "superscript".',
61 ['--footnote-references'],
62 {'choices': ['superscript', 'brackets'], 'default': 'superscript',
63 'metavar': '<format>',
64 'overrides': 'trim_footnote_reference_space'}),
65 ('Use \\cite command for citations. ',
66 ['--use-latex-citations'],
67 {'default': 0, 'action': 'store_true',
68 'validator': frontend.validate_boolean}),
69 ('Use figure floats for citations '
70 '(might get mixed with real figures). (default)',
71 ['--figure-citations'],
72 {'dest': 'use_latex_citations', 'action': 'store_false',
73 'validator': frontend.validate_boolean}),
74 ('Format for block quote attributions: one of "dash" (em-dash '
75 'prefix), "parentheses"/"parens", or "none". Default is "dash".',
76 ['--attribution'],
77 {'choices': ['dash', 'parentheses', 'parens', 'none'],
78 'default': 'dash', 'metavar': '<format>'}),
79 ('Specify LaTeX packages/stylesheets. '
80 ' A style is referenced with \\usepackage if extension is '
81 '".sty" or omitted and with \\input else. '
82 ' Overrides previous --stylesheet and --stylesheet-path settings.',
83 ['--stylesheet'],
84 {'default': '', 'metavar': '<file[,file,...]>',
85 'overrides': 'stylesheet_path',
86 'validator': frontend.validate_comma_separated_list}),
87 ('Comma separated list of LaTeX packages/stylesheets. '
88 'Relative paths are expanded if a matching file is found in '
89 'the --stylesheet-dirs. With --link-stylesheet, '
90 'the path is rewritten relative to the output *.tex file. ',
91 ['--stylesheet-path'],
92 {'metavar': '<file[,file,...]>', 'overrides': 'stylesheet',
93 'validator': frontend.validate_comma_separated_list}),
94 ('Link to the stylesheet(s) in the output file. (default)',
95 ['--link-stylesheet'],
96 {'dest': 'embed_stylesheet', 'action': 'store_false'}),
97 ('Embed the stylesheet(s) in the output file. '
98 'Stylesheets must be accessible during processing. ',
99 ['--embed-stylesheet'],
100 {'default': 0, 'action': 'store_true',
101 'validator': frontend.validate_boolean}),
102 ('Comma-separated list of directories where stylesheets are found. '
103 'Used by --stylesheet-path when expanding relative path arguments. '
104 'Default: "."',
105 ['--stylesheet-dirs'],
106 {'metavar': '<dir[,dir,...]>',
107 'validator': frontend.validate_comma_separated_list,
108 'default': ['.']}),
109 ('Customization by LaTeX code in the preamble. '
110 'Default: select PDF standard fonts (Times, Helvetica, Courier).',
111 ['--latex-preamble'],
112 {'default': default_preamble}),
113 ('Specify the template file. Default: "%s".' % default_template,
114 ['--template'],
115 {'default': default_template, 'metavar': '<file>'}),
116 ('Table of contents by LaTeX. (default) ',
117 ['--use-latex-toc'],
118 {'default': 1, 'action': 'store_true',
119 'validator': frontend.validate_boolean}),
120 ('Table of contents by Docutils (without page numbers). ',
121 ['--use-docutils-toc'],
122 {'dest': 'use_latex_toc', 'action': 'store_false',
123 'validator': frontend.validate_boolean}),
124 ('Add parts on top of the section hierarchy.',
125 ['--use-part-section'],
126 {'default': 0, 'action': 'store_true',
127 'validator': frontend.validate_boolean}),
128 ('Attach author and date to the document info table. (default) ',
129 ['--use-docutils-docinfo'],
130 {'dest': 'use_latex_docinfo', 'action': 'store_false',
131 'validator': frontend.validate_boolean}),
132 ('Attach author and date to the document title.',
133 ['--use-latex-docinfo'],
134 {'default': 0, 'action': 'store_true',
135 'validator': frontend.validate_boolean}),
136 ("Typeset abstract as topic. (default)",
137 ['--topic-abstract'],
138 {'dest': 'use_latex_abstract', 'action': 'store_false',
139 'validator': frontend.validate_boolean}),
140 ("Use LaTeX abstract environment for the document's abstract. ",
141 ['--use-latex-abstract'],
142 {'default': 0, 'action': 'store_true',
143 'validator': frontend.validate_boolean}),
144 ('Color of any hyperlinks embedded in text '
145 '(default: "blue", "false" to disable).',
146 ['--hyperlink-color'], {'default': 'blue'}),
147 ('Additional options to the "hyperref" package '
148 '(default: "").',
149 ['--hyperref-options'], {'default': ''}),
150 ('Enable compound enumerators for nested enumerated lists '
151 '(e.g. "1.2.a.ii"). Default: disabled.',
152 ['--compound-enumerators'],
153 {'default': None, 'action': 'store_true',
154 'validator': frontend.validate_boolean}),
155 ('Disable compound enumerators for nested enumerated lists. '
156 'This is the default.',
157 ['--no-compound-enumerators'],
158 {'action': 'store_false', 'dest': 'compound_enumerators'}),
159 ('Enable section ("." subsection ...) prefixes for compound '
160 'enumerators. This has no effect without --compound-enumerators.'
161 'Default: disabled.',
162 ['--section-prefix-for-enumerators'],
163 {'default': None, 'action': 'store_true',
164 'validator': frontend.validate_boolean}),
165 ('Disable section prefixes for compound enumerators. '
166 'This is the default.',
167 ['--no-section-prefix-for-enumerators'],
168 {'action': 'store_false', 'dest': 'section_prefix_for_enumerators'}),
169 ('Set the separator between section number and enumerator '
170 'for compound enumerated lists. Default is "-".',
171 ['--section-enumerator-separator'],
172 {'default': '-', 'metavar': '<char>'}),
173 ('When possible, use the specified environment for literal-blocks. '
174 'Default is quoting of whitespace and special chars.',
175 ['--literal-block-env'],
176 {'default': ''}),
177 ('When possible, use verbatim for literal-blocks. '
178 'Compatibility alias for "--literal-block-env=verbatim".',
179 ['--use-verbatim-when-possible'],
180 {'default': 0, 'action': 'store_true',
181 'validator': frontend.validate_boolean}),
182 ('Table style. "standard" with horizontal and vertical lines, '
183 '"booktabs" (LaTeX booktabs style) only horizontal lines '
184 'above and below the table and below the header or "borderless". '
185 'Default: "standard"',
186 ['--table-style'],
187 {'default': ['standard'],
188 'metavar': '<format>',
189 'action': 'append',
190 'validator': frontend.validate_comma_separated_list,
191 'choices': table_style_values}),
192 ('LaTeX graphicx package option. '
193 'Possible values are "dvips", "pdftex". "auto" includes LaTeX code '
194 'to use "pdftex" if processing with pdf(la)tex and dvips otherwise. '
195 'Default is no option.',
196 ['--graphicx-option'],
197 {'default': ''}),
198 ('LaTeX font encoding. '
199 'Possible values are "", "T1" (default), "OT1", "LGR,T1" or '
200 'any other combination of options to the `fontenc` package. ',
201 ['--font-encoding'],
202 {'default': 'T1'}),
203 ('Per default the latex-writer puts the reference title into '
204 'hyperreferences. Specify "ref*" or "pageref*" to get the section '
205 'number or the page number.',
206 ['--reference-label'],
207 {'default': None, }),
208 ('Specify style and database for bibtex, for example '
209 '"--use-bibtex=mystyle,mydb1,mydb2".',
210 ['--use-bibtex'],
211 {'default': None, }),
214 settings_defaults = {'sectnum_depth': 0 # updated by SectNum transform
216 config_section = 'latex2e writer'
217 config_section_dependencies = ('writers',)
219 head_parts = ('head_prefix', 'requirements', 'latex_preamble',
220 'stylesheet', 'fallbacks', 'pdfsetup',
221 'title', 'subtitle', 'titledata')
222 visitor_attributes = head_parts + ('body_pre_docinfo', 'docinfo',
223 'dedication', 'abstract', 'body')
225 output = None
226 """Final translated form of `document`."""
228 def __init__(self):
229 writers.Writer.__init__(self)
230 self.translator_class = LaTeXTranslator
232 # Override parent method to add latex-specific transforms
233 def get_transforms(self):
234 return writers.Writer.get_transforms(self) + [
235 # Convert specific admonitions to generic one
236 writer_aux.Admonitions,
237 # TODO: footnote collection transform
240 def translate(self):
241 visitor = self.translator_class(self.document)
242 self.document.walkabout(visitor)
243 # copy parts
244 for part in self.visitor_attributes:
245 setattr(self, part, getattr(visitor, part))
246 # get template string from file
247 try:
248 template_file = open(self.document.settings.template, 'rb')
249 except IOError:
250 template_file = open(os.path.join(self.default_template_path,
251 self.document.settings.template), 'rb')
252 template = string.Template(unicode(template_file.read(), 'utf-8'))
253 template_file.close()
254 # fill template
255 self.assemble_parts() # create dictionary of parts
256 self.output = template.substitute(self.parts)
258 def assemble_parts(self):
259 """Assemble the `self.parts` dictionary of output fragments."""
260 writers.Writer.assemble_parts(self)
261 for part in self.visitor_attributes:
262 lines = getattr(self, part)
263 if part in self.head_parts:
264 if lines:
265 lines.append('') # to get a trailing newline
266 self.parts[part] = '\n'.join(lines)
267 else:
268 # body contains inline elements, so join without newline
269 self.parts[part] = ''.join(lines)
272 class Babel(object):
273 """Language specifics for LaTeX."""
275 # TeX (babel) language names:
276 # ! not all of these are supported by Docutils!
278 # based on LyX' languages file with adaptions to `BCP 47`_
279 # (http://www.rfc-editor.org/rfc/bcp/bcp47.txt) and
280 # http://www.tug.org/TUGboat/Articles/tb29-3/tb93miklavec.pdf
281 # * the key without subtags is the default
282 # * case is ignored
283 # cf. http://docutils.sourceforge.net/docs/howto/i18n.html
284 # http://www.w3.org/International/articles/language-tags/
285 # and http://www.iana.org/assignments/language-subtag-registry
286 language_codes = {
287 # code TeX/Babel-name comment
288 'af': 'afrikaans',
289 'ar': 'arabic',
290 # 'be': 'belarusian',
291 'bg': 'bulgarian',
292 'br': 'breton',
293 'ca': 'catalan',
294 # 'cop': 'coptic',
295 'cs': 'czech',
296 'cy': 'welsh',
297 'da': 'danish',
298 'de': 'ngerman', # new spelling (de_1996)
299 'de-1901': 'german', # old spelling
300 'de-AT': 'naustrian',
301 'de-AT-1901': 'austrian',
302 'dsb': 'lowersorbian',
303 'el': 'greek', # monotonic (el-monoton)
304 'el-polyton': 'polutonikogreek',
305 'en': 'english', # TeX' default language
306 'en-AU': 'australian',
307 'en-CA': 'canadian',
308 'en-GB': 'british',
309 'en-NZ': 'newzealand',
310 'en-US': 'american',
311 'eo': 'esperanto',
312 'es': 'spanish',
313 'et': 'estonian',
314 'eu': 'basque',
315 # 'fa': 'farsi',
316 'fi': 'finnish',
317 'fr': 'french',
318 'fr-CA': 'canadien',
319 'ga': 'irish', # Irish Gaelic
320 # 'grc': # Ancient Greek
321 'grc-ibycus': 'ibycus', # Ibycus encoding
322 'gl': 'galician',
323 'he': 'hebrew',
324 'hr': 'croatian',
325 'hsb': 'uppersorbian',
326 'hu': 'magyar',
327 'ia': 'interlingua',
328 'id': 'bahasai', # Bahasa (Indonesian)
329 'is': 'icelandic',
330 'it': 'italian',
331 'ja': 'japanese',
332 'kk': 'kazakh',
333 'la': 'latin',
334 'lt': 'lithuanian',
335 'lv': 'latvian',
336 'mn': 'mongolian', # Mongolian, Cyrillic script (mn-cyrl)
337 'ms': 'bahasam', # Bahasa (Malay)
338 'nb': 'norsk', # Norwegian Bokmal
339 'nl': 'dutch',
340 'nn': 'nynorsk', # Norwegian Nynorsk
341 'no': 'norsk', # Norwegian (Bokmal)
342 'pl': 'polish',
343 'pt': 'portuges',
344 'pt-BR': 'brazil',
345 'ro': 'romanian',
346 'ru': 'russian',
347 'se': 'samin', # North Sami
348 'sh-Cyrl': 'serbianc', # Serbo-Croatian, Cyrillic script
349 'sh-Latn': 'serbian', # Serbo-Croatian, Latin script see also 'hr'
350 'sk': 'slovak',
351 'sl': 'slovene',
352 'sq': 'albanian',
353 'sr': 'serbianc', # Serbian, Cyrillic script (contributed)
354 'sr-Latn': 'serbian', # Serbian, Latin script
355 'sv': 'swedish',
356 # 'th': 'thai',
357 'tr': 'turkish',
358 'uk': 'ukrainian',
359 'vi': 'vietnam',
360 # zh-Latn: Chinese Pinyin
362 # normalize (downcase) keys
363 language_codes = dict([(k.lower(), v) for (k,v) in language_codes.items()])
365 warn_msg = 'Language "%s" not supported by LaTeX (babel)'
367 # "Active characters" are shortcuts that start a LaTeX macro and may need
368 # escaping for literals use. Characters that prevent literal use (e.g.
369 # starting accent macros like "a -> ä) will be deactivated if one of the
370 # defining languages is used in the document.
371 # Special cases:
372 # ~ (tilde) -- used in estonian, basque, galician, and old versions of
373 # spanish -- cannot be deactivated as it denotes a no-break space macro,
374 # " (straight quote) -- used in albanian, austrian, basque
375 # brazil, bulgarian, catalan, czech, danish, dutch, estonian,
376 # finnish, galician, german, icelandic, italian, latin, naustrian,
377 # ngerman, norsk, nynorsk, polish, portuges, russian, serbian, slovak,
378 # slovene, spanish, swedish, ukrainian, and uppersorbian --
379 # is escaped as ``\textquotedbl``.
380 active_chars = {# TeX/Babel-name: active characters to deactivate
381 # 'breton': ':;!?' # ensure whitespace
382 # 'esperanto': '^',
383 # 'estonian': '~"`',
384 # 'french': ':;!?' # ensure whitespace
385 'galician': '.<>', # also '~"'
386 # 'magyar': '`', # for special hyphenation cases
387 'spanish': '.<>', # old versions also '~'
388 # 'turkish': ':!=' # ensure whitespace
391 def __init__(self, language_code, reporter=None):
392 self.reporter = reporter
393 self.language = self.language_name(language_code)
394 self.otherlanguages = {}
396 def __call__(self):
397 """Return the babel call with correct options and settings"""
398 languages = sorted(self.otherlanguages.keys())
399 languages.append(self.language or 'english')
400 self.setup = [r'\usepackage[%s]{babel}' % ','.join(languages)]
401 # Deactivate "active characters"
402 shorthands = []
403 for c in ''.join([self.active_chars.get(l, '') for l in languages]):
404 if c not in shorthands:
405 shorthands.append(c)
406 if shorthands:
407 self.setup.append(r'\AtBeginDocument{\shorthandoff{%s}}'
408 % ''.join(shorthands))
409 # Including '~' in shorthandoff prevents its use as no-break space
410 if 'galician' in languages:
411 self.setup.append(r'\deactivatetilden % restore ~ in Galician')
412 if 'estonian' in languages:
413 self.setup.extend([r'\makeatletter',
414 r' \addto\extrasestonian{\bbl@deactivate{~}}',
415 r'\makeatother'])
416 if 'basque' in languages:
417 self.setup.extend([r'\makeatletter',
418 r' \addto\extrasbasque{\bbl@deactivate{~}}',
419 r'\makeatother'])
420 if (languages[-1] == 'english' and
421 'french' in self.otherlanguages.keys()):
422 self.setup += ['% Prevent side-effects if French hyphenation '
423 'patterns are not loaded:',
424 r'\frenchbsetup{StandardLayout}',
425 r'\AtBeginDocument{\selectlanguage{%s}'
426 r'\noextrasfrench}' % self.language]
427 return '\n'.join(self.setup)
429 def language_name(self, language_code):
430 """Return TeX language name for `language_code`"""
431 for tag in utils.normalize_language_tag(language_code):
432 try:
433 return self.language_codes[tag]
434 except KeyError:
435 pass
436 if self.reporter is not None:
437 self.reporter.warning(self.warn_msg % language_code)
438 return ''
440 def get_language(self):
441 # Obsolete, kept for backwards compatibility with Sphinx
442 return self.language
445 # Building blocks for the latex preamble
446 # --------------------------------------
448 class SortableDict(dict):
449 """Dictionary with additional sorting methods
451 Tip: use key starting with with '_' for sorting before small letters
452 and with '~' for sorting after small letters.
454 def sortedkeys(self):
455 """Return sorted list of keys"""
456 keys = self.keys()
457 keys.sort()
458 return keys
460 def sortedvalues(self):
461 """Return list of values sorted by keys"""
462 return [self[key] for key in self.sortedkeys()]
465 # PreambleCmds
466 # `````````````
467 # A container for LaTeX code snippets that can be
468 # inserted into the preamble if required in the document.
470 # .. The package 'makecmds' would enable shorter definitions using the
471 # \providelength and \provideenvironment commands.
472 # However, it is pretty non-standard (texlive-latex-extra).
474 class PreambleCmds(object):
475 """Building blocks for the latex preamble."""
477 PreambleCmds.abstract = r"""
478 % abstract title
479 \providecommand*{\DUtitleabstract}[1]{\centerline{\textbf{#1}}}"""
481 PreambleCmds.admonition = r"""
482 % admonition (specially marked topic)
483 \providecommand{\DUadmonition}[2][class-arg]{%
484 % try \DUadmonition#1{#2}:
485 \ifcsname DUadmonition#1\endcsname%
486 \csname DUadmonition#1\endcsname{#2}%
487 \else
488 \begin{center}
489 \fbox{\parbox{0.9\linewidth}{#2}}
490 \end{center}
492 }"""
494 ## PreambleCmds.caption = r"""% configure caption layout
495 ## \usepackage{caption}
496 ## \captionsetup{singlelinecheck=false}% no exceptions for one-liners"""
498 PreambleCmds.color = r"""\usepackage{color}"""
500 PreambleCmds.docinfo = r"""
501 % docinfo (width of docinfo table)
502 \DUprovidelength{\DUdocinfowidth}{0.9\linewidth}"""
503 # PreambleCmds.docinfo._depends = 'providelength'
505 PreambleCmds.dedication = r"""
506 % dedication topic
507 \providecommand*{\DUCLASSdedication}{%
508 \renewenvironment{quote}{\begin{center}}{\end{center}}%
509 }"""
511 PreambleCmds.duclass = r"""
512 % class handling for environments (block-level elements)
513 % \begin{DUclass}{spam} tries \DUCLASSspam and
514 % \end{DUclass}{spam} tries \endDUCLASSspam
515 \ifx\DUclass\undefined % poor man's "provideenvironment"
516 \newenvironment{DUclass}[1]%
517 {\def\DocutilsClassFunctionName{DUCLASS#1}% arg cannot be used in end-part of environment.
518 \csname \DocutilsClassFunctionName \endcsname}%
519 {\csname end\DocutilsClassFunctionName \endcsname}%
520 \fi"""
522 PreambleCmds.error = r"""
523 % error admonition title
524 \providecommand*{\DUtitleerror}[1]{\DUtitle{\color{red}#1}}"""
526 PreambleCmds.fieldlist = r"""
527 % fieldlist environment
528 \ifthenelse{\isundefined{\DUfieldlist}}{
529 \newenvironment{DUfieldlist}%
530 {\quote\description}
531 {\enddescription\endquote}
532 }{}"""
534 PreambleCmds.float_settings = r"""\usepackage{float} % float configuration
535 \floatplacement{figure}{H} % place figures here definitely"""
537 PreambleCmds.footnotes = r"""% numeric or symbol footnotes with hyperlinks
538 \providecommand*{\DUfootnotemark}[3]{%
539 \raisebox{1em}{\hypertarget{#1}{}}%
540 \hyperlink{#2}{\textsuperscript{#3}}%
542 \providecommand{\DUfootnotetext}[4]{%
543 \begingroup%
544 \renewcommand{\thefootnote}{%
545 \protect\raisebox{1em}{\protect\hypertarget{#1}{}}%
546 \protect\hyperlink{#2}{#3}}%
547 \footnotetext{#4}%
548 \endgroup%
549 }"""
551 PreambleCmds.graphicx_auto = r"""% Check output format
552 \ifx\pdftexversion\undefined
553 \usepackage{graphicx}
554 \else
555 \usepackage[pdftex]{graphicx}
556 \fi"""
558 PreambleCmds.highlight_rules = r"""% basic code highlight:
559 \providecommand*\DUrolecomment[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
560 \providecommand*\DUroledeleted[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
561 \providecommand*\DUrolekeyword[1]{\textbf{#1}}
562 \providecommand*\DUrolestring[1]{\textit{#1}}"""
564 PreambleCmds.inline = r"""
565 % inline markup (custom roles)
566 % \DUrole{#1}{#2} tries \DUrole#1{#2}
567 \providecommand*{\DUrole}[2]{%
568 % backwards compatibility: try \docutilsrole#1{#2}
569 \ifcsname docutilsrole#1\endcsname%
570 \csname docutilsrole#1\endcsname{#2}%
571 \else
572 \csname DUrole#1\endcsname{#2}%
573 \fi%
574 }"""
576 PreambleCmds.legend = r"""
577 % legend environment
578 \ifthenelse{\isundefined{\DUlegend}}{
579 \newenvironment{DUlegend}{\small}{}
580 }{}"""
582 PreambleCmds.lineblock = r"""
583 % lineblock environment
584 \DUprovidelength{\DUlineblockindent}{2.5em}
585 \ifthenelse{\isundefined{\DUlineblock}}{
586 \newenvironment{DUlineblock}[1]{%
587 \list{}{\setlength{\partopsep}{\parskip}
588 \addtolength{\partopsep}{\baselineskip}
589 \setlength{\topsep}{0pt}
590 \setlength{\itemsep}{0.15\baselineskip}
591 \setlength{\parsep}{0pt}
592 \setlength{\leftmargin}{#1}}
593 \raggedright
595 {\endlist}
596 }{}"""
597 # PreambleCmds.lineblock._depends = 'providelength'
599 PreambleCmds.linking = r"""
600 %% hyperlinks:
601 \ifthenelse{\isundefined{\hypersetup}}{
602 \usepackage[%s]{hyperref}
603 \usepackage{bookmark}
604 \urlstyle{same} %% normal text font (alternatives: tt, rm, sf)
605 }{}"""
607 PreambleCmds.minitoc = r"""%% local table of contents
608 \usepackage{minitoc}"""
610 PreambleCmds.optionlist = r"""
611 % optionlist environment
612 \providecommand*{\DUoptionlistlabel}[1]{\bf #1 \hfill}
613 \DUprovidelength{\DUoptionlistindent}{3cm}
614 \ifthenelse{\isundefined{\DUoptionlist}}{
615 \newenvironment{DUoptionlist}{%
616 \list{}{\setlength{\labelwidth}{\DUoptionlistindent}
617 \setlength{\rightmargin}{1cm}
618 \setlength{\leftmargin}{\rightmargin}
619 \addtolength{\leftmargin}{\labelwidth}
620 \addtolength{\leftmargin}{\labelsep}
621 \renewcommand{\makelabel}{\DUoptionlistlabel}}
623 {\endlist}
624 }{}"""
625 # PreambleCmds.optionlist._depends = 'providelength'
627 PreambleCmds.providelength = r"""
628 % providelength (provide a length variable and set default, if it is new)
629 \providecommand*{\DUprovidelength}[2]{
630 \ifthenelse{\isundefined{#1}}{\newlength{#1}\setlength{#1}{#2}}{}
631 }"""
633 PreambleCmds.rubric = r"""
634 % rubric (informal heading)
635 \providecommand*{\DUrubric}[1]{%
636 \subsubsection*{\centering\textit{\textmd{#1}}}}"""
638 PreambleCmds.sidebar = r"""
639 % sidebar (text outside the main text flow)
640 \providecommand{\DUsidebar}[1]{%
641 \begin{center}
642 \colorbox[gray]{0.80}{\parbox{0.9\linewidth}{#1}}
643 \end{center}
644 }"""
646 PreambleCmds.subtitle = r"""
647 % subtitle (for topic/sidebar)
648 \providecommand*{\DUsubtitle}[1]{\par\emph{#1}\smallskip}"""
650 PreambleCmds.documentsubtitle = r"""
651 % subtitle (in document title)
652 \providecommand*{\DUdocumentsubtitle}[1]{{\large #1}}"""
654 PreambleCmds.table = r"""\usepackage{longtable,ltcaption,array}
655 \setlength{\extrarowheight}{2pt}
656 \newlength{\DUtablewidth} % internal use in tables"""
658 # Options [force,almostfull] prevent spurious error messages, see
659 # de.comp.text.tex/2005-12/msg01855
660 PreambleCmds.textcomp = """\
661 \\usepackage{textcomp} % text symbol macros"""
663 PreambleCmds.textsubscript = r"""
664 % text mode subscript
665 \ifx\textsubscript\undefined
666 \usepackage{fixltx2e} % since 2015 loaded by default
667 \fi"""
669 PreambleCmds.titlereference = r"""
670 % titlereference role
671 \providecommand*{\DUroletitlereference}[1]{\textsl{#1}}"""
673 PreambleCmds.title = r"""
674 % title for topics, admonitions, unsupported section levels, and sidebar
675 \providecommand*{\DUtitle}[2][class-arg]{%
676 % call \DUtitle#1{#2} if it exists:
677 \ifcsname DUtitle#1\endcsname%
678 \csname DUtitle#1\endcsname{#2}%
679 \else
680 \smallskip\noindent\textbf{#2}\smallskip%
682 }"""
684 PreambleCmds.transition = r"""
685 % transition (break, fancybreak, anonymous section)
686 \providecommand*{\DUtransition}{%
687 \hspace*{\fill}\hrulefill\hspace*{\fill}
688 \vskip 0.5\baselineskip
689 }"""
692 # LaTeX encoding maps
693 # -------------------
694 # ::
696 class CharMaps(object):
697 """LaTeX representations for active and Unicode characters."""
699 # characters that need escaping even in `alltt` environments:
700 alltt = {
701 ord('\\'): ur'\textbackslash{}',
702 ord('{'): ur'\{',
703 ord('}'): ur'\}',
705 # characters that normally need escaping:
706 special = {
707 ord('#'): ur'\#',
708 ord('$'): ur'\$',
709 ord('%'): ur'\%',
710 ord('&'): ur'\&',
711 ord('~'): ur'\textasciitilde{}',
712 ord('_'): ur'\_',
713 ord('^'): ur'\textasciicircum{}',
714 # straight double quotes are 'active' in many languages
715 ord('"'): ur'\textquotedbl{}',
716 # Square brackets are ordinary chars and cannot be escaped with '\',
717 # so we put them in a group '{[}'. (Alternative: ensure that all
718 # macros with optional arguments are terminated with {} and text
719 # inside any optional argument is put in a group ``[{text}]``).
720 # Commands with optional args inside an optional arg must be put in a
721 # group, e.g. ``\item[{\hyperref[label]{text}}]``.
722 ord('['): ur'{[}',
723 ord(']'): ur'{]}',
724 # the soft hyphen is unknown in 8-bit text
725 # and not properly handled by XeTeX
726 0x00AD: ur'\-', # SOFT HYPHEN
728 # Unicode chars that are not recognized by LaTeX's utf8 encoding
729 unsupported_unicode = {
730 # TODO: ensure white space also at the beginning of a line?
731 # 0x00A0: ur'\leavevmode\nobreak\vadjust{}~'
732 0x2000: ur'\enskip', # EN QUAD
733 0x2001: ur'\quad', # EM QUAD
734 0x2002: ur'\enskip', # EN SPACE
735 0x2003: ur'\quad', # EM SPACE
736 0x2008: ur'\,', # PUNCTUATION SPACE   
737 0x200b: ur'\hspace{0pt}', # ZERO WIDTH SPACE
738 0x202F: ur'\,', # NARROW NO-BREAK SPACE
739 # 0x02d8: ur'\\u{ }', # BREVE
740 0x2011: ur'\hbox{-}', # NON-BREAKING HYPHEN
741 0x212b: ur'\AA', # ANGSTROM SIGN
742 0x21d4: ur'\ensuremath{\Leftrightarrow}',
743 # Docutils footnote symbols:
744 0x2660: ur'\ensuremath{\spadesuit}',
745 0x2663: ur'\ensuremath{\clubsuit}',
746 0xfb00: ur'ff', # LATIN SMALL LIGATURE FF
747 0xfb01: ur'fi', # LATIN SMALL LIGATURE FI
748 0xfb02: ur'fl', # LATIN SMALL LIGATURE FL
749 0xfb03: ur'ffi', # LATIN SMALL LIGATURE FFI
750 0xfb04: ur'ffl', # LATIN SMALL LIGATURE FFL
752 # Unicode chars that are recognized by LaTeX's utf8 encoding
753 utf8_supported_unicode = {
754 0x00A0: ur'~', # NO-BREAK SPACE
755 0x00AB: ur'\guillemotleft{}', # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
756 0x00bb: ur'\guillemotright{}', # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
757 0x200C: ur'\textcompwordmark{}', # ZERO WIDTH NON-JOINER
758 0x2013: ur'\textendash{}',
759 0x2014: ur'\textemdash{}',
760 0x2018: ur'\textquoteleft{}',
761 0x2019: ur'\textquoteright{}',
762 0x201A: ur'\quotesinglbase{}', # SINGLE LOW-9 QUOTATION MARK
763 0x201C: ur'\textquotedblleft{}',
764 0x201D: ur'\textquotedblright{}',
765 0x201E: ur'\quotedblbase{}', # DOUBLE LOW-9 QUOTATION MARK
766 0x2030: ur'\textperthousand{}', # PER MILLE SIGN
767 0x2031: ur'\textpertenthousand{}', # PER TEN THOUSAND SIGN
768 0x2039: ur'\guilsinglleft{}',
769 0x203A: ur'\guilsinglright{}',
770 0x2423: ur'\textvisiblespace{}', # OPEN BOX
771 0x2020: ur'\dag{}',
772 0x2021: ur'\ddag{}',
773 0x2026: ur'\dots{}',
774 0x2122: ur'\texttrademark{}',
776 # recognized with 'utf8', if textcomp is loaded
777 textcomp = {
778 # Latin-1 Supplement
779 0x00a2: ur'\textcent{}', # ¢ CENT SIGN
780 0x00a4: ur'\textcurrency{}', # ¤ CURRENCY SYMBOL
781 0x00a5: ur'\textyen{}', # ¥ YEN SIGN
782 0x00a6: ur'\textbrokenbar{}', # ¦ BROKEN BAR
783 0x00a7: ur'\textsection{}', # § SECTION SIGN
784 0x00a8: ur'\textasciidieresis{}', # ¨ DIAERESIS
785 0x00a9: ur'\textcopyright{}', # © COPYRIGHT SIGN
786 0x00aa: ur'\textordfeminine{}', # ª FEMININE ORDINAL INDICATOR
787 0x00ac: ur'\textlnot{}', # ¬ NOT SIGN
788 0x00ae: ur'\textregistered{}', # ® REGISTERED SIGN
789 0x00af: ur'\textasciimacron{}', # ¯ MACRON
790 0x00b0: ur'\textdegree{}', # ° DEGREE SIGN
791 0x00b1: ur'\textpm{}', # ± PLUS-MINUS SIGN
792 0x00b2: ur'\texttwosuperior{}', # ² SUPERSCRIPT TWO
793 0x00b3: ur'\textthreesuperior{}', # ³ SUPERSCRIPT THREE
794 0x00b4: ur'\textasciiacute{}', # ´ ACUTE ACCENT
795 0x00b5: ur'\textmu{}', # µ MICRO SIGN
796 0x00b6: ur'\textparagraph{}', # ¶ PILCROW SIGN # != \textpilcrow
797 0x00b9: ur'\textonesuperior{}', # ¹ SUPERSCRIPT ONE
798 0x00ba: ur'\textordmasculine{}', # º MASCULINE ORDINAL INDICATOR
799 0x00bc: ur'\textonequarter{}', # 1/4 FRACTION
800 0x00bd: ur'\textonehalf{}', # 1/2 FRACTION
801 0x00be: ur'\textthreequarters{}', # 3/4 FRACTION
802 0x00d7: ur'\texttimes{}', # × MULTIPLICATION SIGN
803 0x00f7: ur'\textdiv{}', # ÷ DIVISION SIGN
804 # others
805 0x0192: ur'\textflorin{}', # LATIN SMALL LETTER F WITH HOOK
806 0x02b9: ur'\textasciiacute{}', # MODIFIER LETTER PRIME
807 0x02ba: ur'\textacutedbl{}', # MODIFIER LETTER DOUBLE PRIME
808 0x2016: ur'\textbardbl{}', # DOUBLE VERTICAL LINE
809 0x2022: ur'\textbullet{}', # BULLET
810 0x2032: ur'\textasciiacute{}', # PRIME
811 0x2033: ur'\textacutedbl{}', # DOUBLE PRIME
812 0x2035: ur'\textasciigrave{}', # REVERSED PRIME
813 0x2036: ur'\textgravedbl{}', # REVERSED DOUBLE PRIME
814 0x203b: ur'\textreferencemark{}', # REFERENCE MARK
815 0x203d: ur'\textinterrobang{}', # INTERROBANG
816 0x2044: ur'\textfractionsolidus{}', # FRACTION SLASH
817 0x2045: ur'\textlquill{}', # LEFT SQUARE BRACKET WITH QUILL
818 0x2046: ur'\textrquill{}', # RIGHT SQUARE BRACKET WITH QUILL
819 0x2052: ur'\textdiscount{}', # COMMERCIAL MINUS SIGN
820 0x20a1: ur'\textcolonmonetary{}', # COLON SIGN
821 0x20a3: ur'\textfrenchfranc{}', # FRENCH FRANC SIGN
822 0x20a4: ur'\textlira{}', # LIRA SIGN
823 0x20a6: ur'\textnaira{}', # NAIRA SIGN
824 0x20a9: ur'\textwon{}', # WON SIGN
825 0x20ab: ur'\textdong{}', # DONG SIGN
826 0x20ac: ur'\texteuro{}', # EURO SIGN
827 0x20b1: ur'\textpeso{}', # PESO SIGN
828 0x20b2: ur'\textguarani{}', # GUARANI SIGN
829 0x2103: ur'\textcelsius{}', # DEGREE CELSIUS
830 0x2116: ur'\textnumero{}', # NUMERO SIGN
831 0x2117: ur'\textcircledP{}', # SOUND RECORDING COYRIGHT
832 0x211e: ur'\textrecipe{}', # PRESCRIPTION TAKE
833 0x2120: ur'\textservicemark{}', # SERVICE MARK
834 0x2122: ur'\texttrademark{}', # TRADE MARK SIGN
835 0x2126: ur'\textohm{}', # OHM SIGN
836 0x2127: ur'\textmho{}', # INVERTED OHM SIGN
837 0x212e: ur'\textestimated{}', # ESTIMATED SYMBOL
838 0x2190: ur'\textleftarrow{}', # LEFTWARDS ARROW
839 0x2191: ur'\textuparrow{}', # UPWARDS ARROW
840 0x2192: ur'\textrightarrow{}', # RIGHTWARDS ARROW
841 0x2193: ur'\textdownarrow{}', # DOWNWARDS ARROW
842 0x2212: ur'\textminus{}', # MINUS SIGN
843 0x2217: ur'\textasteriskcentered{}', # ASTERISK OPERATOR
844 0x221a: ur'\textsurd{}', # SQUARE ROOT
845 0x2422: ur'\textblank{}', # BLANK SYMBOL
846 0x25e6: ur'\textopenbullet{}', # WHITE BULLET
847 0x25ef: ur'\textbigcircle{}', # LARGE CIRCLE
848 0x266a: ur'\textmusicalnote{}', # EIGHTH NOTE
849 0x26ad: ur'\textmarried{}', # MARRIAGE SYMBOL
850 0x26ae: ur'\textdivorced{}', # DIVORCE SYMBOL
851 0x27e8: ur'\textlangle{}', # MATHEMATICAL LEFT ANGLE BRACKET
852 0x27e9: ur'\textrangle{}', # MATHEMATICAL RIGHT ANGLE BRACKET
854 # Unicode chars that require a feature/package to render
855 pifont = {
856 0x2665: ur'\ding{170}', # black heartsuit
857 0x2666: ur'\ding{169}', # black diamondsuit
858 0x2713: ur'\ding{51}', # check mark
859 0x2717: ur'\ding{55}', # check mark
861 # TODO: greek alphabet ... ?
862 # see also LaTeX codec
863 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252124
864 # and unimap.py from TeXML
867 class DocumentClass(object):
868 """Details of a LaTeX document class."""
870 def __init__(self, document_class, with_part=False):
871 self.document_class = document_class
872 self._with_part = with_part
873 self.sections = ['section', 'subsection', 'subsubsection',
874 'paragraph', 'subparagraph']
875 if self.document_class in ('book', 'memoir', 'report',
876 'scrbook', 'scrreprt'):
877 self.sections.insert(0, 'chapter')
878 if self._with_part:
879 self.sections.insert(0, 'part')
881 def section(self, level):
882 """Return the LaTeX section name for section `level`.
884 The name depends on the specific document class.
885 Level is 1,2,3..., as level 0 is the title.
887 if level <= len(self.sections):
888 return self.sections[level-1]
889 else: # unsupported levels
890 return 'DUtitle[section%s]' % roman.toRoman(level)
892 class Table(object):
893 """Manage a table while traversing.
895 Maybe change to a mixin defining the visit/departs, but then
896 class Table internal variables are in the Translator.
898 Table style might be
900 :standard: horizontal and vertical lines
901 :booktabs: only horizontal lines (requires "booktabs" LaTeX package)
902 :borderless: no borders around table cells
903 :nolines: alias for borderless
905 :colwidths-auto: column widths determined by LaTeX
906 :colwidths-given: use colum widths from rST source
908 def __init__(self, translator, latex_type):
909 self._translator = translator
910 self._latex_type = latex_type
911 self._open = False
912 # miscellaneous attributes
913 self._attrs = {}
914 self._col_width = []
915 self._rowspan = []
916 self.stubs = []
917 self.colwidths_auto = False
918 self._in_thead = 0
920 def open(self):
921 self._open = True
922 self._col_specs = []
923 self.caption = []
924 self._attrs = {}
925 self._in_head = False # maybe context with search
926 def close(self):
927 self._open = False
928 self._col_specs = None
929 self.caption = []
930 self._attrs = {}
931 self.stubs = []
932 self.colwidths_auto = False
934 def is_open(self):
935 return self._open
937 def set_table_style(self, table_style, classes):
938 borders = [cls.replace('nolines', 'borderless')
939 for cls in table_style+classes
940 if cls in ('standard','booktabs','borderless', 'nolines')]
941 try:
942 self.borders = borders[-1]
943 except IndexError:
944 self.borders = 'standard'
945 self.colwidths_auto = (('colwidths-auto' in classes
946 and 'colwidths-given' not in table_style)
947 or ('colwidths-auto' in table_style
948 and ('colwidths-given' not in classes)))
950 def get_latex_type(self):
951 if self._latex_type == 'longtable' and not self.caption:
952 # do not advance the "table" counter (requires "ltcaption" package)
953 return('longtable*')
954 return self._latex_type
956 def set(self,attr,value):
957 self._attrs[attr] = value
958 def get(self,attr):
959 if attr in self._attrs:
960 return self._attrs[attr]
961 return None
963 def get_vertical_bar(self):
964 if self.borders == 'standard':
965 return '|'
966 return ''
968 # horizontal lines are drawn below a row,
969 def get_opening(self):
970 align_map = {'left': 'l',
971 'center': 'c',
972 'right': 'r'}
973 align = align_map.get(self.get('align') or 'center')
974 opening = [r'\begin{%s}[%s]' % (self.get_latex_type(), align)]
975 if not self.colwidths_auto:
976 opening.insert(0, r'\setlength{\DUtablewidth}{\linewidth}')
977 return '\n'.join(opening)
979 def get_closing(self):
980 closing = []
981 if self.borders == 'booktabs':
982 closing.append(r'\bottomrule')
983 # elif self.borders == 'standard':
984 # closing.append(r'\hline')
985 closing.append(r'\end{%s}' % self.get_latex_type())
986 return '\n'.join(closing)
988 def visit_colspec(self, node):
989 self._col_specs.append(node)
990 # "stubs" list is an attribute of the tgroup element:
991 self.stubs.append(node.attributes.get('stub'))
993 def get_colspecs(self, node):
994 """Return column specification for longtable.
996 Assumes reST line length being 80 characters.
997 Table width is hairy.
999 === ===
1000 ABC DEF
1001 === ===
1003 usually gets to narrow, therefore we add 1 (fiddlefactor).
1005 bar = self.get_vertical_bar()
1006 self._rowspan= [0] * len(self._col_specs)
1007 self._col_width = []
1008 if self.colwidths_auto:
1009 latex_table_spec = (bar+'l')*len(self._col_specs)
1010 return latex_table_spec+bar
1011 width = 80
1012 total_width = 0.0
1013 # first see if we get too wide.
1014 for node in self._col_specs:
1015 colwidth = float(node['colwidth']+1) / width
1016 total_width += colwidth
1017 # donot make it full linewidth
1018 factor = 0.93
1019 if total_width > 1.0:
1020 factor /= total_width
1021 latex_table_spec = ''
1022 for node in self._col_specs:
1023 colwidth = factor * float(node['colwidth']+1) / width
1024 self._col_width.append(colwidth+0.005)
1025 latex_table_spec += '%sp{%.3f\\DUtablewidth}' % (bar, colwidth+0.005)
1026 return latex_table_spec+bar
1028 def get_column_width(self):
1029 """Return columnwidth for current cell (not multicell)."""
1030 try:
1031 return '%.2f\\DUtablewidth' % self._col_width[self._cell_in_row]
1032 except IndexError:
1033 return '*'
1035 def get_multicolumn_width(self, start, len_):
1036 """Return sum of columnwidths for multicell."""
1037 try:
1038 mc_width = sum([width
1039 for width in ([self._col_width[start + co]
1040 for co in range (len_)])])
1041 return 'p{%.2f\\DUtablewidth}' % mc_width
1042 except IndexError:
1043 return 'l'
1045 def get_caption(self):
1046 if not self.caption:
1047 return ''
1048 caption = ''.join(self.caption)
1049 if 1 == self._translator.thead_depth():
1050 return r'\caption{%s}\\' '\n' % caption
1051 return r'\caption[]{%s (... continued)}\\' '\n' % caption
1053 def need_recurse(self):
1054 if self._latex_type == 'longtable':
1055 return 1 == self._translator.thead_depth()
1056 return 0
1058 def visit_thead(self):
1059 self._in_thead += 1
1060 if self.borders == 'standard':
1061 return ['\\hline\n']
1062 elif self.borders == 'booktabs':
1063 return ['\\toprule\n']
1064 return []
1066 def depart_thead(self):
1067 a = []
1068 #if self.borders == 'standard':
1069 # a.append('\\hline\n')
1070 if self.borders == 'booktabs':
1071 a.append('\\midrule\n')
1072 if self._latex_type == 'longtable':
1073 if 1 == self._translator.thead_depth():
1074 a.append('\\endfirsthead\n')
1075 else:
1076 a.append('\\endhead\n')
1077 a.append(r'\multicolumn{%d}{c}' % len(self._col_specs) +
1078 r'{\hfill ... continued on next page} \\')
1079 a.append('\n\\endfoot\n\\endlastfoot\n')
1080 # for longtable one could add firsthead, foot and lastfoot
1081 self._in_thead -= 1
1082 return a
1084 def visit_row(self):
1085 self._cell_in_row = 0
1087 def depart_row(self):
1088 res = [' \\\\\n']
1089 self._cell_in_row = None # remove cell counter
1090 for i in range(len(self._rowspan)):
1091 if (self._rowspan[i]>0):
1092 self._rowspan[i] -= 1
1094 if self.borders == 'standard':
1095 rowspans = [i+1 for i in range(len(self._rowspan))
1096 if (self._rowspan[i]<=0)]
1097 if len(rowspans)==len(self._rowspan):
1098 res.append('\\hline\n')
1099 else:
1100 cline = ''
1101 rowspans.reverse()
1102 # TODO merge clines
1103 while True:
1104 try:
1105 c_start = rowspans.pop()
1106 except:
1107 break
1108 cline += '\\cline{%d-%d}\n' % (c_start,c_start)
1109 res.append(cline)
1110 return res
1112 def set_rowspan(self,cell,value):
1113 try:
1114 self._rowspan[cell] = value
1115 except:
1116 pass
1118 def get_rowspan(self,cell):
1119 try:
1120 return self._rowspan[cell]
1121 except:
1122 return 0
1124 def get_entry_number(self):
1125 return self._cell_in_row
1127 def visit_entry(self):
1128 self._cell_in_row += 1
1130 def is_stub_column(self):
1131 if len(self.stubs) >= self._cell_in_row:
1132 return self.stubs[self._cell_in_row]
1133 return False
1136 class LaTeXTranslator(nodes.NodeVisitor):
1138 Generate code for 8-bit LaTeX from a Docutils document tree.
1140 See the docstring of docutils.writers._html_base.HTMLTranslator for
1141 notes on and examples of safe subclassing.
1144 # When options are given to the documentclass, latex will pass them
1145 # to other packages, as done with babel.
1146 # Dummy settings might be taken from document settings
1148 # Generate code for typesetting with 8-bit latex/pdflatex vs.
1149 # xelatex/lualatex engine. Overwritten by the XeTeX writer
1150 is_xetex = False
1152 # Config setting defaults
1153 # -----------------------
1155 # TODO: use mixins for different implementations.
1156 # list environment for docinfo. else tabularx
1157 ## use_optionlist_for_docinfo = False # TODO: NOT YET IN USE
1159 # Use compound enumerations (1.A.1.)
1160 compound_enumerators = False
1162 # If using compound enumerations, include section information.
1163 section_prefix_for_enumerators = False
1165 # This is the character that separates the section ("." subsection ...)
1166 # prefix from the regular list enumerator.
1167 section_enumerator_separator = '-'
1169 # Auxiliary variables
1170 # -------------------
1172 has_latex_toc = False # is there a toc in the doc? (needed by minitoc)
1173 is_toc_list = False # is the current bullet_list a ToC?
1174 section_level = 0
1176 # Flags to encode():
1177 # inside citation reference labels underscores dont need to be escaped
1178 inside_citation_reference_label = False
1179 verbatim = False # do not encode
1180 insert_non_breaking_blanks = False # replace blanks by "~"
1181 insert_newline = False # add latex newline commands
1182 literal = False # literal text (block or inline)
1183 alltt = False # inside `alltt` environment
1185 def __init__(self, document, babel_class=Babel):
1186 nodes.NodeVisitor.__init__(self, document)
1187 # Reporter
1188 # ~~~~~~~~
1189 self.warn = self.document.reporter.warning
1190 self.error = self.document.reporter.error
1192 # Settings
1193 # ~~~~~~~~
1194 self.settings = settings = document.settings
1195 self.latex_encoding = self.to_latex_encoding(settings.output_encoding)
1196 self.use_latex_toc = settings.use_latex_toc
1197 self.use_latex_docinfo = settings.use_latex_docinfo
1198 self._use_latex_citations = settings.use_latex_citations
1199 self._reference_label = settings.reference_label
1200 self.hyperlink_color = settings.hyperlink_color
1201 self.compound_enumerators = settings.compound_enumerators
1202 self.font_encoding = getattr(settings, 'font_encoding', '')
1203 self.section_prefix_for_enumerators = (
1204 settings.section_prefix_for_enumerators)
1205 self.section_enumerator_separator = (
1206 settings.section_enumerator_separator.replace('_', r'\_'))
1207 # literal blocks:
1208 self.literal_block_env = 'alltt'
1209 self.literal_block_options = ''
1210 if settings.literal_block_env != '':
1211 (none,
1212 self.literal_block_env,
1213 self.literal_block_options,
1214 none ) = re.split(r'(\w+)(.*)', settings.literal_block_env)
1215 elif settings.use_verbatim_when_possible:
1216 self.literal_block_env = 'verbatim'
1218 if self.settings.use_bibtex:
1219 self.bibtex = self.settings.use_bibtex.split(',',1)
1220 # TODO avoid errors on not declared citations.
1221 else:
1222 self.bibtex = None
1223 # language module for Docutils-generated text
1224 # (labels, bibliographic_fields, and author_separators)
1225 self.language_module = languages.get_language(settings.language_code,
1226 document.reporter)
1227 self.babel = babel_class(settings.language_code, document.reporter)
1228 self.author_separator = self.language_module.author_separators[0]
1229 d_options = [self.settings.documentoptions]
1230 if self.babel.language not in ('english', ''):
1231 d_options.append(self.babel.language)
1232 self.documentoptions = ','.join(filter(None, d_options))
1233 self.d_class = DocumentClass(settings.documentclass,
1234 settings.use_part_section)
1235 # graphic package options:
1236 if self.settings.graphicx_option == '':
1237 self.graphicx_package = r'\usepackage{graphicx}'
1238 elif self.settings.graphicx_option.lower() == 'auto':
1239 self.graphicx_package = PreambleCmds.graphicx_auto
1240 else:
1241 self.graphicx_package = (r'\usepackage[%s]{graphicx}' %
1242 self.settings.graphicx_option)
1243 # footnotes:
1244 self.docutils_footnotes = settings.docutils_footnotes
1245 # @@ table_style: list of values from fixed set: warn?
1246 # for s in self.settings.table_style:
1247 # if s not in Writer.table_style_values:
1248 # self.warn('Ignoring value "%s" in "table-style" setting.' %s)
1250 # Output collection stacks
1251 # ~~~~~~~~~~~~~~~~~~~~~~~~
1253 # Document parts
1254 self.head_prefix = [r'\documentclass[%s]{%s}' %
1255 (self.documentoptions, self.settings.documentclass)]
1256 self.requirements = SortableDict() # made a list in depart_document()
1257 self.requirements['__static'] = r'\usepackage{ifthen}'
1258 self.latex_preamble = [settings.latex_preamble]
1259 self.fallbacks = SortableDict() # made a list in depart_document()
1260 self.pdfsetup = [] # PDF properties (hyperref package)
1261 self.title = []
1262 self.subtitle = []
1263 self.titledata = [] # \title, \author, \date
1264 ## self.body_prefix = ['\\begin{document}\n']
1265 self.body_pre_docinfo = [] # \maketitle
1266 self.docinfo = []
1267 self.dedication = []
1268 self.abstract = []
1269 self.body = []
1270 ## self.body_suffix = ['\\end{document}\n']
1272 self.context = []
1273 """Heterogeneous stack.
1275 Used by visit_* and depart_* functions in conjunction with the tree
1276 traversal. Make sure that the pops correspond to the pushes."""
1278 # Title metadata:
1279 self.title_labels = []
1280 self.subtitle_labels = []
1281 # (if use_latex_docinfo: collects lists of
1282 # author/organization/contact/address lines)
1283 self.author_stack = []
1284 self.date = []
1286 # PDF properties: pdftitle, pdfauthor
1287 # TODO?: pdfcreator, pdfproducer, pdfsubject, pdfkeywords
1288 self.pdfinfo = []
1289 self.pdfauthor = []
1291 # Stack of section counters so that we don't have to use_latex_toc.
1292 # This will grow and shrink as processing occurs.
1293 # Initialized for potential first-level sections.
1294 self._section_number = [0]
1296 # The current stack of enumerations so that we can expand
1297 # them into a compound enumeration.
1298 self._enumeration_counters = []
1299 # The maximum number of enumeration counters we've used.
1300 # If we go beyond this number, we need to create a new
1301 # counter; otherwise, just reuse an old one.
1302 self._max_enumeration_counters = 0
1304 self._bibitems = []
1306 # object for a table while processing.
1307 self.table_stack = []
1308 self.active_table = Table(self, 'longtable')
1310 # Where to collect the output of visitor methods (default: body)
1311 self.out = self.body
1312 self.out_stack = [] # stack of output collectors
1314 # Process settings
1315 # ~~~~~~~~~~~~~~~~
1316 # Encodings:
1317 # Docutils' output-encoding => TeX input encoding
1318 if self.latex_encoding != 'ascii':
1319 self.requirements['_inputenc'] = (r'\usepackage[%s]{inputenc}'
1320 % self.latex_encoding)
1321 # TeX font encoding
1322 if not self.is_xetex:
1323 if self.font_encoding:
1324 self.requirements['_fontenc'] = (r'\usepackage[%s]{fontenc}' %
1325 self.font_encoding)
1326 # ensure \textquotedbl is defined:
1327 for enc in self.font_encoding.split(','):
1328 enc = enc.strip()
1329 if enc == 'OT1':
1330 self.requirements['_textquotedblOT1'] = (
1331 r'\DeclareTextSymbol{\textquotedbl}{OT1}{`\"}')
1332 elif enc not in ('T1', 'T2A', 'T2B', 'T2C', 'T4', 'T5'):
1333 self.requirements['_textquotedbl'] = (
1334 r'\DeclareTextSymbolDefault{\textquotedbl}{T1}')
1335 # page layout with typearea (if there are relevant document options)
1336 if (settings.documentclass.find('scr') == -1 and
1337 (self.documentoptions.find('DIV') != -1 or
1338 self.documentoptions.find('BCOR') != -1)):
1339 self.requirements['typearea'] = r'\usepackage{typearea}'
1341 # Stylesheets
1342 # (the name `self.stylesheet` is singular because only one
1343 # stylesheet was supported before Docutils 0.6).
1344 self.stylesheet = [self.stylesheet_call(path)
1345 for path in utils.get_stylesheet_list(settings)]
1347 # PDF setup
1348 if self.hyperlink_color in ('0', 'false', 'False', ''):
1349 self.hyperref_options = ''
1350 else:
1351 self.hyperref_options = 'colorlinks=true,linkcolor=%s,urlcolor=%s' % (
1352 self.hyperlink_color, self.hyperlink_color)
1353 if settings.hyperref_options:
1354 self.hyperref_options += ',' + settings.hyperref_options
1356 # LaTeX Toc
1357 # include all supported sections in toc and PDF bookmarks
1358 # (or use documentclass-default (as currently))?
1359 ## if self.use_latex_toc:
1360 ## self.requirements['tocdepth'] = (r'\setcounter{tocdepth}{%d}' %
1361 ## len(self.d_class.sections))
1363 # Section numbering
1364 if settings.sectnum_xform: # section numbering by Docutils
1365 PreambleCmds.secnumdepth = r'\setcounter{secnumdepth}{0}'
1366 else: # section numbering by LaTeX:
1367 secnumdepth = settings.sectnum_depth
1368 # Possible values of settings.sectnum_depth:
1369 # None "sectnum" directive without depth arg -> LaTeX default
1370 # 0 no "sectnum" directive -> no section numbers
1371 # >0 value of "depth" argument -> translate to LaTeX levels:
1372 # -1 part (0 with "article" document class)
1373 # 0 chapter (missing in "article" document class)
1374 # 1 section
1375 # 2 subsection
1376 # 3 subsubsection
1377 # 4 paragraph
1378 # 5 subparagraph
1379 if secnumdepth is not None:
1380 # limit to supported levels
1381 secnumdepth = min(secnumdepth, len(self.d_class.sections))
1382 # adjust to document class and use_part_section settings
1383 if 'chapter' in self.d_class.sections:
1384 secnumdepth -= 1
1385 if self.d_class.sections[0] == 'part':
1386 secnumdepth -= 1
1387 PreambleCmds.secnumdepth = \
1388 r'\setcounter{secnumdepth}{%d}' % secnumdepth
1390 # start with specified number:
1391 if (hasattr(settings, 'sectnum_start') and
1392 settings.sectnum_start != 1):
1393 self.requirements['sectnum_start'] = (
1394 r'\setcounter{%s}{%d}' % (self.d_class.sections[0],
1395 settings.sectnum_start-1))
1396 # TODO: currently ignored (configure in a stylesheet):
1397 ## settings.sectnum_prefix
1398 ## settings.sectnum_suffix
1400 # Auxiliary Methods
1401 # -----------------
1403 def stylesheet_call(self, path):
1404 """Return code to reference or embed stylesheet file `path`"""
1405 # is it a package (no extension or *.sty) or "normal" tex code:
1406 (base, ext) = os.path.splitext(path)
1407 is_package = ext in ['.sty', '']
1408 # Embed content of style file:
1409 if self.settings.embed_stylesheet:
1410 if is_package:
1411 path = base + '.sty' # ensure extension
1412 try:
1413 content = io.FileInput(source_path=path,
1414 encoding='utf-8').read()
1415 self.settings.record_dependencies.add(path)
1416 except IOError, err:
1417 msg = u"Cannot embed stylesheet '%s':\n %s." % (
1418 path, SafeString(err.strerror))
1419 self.document.reporter.error(msg)
1420 return '% ' + msg.replace('\n', '\n% ')
1421 if is_package:
1422 content = '\n'.join([r'\makeatletter',
1423 content,
1424 r'\makeatother'])
1425 return '%% embedded stylesheet: %s\n%s' % (path, content)
1426 # Link to style file:
1427 if is_package:
1428 path = base # drop extension
1429 cmd = r'\usepackage{%s}'
1430 else:
1431 cmd = r'\input{%s}'
1432 if self.settings.stylesheet_path:
1433 # adapt path relative to output (cf. config.html#stylesheet-path)
1434 path = utils.relative_path(self.settings._destination, path)
1435 return cmd % path
1437 def to_latex_encoding(self,docutils_encoding):
1438 """Translate docutils encoding name into LaTeX's.
1440 Default method is remove "-" and "_" chars from docutils_encoding.
1442 tr = { 'iso-8859-1': 'latin1', # west european
1443 'iso-8859-2': 'latin2', # east european
1444 'iso-8859-3': 'latin3', # esperanto, maltese
1445 'iso-8859-4': 'latin4', # north european, scandinavian, baltic
1446 'iso-8859-5': 'iso88595', # cyrillic (ISO)
1447 'iso-8859-9': 'latin5', # turkish
1448 'iso-8859-15': 'latin9', # latin9, update to latin1.
1449 'mac_cyrillic': 'maccyr', # cyrillic (on Mac)
1450 'windows-1251': 'cp1251', # cyrillic (on Windows)
1451 'koi8-r': 'koi8-r', # cyrillic (Russian)
1452 'koi8-u': 'koi8-u', # cyrillic (Ukrainian)
1453 'windows-1250': 'cp1250', #
1454 'windows-1252': 'cp1252', #
1455 'us-ascii': 'ascii', # ASCII (US)
1456 # unmatched encodings
1457 #'': 'applemac',
1458 #'': 'ansinew', # windows 3.1 ansi
1459 #'': 'ascii', # ASCII encoding for the range 32--127.
1460 #'': 'cp437', # dos latin us
1461 #'': 'cp850', # dos latin 1
1462 #'': 'cp852', # dos latin 2
1463 #'': 'decmulti',
1464 #'': 'latin10',
1465 #'iso-8859-6': '' # arabic
1466 #'iso-8859-7': '' # greek
1467 #'iso-8859-8': '' # hebrew
1468 #'iso-8859-10': '' # latin6, more complete iso-8859-4
1470 encoding = docutils_encoding.lower()
1471 if encoding in tr:
1472 return tr[encoding]
1473 # drop hyphen or low-line from "latin-1", "latin_1", "utf-8" and similar
1474 encoding = encoding.replace('_', '').replace('-', '')
1475 # strip the error handler
1476 return encoding.split(':')[0]
1478 def language_label(self, docutil_label):
1479 return self.language_module.labels[docutil_label]
1481 def encode(self, text):
1482 """Return text with 'problematic' characters escaped.
1484 * Escape the special printing characters ``# $ % & ~ _ ^ \\ { }``,
1485 square brackets ``[ ]``, double quotes and (in OT1) ``< | >``.
1486 * Translate non-supported Unicode characters.
1487 * Separate ``-`` (and more in literal text) to prevent input ligatures.
1489 if self.verbatim:
1490 return text
1491 # Set up the translation table:
1492 table = CharMaps.alltt.copy()
1493 if not self.alltt:
1494 table.update(CharMaps.special)
1495 # keep the underscore in citation references
1496 if self.inside_citation_reference_label:
1497 del(table[ord('_')])
1498 # Workarounds for OT1 font-encoding
1499 if self.font_encoding in ['OT1', ''] and not self.is_xetex:
1500 # * out-of-order characters in cmtt
1501 if self.literal:
1502 # replace underscore by underlined blank,
1503 # because this has correct width.
1504 table[ord('_')] = u'\\underline{~}'
1505 # the backslash doesn't work, so we use a mirrored slash.
1506 # \reflectbox is provided by graphicx:
1507 self.requirements['graphicx'] = self.graphicx_package
1508 table[ord('\\')] = ur'\reflectbox{/}'
1509 # * ``< | >`` come out as different chars (except for cmtt):
1510 else:
1511 table[ord('|')] = ur'\textbar{}'
1512 table[ord('<')] = ur'\textless{}'
1513 table[ord('>')] = ur'\textgreater{}'
1514 if self.insert_non_breaking_blanks:
1515 table[ord(' ')] = ur'~'
1516 # Unicode replacements for 8-bit tex engines (not required with XeTeX/LuaTeX):
1517 if not self.is_xetex:
1518 if not self.latex_encoding.startswith('utf8'):
1519 table.update(CharMaps.unsupported_unicode)
1520 table.update(CharMaps.utf8_supported_unicode)
1521 table.update(CharMaps.textcomp)
1522 table.update(CharMaps.pifont)
1523 # Characters that require a feature/package to render
1524 for ch in text:
1525 cp = ord(ch)
1526 if cp in CharMaps.textcomp:
1527 self.requirements['textcomp'] = PreambleCmds.textcomp
1528 elif cp in CharMaps.pifont:
1529 self.requirements['pifont'] = '\\usepackage{pifont}'
1530 # preamble-definitions for unsupported Unicode characters
1531 elif (self.latex_encoding == 'utf8'
1532 and cp in CharMaps.unsupported_unicode):
1533 self.requirements['_inputenc'+str(cp)] = (
1534 '\\DeclareUnicodeCharacter{%04X}{%s}'
1535 % (cp, CharMaps.unsupported_unicode[cp]))
1536 text = text.translate(table)
1538 # Break up input ligatures e.g. '--' to '-{}-'.
1539 if not self.is_xetex: # Not required with xetex/luatex
1540 separate_chars = '-'
1541 # In monospace-font, we also separate ',,', '``' and "''" and some
1542 # other characters which can't occur in non-literal text.
1543 if self.literal:
1544 separate_chars += ',`\'"<>'
1545 for char in separate_chars * 2:
1546 # Do it twice ("* 2") because otherwise we would replace
1547 # '---' by '-{}--'.
1548 text = text.replace(char + char, char + '{}' + char)
1550 # Literal line breaks (in address or literal blocks):
1551 if self.insert_newline:
1552 lines = text.split('\n')
1553 # Add a protected space to blank lines (except the last)
1554 # to avoid ``! LaTeX Error: There's no line here to end.``
1555 for i, line in enumerate(lines[:-1]):
1556 if not line.lstrip():
1557 lines[i] += '~'
1558 text = (r'\\' + '\n').join(lines)
1559 if self.literal and not self.insert_non_breaking_blanks:
1560 # preserve runs of spaces but allow wrapping
1561 text = text.replace(' ', ' ~')
1562 return text
1564 def attval(self, text,
1565 whitespace=re.compile('[\n\r\t\v\f]')):
1566 """Cleanse, encode, and return attribute value text."""
1567 return self.encode(whitespace.sub(' ', text))
1569 # TODO: is this used anywhere? -> update (use template) or delete
1570 ## def astext(self):
1571 ## """Assemble document parts and return as string."""
1572 ## head = '\n'.join(self.head_prefix + self.stylesheet + self.head)
1573 ## body = ''.join(self.body_prefix + self.body + self.body_suffix)
1574 ## return head + '\n' + body
1576 def is_inline(self, node):
1577 """Check whether a node represents an inline or block-level element"""
1578 return isinstance(node.parent, nodes.TextElement)
1580 def append_hypertargets(self, node):
1581 """Append hypertargets for all ids of `node`"""
1582 # hypertarget places the anchor at the target's baseline,
1583 # so we raise it explicitly
1584 self.out.append('%\n'.join(['\\raisebox{1em}{\\hypertarget{%s}{}}' %
1585 id for id in node['ids']]))
1587 def ids_to_labels(self, node, set_anchor=True):
1588 """Return list of label definitions for all ids of `node`
1590 If `set_anchor` is True, an anchor is set with \\phantomsection.
1592 labels = ['\\label{%s}' % id for id in node.get('ids', [])]
1593 if set_anchor and labels:
1594 labels.insert(0, '\\phantomsection')
1595 return labels
1597 def set_align_from_classes(self, node):
1598 """Convert ``align-*`` class arguments into alignment args."""
1599 # separate:
1600 align = [cls for cls in node['classes'] if cls.startswith('align-')]
1601 if align:
1602 node['align'] = align[-1].replace('align-', '')
1603 node['classes'] = [cls for cls in node['classes']
1604 if not cls.startswith('align-')]
1606 def insert_align_declaration(self, node, default=None):
1607 align = node.get('align', default)
1608 if align == 'left':
1609 self.out.append('\\raggedright\n')
1610 elif align == 'center':
1611 self.out.append('\\centering\n')
1612 elif align == 'right':
1613 self.out.append('\\raggedleft\n')
1615 def duclass_open(self, node):
1616 """Open a group and insert declarations for class values."""
1617 if not isinstance(node.parent, nodes.compound):
1618 self.out.append('\n')
1619 for cls in node['classes']:
1620 if cls.startswith('language-'):
1621 language = self.babel.language_name(cls[9:])
1622 if language:
1623 self.babel.otherlanguages[language] = True
1624 self.out.append('\\begin{selectlanguage}{%s}\n' % language)
1625 else:
1626 self.fallbacks['DUclass'] = PreambleCmds.duclass
1627 self.out.append('\\begin{DUclass}{%s}\n' % cls)
1629 def duclass_close(self, node):
1630 """Close a group of class declarations."""
1631 for cls in reversed(node['classes']):
1632 if cls.startswith('language-'):
1633 language = self.babel.language_name(cls[9:])
1634 if language:
1635 self.babel.otherlanguages[language] = True
1636 self.out.append('\\end{selectlanguage}\n')
1637 else:
1638 self.fallbacks['DUclass'] = PreambleCmds.duclass
1639 self.out.append('\\end{DUclass}\n')
1641 def push_output_collector(self, new_out):
1642 self.out_stack.append(self.out)
1643 self.out = new_out
1645 def pop_output_collector(self):
1646 self.out = self.out_stack.pop()
1648 # Visitor methods
1649 # ---------------
1651 def visit_Text(self, node):
1652 self.out.append(self.encode(node.astext()))
1654 def depart_Text(self, node):
1655 pass
1657 def visit_abbreviation(self, node):
1658 node['classes'].insert(0, 'abbreviation')
1659 self.visit_inline(node)
1661 def depart_abbreviation(self, node):
1662 self.depart_inline(node)
1664 def visit_acronym(self, node):
1665 node['classes'].insert(0, 'acronym')
1666 self.visit_inline(node)
1668 def depart_acronym(self, node):
1669 self.depart_inline(node)
1671 def visit_address(self, node):
1672 self.visit_docinfo_item(node, 'address')
1674 def depart_address(self, node):
1675 self.depart_docinfo_item(node)
1677 def visit_admonition(self, node):
1678 self.fallbacks['admonition'] = PreambleCmds.admonition
1679 if 'error' in node['classes']:
1680 self.fallbacks['error'] = PreambleCmds.error
1681 # strip the generic 'admonition' from the list of classes
1682 node['classes'] = [cls for cls in node['classes']
1683 if cls != 'admonition']
1684 self.out.append('\n\\DUadmonition[%s]{' % ','.join(node['classes']))
1686 def depart_admonition(self, node=None):
1687 self.out.append('}\n')
1689 def visit_author(self, node):
1690 self.visit_docinfo_item(node, 'author')
1692 def depart_author(self, node):
1693 self.depart_docinfo_item(node)
1695 def visit_authors(self, node):
1696 # not used: visit_author is called anyway for each author.
1697 pass
1699 def depart_authors(self, node):
1700 pass
1702 def visit_block_quote(self, node):
1703 self.duclass_open(node)
1704 self.out.append( '\\begin{quote}')
1706 def depart_block_quote(self, node):
1707 self.out.append( '\\end{quote}\n')
1708 self.duclass_close(node)
1710 def visit_bullet_list(self, node):
1711 self.duclass_open(node)
1712 if self.is_toc_list:
1713 self.out.append( '\\begin{list}{}{}' )
1714 else:
1715 self.out.append( '\\begin{itemize}' )
1717 def depart_bullet_list(self, node):
1718 if self.is_toc_list:
1719 self.out.append( '\\end{list}\n' )
1720 else:
1721 self.out.append( '\\end{itemize}\n' )
1722 self.duclass_close(node)
1724 def visit_superscript(self, node):
1725 self.out.append(r'\textsuperscript{')
1726 if node['classes']:
1727 self.visit_inline(node)
1729 def depart_superscript(self, node):
1730 if node['classes']:
1731 self.depart_inline(node)
1732 self.out.append('}')
1734 def visit_subscript(self, node):
1735 self.fallbacks['textsubscript'] = PreambleCmds.textsubscript
1736 self.out.append(r'\textsubscript{')
1737 if node['classes']:
1738 self.visit_inline(node)
1740 def depart_subscript(self, node):
1741 if node['classes']:
1742 self.depart_inline(node)
1743 self.out.append('}')
1745 def visit_caption(self, node):
1746 self.out.append('\n\\caption{')
1748 def depart_caption(self, node):
1749 self.out.append('}\n')
1751 def visit_title_reference(self, node):
1752 self.fallbacks['titlereference'] = PreambleCmds.titlereference
1753 self.out.append(r'\DUroletitlereference{')
1754 if node['classes']:
1755 self.visit_inline(node)
1757 def depart_title_reference(self, node):
1758 if node['classes']:
1759 self.depart_inline(node)
1760 self.out.append( '}' )
1762 def visit_citation(self, node):
1763 # TODO maybe use cite bibitems
1764 if self._use_latex_citations:
1765 self.push_output_collector([])
1766 else:
1767 # TODO: do we need these?
1768 ## self.requirements['~fnt_floats'] = PreambleCmds.footnote_floats
1769 self.out.append(r'\begin{figure}[b]')
1770 self.append_hypertargets(node)
1772 def depart_citation(self, node):
1773 if self._use_latex_citations:
1774 label = self.out[0]
1775 text = ''.join(self.out[1:])
1776 self._bibitems.append([label, text])
1777 self.pop_output_collector()
1778 else:
1779 self.out.append('\\end{figure}\n')
1781 def visit_citation_reference(self, node):
1782 if self._use_latex_citations:
1783 if not self.inside_citation_reference_label:
1784 self.out.append(r'\cite{')
1785 self.inside_citation_reference_label = 1
1786 else:
1787 assert self.body[-1] in (' ', '\n'),\
1788 'unexpected non-whitespace while in reference label'
1789 del self.body[-1]
1790 else:
1791 href = ''
1792 if 'refid' in node:
1793 href = node['refid']
1794 elif 'refname' in node:
1795 href = self.document.nameids[node['refname']]
1796 self.out.append('\\hyperlink{%s}{[' % href)
1798 def depart_citation_reference(self, node):
1799 if self._use_latex_citations:
1800 followup_citation = False
1801 # check for a following citation separated by a space or newline
1802 next_siblings = node.traverse(descend=False, siblings=True,
1803 include_self=False)
1804 if len(next_siblings) > 1:
1805 next = next_siblings[0]
1806 if (isinstance(next, nodes.Text) and
1807 next.astext() in (' ', '\n')):
1808 if next_siblings[1].__class__ == node.__class__:
1809 followup_citation = True
1810 if followup_citation:
1811 self.out.append(',')
1812 else:
1813 self.out.append('}')
1814 self.inside_citation_reference_label = False
1815 else:
1816 self.out.append(']}')
1818 def visit_classifier(self, node):
1819 self.out.append( '(\\textbf{' )
1821 def depart_classifier(self, node):
1822 self.out.append( '})' )
1824 def visit_colspec(self, node):
1825 self.active_table.visit_colspec(node)
1827 def depart_colspec(self, node):
1828 pass
1830 def visit_comment(self, node):
1831 if not isinstance(node.parent, nodes.compound):
1832 self.out.append('\n')
1833 # Precede every line with a comment sign, wrap in newlines
1834 self.out.append('%% %s\n' % node.astext().replace('\n', '\n% '))
1835 raise nodes.SkipNode
1837 def depart_comment(self, node):
1838 pass
1840 def visit_compound(self, node):
1841 if isinstance(node.parent, nodes.compound):
1842 self.out.append('\n')
1843 node['classes'].insert(0, 'compound')
1844 self.duclass_open(node)
1846 def depart_compound(self, node):
1847 self.duclass_close(node)
1849 def visit_contact(self, node):
1850 self.visit_docinfo_item(node, 'contact')
1852 def depart_contact(self, node):
1853 self.depart_docinfo_item(node)
1855 def visit_container(self, node):
1856 self.duclass_open(node)
1858 def depart_container(self, node):
1859 self.duclass_close(node)
1861 def visit_copyright(self, node):
1862 self.visit_docinfo_item(node, 'copyright')
1864 def depart_copyright(self, node):
1865 self.depart_docinfo_item(node)
1867 def visit_date(self, node):
1868 self.visit_docinfo_item(node, 'date')
1870 def depart_date(self, node):
1871 self.depart_docinfo_item(node)
1873 def visit_decoration(self, node):
1874 # header and footer
1875 pass
1877 def depart_decoration(self, node):
1878 pass
1880 def visit_definition(self, node):
1881 pass
1883 def depart_definition(self, node):
1884 self.out.append('\n') # TODO: just pass?
1886 def visit_definition_list(self, node):
1887 self.duclass_open(node)
1888 self.out.append( '\\begin{description}\n' )
1890 def depart_definition_list(self, node):
1891 self.out.append( '\\end{description}\n' )
1892 self.duclass_close(node)
1894 def visit_definition_list_item(self, node):
1895 pass
1897 def depart_definition_list_item(self, node):
1898 pass
1900 def visit_description(self, node):
1901 self.out.append(' ')
1903 def depart_description(self, node):
1904 pass
1906 def visit_docinfo(self, node):
1907 self.push_output_collector(self.docinfo)
1909 def depart_docinfo(self, node):
1910 self.pop_output_collector()
1911 # Some itmes (e.g. author) end up at other places
1912 if self.docinfo:
1913 # tabularx: automatic width of columns, no page breaks allowed.
1914 self.requirements['tabularx'] = r'\usepackage{tabularx}'
1915 self.fallbacks['_providelength'] = PreambleCmds.providelength
1916 self.fallbacks['docinfo'] = PreambleCmds.docinfo
1918 self.docinfo.insert(0, '\n% Docinfo\n'
1919 '\\begin{center}\n'
1920 '\\begin{tabularx}{\\DUdocinfowidth}{lX}\n')
1921 self.docinfo.append('\\end{tabularx}\n'
1922 '\\end{center}\n')
1924 def visit_docinfo_item(self, node, name):
1925 if name == 'author':
1926 self.pdfauthor.append(self.attval(node.astext()))
1927 if self.use_latex_docinfo:
1928 if name in ('author', 'organization', 'contact', 'address'):
1929 # We attach these to the last author. If any of them precedes
1930 # the first author, put them in a separate "author" group
1931 # (in lack of better semantics).
1932 if name == 'author' or not self.author_stack:
1933 self.author_stack.append([])
1934 if name == 'address': # newlines are meaningful
1935 self.insert_newline = True
1936 text = self.encode(node.astext())
1937 self.insert_newline = False
1938 else:
1939 text = self.attval(node.astext())
1940 self.author_stack[-1].append(text)
1941 raise nodes.SkipNode
1942 elif name == 'date':
1943 self.date.append(self.attval(node.astext()))
1944 raise nodes.SkipNode
1945 self.out.append('\\textbf{%s}: &\n\t' % self.language_label(name))
1946 if name == 'address':
1947 self.insert_newline = True
1948 self.out.append('{\\raggedright\n')
1949 self.context.append(' } \\\\\n')
1950 else:
1951 self.context.append(' \\\\\n')
1953 def depart_docinfo_item(self, node):
1954 self.out.append(self.context.pop())
1955 # for address we did set insert_newline
1956 self.insert_newline = False
1958 def visit_doctest_block(self, node):
1959 self.visit_literal_block(node)
1961 def depart_doctest_block(self, node):
1962 self.depart_literal_block(node)
1964 def visit_document(self, node):
1965 # titled document?
1966 if (self.use_latex_docinfo or len(node) and
1967 isinstance(node[0], nodes.title)):
1968 self.title_labels += self.ids_to_labels(node, set_anchor=False)
1970 def depart_document(self, node):
1971 # Complete header with information gained from walkabout
1972 # * language setup
1973 if (self.babel.otherlanguages or
1974 self.babel.language not in ('', 'english')):
1975 self.requirements['babel'] = self.babel()
1976 # * conditional requirements (before style sheet)
1977 self.requirements = self.requirements.sortedvalues()
1978 # * coditional fallback definitions (after style sheet)
1979 self.fallbacks = self.fallbacks.sortedvalues()
1980 # * PDF properties
1981 self.pdfsetup.append(PreambleCmds.linking % self.hyperref_options)
1982 if self.pdfauthor:
1983 authors = self.author_separator.join(self.pdfauthor)
1984 self.pdfinfo.append(' pdfauthor={%s}' % authors)
1985 if self.pdfinfo:
1986 self.pdfsetup += [r'\hypersetup{'] + self.pdfinfo + ['}']
1987 # Complete body
1988 # * document title (with "use_latex_docinfo" also
1989 # 'author', 'organization', 'contact', 'address' and 'date')
1990 if self.title or (
1991 self.use_latex_docinfo and (self.author_stack or self.date)):
1992 # with the default template, titledata is written to the preamble
1993 self.titledata.append('%%% Title Data')
1994 # \title (empty \title prevents error with \maketitle)
1995 if self.title:
1996 self.title.insert(0, '\\phantomsection%\n ')
1997 title = [''.join(self.title)] + self.title_labels
1998 if self.subtitle:
1999 title += [r'\\ % subtitle',
2000 r'\DUdocumentsubtitle{%s}' % ''.join(self.subtitle)
2001 ] + self.subtitle_labels
2002 self.titledata.append(r'\title{%s}' % '%\n '.join(title))
2003 # \author (empty \author prevents warning with \maketitle)
2004 authors = ['\\\\\n'.join(author_entry)
2005 for author_entry in self.author_stack]
2006 self.titledata.append(r'\author{%s}' %
2007 ' \\and\n'.join(authors))
2008 # \date (empty \date prevents defaulting to \today)
2009 self.titledata.append(r'\date{%s}' % ', '.join(self.date))
2010 # \maketitle in the body formats title with LaTeX
2011 self.body_pre_docinfo.append('\\maketitle\n')
2013 # * bibliography
2014 # TODO insertion point of bibliography should be configurable.
2015 if self._use_latex_citations and len(self._bibitems)>0:
2016 if not self.bibtex:
2017 widest_label = ''
2018 for bi in self._bibitems:
2019 if len(widest_label)<len(bi[0]):
2020 widest_label = bi[0]
2021 self.out.append('\n\\begin{thebibliography}{%s}\n' %
2022 widest_label)
2023 for bi in self._bibitems:
2024 # cite_key: underscores must not be escaped
2025 cite_key = bi[0].replace(r'\_','_')
2026 self.out.append('\\bibitem[%s]{%s}{%s}\n' %
2027 (bi[0], cite_key, bi[1]))
2028 self.out.append('\\end{thebibliography}\n')
2029 else:
2030 self.out.append('\n\\bibliographystyle{%s}\n' %
2031 self.bibtex[0])
2032 self.out.append('\\bibliography{%s}\n' % self.bibtex[1])
2033 # * make sure to generate a toc file if needed for local contents:
2034 if 'minitoc' in self.requirements and not self.has_latex_toc:
2035 self.out.append('\n\\faketableofcontents % for local ToCs\n')
2037 def visit_emphasis(self, node):
2038 self.out.append('\\emph{')
2039 if node['classes']:
2040 self.visit_inline(node)
2042 def depart_emphasis(self, node):
2043 if node['classes']:
2044 self.depart_inline(node)
2045 self.out.append('}')
2047 # Append column delimiters and advance column counter,
2048 # if the current cell is a multi-row continuation."""
2049 def insert_additional_table_colum_delimiters(self):
2050 while self.active_table.get_rowspan(
2051 self.active_table.get_entry_number()):
2052 self.out.append(' & ')
2053 self.active_table.visit_entry() # increment cell count
2055 def visit_entry(self, node):
2056 # cell separation
2057 if self.active_table.get_entry_number() == 0:
2058 self.insert_additional_table_colum_delimiters()
2059 else:
2060 self.out.append(' & ')
2062 # multirow, multicolumn
2063 if 'morerows' in node and 'morecols' in node:
2064 raise NotImplementedError('Cells that '
2065 'span multiple rows *and* columns currently not supported, sorry.')
2066 # TODO: should be possible with LaTeX, see e.g.
2067 # http://texblog.org/2012/12/21/multi-column-and-multi-row-cells-in-latex-tables/
2068 # multirow in LaTeX simply will enlarge the cell over several rows
2069 # (the following n if n is positive, the former if negative).
2070 if 'morerows' in node:
2071 self.requirements['multirow'] = r'\usepackage{multirow}'
2072 mrows = node['morerows'] + 1
2073 self.active_table.set_rowspan(
2074 self.active_table.get_entry_number(), mrows)
2075 self.out.append('\\multirow{%d}{%s}{' %
2076 (mrows, self.active_table.get_column_width()))
2077 self.context.append('}')
2078 elif 'morecols' in node:
2079 # the vertical bar before column is missing if it is the first
2080 # column. the one after always.
2081 if self.active_table.get_entry_number() == 0:
2082 bar1 = self.active_table.get_vertical_bar()
2083 else:
2084 bar1 = ''
2085 mcols = node['morecols'] + 1
2086 self.out.append('\\multicolumn{%d}{%s%s%s}{' %
2087 (mcols, bar1,
2088 self.active_table.get_multicolumn_width(
2089 self.active_table.get_entry_number(),
2090 mcols),
2091 self.active_table.get_vertical_bar()))
2092 self.context.append('}')
2093 else:
2094 self.context.append('')
2096 # bold header/stub-column
2097 if len(node) and (isinstance(node.parent.parent, nodes.thead)
2098 or self.active_table.is_stub_column()):
2099 self.out.append('\\textbf{')
2100 self.context.append('}')
2101 else:
2102 self.context.append('')
2104 # if line ends with '{', mask line break to prevent spurious whitespace
2105 if not self.active_table.colwidths_auto and self.out[-1].endswith("{"):
2106 self.out.append("%")
2108 self.active_table.visit_entry() # increment cell count
2110 def depart_entry(self, node):
2111 self.out.append(self.context.pop()) # header / not header
2112 self.out.append(self.context.pop()) # multirow/column
2113 # insert extra "&"s, if following rows are spanned from above:
2114 self.insert_additional_table_colum_delimiters()
2116 def visit_row(self, node):
2117 self.active_table.visit_row()
2119 def depart_row(self, node):
2120 self.out.extend(self.active_table.depart_row())
2122 def visit_enumerated_list(self, node):
2123 # enumeration styles:
2124 types = {'': '',
2125 'arabic':'arabic',
2126 'loweralpha':'alph',
2127 'upperalpha':'Alph',
2128 'lowerroman':'roman',
2129 'upperroman':'Roman'}
2130 # the 4 default LaTeX enumeration labels: präfix, enumtype, suffix,
2131 labels = [('', 'arabic', '.'), # 1.
2132 ('(', 'alph', ')'), # (a)
2133 ('', 'roman', '.'), # i.
2134 ('', 'Alph', '.')] # A.
2136 prefix = ''
2137 if self.compound_enumerators:
2138 if (self.section_prefix_for_enumerators and self.section_level
2139 and not self._enumeration_counters):
2140 prefix = '.'.join([str(n) for n in
2141 self._section_number[:self.section_level]]
2142 ) + self.section_enumerator_separator
2143 if self._enumeration_counters:
2144 prefix += self._enumeration_counters[-1]
2145 # TODO: use LaTeX default for unspecified label-type?
2146 # (needs change of parser)
2147 prefix += node.get('prefix', '')
2148 enumtype = types[node.get('enumtype' '')]
2149 suffix = node.get('suffix', '')
2151 enumeration_level = len(self._enumeration_counters)+1
2152 counter_name = 'enum' + roman.toRoman(enumeration_level).lower()
2153 label = r'%s\%s{%s}%s' % (prefix, enumtype, counter_name, suffix)
2154 self._enumeration_counters.append(label)
2156 self.duclass_open(node)
2157 if enumeration_level <= 4:
2158 self.out.append('\\begin{enumerate}')
2159 if (prefix, enumtype, suffix
2160 ) != labels[enumeration_level-1]:
2161 self.out.append('\n\\renewcommand{\\label%s}{%s}' %
2162 (counter_name, label))
2163 else:
2164 self.fallbacks[counter_name] = '\\newcounter{%s}' % counter_name
2165 self.out.append('\\begin{list}')
2166 self.out.append('{%s}' % label)
2167 self.out.append('{\\usecounter{%s}}' % counter_name)
2168 if 'start' in node:
2169 self.out.append('\n\\setcounter{%s}{%d}' %
2170 (counter_name,node['start']-1))
2173 def depart_enumerated_list(self, node):
2174 if len(self._enumeration_counters) <= 4:
2175 self.out.append('\\end{enumerate}\n')
2176 else:
2177 self.out.append('\\end{list}\n')
2178 self.duclass_close(node)
2179 self._enumeration_counters.pop()
2181 def visit_field(self, node):
2182 # real output is done in siblings: _argument, _body, _name
2183 pass
2185 def depart_field(self, node):
2186 pass
2187 ##self.out.append('%[depart_field]\n')
2189 def visit_field_argument(self, node):
2190 self.out.append('%[visit_field_argument]\n')
2192 def depart_field_argument(self, node):
2193 self.out.append('%[depart_field_argument]\n')
2195 def visit_field_body(self, node):
2196 pass
2198 def depart_field_body(self, node):
2199 if self.out is self.docinfo:
2200 self.out.append(r'\\'+'\n')
2202 def visit_field_list(self, node):
2203 self.duclass_open(node)
2204 if self.out is not self.docinfo:
2205 self.fallbacks['fieldlist'] = PreambleCmds.fieldlist
2206 self.out.append('\\begin{DUfieldlist}')
2208 def depart_field_list(self, node):
2209 if self.out is not self.docinfo:
2210 self.out.append('\\end{DUfieldlist}\n')
2211 self.duclass_close(node)
2213 def visit_field_name(self, node):
2214 if self.out is self.docinfo:
2215 self.out.append('\\textbf{')
2216 else:
2217 # Commands with optional args inside an optional arg must be put
2218 # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
2219 self.out.append('\n\\item[{')
2221 def depart_field_name(self, node):
2222 if self.out is self.docinfo:
2223 self.out.append('}: &')
2224 else:
2225 self.out.append(':}]')
2227 def visit_figure(self, node):
2228 self.requirements['float_settings'] = PreambleCmds.float_settings
2229 self.duclass_open(node)
2230 # The 'align' attribute sets the "outer alignment",
2231 # for "inner alignment" use LaTeX default alignment (similar to HTML)
2232 alignment = node.attributes.get('align', 'center')
2233 if alignment != 'center':
2234 # The LaTeX "figure" environment always uses the full linewidth,
2235 # so "outer alignment" is ignored. Just write a comment.
2236 # TODO: use the wrapfigure environment?
2237 self.out.append('\\begin{figure} %% align = "%s"\n' % alignment)
2238 else:
2239 self.out.append('\\begin{figure}\n')
2240 if node.get('ids'):
2241 self.out += self.ids_to_labels(node) + ['\n']
2243 def depart_figure(self, node):
2244 self.out.append('\\end{figure}\n')
2245 self.duclass_close(node)
2247 def visit_footer(self, node):
2248 self.push_output_collector([])
2249 self.out.append(r'\newcommand{\DUfooter}{')
2251 def depart_footer(self, node):
2252 self.out.append('}')
2253 self.requirements['~footer'] = ''.join(self.out)
2254 self.pop_output_collector()
2256 def visit_footnote(self, node):
2257 try:
2258 backref = node['backrefs'][0]
2259 except IndexError:
2260 backref = node['ids'][0] # no backref, use self-ref instead
2261 if self.docutils_footnotes:
2262 self.fallbacks['footnotes'] = PreambleCmds.footnotes
2263 num = node[0].astext()
2264 if self.settings.footnote_references == 'brackets':
2265 num = '[%s]' % num
2266 self.out.append('%%\n\\DUfootnotetext{%s}{%s}{%s}{' %
2267 (node['ids'][0], backref, self.encode(num)))
2268 if node['ids'] == node['names']:
2269 self.out += self.ids_to_labels(node)
2270 # mask newline to prevent spurious whitespace if paragraph follows:
2271 if node[1:] and isinstance(node[1], nodes.paragraph):
2272 self.out.append('%')
2273 ## else: # TODO: "real" LaTeX \footnote{}s
2275 def depart_footnote(self, node):
2276 self.out.append('}\n')
2278 def visit_footnote_reference(self, node):
2279 href = ''
2280 if 'refid' in node:
2281 href = node['refid']
2282 elif 'refname' in node:
2283 href = self.document.nameids[node['refname']]
2284 # if not self.docutils_footnotes:
2285 # TODO: insert footnote content at (or near) this place
2286 # print "footnote-ref to", node['refid']
2287 # footnotes = (self.document.footnotes +
2288 # self.document.autofootnotes +
2289 # self.document.symbol_footnotes)
2290 # for footnote in footnotes:
2291 # # print footnote['ids']
2292 # if node.get('refid', '') in footnote['ids']:
2293 # print 'matches', footnote['ids']
2294 format = self.settings.footnote_references
2295 if format == 'brackets':
2296 self.append_hypertargets(node)
2297 self.out.append('\\hyperlink{%s}{[' % href)
2298 self.context.append(']}')
2299 else:
2300 self.fallbacks['footnotes'] = PreambleCmds.footnotes
2301 self.out.append(r'\DUfootnotemark{%s}{%s}{' %
2302 (node['ids'][0], href))
2303 self.context.append('}')
2305 def depart_footnote_reference(self, node):
2306 self.out.append(self.context.pop())
2308 # footnote/citation label
2309 def label_delim(self, node, bracket, superscript):
2310 if isinstance(node.parent, nodes.footnote):
2311 raise nodes.SkipNode
2312 else:
2313 assert isinstance(node.parent, nodes.citation)
2314 if not self._use_latex_citations:
2315 self.out.append(bracket)
2317 def visit_label(self, node):
2318 """footnote or citation label: in brackets or as superscript"""
2319 self.label_delim(node, '[', '\\textsuperscript{')
2321 def depart_label(self, node):
2322 self.label_delim(node, ']', '}')
2324 # elements generated by the framework e.g. section numbers.
2325 def visit_generated(self, node):
2326 pass
2328 def depart_generated(self, node):
2329 pass
2331 def visit_header(self, node):
2332 self.push_output_collector([])
2333 self.out.append(r'\newcommand{\DUheader}{')
2335 def depart_header(self, node):
2336 self.out.append('}')
2337 self.requirements['~header'] = ''.join(self.out)
2338 self.pop_output_collector()
2340 def to_latex_length(self, length_str, pxunit=None):
2341 """Convert `length_str` with rst length to LaTeX length
2343 if pxunit is not None:
2344 sys.stderr.write('deprecation warning: LaTeXTranslator.to_latex_length()'
2345 ' option `pxunit` will be removed.')
2346 match = re.match(r'(\d*\.?\d*)\s*(\S*)', length_str)
2347 if not match:
2348 return length_str
2349 value, unit = match.groups()[:2]
2350 # no unit or "DTP" points (called 'bp' in TeX):
2351 if unit in ('', 'pt'):
2352 length_str = '%sbp' % value
2353 # percentage: relate to current line width
2354 elif unit == '%':
2355 length_str = '%.3f\\linewidth' % (float(value)/100.0)
2356 elif self.is_xetex and unit == 'px':
2357 # XeTeX does not know the length unit px.
2358 # Use \pdfpxdimen, the macro to set the value of 1 px in pdftex.
2359 # This way, configuring works the same for pdftex and xetex.
2360 self.fallbacks['_providelength'] = PreambleCmds.providelength
2361 self.fallbacks['px'] = '\n\\DUprovidelength{\\pdfpxdimen}{1bp}\n'
2362 length_str = r'%s\pdfpxdimen' % value
2363 return length_str
2365 def visit_image(self, node):
2366 self.requirements['graphicx'] = self.graphicx_package
2367 attrs = node.attributes
2368 # Convert image URI to a local file path
2369 imagepath = urllib.url2pathname(attrs['uri']).replace('\\', '/')
2370 # alignment defaults:
2371 if not 'align' in attrs:
2372 # Set default align of image in a figure to 'center'
2373 if isinstance(node.parent, nodes.figure):
2374 attrs['align'] = 'center'
2375 self.set_align_from_classes(node)
2376 # pre- and postfix (prefix inserted in reverse order)
2377 pre = []
2378 post = []
2379 include_graphics_options = []
2380 align_codes = {
2381 # inline images: by default latex aligns the bottom.
2382 'bottom': ('', ''),
2383 'middle': (r'\raisebox{-0.5\height}{', '}'),
2384 'top': (r'\raisebox{-\height}{', '}'),
2385 # block level images:
2386 'center': (r'\noindent\makebox[\linewidth][c]{', '}'),
2387 'left': (r'\noindent{', r'\hfill}'),
2388 'right': (r'\noindent{\hfill', '}'),}
2389 if 'align' in attrs:
2390 # TODO: warn or ignore non-applicable alignment settings?
2391 try:
2392 align_code = align_codes[attrs['align']]
2393 pre.append(align_code[0])
2394 post.append(align_code[1])
2395 except KeyError:
2396 pass # TODO: warn?
2397 if 'height' in attrs:
2398 include_graphics_options.append('height=%s' %
2399 self.to_latex_length(attrs['height']))
2400 if 'scale' in attrs:
2401 include_graphics_options.append('scale=%f' %
2402 (attrs['scale'] / 100.0))
2403 if 'width' in attrs:
2404 include_graphics_options.append('width=%s' %
2405 self.to_latex_length(attrs['width']))
2406 if not (self.is_inline(node) or
2407 isinstance(node.parent, (nodes.figure, nodes.compound))):
2408 pre.append('\n')
2409 if not (self.is_inline(node) or
2410 isinstance(node.parent, nodes.figure)):
2411 post.append('\n')
2412 pre.reverse()
2413 self.out.extend(pre)
2414 options = ''
2415 if include_graphics_options:
2416 options = '[%s]' % (','.join(include_graphics_options))
2417 self.out.append('\\includegraphics%s{%s}' % (options, imagepath))
2418 self.out.extend(post)
2420 def depart_image(self, node):
2421 if node.get('ids'):
2422 self.out += self.ids_to_labels(node) + ['\n']
2424 def visit_inline(self, node): # <span>, i.e. custom roles
2425 for cls in node['classes']:
2426 if cls.startswith('language-'):
2427 language = self.babel.language_name(cls[9:])
2428 if language:
2429 self.babel.otherlanguages[language] = True
2430 self.out.append(r'\foreignlanguage{%s}{' % language)
2431 else:
2432 self.fallbacks['inline'] = PreambleCmds.inline
2433 self.out.append(r'\DUrole{%s}{' % cls)
2435 def depart_inline(self, node):
2436 self.out.append('}' * len(node['classes']))
2438 def visit_interpreted(self, node):
2439 # @@@ Incomplete, pending a proper implementation on the
2440 # Parser/Reader end.
2441 self.visit_literal(node)
2443 def depart_interpreted(self, node):
2444 self.depart_literal(node)
2446 def visit_legend(self, node):
2447 self.fallbacks['legend'] = PreambleCmds.legend
2448 self.out.append('\\begin{DUlegend}')
2450 def depart_legend(self, node):
2451 self.out.append('\\end{DUlegend}\n')
2453 def visit_line(self, node):
2454 self.out.append(r'\item[] ')
2456 def depart_line(self, node):
2457 self.out.append('\n')
2459 def visit_line_block(self, node):
2460 self.fallbacks['_providelength'] = PreambleCmds.providelength
2461 self.fallbacks['lineblock'] = PreambleCmds.lineblock
2462 self.set_align_from_classes(node)
2463 if isinstance(node.parent, nodes.line_block):
2464 self.out.append('\\item[]\n'
2465 '\\begin{DUlineblock}{\\DUlineblockindent}\n')
2466 # nested line-blocks cannot be given class arguments
2467 else:
2468 self.duclass_open(node)
2469 self.out.append('\\begin{DUlineblock}{0em}\n')
2470 self.insert_align_declaration(node)
2472 def depart_line_block(self, node):
2473 self.out.append('\\end{DUlineblock}\n')
2474 self.duclass_close(node)
2476 def visit_list_item(self, node):
2477 self.out.append('\n\\item ')
2479 def depart_list_item(self, node):
2480 pass
2482 def visit_literal(self, node):
2483 self.literal = True
2484 if 'code' in node['classes'] and (
2485 self.settings.syntax_highlight != 'none'):
2486 self.requirements['color'] = PreambleCmds.color
2487 self.fallbacks['code'] = PreambleCmds.highlight_rules
2488 self.out.append('\\texttt{')
2489 if node['classes']:
2490 self.visit_inline(node)
2492 def depart_literal(self, node):
2493 self.literal = False
2494 if node['classes']:
2495 self.depart_inline(node)
2496 self.out.append('}')
2498 # Literal blocks are used for '::'-prefixed literal-indented
2499 # blocks of text, where the inline markup is not recognized,
2500 # but are also the product of the "parsed-literal" directive,
2501 # where the markup is respected.
2503 # In both cases, we want to use a typewriter/monospaced typeface.
2504 # For "real" literal-blocks, we can use \verbatim, while for all
2505 # the others we must use \mbox or \alltt.
2507 # We can distinguish between the two kinds by the number of
2508 # siblings that compose this node: if it is composed by a
2509 # single element, it's either
2510 # * a real one,
2511 # * a parsed-literal that does not contain any markup, or
2512 # * a parsed-literal containing just one markup construct.
2513 def is_plaintext(self, node):
2514 """Check whether a node can be typeset verbatim"""
2515 return (len(node) == 1) and isinstance(node[0], nodes.Text)
2517 def visit_literal_block(self, node):
2518 """Render a literal block."""
2519 # environments and packages to typeset literal blocks
2520 packages = {'alltt': r'\usepackage{alltt}',
2521 'listing': r'\usepackage{moreverb}',
2522 'lstlisting': r'\usepackage{listings}',
2523 'Verbatim': r'\usepackage{fancyvrb}',
2524 # 'verbatim': '',
2525 'verbatimtab': r'\usepackage{moreverb}'}
2527 if node.get('ids'):
2528 self.out += ['\n'] + self.ids_to_labels(node)
2530 self.duclass_open(node)
2531 if not self.active_table.is_open():
2532 # no quote inside tables, to avoid vertical space between
2533 # table border and literal block.
2534 # TODO: fails if normal text precedes the literal block.
2535 # check parent node instead?
2536 self.out.append('\\begin{quote}\n')
2537 self.context.append('\n\\end{quote}\n')
2538 else:
2539 self.context.append('\n')
2541 if self.is_plaintext(node):
2542 environment = self.literal_block_env
2543 self.requirements['literal_block'] = packages.get(environment, '')
2544 if environment == 'alltt':
2545 self.alltt = True
2546 else:
2547 self.verbatim = True
2548 self.out.append('\\begin{%s}%s\n' %
2549 (environment, self.literal_block_options))
2550 self.context.append('\n\\end{%s}' % environment)
2551 else:
2552 self.literal = True
2553 self.insert_newline = True
2554 self.insert_non_breaking_blanks = True
2555 if 'code' in node['classes'] and (
2556 self.settings.syntax_highlight != 'none'):
2557 self.requirements['color'] = PreambleCmds.color
2558 self.fallbacks['code'] = PreambleCmds.highlight_rules
2559 self.out.append('{\\ttfamily \\raggedright \\noindent\n')
2560 self.context.append('\n}')
2562 def depart_literal_block(self, node):
2563 self.insert_non_breaking_blanks = False
2564 self.insert_newline = False
2565 self.literal = False
2566 self.verbatim = False
2567 self.alltt = False
2568 self.out.append(self.context.pop())
2569 self.out.append(self.context.pop())
2570 self.duclass_close(node)
2572 ## def visit_meta(self, node):
2573 ## self.out.append('[visit_meta]\n')
2574 # TODO: set keywords for pdf?
2575 # But:
2576 # The reStructuredText "meta" directive creates a "pending" node,
2577 # which contains knowledge that the embedded "meta" node can only
2578 # be handled by HTML-compatible writers. The "pending" node is
2579 # resolved by the docutils.transforms.components.Filter transform,
2580 # which checks that the calling writer supports HTML; if it doesn't,
2581 # the "pending" node (and enclosed "meta" node) is removed from the
2582 # document.
2583 # --- docutils/docs/peps/pep-0258.html#transformer
2585 ## def depart_meta(self, node):
2586 ## self.out.append('[depart_meta]\n')
2588 def visit_math(self, node, math_env='$'):
2589 """math role"""
2590 if node['classes']:
2591 self.visit_inline(node)
2592 self.requirements['amsmath'] = r'\usepackage{amsmath}'
2593 math_code = node.astext().translate(unichar2tex.uni2tex_table)
2594 if node.get('ids'):
2595 math_code = '\n'.join([math_code] + self.ids_to_labels(node))
2596 if math_env == '$':
2597 if self.alltt:
2598 wrapper = ur'\(%s\)'
2599 else:
2600 wrapper = u'$%s$'
2601 else:
2602 wrapper = u'\n'.join(['%%',
2603 r'\begin{%s}' % math_env,
2604 '%s',
2605 r'\end{%s}' % math_env])
2606 # print repr(wrapper), repr(math_code)
2607 self.out.append(wrapper % math_code)
2608 if node['classes']:
2609 self.depart_inline(node)
2610 # Content already processed:
2611 raise nodes.SkipNode
2613 def depart_math(self, node):
2614 pass # never reached
2616 def visit_math_block(self, node):
2617 math_env = pick_math_environment(node.astext())
2618 self.visit_math(node, math_env=math_env)
2620 def depart_math_block(self, node):
2621 pass # never reached
2623 def visit_option(self, node):
2624 if self.context[-1]:
2625 # this is not the first option
2626 self.out.append(', ')
2628 def depart_option(self, node):
2629 # flag that the first option is done.
2630 self.context[-1] += 1
2632 def visit_option_argument(self, node):
2633 """Append the delimiter betweeen an option and its argument to body."""
2634 self.out.append(node.get('delimiter', ' '))
2636 def depart_option_argument(self, node):
2637 pass
2639 def visit_option_group(self, node):
2640 self.out.append('\n\\item[')
2641 # flag for first option
2642 self.context.append(0)
2644 def depart_option_group(self, node):
2645 self.context.pop() # the flag
2646 self.out.append('] ')
2648 def visit_option_list(self, node):
2649 self.fallbacks['_providelength'] = PreambleCmds.providelength
2650 self.fallbacks['optionlist'] = PreambleCmds.optionlist
2651 self.duclass_open(node)
2652 self.out.append('\\begin{DUoptionlist}')
2654 def depart_option_list(self, node):
2655 self.out.append('\\end{DUoptionlist}\n')
2656 self.duclass_close(node)
2658 def visit_option_list_item(self, node):
2659 pass
2661 def depart_option_list_item(self, node):
2662 pass
2664 def visit_option_string(self, node):
2665 ##self.out.append(self.starttag(node, 'span', '', CLASS='option'))
2666 pass
2668 def depart_option_string(self, node):
2669 ##self.out.append('</span>')
2670 pass
2672 def visit_organization(self, node):
2673 self.visit_docinfo_item(node, 'organization')
2675 def depart_organization(self, node):
2676 self.depart_docinfo_item(node)
2678 def visit_paragraph(self, node):
2679 # insert blank line, unless
2680 # * the paragraph is first in a list item or compound,
2681 # * follows a non-paragraph node in a compound,
2682 # * is in a table with auto-width columns
2683 index = node.parent.index(node)
2684 if index == 0 and isinstance(node.parent,
2685 (nodes.list_item, nodes.description, nodes.compound)):
2686 pass
2687 elif (index > 0 and isinstance(node.parent, nodes.compound) and
2688 not isinstance(node.parent[index - 1], nodes.paragraph) and
2689 not isinstance(node.parent[index - 1], nodes.compound)):
2690 pass
2691 elif self.active_table.colwidths_auto:
2692 if index == 1: # second paragraph
2693 self.warn('LaTeX merges paragraphs in tables '
2694 'with auto-sized columns!', base_node=node)
2695 if index > 0:
2696 self.out.append('\n')
2697 else:
2698 self.out.append('\n')
2699 if node.get('ids'):
2700 self.out += self.ids_to_labels(node) + ['\n']
2701 if node['classes']:
2702 self.visit_inline(node)
2704 def depart_paragraph(self, node):
2705 if node['classes']:
2706 self.depart_inline(node)
2707 if not self.active_table.colwidths_auto:
2708 self.out.append('\n')
2710 def visit_problematic(self, node):
2711 self.requirements['color'] = PreambleCmds.color
2712 self.out.append('%\n')
2713 self.append_hypertargets(node)
2714 self.out.append(r'\hyperlink{%s}{\textbf{\color{red}' % node['refid'])
2716 def depart_problematic(self, node):
2717 self.out.append('}}')
2719 def visit_raw(self, node):
2720 if not 'latex' in node.get('format', '').split():
2721 raise nodes.SkipNode
2722 if not self.is_inline(node):
2723 self.out.append('\n')
2724 if node['classes']:
2725 self.visit_inline(node)
2726 # append "as-is" skipping any LaTeX-encoding
2727 self.verbatim = True
2729 def depart_raw(self, node):
2730 self.verbatim = False
2731 if node['classes']:
2732 self.depart_inline(node)
2733 if not self.is_inline(node):
2734 self.out.append('\n')
2736 def has_unbalanced_braces(self, string):
2737 """Test whether there are unmatched '{' or '}' characters."""
2738 level = 0
2739 for ch in string:
2740 if ch == '{':
2741 level += 1
2742 if ch == '}':
2743 level -= 1
2744 if level < 0:
2745 return True
2746 return level != 0
2748 def visit_reference(self, node):
2749 # We need to escape #, \, and % if we use the URL in a command.
2750 special_chars = {ord('#'): ur'\#',
2751 ord('%'): ur'\%',
2752 ord('\\'): ur'\\',
2754 # external reference (URL)
2755 if 'refuri' in node:
2756 href = unicode(node['refuri']).translate(special_chars)
2757 # problematic chars double caret and unbalanced braces:
2758 if href.find('^^') != -1 or self.has_unbalanced_braces(href):
2759 self.error(
2760 'External link "%s" not supported by LaTeX.\n'
2761 ' (Must not contain "^^" or unbalanced braces.)' % href)
2762 if node['refuri'] == node.astext():
2763 self.out.append(r'\url{%s}' % href)
2764 raise nodes.SkipNode
2765 self.out.append(r'\href{%s}{' % href)
2766 return
2767 # internal reference
2768 if 'refid' in node:
2769 href = node['refid']
2770 elif 'refname' in node:
2771 href = self.document.nameids[node['refname']]
2772 else:
2773 raise AssertionError('Unknown reference.')
2774 if not self.is_inline(node):
2775 self.out.append('\n')
2776 self.out.append('\\hyperref[%s]{' % href)
2777 if self._reference_label:
2778 self.out.append('\\%s{%s}}' %
2779 (self._reference_label, href.replace('#', '')))
2780 raise nodes.SkipNode
2782 def depart_reference(self, node):
2783 self.out.append('}')
2784 if not self.is_inline(node):
2785 self.out.append('\n')
2787 def visit_revision(self, node):
2788 self.visit_docinfo_item(node, 'revision')
2790 def depart_revision(self, node):
2791 self.depart_docinfo_item(node)
2793 def visit_rubric(self, node):
2794 self.fallbacks['rubric'] = PreambleCmds.rubric
2795 self.duclass_open(node)
2796 self.out.append('\\DUrubric{')
2798 def depart_rubric(self, node):
2799 self.out.append('}\n')
2800 self.duclass_close(node)
2802 def visit_section(self, node):
2803 self.section_level += 1
2804 # Initialize counter for potential subsections:
2805 self._section_number.append(0)
2806 # Counter for this section's level (initialized by parent section):
2807 self._section_number[self.section_level - 1] += 1
2809 def depart_section(self, node):
2810 # Remove counter for potential subsections:
2811 self._section_number.pop()
2812 self.section_level -= 1
2814 def visit_sidebar(self, node):
2815 self.duclass_open(node)
2816 self.requirements['color'] = PreambleCmds.color
2817 self.fallbacks['sidebar'] = PreambleCmds.sidebar
2818 self.out.append('\\DUsidebar{')
2820 def depart_sidebar(self, node):
2821 self.out.append('}\n')
2822 self.duclass_close(node)
2824 attribution_formats = {'dash': (u'—', ''), # EM DASH
2825 'parentheses': ('(', ')'),
2826 'parens': ('(', ')'),
2827 'none': ('', '')}
2829 def visit_attribution(self, node):
2830 prefix, suffix = self.attribution_formats[self.settings.attribution]
2831 self.out.append('\\nopagebreak\n\n\\raggedleft ')
2832 self.out.append(prefix)
2833 self.context.append(suffix)
2835 def depart_attribution(self, node):
2836 self.out.append(self.context.pop() + '\n')
2838 def visit_status(self, node):
2839 self.visit_docinfo_item(node, 'status')
2841 def depart_status(self, node):
2842 self.depart_docinfo_item(node)
2844 def visit_strong(self, node):
2845 self.out.append('\\textbf{')
2846 if node['classes']:
2847 self.visit_inline(node)
2849 def depart_strong(self, node):
2850 if node['classes']:
2851 self.depart_inline(node)
2852 self.out.append('}')
2854 def visit_substitution_definition(self, node):
2855 raise nodes.SkipNode
2857 def visit_substitution_reference(self, node):
2858 self.unimplemented_visit(node)
2860 def visit_subtitle(self, node):
2861 if isinstance(node.parent, nodes.document):
2862 self.push_output_collector(self.subtitle)
2863 self.fallbacks['documentsubtitle'] = PreambleCmds.documentsubtitle
2864 self.subtitle_labels += self.ids_to_labels(node, set_anchor=False)
2865 # section subtitle: "starred" (no number, not in ToC)
2866 elif isinstance(node.parent, nodes.section):
2867 self.out.append(r'\%s*{' %
2868 self.d_class.section(self.section_level + 1))
2869 else:
2870 self.fallbacks['subtitle'] = PreambleCmds.subtitle
2871 self.out.append('\n\\DUsubtitle[%s]{' % node.parent.tagname)
2873 def depart_subtitle(self, node):
2874 if isinstance(node.parent, nodes.document):
2875 self.pop_output_collector()
2876 else:
2877 self.out.append('}\n')
2879 def visit_system_message(self, node):
2880 self.requirements['color'] = PreambleCmds.color
2881 self.fallbacks['title'] = PreambleCmds.title
2882 node['classes'] = ['system-message']
2883 self.visit_admonition(node)
2884 self.out.append('\n\\DUtitle[system-message]{system-message}\n')
2885 self.append_hypertargets(node)
2886 try:
2887 line = ', line~%s' % node['line']
2888 except KeyError:
2889 line = ''
2890 self.out.append('\n\n{\\color{red}%s/%s} in \\texttt{%s}%s\n' %
2891 (node['type'], node['level'],
2892 self.encode(node['source']), line))
2893 if len(node['backrefs']) == 1:
2894 self.out.append('\n\\hyperlink{%s}{' % node['backrefs'][0])
2895 self.context.append('}')
2896 else:
2897 backrefs = ['\\hyperlink{%s}{%d}' % (href, i+1)
2898 for (i, href) in enumerate(node['backrefs'])]
2899 self.context.append('backrefs: ' + ' '.join(backrefs))
2901 def depart_system_message(self, node):
2902 self.out.append(self.context.pop())
2903 self.depart_admonition()
2905 def visit_table(self, node):
2906 self.requirements['table'] = PreambleCmds.table
2907 if self.active_table.is_open():
2908 self.table_stack.append(self.active_table)
2909 # nesting longtable does not work (e.g. 2007-04-18)
2910 self.active_table = Table(self,'tabular')
2911 # A longtable moves before \paragraph and \subparagraph
2912 # section titles if it immediately follows them:
2913 if (self.active_table._latex_type == 'longtable' and
2914 isinstance(node.parent, nodes.section) and
2915 node.parent.index(node) == 1 and
2916 self.d_class.section(self.section_level).find('paragraph') != -1):
2917 self.out.append('\\leavevmode')
2918 self.active_table.open()
2919 self.active_table.set_table_style(self.settings.table_style,
2920 node['classes'])
2921 if 'align' in node:
2922 self.active_table.set('align', node['align'])
2923 if self.active_table.borders == 'booktabs':
2924 self.requirements['booktabs'] = r'\usepackage{booktabs}'
2925 self.push_output_collector([])
2927 def depart_table(self, node):
2928 # wrap content in the right environment:
2929 content = self.out
2930 self.pop_output_collector()
2931 self.out.append('\n' + self.active_table.get_opening())
2932 self.out += content
2933 self.out.append(self.active_table.get_closing() + '\n')
2934 self.active_table.close()
2935 if len(self.table_stack)>0:
2936 self.active_table = self.table_stack.pop()
2937 # Insert hyperlabel after (long)table, as
2938 # other places (beginning, caption) result in LaTeX errors.
2939 if node.get('ids'):
2940 self.out += self.ids_to_labels(node, set_anchor=False) + ['\n']
2942 def visit_target(self, node):
2943 # Skip indirect targets:
2944 if ('refuri' in node # external hyperlink
2945 or 'refid' in node # resolved internal link
2946 or 'refname' in node): # unresolved internal link
2947 ## self.out.append('%% %s\n' % node) # for debugging
2948 return
2949 self.out.append('%\n')
2950 # do we need an anchor (\phantomsection)?
2951 set_anchor = not(isinstance(node.parent, nodes.caption) or
2952 isinstance(node.parent, nodes.title))
2953 # TODO: where else can/must we omit the \phantomsection?
2954 self.out += self.ids_to_labels(node, set_anchor)
2956 def depart_target(self, node):
2957 pass
2959 def visit_tbody(self, node):
2960 # BUG write preamble if not yet done (colspecs not [])
2961 # for tables without heads.
2962 if not self.active_table.get('preamble written'):
2963 self.visit_thead(node)
2964 self.depart_thead(None)
2966 def depart_tbody(self, node):
2967 pass
2969 def visit_term(self, node):
2970 """definition list term"""
2971 # Commands with optional args inside an optional arg must be put
2972 # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
2973 self.out.append('\\item[{')
2975 def depart_term(self, node):
2976 # \leavevmode results in a line break if the
2977 # term is followed by an item list.
2978 self.out.append('}] \leavevmode ')
2980 def visit_tgroup(self, node):
2981 #self.out.append(self.starttag(node, 'colgroup'))
2982 #self.context.append('</colgroup>\n')
2983 pass
2985 def depart_tgroup(self, node):
2986 pass
2988 _thead_depth = 0
2989 def thead_depth (self):
2990 return self._thead_depth
2992 def visit_thead(self, node):
2993 self._thead_depth += 1
2994 if 1 == self.thead_depth():
2995 self.out.append('{%s}\n' % self.active_table.get_colspecs(node))
2996 self.active_table.set('preamble written',1)
2997 self.out.append(self.active_table.get_caption())
2998 self.out.extend(self.active_table.visit_thead())
3000 def depart_thead(self, node):
3001 if node is not None:
3002 self.out.extend(self.active_table.depart_thead())
3003 if self.active_table.need_recurse():
3004 node.walkabout(self)
3005 self._thead_depth -= 1
3007 def visit_title(self, node):
3008 """Append section and other titles."""
3009 # Document title
3010 if node.parent.tagname == 'document':
3011 self.push_output_collector(self.title)
3012 self.context.append('')
3013 self.pdfinfo.append(' pdftitle={%s},' %
3014 self.encode(node.astext()))
3015 # Topic titles (topic, admonition, sidebar)
3016 elif (isinstance(node.parent, nodes.topic) or
3017 isinstance(node.parent, nodes.admonition) or
3018 isinstance(node.parent, nodes.sidebar)):
3019 self.fallbacks['title'] = PreambleCmds.title
3020 classes = ','.join(node.parent['classes'])
3021 if not classes:
3022 classes = node.tagname
3023 self.out.append('\n\\DUtitle[%s]{' % classes)
3024 self.context.append('}\n')
3025 # Table caption
3026 elif isinstance(node.parent, nodes.table):
3027 self.push_output_collector(self.active_table.caption)
3028 self.context.append('')
3029 # Section title
3030 else:
3031 if hasattr(PreambleCmds, 'secnumdepth'):
3032 self.requirements['secnumdepth'] = PreambleCmds.secnumdepth
3033 section_name = self.d_class.section(self.section_level)
3034 self.out.append('\n\n')
3035 # System messages heading in red:
3036 if ('system-messages' in node.parent['classes']):
3037 self.requirements['color'] = PreambleCmds.color
3038 section_title = self.encode(node.astext())
3039 self.out.append(r'\%s[%s]{\color{red}' % (
3040 section_name,section_title))
3041 else:
3042 self.out.append(r'\%s{' % section_name)
3043 if self.section_level > len(self.d_class.sections):
3044 # section level not supported by LaTeX
3045 self.fallbacks['title'] = PreambleCmds.title
3046 # self.out.append('\\phantomsection%\n ')
3047 # label and ToC entry:
3048 bookmark = ['']
3049 # add sections with unsupported level to toc and pdfbookmarks?
3050 ## if self.section_level > len(self.d_class.sections):
3051 ## section_title = self.encode(node.astext())
3052 ## bookmark.append(r'\addcontentsline{toc}{%s}{%s}' %
3053 ## (section_name, section_title))
3054 bookmark += self.ids_to_labels(node.parent, set_anchor=False)
3055 self.context.append('%\n '.join(bookmark) + '%\n}\n')
3057 # MAYBE postfix paragraph and subparagraph with \leavemode to
3058 # ensure floats stay in the section and text starts on a new line.
3060 def depart_title(self, node):
3061 self.out.append(self.context.pop())
3062 if (isinstance(node.parent, nodes.table) or
3063 node.parent.tagname == 'document'):
3064 self.pop_output_collector()
3066 def minitoc(self, node, title, depth):
3067 """Generate a local table of contents with LaTeX package minitoc"""
3068 section_name = self.d_class.section(self.section_level)
3069 # name-prefix for current section level
3070 minitoc_names = {'part': 'part', 'chapter': 'mini'}
3071 if 'chapter' not in self.d_class.sections:
3072 minitoc_names['section'] = 'sect'
3073 try:
3074 minitoc_name = minitoc_names[section_name]
3075 except KeyError: # minitoc only supports part- and toplevel
3076 self.warn('Skipping local ToC at %s level.\n' % section_name +
3077 ' Feature not supported with option "use-latex-toc"',
3078 base_node=node)
3079 return
3080 # Requirements/Setup
3081 self.requirements['minitoc'] = PreambleCmds.minitoc
3082 self.requirements['minitoc-'+minitoc_name] = (r'\do%stoc' %
3083 minitoc_name)
3084 # depth: (Docutils defaults to unlimited depth)
3085 maxdepth = len(self.d_class.sections)
3086 self.requirements['minitoc-%s-depth' % minitoc_name] = (
3087 r'\mtcsetdepth{%stoc}{%d}' % (minitoc_name, maxdepth))
3088 # Process 'depth' argument (!Docutils stores a relative depth while
3089 # minitoc expects an absolute depth!):
3090 offset = {'sect': 1, 'mini': 0, 'part': 0}
3091 if 'chapter' in self.d_class.sections:
3092 offset['part'] = -1
3093 if depth:
3094 self.out.append('\\setcounter{%stocdepth}{%d}' %
3095 (minitoc_name, depth + offset[minitoc_name]))
3096 # title:
3097 self.out.append('\\mtcsettitle{%stoc}{%s}\n' % (minitoc_name, title))
3098 # the toc-generating command:
3099 self.out.append('\\%stoc\n' % minitoc_name)
3101 def visit_topic(self, node):
3102 # Topic nodes can be generic topic, abstract, dedication, or ToC.
3103 # table of contents:
3104 if 'contents' in node['classes']:
3105 self.out.append('\n')
3106 self.out += self.ids_to_labels(node)
3107 # add contents to PDF bookmarks sidebar
3108 if isinstance(node.next_node(), nodes.title):
3109 self.out.append('\n\\pdfbookmark[%d]{%s}{%s}' %
3110 (self.section_level+1,
3111 node.next_node().astext(),
3112 node.get('ids', ['contents'])[0]
3114 if self.use_latex_toc:
3115 title = ''
3116 if isinstance(node.next_node(), nodes.title):
3117 title = self.encode(node.pop(0).astext())
3118 depth = node.get('depth', 0)
3119 if 'local' in node['classes']:
3120 self.minitoc(node, title, depth)
3121 return
3122 if depth:
3123 self.out.append('\\setcounter{tocdepth}{%d}\n' % depth)
3124 if title != 'Contents':
3125 self.out.append('\n\\renewcommand{\\contentsname}{%s}' %
3126 title)
3127 self.out.append('\n\\tableofcontents\n')
3128 self.has_latex_toc = True
3129 else: # Docutils generated contents list
3130 # set flag for visit_bullet_list() and visit_title()
3131 self.is_toc_list = True
3132 elif ('abstract' in node['classes'] and
3133 self.settings.use_latex_abstract):
3134 self.push_output_collector(self.abstract)
3135 self.out.append('\\begin{abstract}')
3136 if isinstance(node.next_node(), nodes.title):
3137 node.pop(0) # LaTeX provides its own title
3138 else:
3139 # special topics:
3140 if 'abstract' in node['classes']:
3141 self.fallbacks['abstract'] = PreambleCmds.abstract
3142 self.push_output_collector(self.abstract)
3143 elif 'dedication' in node['classes']:
3144 self.fallbacks['dedication'] = PreambleCmds.dedication
3145 self.push_output_collector(self.dedication)
3146 else:
3147 node['classes'].insert(0, 'topic')
3148 self.visit_block_quote(node)
3150 def depart_topic(self, node):
3151 self.is_toc_list = False
3152 if ('abstract' in node['classes']
3153 and self.settings.use_latex_abstract):
3154 self.out.append('\\end{abstract}\n')
3155 elif not 'contents' in node['classes']:
3156 self.depart_block_quote(node)
3157 if ('abstract' in node['classes'] or
3158 'dedication' in node['classes']):
3159 self.pop_output_collector()
3161 def visit_transition(self, node):
3162 self.fallbacks['transition'] = PreambleCmds.transition
3163 self.out.append('\n%' + '_' * 75 + '\n')
3164 self.out.append('\\DUtransition\n')
3166 def depart_transition(self, node):
3167 pass
3169 def visit_version(self, node):
3170 self.visit_docinfo_item(node, 'version')
3172 def depart_version(self, node):
3173 self.depart_docinfo_item(node)
3175 def unimplemented_visit(self, node):
3176 raise NotImplementedError('visiting unimplemented node type: %s' %
3177 node.__class__.__name__)
3179 # def unknown_visit(self, node):
3180 # def default_visit(self, node):
3182 # vim: set ts=4 et ai :