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