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