Drop support for Python 2.3.
[docutils.git] / docutils / writers / latex2e / __init__.py
blob8c58806e349f151023adf6aa06aa14c9fa2af5ea
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.error_reporting import SafeString
28 from docutils.transforms import writer_aux
29 from docutils.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 = 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 not self.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',
1337 handle_io_errors=False).read()
1338 self.settings.record_dependencies.add(path)
1339 except IOError, err:
1340 msg = u"Cannot embed stylesheet '%s':\n %s." % (
1341 path, SafeString(err.strerror))
1342 self.document.reporter.error(msg)
1343 return '% ' + msg.replace('\n', '\n% ')
1344 if is_package:
1345 content = '\n'.join([r'\makeatletter',
1346 content,
1347 r'\makeatother'])
1348 return '%% embedded stylesheet: %s\n%s' % (path, content)
1349 # Link to style file:
1350 if is_package:
1351 path = base # drop extension
1352 cmd = r'\usepackage{%s}'
1353 else:
1354 cmd = r'\input{%s}'
1355 if self.settings.stylesheet_path:
1356 # adapt path relative to output (cf. config.html#stylesheet-path)
1357 path = utils.relative_path(self.settings._destination, path)
1358 return cmd % path
1360 def to_latex_encoding(self,docutils_encoding):
1361 """Translate docutils encoding name into LaTeX's.
1363 Default method is remove "-" and "_" chars from docutils_encoding.
1365 tr = { 'iso-8859-1': 'latin1', # west european
1366 'iso-8859-2': 'latin2', # east european
1367 'iso-8859-3': 'latin3', # esperanto, maltese
1368 'iso-8859-4': 'latin4', # north european, scandinavian, baltic
1369 'iso-8859-5': 'iso88595', # cyrillic (ISO)
1370 'iso-8859-9': 'latin5', # turkish
1371 'iso-8859-15': 'latin9', # latin9, update to latin1.
1372 'mac_cyrillic': 'maccyr', # cyrillic (on Mac)
1373 'windows-1251': 'cp1251', # cyrillic (on Windows)
1374 'koi8-r': 'koi8-r', # cyrillic (Russian)
1375 'koi8-u': 'koi8-u', # cyrillic (Ukrainian)
1376 'windows-1250': 'cp1250', #
1377 'windows-1252': 'cp1252', #
1378 'us-ascii': 'ascii', # ASCII (US)
1379 # unmatched encodings
1380 #'': 'applemac',
1381 #'': 'ansinew', # windows 3.1 ansi
1382 #'': 'ascii', # ASCII encoding for the range 32--127.
1383 #'': 'cp437', # dos latin us
1384 #'': 'cp850', # dos latin 1
1385 #'': 'cp852', # dos latin 2
1386 #'': 'decmulti',
1387 #'': 'latin10',
1388 #'iso-8859-6': '' # arabic
1389 #'iso-8859-7': '' # greek
1390 #'iso-8859-8': '' # hebrew
1391 #'iso-8859-10': '' # latin6, more complete iso-8859-4
1393 encoding = docutils_encoding.lower()
1394 if encoding in tr:
1395 return tr[encoding]
1396 # drop hyphen or low-line from "latin-1", "latin_1", "utf-8" and similar
1397 encoding = encoding.replace('_', '').replace('-', '')
1398 # strip the error handler
1399 return encoding.split(':')[0]
1401 def language_label(self, docutil_label):
1402 return self.language_module.labels[docutil_label]
1404 def encode(self, text):
1405 """Return text with 'problematic' characters escaped.
1407 * Escape the ten special printing characters ``# $ % & ~ _ ^ \ { }``,
1408 square brackets ``[ ]``, double quotes and (in OT1) ``< | >``.
1409 * Translate non-supported Unicode characters.
1410 * Separate ``-`` (and more in literal text) to prevent input ligatures.
1412 if self.verbatim:
1413 return text
1415 # Set up the translation table:
1416 table = CharMaps.special.copy()
1417 # keep the underscore in citation references
1418 if self.inside_citation_reference_label:
1419 del(table[ord('_')])
1420 # Workarounds for OT1 font-encoding
1421 if self.font_encoding in ['OT1', ''] and not self.is_xetex:
1422 # * out-of-order characters in cmtt
1423 if self.literal:
1424 # replace underscore by underlined blank,
1425 # because this has correct width.
1426 table[ord('_')] = u'\\underline{~}'
1427 # the backslash doesn't work, so we use a mirrored slash.
1428 # \reflectbox is provided by graphicx:
1429 self.requirements['graphicx'] = self.graphicx_package
1430 table[ord('\\')] = ur'\reflectbox{/}'
1431 # * ``< | >`` come out as different chars (except for cmtt):
1432 else:
1433 table[ord('|')] = ur'\textbar{}'
1434 table[ord('<')] = ur'\textless{}'
1435 table[ord('>')] = ur'\textgreater{}'
1436 if self.insert_non_breaking_blanks:
1437 table[ord(' ')] = ur'~'
1438 if self.literal:
1439 # double quotes are 'active' in some languages
1440 # TODO: use \textquotedbl if font encoding starts with T?
1441 table[ord('"')] = self.babel.literal_double_quote
1442 # Unicode replacements for 8-bit tex engines (not required with XeTeX/LuaTeX):
1443 if not self.is_xetex:
1444 table.update(CharMaps.unsupported_unicode)
1445 if not self.latex_encoding.startswith('utf8'):
1446 table.update(CharMaps.utf8_supported_unicode)
1447 table.update(CharMaps.textcomp)
1448 table.update(CharMaps.pifont)
1449 # Characters that require a feature/package to render
1450 if [True for ch in text if ord(ch) in CharMaps.textcomp]:
1451 self.requirements['textcomp'] = PreambleCmds.textcomp
1452 if [True for ch in text if ord(ch) in CharMaps.pifont]:
1453 self.requirements['pifont'] = '\\usepackage{pifont}'
1455 text = text.translate(table)
1457 # Break up input ligatures e.g. '--' to '-{}-'.
1458 if not self.is_xetex: # Not required with xetex/luatex
1459 separate_chars = '-'
1460 # In monospace-font, we also separate ',,', '``' and "''" and some
1461 # other characters which can't occur in non-literal text.
1462 if self.literal:
1463 separate_chars += ',`\'"<>'
1464 for char in separate_chars * 2:
1465 # Do it twice ("* 2") because otherwise we would replace
1466 # '---' by '-{}--'.
1467 text = text.replace(char + char, char + '{}' + char)
1469 # Literal line breaks (in address or literal blocks):
1470 if self.insert_newline:
1471 lines = text.split('\n')
1472 # Add a protected space to blank lines (except the last)
1473 # to avoid ``! LaTeX Error: There's no line here to end.``
1474 for i, line in enumerate(lines[:-1]):
1475 if not line.lstrip():
1476 lines[i] += '~'
1477 text = (r'\\' + '\n').join(lines)
1478 if not self.literal:
1479 text = self.babel.quote_quotes(text)
1480 if self.literal and not self.insert_non_breaking_blanks:
1481 # preserve runs of spaces but allow wrapping
1482 text = text.replace(' ', ' ~')
1483 return text
1485 def attval(self, text,
1486 whitespace=re.compile('[\n\r\t\v\f]')):
1487 """Cleanse, encode, and return attribute value text."""
1488 return self.encode(whitespace.sub(' ', text))
1490 # TODO: is this used anywhere? -> update (use template) or delete
1491 ## def astext(self):
1492 ## """Assemble document parts and return as string."""
1493 ## head = '\n'.join(self.head_prefix + self.stylesheet + self.head)
1494 ## body = ''.join(self.body_prefix + self.body + self.body_suffix)
1495 ## return head + '\n' + body
1497 def is_inline(self, node):
1498 """Check whether a node represents an inline element"""
1499 return isinstance(node.parent, nodes.TextElement)
1501 def append_hypertargets(self, node):
1502 """Append hypertargets for all ids of `node`"""
1503 # hypertarget places the anchor at the target's baseline,
1504 # so we raise it explicitely
1505 self.out.append('%\n'.join(['\\raisebox{1em}{\\hypertarget{%s}{}}' %
1506 id for id in node['ids']]))
1508 def ids_to_labels(self, node, set_anchor=True):
1509 """Return list of label definitions for all ids of `node`
1511 If `set_anchor` is True, an anchor is set with \phantomsection.
1513 labels = ['\\label{%s}' % id for id in node.get('ids', [])]
1514 if set_anchor and labels:
1515 labels.insert(0, '\\phantomsection')
1516 return labels
1518 def push_output_collector(self, new_out):
1519 self.out_stack.append(self.out)
1520 self.out = new_out
1522 def pop_output_collector(self):
1523 self.out = self.out_stack.pop()
1525 # Visitor methods
1526 # ---------------
1528 def visit_Text(self, node):
1529 self.out.append(self.encode(node.astext()))
1531 def depart_Text(self, node):
1532 pass
1534 def visit_abbreviation(self, node):
1535 node['classes'].insert(0, 'abbreviation')
1536 self.visit_inline(node)
1538 def depart_abbreviation(self, node):
1539 self.depart_inline(node)
1541 def visit_acronym(self, node):
1542 node['classes'].insert(0, 'acronym')
1543 self.visit_inline(node)
1545 def depart_acronym(self, node):
1546 self.depart_inline(node)
1548 def visit_address(self, node):
1549 self.visit_docinfo_item(node, 'address')
1551 def depart_address(self, node):
1552 self.depart_docinfo_item(node)
1554 def visit_admonition(self, node):
1555 self.fallbacks['admonition'] = PreambleCmds.admonition
1556 if 'error' in node['classes']:
1557 self.fallbacks['error'] = PreambleCmds.error
1558 # strip the generic 'admonition' from the list of classes
1559 node['classes'] = [cls for cls in node['classes']
1560 if cls != 'admonition']
1561 self.out.append('\n\\DUadmonition[%s]{\n' % ','.join(node['classes']))
1563 def depart_admonition(self, node=None):
1564 self.out.append('}\n')
1566 def visit_author(self, node):
1567 self.visit_docinfo_item(node, 'author')
1569 def depart_author(self, node):
1570 self.depart_docinfo_item(node)
1572 def visit_authors(self, node):
1573 # not used: visit_author is called anyway for each author.
1574 pass
1576 def depart_authors(self, node):
1577 pass
1579 def visit_block_quote(self, node):
1580 self.out.append( '%\n\\begin{quote}\n')
1581 if node['classes']:
1582 self.visit_inline(node)
1584 def depart_block_quote(self, node):
1585 if node['classes']:
1586 self.depart_inline(node)
1587 self.out.append( '\n\\end{quote}\n')
1589 def visit_bullet_list(self, node):
1590 if self.is_toc_list:
1591 self.out.append( '%\n\\begin{list}{}{}\n' )
1592 else:
1593 self.out.append( '%\n\\begin{itemize}\n' )
1595 def depart_bullet_list(self, node):
1596 if self.is_toc_list:
1597 self.out.append( '\n\\end{list}\n' )
1598 else:
1599 self.out.append( '\n\\end{itemize}\n' )
1601 def visit_superscript(self, node):
1602 self.out.append(r'\textsuperscript{')
1603 if node['classes']:
1604 self.visit_inline(node)
1606 def depart_superscript(self, node):
1607 if node['classes']:
1608 self.depart_inline(node)
1609 self.out.append('}')
1611 def visit_subscript(self, node):
1612 self.out.append(r'\textsubscript{') # requires `fixltx2e`
1613 if node['classes']:
1614 self.visit_inline(node)
1616 def depart_subscript(self, node):
1617 if node['classes']:
1618 self.depart_inline(node)
1619 self.out.append('}')
1621 def visit_caption(self, node):
1622 self.out.append( '\\caption{' )
1624 def depart_caption(self, node):
1625 self.out.append('}\n')
1627 def visit_title_reference(self, node):
1628 self.fallbacks['titlereference'] = PreambleCmds.titlereference
1629 self.out.append(r'\DUroletitlereference{')
1630 if node['classes']:
1631 self.visit_inline(node)
1633 def depart_title_reference(self, node):
1634 if node['classes']:
1635 self.depart_inline(node)
1636 self.out.append( '}' )
1638 def visit_citation(self, node):
1639 # TODO maybe use cite bibitems
1640 if self._use_latex_citations:
1641 self.push_output_collector([])
1642 else:
1643 # TODO: do we need these?
1644 ## self.requirements['~fnt_floats'] = PreambleCmds.footnote_floats
1645 self.out.append(r'\begin{figure}[b]')
1646 self.append_hypertargets(node)
1648 def depart_citation(self, node):
1649 if self._use_latex_citations:
1650 label = self.out[0]
1651 text = ''.join(self.out[1:])
1652 self._bibitems.append([label, text])
1653 self.pop_output_collector()
1654 else:
1655 self.out.append('\\end{figure}\n')
1657 def visit_citation_reference(self, node):
1658 if self._use_latex_citations:
1659 if not self.inside_citation_reference_label:
1660 self.out.append(r'\cite{')
1661 self.inside_citation_reference_label = 1
1662 else:
1663 assert self.body[-1] in (' ', '\n'),\
1664 'unexpected non-whitespace while in reference label'
1665 del self.body[-1]
1666 else:
1667 href = ''
1668 if 'refid' in node:
1669 href = node['refid']
1670 elif 'refname' in node:
1671 href = self.document.nameids[node['refname']]
1672 self.out.append('\\hyperlink{%s}{[' % href)
1674 def depart_citation_reference(self, node):
1675 if self._use_latex_citations:
1676 followup_citation = False
1677 # check for a following citation separated by a space or newline
1678 next_siblings = node.traverse(descend=False, siblings=True,
1679 include_self=False)
1680 if len(next_siblings) > 1:
1681 next = next_siblings[0]
1682 if (isinstance(next, nodes.Text) and
1683 next.astext() in (' ', '\n')):
1684 if next_siblings[1].__class__ == node.__class__:
1685 followup_citation = True
1686 if followup_citation:
1687 self.out.append(',')
1688 else:
1689 self.out.append('}')
1690 self.inside_citation_reference_label = False
1691 else:
1692 self.out.append(']}')
1694 def visit_classifier(self, node):
1695 self.out.append( '(\\textbf{' )
1697 def depart_classifier(self, node):
1698 self.out.append( '})\n' )
1700 def visit_colspec(self, node):
1701 self.active_table.visit_colspec(node)
1703 def depart_colspec(self, node):
1704 pass
1706 def visit_comment(self, node):
1707 # Precede every line with a comment sign, wrap in newlines
1708 self.out.append('\n%% %s\n' % node.astext().replace('\n', '\n% '))
1709 raise nodes.SkipNode
1711 def depart_comment(self, node):
1712 pass
1714 def visit_compound(self, node):
1715 pass
1717 def depart_compound(self, node):
1718 pass
1720 def visit_contact(self, node):
1721 self.visit_docinfo_item(node, 'contact')
1723 def depart_contact(self, node):
1724 self.depart_docinfo_item(node)
1726 def visit_container(self, node):
1727 pass
1729 def depart_container(self, node):
1730 pass
1732 def visit_copyright(self, node):
1733 self.visit_docinfo_item(node, 'copyright')
1735 def depart_copyright(self, node):
1736 self.depart_docinfo_item(node)
1738 def visit_date(self, node):
1739 self.visit_docinfo_item(node, 'date')
1741 def depart_date(self, node):
1742 self.depart_docinfo_item(node)
1744 def visit_decoration(self, node):
1745 # header and footer
1746 pass
1748 def depart_decoration(self, node):
1749 pass
1751 def visit_definition(self, node):
1752 pass
1754 def depart_definition(self, node):
1755 self.out.append('\n')
1757 def visit_definition_list(self, node):
1758 self.out.append( '%\n\\begin{description}\n' )
1760 def depart_definition_list(self, node):
1761 self.out.append( '\\end{description}\n' )
1763 def visit_definition_list_item(self, node):
1764 pass
1766 def depart_definition_list_item(self, node):
1767 pass
1769 def visit_description(self, node):
1770 self.out.append(' ')
1772 def depart_description(self, node):
1773 pass
1775 def visit_docinfo(self, node):
1776 self.push_output_collector(self.docinfo)
1778 def depart_docinfo(self, node):
1779 self.pop_output_collector()
1780 # Some itmes (e.g. author) end up at other places
1781 if self.docinfo:
1782 # tabularx: automatic width of columns, no page breaks allowed.
1783 self.requirements['tabularx'] = r'\usepackage{tabularx}'
1784 self.fallbacks['_providelength'] = PreambleCmds.providelength
1785 self.fallbacks['docinfo'] = PreambleCmds.docinfo
1787 self.docinfo.insert(0, '\n% Docinfo\n'
1788 '\\begin{center}\n'
1789 '\\begin{tabularx}{\\DUdocinfowidth}{lX}\n')
1790 self.docinfo.append('\\end{tabularx}\n'
1791 '\\end{center}\n')
1793 def visit_docinfo_item(self, node, name):
1794 if name == 'author':
1795 self.pdfauthor.append(self.attval(node.astext()))
1796 if self.use_latex_docinfo:
1797 if name in ('author', 'organization', 'contact', 'address'):
1798 # We attach these to the last author. If any of them precedes
1799 # the first author, put them in a separate "author" group
1800 # (in lack of better semantics).
1801 if name == 'author' or not self.author_stack:
1802 self.author_stack.append([])
1803 if name == 'address': # newlines are meaningful
1804 self.insert_newline = True
1805 text = self.encode(node.astext())
1806 self.insert_newline = False
1807 else:
1808 text = self.attval(node.astext())
1809 self.author_stack[-1].append(text)
1810 raise nodes.SkipNode
1811 elif name == 'date':
1812 self.date.append(self.attval(node.astext()))
1813 raise nodes.SkipNode
1814 self.out.append('\\textbf{%s}: &\n\t' % self.language_label(name))
1815 if name == 'address':
1816 self.insert_newline = 1
1817 self.out.append('{\\raggedright\n')
1818 self.context.append(' } \\\\\n')
1819 else:
1820 self.context.append(' \\\\\n')
1822 def depart_docinfo_item(self, node):
1823 self.out.append(self.context.pop())
1824 # for address we did set insert_newline
1825 self.insert_newline = False
1827 def visit_doctest_block(self, node):
1828 self.visit_literal_block(node)
1830 def depart_doctest_block(self, node):
1831 self.depart_literal_block(node)
1833 def visit_document(self, node):
1834 # titled document?
1835 if (self.use_latex_docinfo or len(node) and
1836 isinstance(node[0], nodes.title)):
1837 self.title_labels += self.ids_to_labels(node, set_anchor=False)
1839 def depart_document(self, node):
1840 # Complete header with information gained from walkabout
1841 # * language setup
1842 if (self.babel.otherlanguages or
1843 self.babel.language not in ('', 'english')):
1844 self.requirements['babel'] = self.babel()
1845 # * conditional requirements (before style sheet)
1846 self.requirements = self.requirements.sortedvalues()
1847 # * coditional fallback definitions (after style sheet)
1848 self.fallbacks = self.fallbacks.sortedvalues()
1849 # * PDF properties
1850 self.pdfsetup.append(PreambleCmds.linking % self.hyperref_options)
1851 if self.pdfauthor:
1852 authors = self.author_separator.join(self.pdfauthor)
1853 self.pdfinfo.append(' pdfauthor={%s}' % authors)
1854 if self.pdfinfo:
1855 self.pdfsetup += [r'\hypersetup{'] + self.pdfinfo + ['}']
1856 # Complete body
1857 # * document title (with "use_latex_docinfo" also
1858 # 'author', 'organization', 'contact', 'address' and 'date')
1859 if self.title or (
1860 self.use_latex_docinfo and (self.author_stack or self.date)):
1861 # with the default template, titledata is written to the preamble
1862 self.titledata.append('%%% Title Data')
1863 # \title (empty \title prevents error with \maketitle)
1864 if self.title:
1865 self.title.insert(0, '\phantomsection%\n ')
1866 title = [''.join(self.title)] + self.title_labels
1867 if self.subtitle:
1868 title += [r'\\ % subtitle',
1869 r'\large{%s}' % ''.join(self.subtitle)
1870 ] + self.subtitle_labels
1871 self.titledata.append(r'\title{%s}' % '%\n '.join(title))
1872 # \author (empty \author prevents warning with \maketitle)
1873 authors = ['\\\\\n'.join(author_entry)
1874 for author_entry in self.author_stack]
1875 self.titledata.append(r'\author{%s}' %
1876 ' \\and\n'.join(authors))
1877 # \date (empty \date prevents defaulting to \today)
1878 self.titledata.append(r'\date{%s}' % ', '.join(self.date))
1879 # \maketitle in the body formats title with LaTeX
1880 self.body_pre_docinfo.append('\\maketitle\n')
1882 # * bibliography
1883 # TODO insertion point of bibliography should be configurable.
1884 if self._use_latex_citations and len(self._bibitems)>0:
1885 if not self.bibtex:
1886 widest_label = ''
1887 for bi in self._bibitems:
1888 if len(widest_label)<len(bi[0]):
1889 widest_label = bi[0]
1890 self.out.append('\n\\begin{thebibliography}{%s}\n' %
1891 widest_label)
1892 for bi in self._bibitems:
1893 # cite_key: underscores must not be escaped
1894 cite_key = bi[0].replace(r'\_','_')
1895 self.out.append('\\bibitem[%s]{%s}{%s}\n' %
1896 (bi[0], cite_key, bi[1]))
1897 self.out.append('\\end{thebibliography}\n')
1898 else:
1899 self.out.append('\n\\bibliographystyle{%s}\n' %
1900 self.bibtex[0])
1901 self.out.append('\\bibliography{%s}\n' % self.bibtex[1])
1902 # * make sure to generate a toc file if needed for local contents:
1903 if 'minitoc' in self.requirements and not self.has_latex_toc:
1904 self.out.append('\n\\faketableofcontents % for local ToCs\n')
1906 def visit_emphasis(self, node):
1907 self.out.append('\\emph{')
1908 if node['classes']:
1909 self.visit_inline(node)
1911 def depart_emphasis(self, node):
1912 if node['classes']:
1913 self.depart_inline(node)
1914 self.out.append('}')
1916 def visit_entry(self, node):
1917 self.active_table.visit_entry()
1918 # cell separation
1919 # BUG: the following fails, with more than one multirow
1920 # starting in the second column (or later) see
1921 # ../../../test/functional/input/data/latex.txt
1922 if self.active_table.get_entry_number() == 1:
1923 # if the first row is a multirow, this actually is the second row.
1924 # this gets hairy if rowspans follow each other.
1925 if self.active_table.get_rowspan(0):
1926 count = 0
1927 while self.active_table.get_rowspan(count):
1928 count += 1
1929 self.out.append(' & ')
1930 self.active_table.visit_entry() # increment cell count
1931 else:
1932 self.out.append(' & ')
1933 # multirow, multicolumn
1934 # IN WORK BUG TODO HACK continues here
1935 # multirow in LaTeX simply will enlarge the cell over several rows
1936 # (the following n if n is positive, the former if negative).
1937 if 'morerows' in node and 'morecols' in node:
1938 raise NotImplementedError('Cells that '
1939 'span multiple rows *and* columns are not supported, sorry.')
1940 if 'morerows' in node:
1941 self.requirements['multirow'] = r'\usepackage{multirow}'
1942 count = node['morerows'] + 1
1943 self.active_table.set_rowspan(
1944 self.active_table.get_entry_number()-1,count)
1945 self.out.append('\\multirow{%d}{%s}{%%' %
1946 (count,self.active_table.get_column_width()))
1947 self.context.append('}')
1948 elif 'morecols' in node:
1949 # the vertical bar before column is missing if it is the first
1950 # column. the one after always.
1951 if self.active_table.get_entry_number() == 1:
1952 bar1 = self.active_table.get_vertical_bar()
1953 else:
1954 bar1 = ''
1955 count = node['morecols'] + 1
1956 self.out.append('\\multicolumn{%d}{%sp{%s}%s}{' %
1957 (count, bar1,
1958 self.active_table.get_multicolumn_width(
1959 self.active_table.get_entry_number(),
1960 count),
1961 self.active_table.get_vertical_bar()))
1962 self.context.append('}')
1963 else:
1964 self.context.append('')
1966 # header / not header
1967 if isinstance(node.parent.parent, nodes.thead):
1968 self.out.append('\\textbf{%')
1969 self.context.append('}')
1970 elif self.active_table.is_stub_column():
1971 self.out.append('\\textbf{')
1972 self.context.append('}')
1973 else:
1974 self.context.append('')
1976 def depart_entry(self, node):
1977 self.out.append(self.context.pop()) # header / not header
1978 self.out.append(self.context.pop()) # multirow/column
1979 # if following row is spanned from above.
1980 if self.active_table.get_rowspan(self.active_table.get_entry_number()):
1981 self.out.append(' & ')
1982 self.active_table.visit_entry() # increment cell count
1984 def visit_row(self, node):
1985 self.active_table.visit_row()
1987 def depart_row(self, node):
1988 self.out.extend(self.active_table.depart_row())
1990 def visit_enumerated_list(self, node):
1991 # We create our own enumeration list environment.
1992 # This allows to set the style and starting value
1993 # and unlimited nesting.
1994 enum_style = {'arabic':'arabic',
1995 'loweralpha':'alph',
1996 'upperalpha':'Alph',
1997 'lowerroman':'roman',
1998 'upperroman':'Roman' }
1999 enum_suffix = ''
2000 if 'suffix' in node:
2001 enum_suffix = node['suffix']
2002 enum_prefix = ''
2003 if 'prefix' in node:
2004 enum_prefix = node['prefix']
2005 if self.compound_enumerators:
2006 pref = ''
2007 if self.section_prefix_for_enumerators and self.section_level:
2008 for i in range(self.section_level):
2009 pref += '%d.' % self._section_number[i]
2010 pref = pref[:-1] + self.section_enumerator_separator
2011 enum_prefix += pref
2012 for ctype, cname in self._enumeration_counters:
2013 enum_prefix += '\\%s{%s}.' % (ctype, cname)
2014 enum_type = 'arabic'
2015 if 'enumtype' in node:
2016 enum_type = node['enumtype']
2017 if enum_type in enum_style:
2018 enum_type = enum_style[enum_type]
2020 counter_name = 'listcnt%d' % len(self._enumeration_counters)
2021 self._enumeration_counters.append((enum_type, counter_name))
2022 # If we haven't used this counter name before, then create a
2023 # new counter; otherwise, reset & reuse the old counter.
2024 if len(self._enumeration_counters) > self._max_enumeration_counters:
2025 self._max_enumeration_counters = len(self._enumeration_counters)
2026 self.out.append('\\newcounter{%s}\n' % counter_name)
2027 else:
2028 self.out.append('\\setcounter{%s}{0}\n' % counter_name)
2030 self.out.append('\\begin{list}{%s\\%s{%s}%s}\n' %
2031 (enum_prefix,enum_type,counter_name,enum_suffix))
2032 self.out.append('{\n')
2033 self.out.append('\\usecounter{%s}\n' % counter_name)
2034 # set start after usecounter, because it initializes to zero.
2035 if 'start' in node:
2036 self.out.append('\\addtocounter{%s}{%d}\n' %
2037 (counter_name,node['start']-1))
2038 ## set rightmargin equal to leftmargin
2039 self.out.append('\\setlength{\\rightmargin}{\\leftmargin}\n')
2040 self.out.append('}\n')
2042 def depart_enumerated_list(self, node):
2043 self.out.append('\\end{list}\n')
2044 self._enumeration_counters.pop()
2046 def visit_field(self, node):
2047 # real output is done in siblings: _argument, _body, _name
2048 pass
2050 def depart_field(self, node):
2051 self.out.append('\n')
2052 ##self.out.append('%[depart_field]\n')
2054 def visit_field_argument(self, node):
2055 self.out.append('%[visit_field_argument]\n')
2057 def depart_field_argument(self, node):
2058 self.out.append('%[depart_field_argument]\n')
2060 def visit_field_body(self, node):
2061 pass
2063 def depart_field_body(self, node):
2064 if self.out is self.docinfo:
2065 self.out.append(r'\\')
2067 def visit_field_list(self, node):
2068 if self.out is not self.docinfo:
2069 self.fallbacks['fieldlist'] = PreambleCmds.fieldlist
2070 self.out.append('%\n\\begin{DUfieldlist}\n')
2072 def depart_field_list(self, node):
2073 if self.out is not self.docinfo:
2074 self.out.append('\\end{DUfieldlist}\n')
2076 def visit_field_name(self, node):
2077 if self.out is self.docinfo:
2078 self.out.append('\\textbf{')
2079 else:
2080 # Commands with optional args inside an optional arg must be put
2081 # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
2082 self.out.append('\\item[{')
2084 def depart_field_name(self, node):
2085 if self.out is self.docinfo:
2086 self.out.append('}: &')
2087 else:
2088 self.out.append(':}]')
2090 def visit_figure(self, node):
2091 self.requirements['float_settings'] = PreambleCmds.float_settings
2092 # ! the 'align' attribute should set "outer alignment" !
2093 # For "inner alignment" use LaTeX default alignment (similar to HTML)
2094 ## if ('align' not in node.attributes or
2095 ## node.attributes['align'] == 'center'):
2096 ## align = '\n\\centering'
2097 ## align_end = ''
2098 ## else:
2099 ## # TODO non vertical space for other alignments.
2100 ## align = '\\begin{flush%s}' % node.attributes['align']
2101 ## align_end = '\\end{flush%s}' % node.attributes['align']
2102 ## self.out.append( '\\begin{figure}%s\n' % align )
2103 ## self.context.append( '%s\\end{figure}\n' % align_end )
2104 self.out.append('\\begin{figure}')
2105 if node.get('ids'):
2106 self.out += ['\n'] + self.ids_to_labels(node)
2108 def depart_figure(self, node):
2109 self.out.append('\\end{figure}\n')
2111 def visit_footer(self, node):
2112 self.push_output_collector([])
2113 self.out.append(r'\newcommand{\DUfooter}{')
2115 def depart_footer(self, node):
2116 self.out.append('}')
2117 self.requirements['~footer'] = ''.join(self.out)
2118 self.pop_output_collector()
2120 def visit_footnote(self, node):
2121 try:
2122 backref = node['backrefs'][0]
2123 except IndexError:
2124 backref = node['ids'][0] # no backref, use self-ref instead
2125 if self.settings.figure_footnotes:
2126 self.requirements['~fnt_floats'] = PreambleCmds.footnote_floats
2127 self.out.append('\\begin{figure}[b]')
2128 self.append_hypertargets(node)
2129 if node.get('id') == node.get('name'): # explicite label
2130 self.out += self.ids_to_labels(node)
2131 elif self.docutils_footnotes:
2132 self.fallbacks['footnotes'] = PreambleCmds.footnotes
2133 num,text = node.astext().split(None,1)
2134 if self.settings.footnote_references == 'brackets':
2135 num = '[%s]' % num
2136 self.out.append('%%\n\\DUfootnotetext{%s}{%s}{%s}{' %
2137 (node['ids'][0], backref, self.encode(num)))
2138 if node['ids'] == node['names']:
2139 self.out += self.ids_to_labels(node)
2140 # mask newline to prevent spurious whitespace:
2141 self.out.append('%')
2142 ## else: # TODO: "real" LaTeX \footnote{}s
2144 def depart_footnote(self, node):
2145 if self.figure_footnotes:
2146 self.out.append('\\end{figure}\n')
2147 else:
2148 self.out.append('}\n')
2150 def visit_footnote_reference(self, node):
2151 href = ''
2152 if 'refid' in node:
2153 href = node['refid']
2154 elif 'refname' in node:
2155 href = self.document.nameids[node['refname']]
2156 # if not self.docutils_footnotes:
2157 # TODO: insert footnote content at (or near) this place
2158 # print "footnote-ref to", node['refid']
2159 # footnotes = (self.document.footnotes +
2160 # self.document.autofootnotes +
2161 # self.document.symbol_footnotes)
2162 # for footnote in footnotes:
2163 # # print footnote['ids']
2164 # if node.get('refid', '') in footnote['ids']:
2165 # print 'matches', footnote['ids']
2166 format = self.settings.footnote_references
2167 if format == 'brackets':
2168 self.append_hypertargets(node)
2169 self.out.append('\\hyperlink{%s}{[' % href)
2170 self.context.append(']}')
2171 else:
2172 self.fallbacks['footnotes'] = PreambleCmds.footnotes
2173 self.out.append(r'\DUfootnotemark{%s}{%s}{' %
2174 (node['ids'][0], href))
2175 self.context.append('}')
2177 def depart_footnote_reference(self, node):
2178 self.out.append(self.context.pop())
2180 # footnote/citation label
2181 def label_delim(self, node, bracket, superscript):
2182 if isinstance(node.parent, nodes.footnote):
2183 if not self.figure_footnotes:
2184 raise nodes.SkipNode
2185 if self.settings.footnote_references == 'brackets':
2186 self.out.append(bracket)
2187 else:
2188 self.out.append(superscript)
2189 else:
2190 assert isinstance(node.parent, nodes.citation)
2191 if not self._use_latex_citations:
2192 self.out.append(bracket)
2194 def visit_label(self, node):
2195 """footnote or citation label: in brackets or as superscript"""
2196 self.label_delim(node, '[', '\\textsuperscript{')
2198 def depart_label(self, node):
2199 self.label_delim(node, ']', '}')
2201 # elements generated by the framework e.g. section numbers.
2202 def visit_generated(self, node):
2203 pass
2205 def depart_generated(self, node):
2206 pass
2208 def visit_header(self, node):
2209 self.push_output_collector([])
2210 self.out.append(r'\newcommand{\DUheader}{')
2212 def depart_header(self, node):
2213 self.out.append('}')
2214 self.requirements['~header'] = ''.join(self.out)
2215 self.pop_output_collector()
2217 def to_latex_length(self, length_str, pxunit=None):
2218 """Convert `length_str` with rst lenght to LaTeX length
2220 if pxunit is not None:
2221 sys.stderr.write('deprecation warning: LaTeXTranslator.to_latex_length()'
2222 ' option `pxunit` will be removed.')
2223 match = re.match('(\d*\.?\d*)\s*(\S*)', length_str)
2224 if not match:
2225 return length_str
2226 value, unit = match.groups()[:2]
2227 # no unit or "DTP" points (called 'bp' in TeX):
2228 if unit in ('', 'pt'):
2229 length_str = '%sbp' % value
2230 # percentage: relate to current line width
2231 elif unit == '%':
2232 length_str = '%.3f\\linewidth' % (float(value)/100.0)
2233 elif self.is_xetex and unit == 'px':
2234 # XeTeX does not know the length unit px.
2235 # Use \pdfpxdimen, the macro to set the value of 1 px in pdftex.
2236 # This way, configuring works the same for pdftex and xetex.
2237 self.fallbacks['_providelength'] = PreambleCmds.providelength
2238 self.fallbacks['px'] = '\n\\DUprovidelength{\\pdfpxdimen}{1bp}\n'
2239 length_str = r'%s\pdfpxdimen' % value
2240 return length_str
2242 def visit_image(self, node):
2243 self.requirements['graphicx'] = self.graphicx_package
2244 attrs = node.attributes
2245 # Convert image URI to a local file path
2246 imagepath = urllib.url2pathname(attrs['uri']).replace('\\', '/')
2247 # alignment defaults:
2248 if not 'align' in attrs:
2249 # Set default align of image in a figure to 'center'
2250 if isinstance(node.parent, nodes.figure):
2251 attrs['align'] = 'center'
2252 # query 'align-*' class argument
2253 for cls in node['classes']:
2254 if cls.startswith('align-'):
2255 attrs['align'] = cls.split('-')[1]
2256 # pre- and postfix (prefix inserted in reverse order)
2257 pre = []
2258 post = []
2259 include_graphics_options = []
2260 display_style = ('block-', 'inline-')[self.is_inline(node)]
2261 align_codes = {
2262 # inline images: by default latex aligns the bottom.
2263 'bottom': ('', ''),
2264 'middle': (r'\raisebox{-0.5\height}{', '}'),
2265 'top': (r'\raisebox{-\height}{', '}'),
2266 # block level images:
2267 'center': (r'\noindent\makebox[\textwidth][c]{', '}'),
2268 'left': (r'\noindent{', r'\hfill}'),
2269 'right': (r'\noindent{\hfill', '}'),}
2270 if 'align' in attrs:
2271 try:
2272 align_code = align_codes[attrs['align']]
2273 pre.append(align_code[0])
2274 post.append(align_code[1])
2275 except KeyError:
2276 pass # TODO: warn?
2277 if 'height' in attrs:
2278 include_graphics_options.append('height=%s' %
2279 self.to_latex_length(attrs['height']))
2280 if 'scale' in attrs:
2281 include_graphics_options.append('scale=%f' %
2282 (attrs['scale'] / 100.0))
2283 if 'width' in attrs:
2284 include_graphics_options.append('width=%s' %
2285 self.to_latex_length(attrs['width']))
2286 if not self.is_inline(node):
2287 pre.append('\n')
2288 post.append('\n')
2289 pre.reverse()
2290 self.out.extend(pre)
2291 options = ''
2292 if include_graphics_options:
2293 options = '[%s]' % (','.join(include_graphics_options))
2294 self.out.append('\\includegraphics%s{%s}' % (options, imagepath))
2295 self.out.extend(post)
2297 def depart_image(self, node):
2298 if node.get('ids'):
2299 self.out += self.ids_to_labels(node) + ['\n']
2301 def visit_inline(self, node): # <span>, i.e. custom roles
2302 # Make a copy to keep ``node['classes']`` True if a
2303 # language argument is popped (used in conditional calls of
2304 # depart_inline()):
2305 classes = node['classes'][:]
2306 self.context.append('}' * len(classes))
2307 # handle language specification:
2308 language_tags = [cls for cls in classes
2309 if cls.startswith('language-')]
2310 if language_tags:
2311 language = self.babel.language_name(language_tags[0][9:])
2312 if language:
2313 self.babel.otherlanguages[language] = True
2314 self.out.append(r'\otherlanguage{%s}{' % language)
2315 classes.pop(classes.index(language_tags[0]))
2316 if not classes:
2317 return
2318 # mark up for styling with custom macros
2319 if 'align-center' in classes:
2320 self.fallbacks['align-center'] = PreambleCmds.align_center
2321 self.fallbacks['inline'] = PreambleCmds.inline
2322 self.out += [r'\DUrole{%s}{' % cls for cls in classes]
2324 def depart_inline(self, node):
2325 self.out.append(self.context.pop())
2327 def visit_interpreted(self, node):
2328 # @@@ Incomplete, pending a proper implementation on the
2329 # Parser/Reader end.
2330 self.visit_literal(node)
2332 def depart_interpreted(self, node):
2333 self.depart_literal(node)
2335 def visit_legend(self, node):
2336 self.fallbacks['legend'] = PreambleCmds.legend
2337 self.out.append('\\begin{DUlegend}')
2339 def depart_legend(self, node):
2340 self.out.append('\\end{DUlegend}\n')
2342 def visit_line(self, node):
2343 self.out.append('\item[] ')
2345 def depart_line(self, node):
2346 self.out.append('\n')
2348 def visit_line_block(self, node):
2349 self.fallbacks['_providelength'] = PreambleCmds.providelength
2350 self.fallbacks['lineblock'] = PreambleCmds.lineblock
2351 if isinstance(node.parent, nodes.line_block):
2352 self.out.append('\\item[]\n'
2353 '\\begin{DUlineblock}{\\DUlineblockindent}\n')
2354 else:
2355 self.out.append('\n\\begin{DUlineblock}{0em}\n')
2356 if node['classes']:
2357 self.visit_inline(node)
2358 self.out.append('\n')
2360 def depart_line_block(self, node):
2361 if node['classes']:
2362 self.depart_inline(node)
2363 self.out.append('\n')
2364 self.out.append('\\end{DUlineblock}\n')
2366 def visit_list_item(self, node):
2367 self.out.append('\n\\item ')
2369 def depart_list_item(self, node):
2370 pass
2372 def visit_literal(self, node):
2373 self.literal = True
2374 self.out.append('\\texttt{')
2375 if node['classes']:
2376 self.visit_inline(node)
2378 def depart_literal(self, node):
2379 self.literal = False
2380 if node['classes']:
2381 self.depart_inline(node)
2382 self.out.append('}')
2384 # Literal blocks are used for '::'-prefixed literal-indented
2385 # blocks of text, where the inline markup is not recognized,
2386 # but are also the product of the "parsed-literal" directive,
2387 # where the markup is respected.
2389 # In both cases, we want to use a typewriter/monospaced typeface.
2390 # For "real" literal-blocks, we can use \verbatim, while for all
2391 # the others we must use \mbox or \alltt.
2393 # We can distinguish between the two kinds by the number of
2394 # siblings that compose this node: if it is composed by a
2395 # single element, it's either
2396 # * a real one,
2397 # * a parsed-literal that does not contain any markup, or
2398 # * a parsed-literal containing just one markup construct.
2399 def is_plaintext(self, node):
2400 """Check whether a node can be typeset verbatim"""
2401 return (len(node) == 1) and isinstance(node[0], nodes.Text)
2403 def visit_literal_block(self, node):
2404 """Render a literal block."""
2405 # environments and packages to typeset literal blocks
2406 packages = {'listing': r'\usepackage{moreverb}',
2407 'lstlisting': r'\usepackage{listings}',
2408 'Verbatim': r'\usepackage{fancyvrb}',
2409 # 'verbatim': '',
2410 'verbatimtab': r'\usepackage{moreverb}'}
2412 if not self.active_table.is_open():
2413 # no quote inside tables, to avoid vertical space between
2414 # table border and literal block.
2415 # BUG: fails if normal text preceeds the literal block.
2416 self.out.append('%\n\\begin{quote}')
2417 self.context.append('\n\\end{quote}\n')
2418 else:
2419 self.out.append('\n')
2420 self.context.append('\n')
2421 if self.literal_block_env != '' and self.is_plaintext(node):
2422 self.requirements['literal_block'] = packages.get(
2423 self.literal_block_env, '')
2424 self.verbatim = True
2425 self.out.append('\\begin{%s}%s\n' % (self.literal_block_env,
2426 self.literal_block_options))
2427 else:
2428 self.literal = True
2429 self.insert_newline = True
2430 self.insert_non_breaking_blanks = True
2431 self.out.append('{\\ttfamily \\raggedright \\noindent\n')
2433 def depart_literal_block(self, node):
2434 if self.verbatim:
2435 self.out.append('\n\\end{%s}\n' % self.literal_block_env)
2436 self.verbatim = False
2437 else:
2438 self.out.append('\n}')
2439 self.insert_non_breaking_blanks = False
2440 self.insert_newline = False
2441 self.literal = False
2442 self.out.append(self.context.pop())
2444 ## def visit_meta(self, node):
2445 ## self.out.append('[visit_meta]\n')
2446 # TODO: set keywords for pdf?
2447 # But:
2448 # The reStructuredText "meta" directive creates a "pending" node,
2449 # which contains knowledge that the embedded "meta" node can only
2450 # be handled by HTML-compatible writers. The "pending" node is
2451 # resolved by the docutils.transforms.components.Filter transform,
2452 # which checks that the calling writer supports HTML; if it doesn't,
2453 # the "pending" node (and enclosed "meta" node) is removed from the
2454 # document.
2455 # --- docutils/docs/peps/pep-0258.html#transformer
2457 ## def depart_meta(self, node):
2458 ## self.out.append('[depart_meta]\n')
2460 def visit_math(self, node, math_env='$'):
2461 """math role"""
2462 if node['classes']:
2463 self.visit_inline(node)
2464 self.requirements['amsmath'] = r'\usepackage{amsmath}'
2465 math_code = node.astext().translate(unichar2tex.uni2tex_table)
2466 if node.get('ids'):
2467 math_code = '\n'.join([math_code] + self.ids_to_labels(node))
2468 if math_env == '$':
2469 wrapper = u'$%s$'
2470 else:
2471 wrapper = u'\n'.join(['%%',
2472 r'\begin{%s}' % math_env,
2473 '%s',
2474 r'\end{%s}' % math_env])
2475 # print repr(wrapper), repr(math_code)
2476 self.out.append(wrapper % math_code)
2477 if node['classes']:
2478 self.depart_inline(node)
2479 # Content already processed:
2480 raise nodes.SkipNode
2482 def depart_math(self, node):
2483 pass # never reached
2485 def visit_math_block(self, node):
2486 math_env = pick_math_environment(node.astext())
2487 self.visit_math(node, math_env=math_env)
2489 def depart_math_block(self, node):
2490 pass # never reached
2492 def visit_option(self, node):
2493 if self.context[-1]:
2494 # this is not the first option
2495 self.out.append(', ')
2497 def depart_option(self, node):
2498 # flag that the first option is done.
2499 self.context[-1] += 1
2501 def visit_option_argument(self, node):
2502 """Append the delimiter betweeen an option and its argument to body."""
2503 self.out.append(node.get('delimiter', ' '))
2505 def depart_option_argument(self, node):
2506 pass
2508 def visit_option_group(self, node):
2509 self.out.append('\n\\item[')
2510 # flag for first option
2511 self.context.append(0)
2513 def depart_option_group(self, node):
2514 self.context.pop() # the flag
2515 self.out.append('] ')
2517 def visit_option_list(self, node):
2518 self.fallbacks['_providelength'] = PreambleCmds.providelength
2519 self.fallbacks['optionlist'] = PreambleCmds.optionlist
2520 self.out.append('%\n\\begin{DUoptionlist}\n')
2522 def depart_option_list(self, node):
2523 self.out.append('\n\\end{DUoptionlist}\n')
2525 def visit_option_list_item(self, node):
2526 pass
2528 def depart_option_list_item(self, node):
2529 pass
2531 def visit_option_string(self, node):
2532 ##self.out.append(self.starttag(node, 'span', '', CLASS='option'))
2533 pass
2535 def depart_option_string(self, node):
2536 ##self.out.append('</span>')
2537 pass
2539 def visit_organization(self, node):
2540 self.visit_docinfo_item(node, 'organization')
2542 def depart_organization(self, node):
2543 self.depart_docinfo_item(node)
2545 def visit_paragraph(self, node):
2546 # insert blank line, if the paragraph is not first in a list item
2547 # nor follows a non-paragraph node in a compound
2548 index = node.parent.index(node)
2549 if (index == 0 and (isinstance(node.parent, nodes.list_item) or
2550 isinstance(node.parent, nodes.description))):
2551 pass
2552 elif (index > 0 and isinstance(node.parent, nodes.compound) and
2553 not isinstance(node.parent[index - 1], nodes.paragraph) and
2554 not isinstance(node.parent[index - 1], nodes.compound)):
2555 pass
2556 else:
2557 self.out.append('\n')
2558 if node.get('ids'):
2559 self.out += self.ids_to_labels(node) + ['\n']
2560 if node['classes']:
2561 self.visit_inline(node)
2563 def depart_paragraph(self, node):
2564 if node['classes']:
2565 self.depart_inline(node)
2566 self.out.append('\n')
2568 def visit_problematic(self, node):
2569 self.requirements['color'] = PreambleCmds.color
2570 self.out.append('%\n')
2571 self.append_hypertargets(node)
2572 self.out.append(r'\hyperlink{%s}{\textbf{\color{red}' % node['refid'])
2574 def depart_problematic(self, node):
2575 self.out.append('}}')
2577 def visit_raw(self, node):
2578 if not 'latex' in node.get('format', '').split():
2579 raise nodes.SkipNode
2580 if not self.is_inline(node):
2581 self.out.append('\n')
2582 if node['classes']:
2583 self.visit_inline(node)
2584 # append "as-is" skipping any LaTeX-encoding
2585 self.verbatim = True
2587 def depart_raw(self, node):
2588 self.verbatim = False
2589 if node['classes']:
2590 self.depart_inline(node)
2591 if not self.is_inline(node):
2592 self.out.append('\n')
2594 def has_unbalanced_braces(self, string):
2595 """Test whether there are unmatched '{' or '}' characters."""
2596 level = 0
2597 for ch in string:
2598 if ch == '{':
2599 level += 1
2600 if ch == '}':
2601 level -= 1
2602 if level < 0:
2603 return True
2604 return level != 0
2606 def visit_reference(self, node):
2607 # We need to escape #, \, and % if we use the URL in a command.
2608 special_chars = {ord('#'): ur'\#',
2609 ord('%'): ur'\%',
2610 ord('\\'): ur'\\',
2612 # external reference (URL)
2613 if 'refuri' in node:
2614 href = unicode(node['refuri']).translate(special_chars)
2615 # problematic chars double caret and unbalanced braces:
2616 if href.find('^^') != -1 or self.has_unbalanced_braces(href):
2617 self.error(
2618 'External link "%s" not supported by LaTeX.\n'
2619 ' (Must not contain "^^" or unbalanced braces.)' % href)
2620 if node['refuri'] == node.astext():
2621 self.out.append(r'\url{%s}' % href)
2622 raise nodes.SkipNode
2623 self.out.append(r'\href{%s}{' % href)
2624 return
2625 # internal reference
2626 if 'refid' in node:
2627 href = node['refid']
2628 elif 'refname' in node:
2629 href = self.document.nameids[node['refname']]
2630 else:
2631 raise AssertionError('Unknown reference.')
2632 if not self.is_inline(node):
2633 self.out.append('\n')
2634 self.out.append('\\hyperref[%s]{' % href)
2635 if self._reference_label:
2636 self.out.append('\\%s{%s}}' %
2637 (self._reference_label, href.replace('#', '')))
2638 raise nodes.SkipNode
2640 def depart_reference(self, node):
2641 self.out.append('}')
2642 if not self.is_inline(node):
2643 self.out.append('\n')
2645 def visit_revision(self, node):
2646 self.visit_docinfo_item(node, 'revision')
2648 def depart_revision(self, node):
2649 self.depart_docinfo_item(node)
2651 def visit_section(self, node):
2652 self.section_level += 1
2653 # Initialize counter for potential subsections:
2654 self._section_number.append(0)
2655 # Counter for this section's level (initialized by parent section):
2656 self._section_number[self.section_level - 1] += 1
2658 def depart_section(self, node):
2659 # Remove counter for potential subsections:
2660 self._section_number.pop()
2661 self.section_level -= 1
2663 def visit_sidebar(self, node):
2664 self.requirements['color'] = PreambleCmds.color
2665 self.fallbacks['sidebar'] = PreambleCmds.sidebar
2666 self.out.append('\n\\DUsidebar{\n')
2668 def depart_sidebar(self, node):
2669 self.out.append('}\n')
2671 attribution_formats = {'dash': (u'—', ''), # EM DASH
2672 'parentheses': ('(', ')'),
2673 'parens': ('(', ')'),
2674 'none': ('', '')}
2676 def visit_attribution(self, node):
2677 prefix, suffix = self.attribution_formats[self.settings.attribution]
2678 self.out.append('\\nopagebreak\n\n\\raggedleft ')
2679 self.out.append(prefix)
2680 self.context.append(suffix)
2682 def depart_attribution(self, node):
2683 self.out.append(self.context.pop() + '\n')
2685 def visit_status(self, node):
2686 self.visit_docinfo_item(node, 'status')
2688 def depart_status(self, node):
2689 self.depart_docinfo_item(node)
2691 def visit_strong(self, node):
2692 self.out.append('\\textbf{')
2693 if node['classes']:
2694 self.visit_inline(node)
2696 def depart_strong(self, node):
2697 if node['classes']:
2698 self.depart_inline(node)
2699 self.out.append('}')
2701 def visit_substitution_definition(self, node):
2702 raise nodes.SkipNode
2704 def visit_substitution_reference(self, node):
2705 self.unimplemented_visit(node)
2707 def visit_subtitle(self, node):
2708 if isinstance(node.parent, nodes.document):
2709 self.push_output_collector(self.subtitle)
2710 self.subtitle_labels += self.ids_to_labels(node, set_anchor=False)
2711 # section subtitle: "starred" (no number, not in ToC)
2712 elif isinstance(node.parent, nodes.section):
2713 self.out.append(r'\%s*{' %
2714 self.d_class.section(self.section_level + 1))
2715 else:
2716 self.fallbacks['subtitle'] = PreambleCmds.subtitle
2717 self.out.append('\n\\DUsubtitle[%s]{' % node.parent.tagname)
2719 def depart_subtitle(self, node):
2720 if isinstance(node.parent, nodes.document):
2721 self.pop_output_collector()
2722 else:
2723 self.out.append('}\n')
2725 def visit_system_message(self, node):
2726 self.requirements['color'] = PreambleCmds.color
2727 self.fallbacks['title'] = PreambleCmds.title
2728 node['classes'] = ['system-message']
2729 self.visit_admonition(node)
2730 self.out.append('\\DUtitle[system-message]{system-message}\n')
2731 self.append_hypertargets(node)
2732 try:
2733 line = ', line~%s' % node['line']
2734 except KeyError:
2735 line = ''
2736 self.out.append('\n\n{\color{red}%s/%s} in \\texttt{%s}%s\n' %
2737 (node['type'], node['level'],
2738 self.encode(node['source']), line))
2739 if len(node['backrefs']) == 1:
2740 self.out.append('\n\\hyperlink{%s}{' % node['backrefs'][0])
2741 self.context.append('}')
2742 else:
2743 backrefs = ['\\hyperlink{%s}{%d}' % (href, i+1)
2744 for (i, href) in enumerate(node['backrefs'])]
2745 self.context.append('backrefs: ' + ' '.join(backrefs))
2747 def depart_system_message(self, node):
2748 self.out.append(self.context.pop())
2749 self.depart_admonition()
2751 def visit_table(self, node):
2752 self.requirements['table'] = PreambleCmds.table
2753 if self.active_table.is_open():
2754 self.table_stack.append(self.active_table)
2755 # nesting longtable does not work (e.g. 2007-04-18)
2756 self.active_table = Table(self,'tabular',self.settings.table_style)
2757 # A longtable moves before \paragraph and \subparagraph
2758 # section titles if it immediately follows them:
2759 if (self.active_table._latex_type == 'longtable' and
2760 isinstance(node.parent, nodes.section) and
2761 node.parent.index(node) == 1 and
2762 self.d_class.section(self.section_level).find('paragraph') != -1):
2763 self.out.append('\\leavevmode')
2764 self.active_table.open()
2765 for cls in node['classes']:
2766 self.active_table.set_table_style(cls)
2767 if self.active_table._table_style == 'booktabs':
2768 self.requirements['booktabs'] = r'\usepackage{booktabs}'
2769 self.push_output_collector([])
2771 def depart_table(self, node):
2772 # wrap content in the right environment:
2773 content = self.out
2774 self.pop_output_collector()
2775 self.out.append('\n' + self.active_table.get_opening())
2776 self.out += content
2777 self.out.append(self.active_table.get_closing() + '\n')
2778 self.active_table.close()
2779 if len(self.table_stack)>0:
2780 self.active_table = self.table_stack.pop()
2781 else:
2782 self.active_table.set_table_style(self.settings.table_style)
2783 # Insert hyperlabel after (long)table, as
2784 # other places (beginning, caption) result in LaTeX errors.
2785 if node.get('ids'):
2786 self.out += self.ids_to_labels(node, set_anchor=False) + ['\n']
2788 def visit_target(self, node):
2789 # Skip indirect targets:
2790 if ('refuri' in node # external hyperlink
2791 or 'refid' in node # resolved internal link
2792 or 'refname' in node): # unresolved internal link
2793 ## self.out.append('%% %s\n' % node) # for debugging
2794 return
2795 self.out.append('%\n')
2796 # do we need an anchor (\phantomsection)?
2797 set_anchor = not(isinstance(node.parent, nodes.caption) or
2798 isinstance(node.parent, nodes.title))
2799 # TODO: where else can/must we omit the \phantomsection?
2800 self.out += self.ids_to_labels(node, set_anchor)
2802 def depart_target(self, node):
2803 pass
2805 def visit_tbody(self, node):
2806 # BUG write preamble if not yet done (colspecs not [])
2807 # for tables without heads.
2808 if not self.active_table.get('preamble written'):
2809 self.visit_thead(None)
2810 self.depart_thead(None)
2812 def depart_tbody(self, node):
2813 pass
2815 def visit_term(self, node):
2816 """definition list term"""
2817 # Commands with optional args inside an optional arg must be put
2818 # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
2819 self.out.append('\\item[{')
2821 def depart_term(self, node):
2822 # \leavevmode results in a line break if the
2823 # term is followed by an item list.
2824 self.out.append('}] \leavevmode ')
2826 def visit_tgroup(self, node):
2827 #self.out.append(self.starttag(node, 'colgroup'))
2828 #self.context.append('</colgroup>\n')
2829 pass
2831 def depart_tgroup(self, node):
2832 pass
2834 _thead_depth = 0
2835 def thead_depth (self):
2836 return self._thead_depth
2838 def visit_thead(self, node):
2839 self._thead_depth += 1
2840 if 1 == self.thead_depth():
2841 self.out.append('{%s}\n' % self.active_table.get_colspecs())
2842 self.active_table.set('preamble written',1)
2843 self.out.append(self.active_table.get_caption())
2844 self.out.extend(self.active_table.visit_thead())
2846 def depart_thead(self, node):
2847 if node is not None:
2848 self.out.extend(self.active_table.depart_thead())
2849 if self.active_table.need_recurse():
2850 node.walkabout(self)
2851 self._thead_depth -= 1
2853 def visit_title(self, node):
2854 """Append section and other titles."""
2855 # Document title
2856 if node.parent.tagname == 'document':
2857 self.push_output_collector(self.title)
2858 self.context.append('')
2859 self.pdfinfo.append(' pdftitle={%s},' %
2860 self.encode(node.astext()))
2861 # Topic titles (topic, admonition, sidebar)
2862 elif (isinstance(node.parent, nodes.topic) or
2863 isinstance(node.parent, nodes.admonition) or
2864 isinstance(node.parent, nodes.sidebar)):
2865 self.fallbacks['title'] = PreambleCmds.title
2866 classes = ','.join(node.parent['classes'])
2867 if not classes:
2868 classes = node.tagname
2869 self.out.append('\\DUtitle[%s]{' % classes)
2870 self.context.append('}\n')
2871 # Table caption
2872 elif isinstance(node.parent, nodes.table):
2873 self.push_output_collector(self.active_table.caption)
2874 self.context.append('')
2875 # Section title
2876 else:
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 :