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