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