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