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