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