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