3 # Author: Engelbert Gruber, Günter Milde
4 # Maintainer: docutils-develop@lists.sourceforge.net
5 # Copyright: This module has been placed in the public domain.
7 """LaTeX2e document tree Writer."""
9 __docformat__
= 'reStructuredText'
11 # code contributions from several people included, thanks to all.
12 # some named: David Abrahams, Julien Letessier, Lele Gaifax, and others.
14 # convention deactivate code by two # i.e. ##.
25 import docutils
.utils
.roman
as roman
26 from docutils
import frontend
, nodes
, languages
, writers
, utils
, io
27 from docutils
.utils
.error_reporting
import SafeString
28 from docutils
.transforms
import writer_aux
29 from docutils
.utils
.math
import pick_math_environment
, unichar2tex
31 class Writer(writers
.Writer
):
33 supported
= ('latex','latex2e')
34 """Formats this writer supports."""
36 default_template
= 'default.tex'
37 default_template_path
= os
.path
.dirname(__file__
)
39 default_preamble
= '\n'.join([r
'% PDF Standard Fonts',
40 r
'\usepackage{mathptmx} % Times',
41 r
'\usepackage[scaled=.90]{helvet}',
42 r
'\usepackage{courier}'])
44 'LaTeX-Specific Options',
46 (('Specify documentclass. Default is "article".',
48 {'default': 'article', }),
49 ('Specify document options. Multiple options can be given, '
50 'separated by commas. Default is "a4paper".',
51 ['--documentoptions'],
52 {'default': 'a4paper', }),
53 ('Footnotes with numbers/symbols by Docutils. (default)',
54 ['--docutils-footnotes'],
55 {'default': True, 'action': 'store_true',
56 'validator': frontend
.validate_boolean
}),
57 ('Alias for --docutils-footnotes (deprecated)',
58 ['--use-latex-footnotes'],
59 {'action': 'store_true',
60 'validator': frontend
.validate_boolean
}),
61 ('Use figure floats for footnote text (deprecated)',
62 ['--figure-footnotes'],
63 {'action': 'store_true',
64 'validator': frontend
.validate_boolean
}),
65 ('Format for footnote references: one of "superscript" or '
66 '"brackets". Default is "superscript".',
67 ['--footnote-references'],
68 {'choices': ['superscript', 'brackets'], 'default': 'superscript',
69 'metavar': '<format>',
70 'overrides': 'trim_footnote_reference_space'}),
71 ('Use \\cite command for citations. ',
72 ['--use-latex-citations'],
73 {'default': 0, 'action': 'store_true',
74 'validator': frontend
.validate_boolean
}),
75 ('Use figure floats for citations '
76 '(might get mixed with real figures). (default)',
77 ['--figure-citations'],
78 {'dest': 'use_latex_citations', 'action': 'store_false',
79 'validator': frontend
.validate_boolean
}),
80 ('Format for block quote attributions: one of "dash" (em-dash '
81 'prefix), "parentheses"/"parens", or "none". Default is "dash".',
83 {'choices': ['dash', 'parentheses', 'parens', 'none'],
84 'default': 'dash', 'metavar': '<format>'}),
85 ('Specify LaTeX packages/stylesheets. '
86 ' A style is referenced with \\usepackage if extension is '
87 '".sty" or omitted and with \\input else. '
88 ' Overrides previous --stylesheet and --stylesheet-path settings.',
90 {'default': '', 'metavar': '<file>',
91 'overrides': 'stylesheet_path',
92 'validator': frontend
.validate_comma_separated_list
}),
93 ('Like --stylesheet, but the path is rewritten '
94 'relative to the output file. ',
95 ['--stylesheet-path'],
96 {'metavar': '<file>', 'overrides': 'stylesheet',
97 'validator': frontend
.validate_comma_separated_list
}),
98 ('Link to the stylesheet(s) in the output file. (default)',
99 ['--link-stylesheet'],
100 {'dest': 'embed_stylesheet', 'action': 'store_false'}),
101 ('Embed the stylesheet(s) in the output file. '
102 'Stylesheets must be accessible during processing. ',
103 ['--embed-stylesheet'],
104 {'default': 0, 'action': 'store_true',
105 'validator': frontend
.validate_boolean
}),
106 ('Customization by LaTeX code in the preamble. '
107 'Default: select PDF standard fonts (Times, Helvetica, Courier).',
108 ['--latex-preamble'],
109 {'default': default_preamble
}),
110 ('Specify the template file. Default: "%s".' % default_template
,
112 {'default': default_template
, 'metavar': '<file>'}),
113 ('Table of contents by LaTeX. (default) ',
115 {'default': 1, 'action': 'store_true',
116 'validator': frontend
.validate_boolean
}),
117 ('Table of contents by Docutils (without page numbers). ',
118 ['--use-docutils-toc'],
119 {'dest': 'use_latex_toc', 'action': 'store_false',
120 'validator': frontend
.validate_boolean
}),
121 ('Add parts on top of the section hierarchy.',
122 ['--use-part-section'],
123 {'default': 0, 'action': 'store_true',
124 'validator': frontend
.validate_boolean
}),
125 ('Attach author and date to the document info table. (default) ',
126 ['--use-docutils-docinfo'],
127 {'dest': 'use_latex_docinfo', 'action': 'store_false',
128 'validator': frontend
.validate_boolean
}),
129 ('Attach author and date to the document title.',
130 ['--use-latex-docinfo'],
131 {'default': 0, 'action': 'store_true',
132 'validator': frontend
.validate_boolean
}),
133 ("Typeset abstract as topic. (default)",
134 ['--topic-abstract'],
135 {'dest': 'use_latex_abstract', 'action': 'store_false',
136 'validator': frontend
.validate_boolean
}),
137 ("Use LaTeX abstract environment for the document's abstract. ",
138 ['--use-latex-abstract'],
139 {'default': 0, 'action': 'store_true',
140 'validator': frontend
.validate_boolean
}),
141 ('Color of any hyperlinks embedded in text '
142 '(default: "blue", "false" to disable).',
143 ['--hyperlink-color'], {'default': 'blue'}),
144 ('Additional options to the "hyperref" package '
146 ['--hyperref-options'], {'default': ''}),
147 ('Enable compound enumerators for nested enumerated lists '
148 '(e.g. "1.2.a.ii"). Default: disabled.',
149 ['--compound-enumerators'],
150 {'default': None, 'action': 'store_true',
151 'validator': frontend
.validate_boolean
}),
152 ('Disable compound enumerators for nested enumerated lists. '
153 'This is the default.',
154 ['--no-compound-enumerators'],
155 {'action': 'store_false', 'dest': 'compound_enumerators'}),
156 ('Enable section ("." subsection ...) prefixes for compound '
157 'enumerators. This has no effect without --compound-enumerators.'
158 'Default: disabled.',
159 ['--section-prefix-for-enumerators'],
160 {'default': None, 'action': 'store_true',
161 'validator': frontend
.validate_boolean
}),
162 ('Disable section prefixes for compound enumerators. '
163 'This is the default.',
164 ['--no-section-prefix-for-enumerators'],
165 {'action': 'store_false', 'dest': 'section_prefix_for_enumerators'}),
166 ('Set the separator between section number and enumerator '
167 'for compound enumerated lists. Default is "-".',
168 ['--section-enumerator-separator'],
169 {'default': '-', 'metavar': '<char>'}),
170 ('When possibile, use the specified environment for literal-blocks. '
171 'Default is quoting of whitespace and special chars.',
172 ['--literal-block-env'],
174 ('When possibile, use verbatim for literal-blocks. '
175 'Compatibility alias for "--literal-block-env=verbatim".',
176 ['--use-verbatim-when-possible'],
177 {'default': 0, 'action': 'store_true',
178 'validator': frontend
.validate_boolean
}),
179 ('Table style. "standard" with horizontal and vertical lines, '
180 '"booktabs" (LaTeX booktabs style) only horizontal lines '
181 'above and below the table and below the header or "borderless". '
182 'Default: "standard"',
184 {'choices': ['standard', 'booktabs','nolines', 'borderless'],
185 'default': 'standard',
186 'metavar': '<format>'}),
187 ('LaTeX graphicx package option. '
188 'Possible values are "dvips", "pdftex". "auto" includes LaTeX code '
189 'to use "pdftex" if processing with pdf(la)tex and dvips otherwise. '
190 'Default is no option.',
191 ['--graphicx-option'],
193 ('LaTeX font encoding. '
194 'Possible values are "", "T1" (default), "OT1", "LGR,T1" or '
195 'any other combination of options to the `fontenc` package. ',
198 ('Per default the latex-writer puts the reference title into '
199 'hyperreferences. Specify "ref*" or "pageref*" to get the section '
200 'number or the page number.',
201 ['--reference-label'],
202 {'default': None, }),
203 ('Specify style and database for bibtex, for example '
204 '"--use-bibtex=mystyle,mydb1,mydb2".',
206 {'default': None, }),
209 settings_defaults
= {'sectnum_depth': 0 # updated by SectNum transform
211 relative_path_settings
= ('stylesheet_path',)
213 config_section
= 'latex2e writer'
214 config_section_dependencies
= ('writers',)
216 head_parts
= ('head_prefix', 'requirements', 'latex_preamble',
217 'stylesheet', 'fallbacks', 'pdfsetup',
218 'title', 'subtitle', 'titledata')
219 visitor_attributes
= head_parts
+ ('body_pre_docinfo', 'docinfo',
220 'dedication', 'abstract', 'body')
223 """Final translated form of `document`."""
226 writers
.Writer
.__init
__(self
)
227 self
.translator_class
= LaTeXTranslator
229 # Override parent method to add latex-specific transforms
230 def get_transforms(self
):
231 return writers
.Writer
.get_transforms(self
) + [
232 # Convert specific admonitions to generic one
233 writer_aux
.Admonitions
,
234 # TODO: footnote collection transform
238 visitor
= self
.translator_class(self
.document
)
239 self
.document
.walkabout(visitor
)
241 for part
in self
.visitor_attributes
:
242 setattr(self
, part
, getattr(visitor
, part
))
243 # get template string from file
245 template_file
= open(self
.document
.settings
.template
, 'rb')
247 template_file
= open(os
.path
.join(self
.default_template_path
,
248 self
.document
.settings
.template
), 'rb')
249 template
= string
.Template(unicode(template_file
.read(), 'utf-8'))
250 template_file
.close()
252 self
.assemble_parts() # create dictionary of parts
253 self
.output
= template
.substitute(self
.parts
)
255 def assemble_parts(self
):
256 """Assemble the `self.parts` dictionary of output fragments."""
257 writers
.Writer
.assemble_parts(self
)
258 for part
in self
.visitor_attributes
:
259 lines
= getattr(self
, part
)
260 if part
in self
.head_parts
:
262 lines
.append('') # to get a trailing newline
263 self
.parts
[part
] = '\n'.join(lines
)
265 # body contains inline elements, so join without newline
266 self
.parts
[part
] = ''.join(lines
)
270 """Language specifics for LaTeX."""
272 # TeX (babel) language names:
273 # ! not all of these are supported by Docutils!
275 # based on LyX' languages file with adaptions to `BCP 47`_
276 # (http://www.rfc-editor.org/rfc/bcp/bcp47.txt) and
277 # http://www.tug.org/TUGboat/Articles/tb29-3/tb93miklavec.pdf
278 # * the key without subtags is the default
280 # cf. http://docutils.sourceforge.net/docs/howto/i18n.html
281 # http://www.w3.org/International/articles/language-tags/
282 # and http://www.iana.org/assignments/language-subtag-registry
284 # code TeX/Babel-name comment
287 # 'be': 'belarusian',
295 'de': 'ngerman', # new spelling (de_1996)
296 'de-1901': 'german', # old spelling
297 'de-AT': 'naustrian',
298 'de-AT-1901': 'austrian',
299 'dsb': 'lowersorbian',
300 'el': 'greek', # monotonic (el-monoton)
301 'el-polyton': 'polutonikogreek',
302 'en': 'english', # TeX' default language
303 'en-AU': 'australian',
306 'en-NZ': 'newzealand',
308 'eo': 'esperanto', # '^' is active
316 'ga': 'irish', # Irish Gaelic
317 # 'grc': # Ancient Greek
318 'grc-ibycus': 'ibycus', # Ibycus encoding
322 'hsb': 'uppersorbian',
325 'id': 'bahasai', # Bahasa (Indonesian)
333 'mn': 'mongolian', # Mongolian, Cyrillic script (mn-cyrl)
334 'ms': 'bahasam', # Bahasa (Malay)
335 'nb': 'norsk', # Norwegian Bokmal
337 'nn': 'nynorsk', # Norwegian Nynorsk
338 'no': 'norsk', # Norwegian Bokmal
343 'ru': 'russian', # '"' is active
344 'se': 'samin', # North Sami
345 # sh-Cyrl: Serbo-Croatian, Cyrillic script
346 'sh-Latn': 'serbian', # Serbo-Croatian, Latin script
350 # 'sr-Cyrl': Serbian, Cyrillic script (sr-cyrl)
351 'sr-Latn': 'serbian', # Serbian, Latin script, " active.
357 # zh-Latn: Chinese Pinyin
359 # normalize (downcase) keys
360 language_codes
= dict([(k
.lower(), v
) for (k
,v
) in language_codes
.items()])
362 warn_msg
= 'Language "%s" not supported by LaTeX (babel)'
364 def __init__(self
, language_code
, reporter
=None):
365 self
.reporter
= reporter
366 self
.language
= self
.language_name(language_code
)
367 self
.otherlanguages
= {}
369 self
.quotes
= ('``', "''")
370 # language dependent configuration:
371 # double quotes are "active" in some languages (e.g. German).
372 self
.literal_double_quote
= u
'"'
373 if self
.language
in ('ngerman', 'german', 'austrian', 'naustrian',
375 self
.quotes
= (r
'\glqq{}', r
'\grqq{}')
376 self
.literal_double_quote
= ur
'\dq{}'
377 if self
.language
== 'french':
378 self
.quotes
= (r
'\og{}', r
'\fg{}')
379 if self
.language
== 'italian':
380 self
.literal_double_quote
= ur
'{\char`\"}'
383 """Return the babel call with correct options and settings"""
384 languages
= sorted(self
.otherlanguages
.keys())
385 languages
.append(self
.language
or 'english')
386 self
.setup
= [r
'\usepackage[%s]{babel}' % ','.join(languages
)]
387 if 'spanish' in languages
:
388 # reset active chars to the original meaning:
390 r
'\addto\shorthandsspanish{\spanishdeactivate{."~<>}}')
391 # or prepend r'\def\spanishoptions{es-noshorthands}'
392 if (languages
[-1] == 'english' and
393 'french' in self
.otherlanguages
.keys()):
394 self
.setup
+= ['% Prevent side-effects if French hyphenation '
395 'patterns are not loaded:',
396 r
'\frenchbsetup{StandardLayout}',
397 r
'\AtBeginDocument{\selectlanguage{%s}'
398 r
'\noextrasfrench}' % self
.language
]
399 return '\n'.join(self
.setup
)
401 def next_quote(self
):
402 q
= self
.quotes
[self
.quote_index
]
403 self
.quote_index
= (self
.quote_index
+1) % 2
406 def quote_quotes(self
,text
):
408 for part
in text
.split('"'):
412 t
+= self
.next_quote() + part
415 def language_name(self
, language_code
):
416 """Return TeX language name for `language_code`"""
417 for tag
in utils
.normalize_language_tag(language_code
):
419 return self
.language_codes
[tag
]
422 if self
.reporter
is not None:
423 self
.reporter
.warning(self
.warn_msg
% language_code
)
426 def get_language(self
):
427 """Return `self.language` (for backwards compatibility with Sphinx).
432 # Building blocks for the latex preamble
433 # --------------------------------------
435 class SortableDict(dict):
436 """Dictionary with additional sorting methods
438 Tip: use key starting with with '_' for sorting before small letters
439 and with '~' for sorting after small letters.
441 def sortedkeys(self
):
442 """Return sorted list of keys"""
447 def sortedvalues(self
):
448 """Return list of values sorted by keys"""
449 return [self
[key
] for key
in self
.sortedkeys()]
454 # A container for LaTeX code snippets that can be
455 # inserted into the preamble if required in the document.
457 # .. The package 'makecmds' would enable shorter definitions using the
458 # \providelength and \provideenvironment commands.
459 # However, it is pretty non-standard (texlive-latex-extra).
461 class PreambleCmds(object):
462 """Building blocks for the latex preamble."""
464 PreambleCmds
.abstract
= r
"""
466 \providecommand*{\DUtitleabstract}[1]{\centerline{\textbf{#1}}}"""
468 PreambleCmds
.admonition
= r
"""
469 % admonition (specially marked topic)
470 \providecommand{\DUadmonition}[2][class-arg]{%
471 % try \DUadmonition#1{#2}:
472 \ifcsname DUadmonition#1\endcsname%
473 \csname DUadmonition#1\endcsname{#2}%
476 \fbox{\parbox{0.9\textwidth}{#2}}
481 PreambleCmds
.align_center
= r
"""
483 \@namedef{DUrolealign-center}{\centering}
487 ## PreambleCmds.caption = r"""% configure caption layout
488 ## \usepackage{caption}
489 ## \captionsetup{singlelinecheck=false}% no exceptions for one-liners"""
491 PreambleCmds
.color
= r
"""\usepackage{color}"""
493 PreambleCmds
.docinfo
= r
"""
494 % docinfo (width of docinfo table)
495 \DUprovidelength{\DUdocinfowidth}{0.9\textwidth}"""
496 # PreambleCmds.docinfo._depends = 'providelength'
498 PreambleCmds
.dedication
= r
"""
500 \providecommand{\DUtopicdedication}[1]{\begin{center}#1\end{center}}"""
502 PreambleCmds
.error
= r
"""
503 % error admonition title
504 \providecommand*{\DUtitleerror}[1]{\DUtitle{\color{red}#1}}"""
505 # PreambleCmds.errortitle._depends = 'color'
507 PreambleCmds
.fieldlist
= r
"""
508 % fieldlist environment
509 \ifthenelse{\isundefined{\DUfieldlist}}{
510 \newenvironment{DUfieldlist}%
512 {\enddescription\endquote}
515 PreambleCmds
.float_settings
= r
"""\usepackage{float} % float configuration
516 \floatplacement{figure}{H} % place figures here definitely"""
518 PreambleCmds
.footnotes
= r
"""% numeric or symbol footnotes with hyperlinks
519 \providecommand*{\DUfootnotemark}[3]{%
520 \raisebox{1em}{\hypertarget{#1}{}}%
521 \hyperlink{#2}{\textsuperscript{#3}}%
523 \providecommand{\DUfootnotetext}[4]{%
525 \renewcommand{\thefootnote}{%
526 \protect\raisebox{1em}{\protect\hypertarget{#1}{}}%
527 \protect\hyperlink{#2}{#3}}%
532 PreambleCmds
.footnote_floats
= r
"""% settings for footnotes as floats:
533 \setlength{\floatsep}{0.5em}
534 \setlength{\textfloatsep}{\fill}
535 \addtolength{\textfloatsep}{3em}
536 \renewcommand{\textfraction}{0.5}
537 \renewcommand{\topfraction}{0.5}
538 \renewcommand{\bottomfraction}{0.5}
539 \setcounter{totalnumber}{50}
540 \setcounter{topnumber}{50}
541 \setcounter{bottomnumber}{50}"""
543 PreambleCmds
.graphicx_auto
= r
"""% Check output format
544 \ifx\pdftexversion\undefined
545 \usepackage{graphicx}
547 \usepackage[pdftex]{graphicx}
550 PreambleCmds
.highlight_rules
= r
"""% basic code highlight:
551 \providecommand*\DUrolecomment[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
552 \providecommand*\DUroledeleted[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
553 \providecommand*\DUrolekeyword[1]{\textbf{#1}}
554 \providecommand*\DUrolestring[1]{\textit{#1}}"""
556 PreambleCmds
.inline
= r
"""
557 % inline markup (custom roles)
558 % \DUrole{#1}{#2} tries \DUrole#1{#2}
559 \providecommand*{\DUrole}[2]{%
560 \ifcsname DUrole#1\endcsname%
561 \csname DUrole#1\endcsname{#2}%
562 \else% backwards compatibility: try \docutilsrole#1{#2}
563 \ifcsname docutilsrole#1\endcsname%
564 \csname docutilsrole#1\endcsname{#2}%
571 PreambleCmds
.legend
= r
"""
573 \ifthenelse{\isundefined{\DUlegend}}{
574 \newenvironment{DUlegend}{\small}{}
577 PreambleCmds
.lineblock
= r
"""
578 % lineblock environment
579 \DUprovidelength{\DUlineblockindent}{2.5em}
580 \ifthenelse{\isundefined{\DUlineblock}}{
581 \newenvironment{DUlineblock}[1]{%
582 \list{}{\setlength{\partopsep}{\parskip}
583 \addtolength{\partopsep}{\baselineskip}
584 \setlength{\topsep}{0pt}
585 \setlength{\itemsep}{0.15\baselineskip}
586 \setlength{\parsep}{0pt}
587 \setlength{\leftmargin}{#1}}
592 # PreambleCmds.lineblock._depends = 'providelength'
594 PreambleCmds
.linking
= r
"""
596 \ifthenelse{\isundefined{\hypersetup}}{
597 \usepackage[%s]{hyperref}
598 \urlstyle{same} %% normal text font (alternatives: tt, rm, sf)
601 PreambleCmds
.minitoc
= r
"""%% local table of contents
602 \usepackage{minitoc}"""
604 PreambleCmds
.optionlist
= r
"""
605 % optionlist environment
606 \providecommand*{\DUoptionlistlabel}[1]{\bf #1 \hfill}
607 \DUprovidelength{\DUoptionlistindent}{3cm}
608 \ifthenelse{\isundefined{\DUoptionlist}}{
609 \newenvironment{DUoptionlist}{%
610 \list{}{\setlength{\labelwidth}{\DUoptionlistindent}
611 \setlength{\rightmargin}{1cm}
612 \setlength{\leftmargin}{\rightmargin}
613 \addtolength{\leftmargin}{\labelwidth}
614 \addtolength{\leftmargin}{\labelsep}
615 \renewcommand{\makelabel}{\DUoptionlistlabel}}
619 # PreambleCmds.optionlist._depends = 'providelength'
621 PreambleCmds
.providelength
= r
"""
622 % providelength (provide a length variable and set default, if it is new)
623 \providecommand*{\DUprovidelength}[2]{
624 \ifthenelse{\isundefined{#1}}{\newlength{#1}\setlength{#1}{#2}}{}
627 PreambleCmds
.rubric
= r
"""
628 % rubric (informal heading)
629 \providecommand*{\DUrubric}[2][class-arg]{%
630 \subsubsection*{\centering\textit{\textmd{#2}}}}"""
632 PreambleCmds
.sidebar
= r
"""
633 % sidebar (text outside the main text flow)
634 \providecommand{\DUsidebar}[2][class-arg]{%
636 \colorbox[gray]{0.80}{\parbox{0.9\textwidth}{#2}}
640 PreambleCmds
.subtitle
= r
"""
641 % subtitle (for topic/sidebar)
642 \providecommand*{\DUsubtitle}[2][class-arg]{\par\emph{#2}\smallskip}"""
644 PreambleCmds
.table
= r
"""\usepackage{longtable,ltcaption,array}
645 \setlength{\extrarowheight}{2pt}
646 \newlength{\DUtablewidth} % internal use in tables"""
648 # Options [force,almostfull] prevent spurious error messages, see
649 # de.comp.text.tex/2005-12/msg01855
650 PreambleCmds
.textcomp
= """\
651 \\usepackage{textcomp} % text symbol macros"""
653 PreambleCmds
.titlereference
= r
"""
654 % titlereference role
655 \providecommand*{\DUroletitlereference}[1]{\textsl{#1}}"""
657 PreambleCmds
.title
= r
"""
658 % title for topics, admonitions, unsupported section levels, and sidebar
659 \providecommand*{\DUtitle}[2][class-arg]{%
660 % call \DUtitle#1{#2} if it exists:
661 \ifcsname DUtitle#1\endcsname%
662 \csname DUtitle#1\endcsname{#2}%
664 \smallskip\noindent\textbf{#2}\smallskip%
668 PreambleCmds
.topic
= r
"""
669 % topic (quote with heading)
670 \providecommand{\DUtopic}[2][class-arg]{%
671 \ifcsname DUtopic#1\endcsname%
672 \csname DUtopic#1\endcsname{#2}%
674 \begin{quote}#2\end{quote}
678 PreambleCmds
.transition
= r
"""
679 % transition (break, fancybreak, anonymous section)
680 \providecommand*{\DUtransition}[1][class-arg]{%
681 \hspace*{\fill}\hrulefill\hspace*{\fill}
682 \vskip 0.5\baselineskip
686 # LaTeX encoding maps
687 # -------------------
690 class CharMaps(object):
691 """LaTeX representations for active and Unicode characters."""
693 # characters that always need escaping:
699 ord('~'): ur
'\textasciitilde{}',
701 ord('^'): ur
'\textasciicircum{}',
702 ord('\\'): ur
'\textbackslash{}',
705 # Square brackets are ordinary chars and cannot be escaped with '\',
706 # so we put them in a group '{[}'. (Alternative: ensure that all
707 # macros with optional arguments are terminated with {} and text
708 # inside any optional argument is put in a group ``[{text}]``).
709 # Commands with optional args inside an optional arg must be put in a
710 # group, e.g. ``\item[{\hyperref[label]{text}}]``.
713 # the soft hyphen is unknown in 8-bit text and not properly handled by XeTeX
714 0x00AD: ur
'\-', # SOFT HYPHEN
716 # Unicode chars that are not recognized by LaTeX's utf8 encoding
717 unsupported_unicode
= {
718 0x00A0: ur
'~', # NO-BREAK SPACE
719 # TODO: ensure white space also at the beginning of a line?
720 # 0x00A0: ur'\leavevmode\nobreak\vadjust{}~'
721 0x2008: ur
'\,', # PUNCTUATION SPACE
722 0x2011: ur
'\hbox{-}', # NON-BREAKING HYPHEN
723 0x202F: ur
'\,', # NARROW NO-BREAK SPACE
724 0x21d4: ur
'$\Leftrightarrow$',
725 # Docutils footnote symbols:
726 0x2660: ur
'$\spadesuit$',
727 0x2663: ur
'$\clubsuit$',
729 # Unicode chars that are recognized by LaTeX's utf8 encoding
730 utf8_supported_unicode
= {
731 0x00AB: ur
'\guillemotleft', # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
732 0x00bb: ur
'\guillemotright', # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
733 0x200C: ur
'\textcompwordmark', # ZERO WIDTH NON-JOINER
734 0x2013: ur
'\textendash{}',
735 0x2014: ur
'\textemdash{}',
736 0x2018: ur
'\textquoteleft{}',
737 0x2019: ur
'\textquoteright{}',
738 0x201A: ur
'\quotesinglbase{}', # SINGLE LOW-9 QUOTATION MARK
739 0x201C: ur
'\textquotedblleft{}',
740 0x201D: ur
'\textquotedblright{}',
741 0x201E: ur
'\quotedblbase{}', # DOUBLE LOW-9 QUOTATION MARK
742 0x2030: ur
'\textperthousand{}', # PER MILLE SIGN
743 0x2031: ur
'\textpertenthousand{}', # PER TEN THOUSAND SIGN
744 0x2039: ur
'\guilsinglleft{}',
745 0x203A: ur
'\guilsinglright{}',
746 0x2423: ur
'\textvisiblespace{}', # OPEN BOX
750 0x2122: ur
'\texttrademark{}',
752 # recognized with 'utf8', if textcomp is loaded
755 0x00a2: ur
'\textcent{}', # ¢ CENT SIGN
756 0x00a4: ur
'\textcurrency{}', # ¤ CURRENCY SYMBOL
757 0x00a5: ur
'\textyen{}', # ¥ YEN SIGN
758 0x00a6: ur
'\textbrokenbar{}', # ¦ BROKEN BAR
759 0x00a7: ur
'\textsection{}', # § SECTION SIGN
760 0x00a8: ur
'\textasciidieresis{}', # ¨ DIAERESIS
761 0x00a9: ur
'\textcopyright{}', # © COPYRIGHT SIGN
762 0x00aa: ur
'\textordfeminine{}', # ª FEMININE ORDINAL INDICATOR
763 0x00ac: ur
'\textlnot{}', # ¬ NOT SIGN
764 0x00ae: ur
'\textregistered{}', # ® REGISTERED SIGN
765 0x00af: ur
'\textasciimacron{}', # ¯ MACRON
766 0x00b0: ur
'\textdegree{}', # ° DEGREE SIGN
767 0x00b1: ur
'\textpm{}', # ± PLUS-MINUS SIGN
768 0x00b2: ur
'\texttwosuperior{}', # ² SUPERSCRIPT TWO
769 0x00b3: ur
'\textthreesuperior{}', # ³ SUPERSCRIPT THREE
770 0x00b4: ur
'\textasciiacute{}', # ´ ACUTE ACCENT
771 0x00b5: ur
'\textmu{}', # µ MICRO SIGN
772 0x00b6: ur
'\textparagraph{}', # ¶ PILCROW SIGN # not equal to \textpilcrow
773 0x00b9: ur
'\textonesuperior{}', # ¹ SUPERSCRIPT ONE
774 0x00ba: ur
'\textordmasculine{}', # º MASCULINE ORDINAL INDICATOR
775 0x00bc: ur
'\textonequarter{}', # 1/4 FRACTION
776 0x00bd: ur
'\textonehalf{}', # 1/2 FRACTION
777 0x00be: ur
'\textthreequarters{}', # 3/4 FRACTION
778 0x00d7: ur
'\texttimes{}', # × MULTIPLICATION SIGN
779 0x00f7: ur
'\textdiv{}', # ÷ DIVISION SIGN
781 0x0192: ur
'\textflorin{}', # LATIN SMALL LETTER F WITH HOOK
782 0x02b9: ur
'\textasciiacute{}', # MODIFIER LETTER PRIME
783 0x02ba: ur
'\textacutedbl{}', # MODIFIER LETTER DOUBLE PRIME
784 0x2016: ur
'\textbardbl{}', # DOUBLE VERTICAL LINE
785 0x2022: ur
'\textbullet{}', # BULLET
786 0x2032: ur
'\textasciiacute{}', # PRIME
787 0x2033: ur
'\textacutedbl{}', # DOUBLE PRIME
788 0x2035: ur
'\textasciigrave{}', # REVERSED PRIME
789 0x2036: ur
'\textgravedbl{}', # REVERSED DOUBLE PRIME
790 0x203b: ur
'\textreferencemark{}', # REFERENCE MARK
791 0x203d: ur
'\textinterrobang{}', # INTERROBANG
792 0x2044: ur
'\textfractionsolidus{}', # FRACTION SLASH
793 0x2045: ur
'\textlquill{}', # LEFT SQUARE BRACKET WITH QUILL
794 0x2046: ur
'\textrquill{}', # RIGHT SQUARE BRACKET WITH QUILL
795 0x2052: ur
'\textdiscount{}', # COMMERCIAL MINUS SIGN
796 0x20a1: ur
'\textcolonmonetary{}', # COLON SIGN
797 0x20a3: ur
'\textfrenchfranc{}', # FRENCH FRANC SIGN
798 0x20a4: ur
'\textlira{}', # LIRA SIGN
799 0x20a6: ur
'\textnaira{}', # NAIRA SIGN
800 0x20a9: ur
'\textwon{}', # WON SIGN
801 0x20ab: ur
'\textdong{}', # DONG SIGN
802 0x20ac: ur
'\texteuro{}', # EURO SIGN
803 0x20b1: ur
'\textpeso{}', # PESO SIGN
804 0x20b2: ur
'\textguarani{}', # GUARANI SIGN
805 0x2103: ur
'\textcelsius{}', # DEGREE CELSIUS
806 0x2116: ur
'\textnumero{}', # NUMERO SIGN
807 0x2117: ur
'\textcircledP{}', # SOUND RECORDING COYRIGHT
808 0x211e: ur
'\textrecipe{}', # PRESCRIPTION TAKE
809 0x2120: ur
'\textservicemark{}', # SERVICE MARK
810 0x2122: ur
'\texttrademark{}', # TRADE MARK SIGN
811 0x2126: ur
'\textohm{}', # OHM SIGN
812 0x2127: ur
'\textmho{}', # INVERTED OHM SIGN
813 0x212e: ur
'\textestimated{}', # ESTIMATED SYMBOL
814 0x2190: ur
'\textleftarrow{}', # LEFTWARDS ARROW
815 0x2191: ur
'\textuparrow{}', # UPWARDS ARROW
816 0x2192: ur
'\textrightarrow{}', # RIGHTWARDS ARROW
817 0x2193: ur
'\textdownarrow{}', # DOWNWARDS ARROW
818 0x2212: ur
'\textminus{}', # MINUS SIGN
819 0x2217: ur
'\textasteriskcentered{}', # ASTERISK OPERATOR
820 0x221a: ur
'\textsurd{}', # SQUARE ROOT
821 0x2422: ur
'\textblank{}', # BLANK SYMBOL
822 0x25e6: ur
'\textopenbullet{}', # WHITE BULLET
823 0x25ef: ur
'\textbigcircle{}', # LARGE CIRCLE
824 0x266a: ur
'\textmusicalnote{}', # EIGHTH NOTE
825 0x26ad: ur
'\textmarried{}', # MARRIAGE SYMBOL
826 0x26ae: ur
'\textdivorced{}', # DIVORCE SYMBOL
827 0x27e8: ur
'\textlangle{}', # MATHEMATICAL LEFT ANGLE BRACKET
828 0x27e9: ur
'\textrangle{}', # MATHEMATICAL RIGHT ANGLE BRACKET
830 # Unicode chars that require a feature/package to render
832 0x2665: ur
'\ding{170}', # black heartsuit
833 0x2666: ur
'\ding{169}', # black diamondsuit
834 0x2713: ur
'\ding{51}', # check mark
835 0x2717: ur
'\ding{55}', # check mark
837 # TODO: greek alphabet ... ?
838 # see also LaTeX codec
839 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252124
840 # and unimap.py from TeXML
843 class DocumentClass(object):
844 """Details of a LaTeX document class."""
846 def __init__(self
, document_class
, with_part
=False):
847 self
.document_class
= document_class
848 self
._with
_part
= with_part
849 self
.sections
= ['section', 'subsection', 'subsubsection',
850 'paragraph', 'subparagraph']
851 if self
.document_class
in ('book', 'memoir', 'report',
852 'scrbook', 'scrreprt'):
853 self
.sections
.insert(0, 'chapter')
855 self
.sections
.insert(0, 'part')
857 def section(self
, level
):
858 """Return the LaTeX section name for section `level`.
860 The name depends on the specific document class.
861 Level is 1,2,3..., as level 0 is the title.
863 if level
<= len(self
.sections
):
864 return self
.sections
[level
-1]
865 else: # unsupported levels
866 return 'DUtitle[section%s]' % roman
.toRoman(level
)
869 """Manage a table while traversing.
871 Maybe change to a mixin defining the visit/departs, but then
872 class Table internal variables are in the Translator.
876 :standard: horizontal and vertical lines
877 :booktabs: only horizontal lines (requires "booktabs" LaTeX package)
878 :borderless: no borders around table cells
879 :nolines: alias for borderless
881 def __init__(self
,translator
,latex_type
,table_style
):
882 self
._translator
= translator
883 self
._latex
_type
= latex_type
884 self
._table
_style
= table_style
886 # miscellaneous attributes
898 self
._in
_head
= False # maybe context with search
901 self
._col
_specs
= None
908 def set_table_style(self
, table_style
):
909 if not table_style
in ('standard','booktabs','borderless','nolines'):
911 self
._table
_style
= table_style
913 def get_latex_type(self
):
914 if self
._latex
_type
== 'longtable' and not self
.caption
:
915 # do not advance the "table" counter (requires "ltcaption" package)
917 return self
._latex
_type
919 def set(self
,attr
,value
):
920 self
._attrs
[attr
] = value
922 if attr
in self
._attrs
:
923 return self
._attrs
[attr
]
926 def get_vertical_bar(self
):
927 if self
._table
_style
== 'standard':
931 # horizontal lines are drawn below a row,
932 def get_opening(self
):
933 return '\n'.join([r
'\setlength{\DUtablewidth}{\linewidth}',
934 r
'\begin{%s}[c]' % self
.get_latex_type()])
936 def get_closing(self
):
938 if self
._table
_style
== 'booktabs':
939 closing
.append(r
'\bottomrule')
940 # elif self._table_style == 'standard':
941 # closing.append(r'\hline')
942 closing
.append(r
'\end{%s}' % self
.get_latex_type())
943 return '\n'.join(closing
)
945 def visit_colspec(self
, node
):
946 self
._col
_specs
.append(node
)
947 # "stubs" list is an attribute of the tgroup element:
948 self
.stubs
.append(node
.attributes
.get('stub'))
950 def get_colspecs(self
):
951 """Return column specification for longtable.
953 Assumes reST line length being 80 characters.
954 Table width is hairy.
960 usually gets to narrow, therefore we add 1 (fiddlefactor).
965 # first see if we get too wide.
966 for node
in self
._col
_specs
:
967 colwidth
= float(node
['colwidth']+1) / width
968 total_width
+= colwidth
971 # donot make it full linewidth
973 if total_width
> 1.0:
974 factor
/= total_width
975 bar
= self
.get_vertical_bar()
976 latex_table_spec
= ''
977 for node
in self
._col
_specs
:
978 colwidth
= factor
* float(node
['colwidth']+1) / width
979 self
._col
_width
.append(colwidth
+0.005)
980 self
._rowspan
.append(0)
981 latex_table_spec
+= '%sp{%.3f\\DUtablewidth}' % (bar
, colwidth
+0.005)
982 return latex_table_spec
+bar
984 def get_column_width(self
):
985 """Return columnwidth for current cell (not multicell)."""
986 return '%.2f\\DUtablewidth' % self
._col
_width
[self
._cell
_in
_row
-1]
988 def get_multicolumn_width(self
, start
, len_
):
989 """Return sum of columnwidths for multicell."""
990 mc_width
= sum([width
991 for width
in ([self
._col
_width
[start
+ co
- 1]
992 for co
in range (len_
)])])
993 return '%.2f\\DUtablewidth' % mc_width
995 def get_caption(self
):
998 caption
= ''.join(self
.caption
)
999 if 1 == self
._translator
.thead_depth():
1000 return r
'\caption{%s}\\' '\n' % caption
1001 return r
'\caption[]{%s (... continued)}\\' '\n' % caption
1003 def need_recurse(self
):
1004 if self
._latex
_type
== 'longtable':
1005 return 1 == self
._translator
.thead_depth()
1008 def visit_thead(self
):
1010 if self
._table
_style
== 'standard':
1011 return ['\\hline\n']
1012 elif self
._table
_style
== 'booktabs':
1013 return ['\\toprule\n']
1016 def depart_thead(self
):
1018 #if self._table_style == 'standard':
1019 # a.append('\\hline\n')
1020 if self
._table
_style
== 'booktabs':
1021 a
.append('\\midrule\n')
1022 if self
._latex
_type
== 'longtable':
1023 if 1 == self
._translator
.thead_depth():
1024 a
.append('\\endfirsthead\n')
1026 a
.append('\\endhead\n')
1027 a
.append(r
'\multicolumn{%d}{c}' % len(self
._col
_specs
) +
1028 r
'{\hfill ... continued on next page} \\')
1029 a
.append('\n\\endfoot\n\\endlastfoot\n')
1030 # for longtable one could add firsthead, foot and lastfoot
1033 def visit_row(self
):
1034 self
._cell
_in
_row
= 0
1035 def depart_row(self
):
1037 self
._cell
_in
_row
= None # remove cell counter
1038 for i
in range(len(self
._rowspan
)):
1039 if (self
._rowspan
[i
]>0):
1040 self
._rowspan
[i
] -= 1
1042 if self
._table
_style
== 'standard':
1043 rowspans
= [i
+1 for i
in range(len(self
._rowspan
))
1044 if (self
._rowspan
[i
]<=0)]
1045 if len(rowspans
)==len(self
._rowspan
):
1046 res
.append('\\hline\n')
1053 c_start
= rowspans
.pop()
1056 cline
+= '\\cline{%d-%d}\n' % (c_start
,c_start
)
1060 def set_rowspan(self
,cell
,value
):
1062 self
._rowspan
[cell
] = value
1065 def get_rowspan(self
,cell
):
1067 return self
._rowspan
[cell
]
1070 def get_entry_number(self
):
1071 return self
._cell
_in
_row
1072 def visit_entry(self
):
1073 self
._cell
_in
_row
+= 1
1074 def is_stub_column(self
):
1075 if len(self
.stubs
) >= self
._cell
_in
_row
:
1076 return self
.stubs
[self
._cell
_in
_row
-1]
1080 class LaTeXTranslator(nodes
.NodeVisitor
):
1082 # When options are given to the documentclass, latex will pass them
1083 # to other packages, as done with babel.
1084 # Dummy settings might be taken from document settings
1086 # Write code for typesetting with 8-bit tex/pdftex (vs. xetex/luatex) engine
1087 # overwritten by the XeTeX writer
1090 # Config setting defaults
1091 # -----------------------
1093 # TODO: use mixins for different implementations.
1094 # list environment for docinfo. else tabularx
1095 ## use_optionlist_for_docinfo = False # TODO: NOT YET IN USE
1097 # Use compound enumerations (1.A.1.)
1098 compound_enumerators
= False
1100 # If using compound enumerations, include section information.
1101 section_prefix_for_enumerators
= False
1103 # This is the character that separates the section ("." subsection ...)
1104 # prefix from the regular list enumerator.
1105 section_enumerator_separator
= '-'
1107 # Auxiliary variables
1108 # -------------------
1110 has_latex_toc
= False # is there a toc in the doc? (needed by minitoc)
1111 is_toc_list
= False # is the current bullet_list a ToC?
1114 # Flags to encode():
1115 # inside citation reference labels underscores dont need to be escaped
1116 inside_citation_reference_label
= False
1117 verbatim
= False # do not encode
1118 insert_non_breaking_blanks
= False # replace blanks by "~"
1119 insert_newline
= False # add latex newline commands
1120 literal
= False # literal text (block or inline)
1123 def __init__(self
, document
, babel_class
=Babel
):
1124 nodes
.NodeVisitor
.__init
__(self
, document
)
1127 self
.warn
= self
.document
.reporter
.warning
1128 self
.error
= self
.document
.reporter
.error
1132 self
.settings
= settings
= document
.settings
1133 self
.latex_encoding
= self
.to_latex_encoding(settings
.output_encoding
)
1134 self
.use_latex_toc
= settings
.use_latex_toc
1135 self
.use_latex_docinfo
= settings
.use_latex_docinfo
1136 self
._use
_latex
_citations
= settings
.use_latex_citations
1137 self
._reference
_label
= settings
.reference_label
1138 self
.hyperlink_color
= settings
.hyperlink_color
1139 self
.compound_enumerators
= settings
.compound_enumerators
1140 self
.font_encoding
= getattr(settings
, 'font_encoding', '')
1141 self
.section_prefix_for_enumerators
= (
1142 settings
.section_prefix_for_enumerators
)
1143 self
.section_enumerator_separator
= (
1144 settings
.section_enumerator_separator
.replace('_', r
'\_'))
1146 self
.literal_block_env
= ''
1147 self
.literal_block_options
= ''
1148 if settings
.literal_block_env
!= '':
1150 self
.literal_block_env
,
1151 self
.literal_block_options
,
1152 none
) = re
.split('(\w+)(.*)', settings
.literal_block_env
)
1153 elif settings
.use_verbatim_when_possible
:
1154 self
.literal_block_env
= 'verbatim'
1156 if self
.settings
.use_bibtex
:
1157 self
.bibtex
= self
.settings
.use_bibtex
.split(',',1)
1158 # TODO avoid errors on not declared citations.
1161 # language module for Docutils-generated text
1162 # (labels, bibliographic_fields, and author_separators)
1163 self
.language_module
= languages
.get_language(settings
.language_code
,
1165 self
.babel
= babel_class(settings
.language_code
, document
.reporter
)
1166 self
.author_separator
= self
.language_module
.author_separators
[0]
1167 d_options
= [self
.settings
.documentoptions
]
1168 if self
.babel
.language
not in ('english', ''):
1169 d_options
.append(self
.babel
.language
)
1170 self
.documentoptions
= ','.join(filter(None, d_options
))
1171 self
.d_class
= DocumentClass(settings
.documentclass
,
1172 settings
.use_part_section
)
1173 # graphic package options:
1174 if self
.settings
.graphicx_option
== '':
1175 self
.graphicx_package
= r
'\usepackage{graphicx}'
1176 elif self
.settings
.graphicx_option
.lower() == 'auto':
1177 self
.graphicx_package
= PreambleCmds
.graphicx_auto
1179 self
.graphicx_package
= (r
'\usepackage[%s]{graphicx}' %
1180 self
.settings
.graphicx_option
)
1182 self
.docutils_footnotes
= settings
.docutils_footnotes
1183 if settings
.use_latex_footnotes
:
1184 self
.docutils_footnotes
= True
1185 self
.warn('`use_latex_footnotes` is deprecated. '
1186 'The setting has been renamed to `docutils_footnotes` '
1187 'and the alias will be removed in a future version.')
1188 self
.figure_footnotes
= settings
.figure_footnotes
1189 if self
.figure_footnotes
:
1190 self
.docutils_footnotes
= True
1191 self
.warn('The "figure footnotes" workaround/setting is strongly '
1192 'deprecated and will be removed in a future version.')
1194 # Output collection stacks
1195 # ~~~~~~~~~~~~~~~~~~~~~~~~
1198 self
.head_prefix
= [r
'\documentclass[%s]{%s}' %
1199 (self
.documentoptions
, self
.settings
.documentclass
)]
1200 self
.requirements
= SortableDict() # made a list in depart_document()
1201 self
.requirements
['__static'] = r
'\usepackage{ifthen}'
1202 self
.latex_preamble
= [settings
.latex_preamble
]
1203 self
.fallbacks
= SortableDict() # made a list in depart_document()
1204 self
.pdfsetup
= [] # PDF properties (hyperref package)
1207 self
.titledata
= [] # \title, \author, \date
1208 ## self.body_prefix = ['\\begin{document}\n']
1209 self
.body_pre_docinfo
= [] # \maketitle
1211 self
.dedication
= []
1214 ## self.body_suffix = ['\\end{document}\n']
1216 # A heterogenous stack used in conjunction with the tree traversal.
1217 # Make sure that the pops correspond to the pushes:
1221 self
.title_labels
= []
1222 self
.subtitle_labels
= []
1223 # (if use_latex_docinfo: collects lists of
1224 # author/organization/contact/address lines)
1225 self
.author_stack
= []
1228 # PDF properties: pdftitle, pdfauthor
1229 # TODO?: pdfcreator, pdfproducer, pdfsubject, pdfkeywords
1233 # Stack of section counters so that we don't have to use_latex_toc.
1234 # This will grow and shrink as processing occurs.
1235 # Initialized for potential first-level sections.
1236 self
._section
_number
= [0]
1238 # The current stack of enumerations so that we can expand
1239 # them into a compound enumeration.
1240 self
._enumeration
_counters
= []
1241 # The maximum number of enumeration counters we've used.
1242 # If we go beyond this number, we need to create a new
1243 # counter; otherwise, just reuse an old one.
1244 self
._max
_enumeration
_counters
= 0
1248 # object for a table while proccessing.
1249 self
.table_stack
= []
1250 self
.active_table
= Table(self
, 'longtable', settings
.table_style
)
1252 # Where to collect the output of visitor methods (default: body)
1253 self
.out
= self
.body
1254 self
.out_stack
= [] # stack of output collectors
1259 # Docutils' output-encoding => TeX input encoding
1260 if self
.latex_encoding
!= 'ascii':
1261 self
.requirements
['_inputenc'] = (r
'\usepackage[%s]{inputenc}'
1262 % self
.latex_encoding
)
1264 if self
.font_encoding
and not self
.is_xetex
:
1265 self
.requirements
['_fontenc'] = (r
'\usepackage[%s]{fontenc}' %
1267 # page layout with typearea (if there are relevant document options)
1268 if (settings
.documentclass
.find('scr') == -1 and
1269 (self
.documentoptions
.find('DIV') != -1 or
1270 self
.documentoptions
.find('BCOR') != -1)):
1271 self
.requirements
['typearea'] = r
'\usepackage{typearea}'
1274 # (the name `self.stylesheet` is singular because only one
1275 # stylesheet was supported before Docutils 0.6).
1276 self
.stylesheet
= [self
.stylesheet_call(path
)
1277 for path
in utils
.get_stylesheet_list(settings
)]
1280 if self
.hyperlink_color
in ('0', 'false', 'False', ''):
1281 self
.hyperref_options
= ''
1283 self
.hyperref_options
= 'colorlinks=true,linkcolor=%s,urlcolor=%s' % (
1284 self
.hyperlink_color
, self
.hyperlink_color
)
1285 if settings
.hyperref_options
:
1286 self
.hyperref_options
+= ',' + settings
.hyperref_options
1289 # include all supported sections in toc and PDF bookmarks
1290 # (or use documentclass-default (as currently))?
1291 ## if self.use_latex_toc:
1292 ## self.requirements['tocdepth'] = (r'\setcounter{tocdepth}{%d}' %
1293 ## len(self.d_class.sections))
1296 if settings
.sectnum_xform
: # section numbering by Docutils
1297 PreambleCmds
.secnumdepth
= r
'\setcounter{secnumdepth}{0}'
1298 else: # section numbering by LaTeX:
1299 secnumdepth
= settings
.sectnum_depth
1300 # Possible values of settings.sectnum_depth:
1301 # None "sectnum" directive without depth arg -> LaTeX default
1302 # 0 no "sectnum" directive -> no section numbers
1303 # >0 value of "depth" argument -> translate to LaTeX levels:
1304 # -1 part (0 with "article" document class)
1305 # 0 chapter (missing in "article" document class)
1311 if secnumdepth
is not None:
1312 # limit to supported levels
1313 secnumdepth
= min(secnumdepth
, len(self
.d_class
.sections
))
1314 # adjust to document class and use_part_section settings
1315 if 'chapter' in self
.d_class
.sections
:
1317 if self
.d_class
.sections
[0] == 'part':
1319 PreambleCmds
.secnumdepth
= \
1320 r
'\setcounter{secnumdepth}{%d}' % secnumdepth
1322 # start with specified number:
1323 if (hasattr(settings
, 'sectnum_start') and
1324 settings
.sectnum_start
!= 1):
1325 self
.requirements
['sectnum_start'] = (
1326 r
'\setcounter{%s}{%d}' % (self
.d_class
.sections
[0],
1327 settings
.sectnum_start
-1))
1328 # TODO: currently ignored (configure in a stylesheet):
1329 ## settings.sectnum_prefix
1330 ## settings.sectnum_suffix
1335 def stylesheet_call(self
, path
):
1336 """Return code to reference or embed stylesheet file `path`"""
1337 # is it a package (no extension or *.sty) or "normal" tex code:
1338 (base
, ext
) = os
.path
.splitext(path
)
1339 is_package
= ext
in ['.sty', '']
1340 # Embed content of style file:
1341 if self
.settings
.embed_stylesheet
:
1343 path
= base
+ '.sty' # ensure extension
1345 content
= io
.FileInput(source_path
=path
,
1346 encoding
='utf-8').read()
1347 self
.settings
.record_dependencies
.add(path
)
1348 except IOError, err
:
1349 msg
= u
"Cannot embed stylesheet '%s':\n %s." % (
1350 path
, SafeString(err
.strerror
))
1351 self
.document
.reporter
.error(msg
)
1352 return '% ' + msg
.replace('\n', '\n% ')
1354 content
= '\n'.join([r
'\makeatletter',
1357 return '%% embedded stylesheet: %s\n%s' % (path
, content
)
1358 # Link to style file:
1360 path
= base
# drop extension
1361 cmd
= r
'\usepackage{%s}'
1364 if self
.settings
.stylesheet_path
:
1365 # adapt path relative to output (cf. config.html#stylesheet-path)
1366 path
= utils
.relative_path(self
.settings
._destination
, path
)
1369 def to_latex_encoding(self
,docutils_encoding
):
1370 """Translate docutils encoding name into LaTeX's.
1372 Default method is remove "-" and "_" chars from docutils_encoding.
1374 tr
= { 'iso-8859-1': 'latin1', # west european
1375 'iso-8859-2': 'latin2', # east european
1376 'iso-8859-3': 'latin3', # esperanto, maltese
1377 'iso-8859-4': 'latin4', # north european, scandinavian, baltic
1378 'iso-8859-5': 'iso88595', # cyrillic (ISO)
1379 'iso-8859-9': 'latin5', # turkish
1380 'iso-8859-15': 'latin9', # latin9, update to latin1.
1381 'mac_cyrillic': 'maccyr', # cyrillic (on Mac)
1382 'windows-1251': 'cp1251', # cyrillic (on Windows)
1383 'koi8-r': 'koi8-r', # cyrillic (Russian)
1384 'koi8-u': 'koi8-u', # cyrillic (Ukrainian)
1385 'windows-1250': 'cp1250', #
1386 'windows-1252': 'cp1252', #
1387 'us-ascii': 'ascii', # ASCII (US)
1388 # unmatched encodings
1390 #'': 'ansinew', # windows 3.1 ansi
1391 #'': 'ascii', # ASCII encoding for the range 32--127.
1392 #'': 'cp437', # dos latin us
1393 #'': 'cp850', # dos latin 1
1394 #'': 'cp852', # dos latin 2
1397 #'iso-8859-6': '' # arabic
1398 #'iso-8859-7': '' # greek
1399 #'iso-8859-8': '' # hebrew
1400 #'iso-8859-10': '' # latin6, more complete iso-8859-4
1402 encoding
= docutils_encoding
.lower()
1405 # drop hyphen or low-line from "latin-1", "latin_1", "utf-8" and similar
1406 encoding
= encoding
.replace('_', '').replace('-', '')
1407 # strip the error handler
1408 return encoding
.split(':')[0]
1410 def language_label(self
, docutil_label
):
1411 return self
.language_module
.labels
[docutil_label
]
1413 def encode(self
, text
):
1414 """Return text with 'problematic' characters escaped.
1416 * Escape the ten special printing characters ``# $ % & ~ _ ^ \ { }``,
1417 square brackets ``[ ]``, double quotes and (in OT1) ``< | >``.
1418 * Translate non-supported Unicode characters.
1419 * Separate ``-`` (and more in literal text) to prevent input ligatures.
1424 # Set up the translation table:
1425 table
= CharMaps
.special
.copy()
1426 # keep the underscore in citation references
1427 if self
.inside_citation_reference_label
:
1428 del(table
[ord('_')])
1429 # Workarounds for OT1 font-encoding
1430 if self
.font_encoding
in ['OT1', ''] and not self
.is_xetex
:
1431 # * out-of-order characters in cmtt
1433 # replace underscore by underlined blank,
1434 # because this has correct width.
1435 table
[ord('_')] = u
'\\underline{~}'
1436 # the backslash doesn't work, so we use a mirrored slash.
1437 # \reflectbox is provided by graphicx:
1438 self
.requirements
['graphicx'] = self
.graphicx_package
1439 table
[ord('\\')] = ur
'\reflectbox{/}'
1440 # * ``< | >`` come out as different chars (except for cmtt):
1442 table
[ord('|')] = ur
'\textbar{}'
1443 table
[ord('<')] = ur
'\textless{}'
1444 table
[ord('>')] = ur
'\textgreater{}'
1445 if self
.insert_non_breaking_blanks
:
1446 table
[ord(' ')] = ur
'~'
1448 # double quotes are 'active' in some languages
1449 # TODO: use \textquotedbl if font encoding starts with T?
1450 table
[ord('"')] = self
.babel
.literal_double_quote
1451 # Unicode replacements for 8-bit tex engines (not required with XeTeX/LuaTeX):
1452 if not self
.is_xetex
:
1453 table
.update(CharMaps
.unsupported_unicode
)
1454 if not self
.latex_encoding
.startswith('utf8'):
1455 table
.update(CharMaps
.utf8_supported_unicode
)
1456 table
.update(CharMaps
.textcomp
)
1457 table
.update(CharMaps
.pifont
)
1458 # Characters that require a feature/package to render
1459 if [True for ch
in text
if ord(ch
) in CharMaps
.textcomp
]:
1460 self
.requirements
['textcomp'] = PreambleCmds
.textcomp
1461 if [True for ch
in text
if ord(ch
) in CharMaps
.pifont
]:
1462 self
.requirements
['pifont'] = '\\usepackage{pifont}'
1464 text
= text
.translate(table
)
1466 # Break up input ligatures e.g. '--' to '-{}-'.
1467 if not self
.is_xetex
: # Not required with xetex/luatex
1468 separate_chars
= '-'
1469 # In monospace-font, we also separate ',,', '``' and "''" and some
1470 # other characters which can't occur in non-literal text.
1472 separate_chars
+= ',`\'"<>'
1473 for char
in separate_chars
* 2:
1474 # Do it twice ("* 2") because otherwise we would replace
1476 text
= text
.replace(char
+ char
, char
+ '{}' + char
)
1478 # Literal line breaks (in address or literal blocks):
1479 if self
.insert_newline
:
1480 lines
= text
.split('\n')
1481 # Add a protected space to blank lines (except the last)
1482 # to avoid ``! LaTeX Error: There's no line here to end.``
1483 for i
, line
in enumerate(lines
[:-1]):
1484 if not line
.lstrip():
1486 text
= (r
'\\' + '\n').join(lines
)
1487 if not self
.literal
:
1488 text
= self
.babel
.quote_quotes(text
)
1489 if self
.literal
and not self
.insert_non_breaking_blanks
:
1490 # preserve runs of spaces but allow wrapping
1491 text
= text
.replace(' ', ' ~')
1494 def attval(self
, text
,
1495 whitespace
=re
.compile('[\n\r\t\v\f]')):
1496 """Cleanse, encode, and return attribute value text."""
1497 return self
.encode(whitespace
.sub(' ', text
))
1499 # TODO: is this used anywhere? -> update (use template) or delete
1500 ## def astext(self):
1501 ## """Assemble document parts and return as string."""
1502 ## head = '\n'.join(self.head_prefix + self.stylesheet + self.head)
1503 ## body = ''.join(self.body_prefix + self.body + self.body_suffix)
1504 ## return head + '\n' + body
1506 def is_inline(self
, node
):
1507 """Check whether a node represents an inline element"""
1508 return isinstance(node
.parent
, nodes
.TextElement
)
1510 def append_hypertargets(self
, node
):
1511 """Append hypertargets for all ids of `node`"""
1512 # hypertarget places the anchor at the target's baseline,
1513 # so we raise it explicitely
1514 self
.out
.append('%\n'.join(['\\raisebox{1em}{\\hypertarget{%s}{}}' %
1515 id for id in node
['ids']]))
1517 def ids_to_labels(self
, node
, set_anchor
=True):
1518 """Return list of label definitions for all ids of `node`
1520 If `set_anchor` is True, an anchor is set with \phantomsection.
1522 labels
= ['\\label{%s}' % id for id in node
.get('ids', [])]
1523 if set_anchor
and labels
:
1524 labels
.insert(0, '\\phantomsection')
1527 def push_output_collector(self
, new_out
):
1528 self
.out_stack
.append(self
.out
)
1531 def pop_output_collector(self
):
1532 self
.out
= self
.out_stack
.pop()
1537 def visit_Text(self
, node
):
1538 self
.out
.append(self
.encode(node
.astext()))
1540 def depart_Text(self
, node
):
1543 def visit_abbreviation(self
, node
):
1544 node
['classes'].insert(0, 'abbreviation')
1545 self
.visit_inline(node
)
1547 def depart_abbreviation(self
, node
):
1548 self
.depart_inline(node
)
1550 def visit_acronym(self
, node
):
1551 node
['classes'].insert(0, 'acronym')
1552 self
.visit_inline(node
)
1554 def depart_acronym(self
, node
):
1555 self
.depart_inline(node
)
1557 def visit_address(self
, node
):
1558 self
.visit_docinfo_item(node
, 'address')
1560 def depart_address(self
, node
):
1561 self
.depart_docinfo_item(node
)
1563 def visit_admonition(self
, node
):
1564 self
.fallbacks
['admonition'] = PreambleCmds
.admonition
1565 if 'error' in node
['classes']:
1566 self
.fallbacks
['error'] = PreambleCmds
.error
1567 # strip the generic 'admonition' from the list of classes
1568 node
['classes'] = [cls
for cls
in node
['classes']
1569 if cls
!= 'admonition']
1570 self
.out
.append('\n\\DUadmonition[%s]{\n' % ','.join(node
['classes']))
1572 def depart_admonition(self
, node
=None):
1573 self
.out
.append('}\n')
1575 def visit_author(self
, node
):
1576 self
.visit_docinfo_item(node
, 'author')
1578 def depart_author(self
, node
):
1579 self
.depart_docinfo_item(node
)
1581 def visit_authors(self
, node
):
1582 # not used: visit_author is called anyway for each author.
1585 def depart_authors(self
, node
):
1588 def visit_block_quote(self
, node
):
1589 self
.out
.append( '%\n\\begin{quote}\n')
1591 self
.visit_inline(node
)
1593 def depart_block_quote(self
, node
):
1595 self
.depart_inline(node
)
1596 self
.out
.append( '\n\\end{quote}\n')
1598 def visit_bullet_list(self
, node
):
1599 if self
.is_toc_list
:
1600 self
.out
.append( '%\n\\begin{list}{}{}\n' )
1602 self
.out
.append( '%\n\\begin{itemize}\n' )
1603 # if node['classes']:
1604 # self.visit_inline(node)
1606 def depart_bullet_list(self
, node
):
1607 # if node['classes']:
1608 # self.depart_inline(node)
1609 if self
.is_toc_list
:
1610 self
.out
.append( '\n\\end{list}\n' )
1612 self
.out
.append( '\n\\end{itemize}\n' )
1614 def visit_superscript(self
, node
):
1615 self
.out
.append(r
'\textsuperscript{')
1617 self
.visit_inline(node
)
1619 def depart_superscript(self
, node
):
1621 self
.depart_inline(node
)
1622 self
.out
.append('}')
1624 def visit_subscript(self
, node
):
1625 self
.out
.append(r
'\textsubscript{') # requires `fixltx2e`
1627 self
.visit_inline(node
)
1629 def depart_subscript(self
, node
):
1631 self
.depart_inline(node
)
1632 self
.out
.append('}')
1634 def visit_caption(self
, node
):
1635 self
.out
.append( '\\caption{' )
1637 def depart_caption(self
, node
):
1638 self
.out
.append('}\n')
1640 def visit_title_reference(self
, node
):
1641 self
.fallbacks
['titlereference'] = PreambleCmds
.titlereference
1642 self
.out
.append(r
'\DUroletitlereference{')
1644 self
.visit_inline(node
)
1646 def depart_title_reference(self
, node
):
1648 self
.depart_inline(node
)
1649 self
.out
.append( '}' )
1651 def visit_citation(self
, node
):
1652 # TODO maybe use cite bibitems
1653 if self
._use
_latex
_citations
:
1654 self
.push_output_collector([])
1656 # TODO: do we need these?
1657 ## self.requirements['~fnt_floats'] = PreambleCmds.footnote_floats
1658 self
.out
.append(r
'\begin{figure}[b]')
1659 self
.append_hypertargets(node
)
1661 def depart_citation(self
, node
):
1662 if self
._use
_latex
_citations
:
1664 text
= ''.join(self
.out
[1:])
1665 self
._bibitems
.append([label
, text
])
1666 self
.pop_output_collector()
1668 self
.out
.append('\\end{figure}\n')
1670 def visit_citation_reference(self
, node
):
1671 if self
._use
_latex
_citations
:
1672 if not self
.inside_citation_reference_label
:
1673 self
.out
.append(r
'\cite{')
1674 self
.inside_citation_reference_label
= 1
1676 assert self
.body
[-1] in (' ', '\n'),\
1677 'unexpected non-whitespace while in reference label'
1682 href
= node
['refid']
1683 elif 'refname' in node
:
1684 href
= self
.document
.nameids
[node
['refname']]
1685 self
.out
.append('\\hyperlink{%s}{[' % href
)
1687 def depart_citation_reference(self
, node
):
1688 if self
._use
_latex
_citations
:
1689 followup_citation
= False
1690 # check for a following citation separated by a space or newline
1691 next_siblings
= node
.traverse(descend
=False, siblings
=True,
1693 if len(next_siblings
) > 1:
1694 next
= next_siblings
[0]
1695 if (isinstance(next
, nodes
.Text
) and
1696 next
.astext() in (' ', '\n')):
1697 if next_siblings
[1].__class
__ == node
.__class
__:
1698 followup_citation
= True
1699 if followup_citation
:
1700 self
.out
.append(',')
1702 self
.out
.append('}')
1703 self
.inside_citation_reference_label
= False
1705 self
.out
.append(']}')
1707 def visit_classifier(self
, node
):
1708 self
.out
.append( '(\\textbf{' )
1710 def depart_classifier(self
, node
):
1711 self
.out
.append( '})\n' )
1713 def visit_colspec(self
, node
):
1714 self
.active_table
.visit_colspec(node
)
1716 def depart_colspec(self
, node
):
1719 def visit_comment(self
, node
):
1720 # Precede every line with a comment sign, wrap in newlines
1721 self
.out
.append('\n%% %s\n' % node
.astext().replace('\n', '\n% '))
1722 raise nodes
.SkipNode
1724 def depart_comment(self
, node
):
1727 def visit_compound(self
, node
):
1730 def depart_compound(self
, node
):
1733 def visit_contact(self
, node
):
1734 self
.visit_docinfo_item(node
, 'contact')
1736 def depart_contact(self
, node
):
1737 self
.depart_docinfo_item(node
)
1739 def visit_container(self
, node
):
1742 def depart_container(self
, node
):
1745 def visit_copyright(self
, node
):
1746 self
.visit_docinfo_item(node
, 'copyright')
1748 def depart_copyright(self
, node
):
1749 self
.depart_docinfo_item(node
)
1751 def visit_date(self
, node
):
1752 self
.visit_docinfo_item(node
, 'date')
1754 def depart_date(self
, node
):
1755 self
.depart_docinfo_item(node
)
1757 def visit_decoration(self
, node
):
1761 def depart_decoration(self
, node
):
1764 def visit_definition(self
, node
):
1767 def depart_definition(self
, node
):
1768 self
.out
.append('\n')
1770 def visit_definition_list(self
, node
):
1771 self
.out
.append( '%\n\\begin{description}\n' )
1773 def depart_definition_list(self
, node
):
1774 self
.out
.append( '\\end{description}\n' )
1776 def visit_definition_list_item(self
, node
):
1779 def depart_definition_list_item(self
, node
):
1782 def visit_description(self
, node
):
1783 self
.out
.append(' ')
1785 def depart_description(self
, node
):
1788 def visit_docinfo(self
, node
):
1789 self
.push_output_collector(self
.docinfo
)
1791 def depart_docinfo(self
, node
):
1792 self
.pop_output_collector()
1793 # Some itmes (e.g. author) end up at other places
1795 # tabularx: automatic width of columns, no page breaks allowed.
1796 self
.requirements
['tabularx'] = r
'\usepackage{tabularx}'
1797 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
1798 self
.fallbacks
['docinfo'] = PreambleCmds
.docinfo
1800 self
.docinfo
.insert(0, '\n% Docinfo\n'
1802 '\\begin{tabularx}{\\DUdocinfowidth}{lX}\n')
1803 self
.docinfo
.append('\\end{tabularx}\n'
1806 def visit_docinfo_item(self
, node
, name
):
1807 if name
== 'author':
1808 self
.pdfauthor
.append(self
.attval(node
.astext()))
1809 if self
.use_latex_docinfo
:
1810 if name
in ('author', 'organization', 'contact', 'address'):
1811 # We attach these to the last author. If any of them precedes
1812 # the first author, put them in a separate "author" group
1813 # (in lack of better semantics).
1814 if name
== 'author' or not self
.author_stack
:
1815 self
.author_stack
.append([])
1816 if name
== 'address': # newlines are meaningful
1817 self
.insert_newline
= True
1818 text
= self
.encode(node
.astext())
1819 self
.insert_newline
= False
1821 text
= self
.attval(node
.astext())
1822 self
.author_stack
[-1].append(text
)
1823 raise nodes
.SkipNode
1824 elif name
== 'date':
1825 self
.date
.append(self
.attval(node
.astext()))
1826 raise nodes
.SkipNode
1827 self
.out
.append('\\textbf{%s}: &\n\t' % self
.language_label(name
))
1828 if name
== 'address':
1829 self
.insert_newline
= 1
1830 self
.out
.append('{\\raggedright\n')
1831 self
.context
.append(' } \\\\\n')
1833 self
.context
.append(' \\\\\n')
1835 def depart_docinfo_item(self
, node
):
1836 self
.out
.append(self
.context
.pop())
1837 # for address we did set insert_newline
1838 self
.insert_newline
= False
1840 def visit_doctest_block(self
, node
):
1841 self
.visit_literal_block(node
)
1843 def depart_doctest_block(self
, node
):
1844 self
.depart_literal_block(node
)
1846 def visit_document(self
, node
):
1848 if (self
.use_latex_docinfo
or len(node
) and
1849 isinstance(node
[0], nodes
.title
)):
1850 self
.title_labels
+= self
.ids_to_labels(node
, set_anchor
=False)
1852 def depart_document(self
, node
):
1853 # Complete header with information gained from walkabout
1855 if (self
.babel
.otherlanguages
or
1856 self
.babel
.language
not in ('', 'english')):
1857 self
.requirements
['babel'] = self
.babel()
1858 # * conditional requirements (before style sheet)
1859 self
.requirements
= self
.requirements
.sortedvalues()
1860 # * coditional fallback definitions (after style sheet)
1861 self
.fallbacks
= self
.fallbacks
.sortedvalues()
1863 self
.pdfsetup
.append(PreambleCmds
.linking
% self
.hyperref_options
)
1865 authors
= self
.author_separator
.join(self
.pdfauthor
)
1866 self
.pdfinfo
.append(' pdfauthor={%s}' % authors
)
1868 self
.pdfsetup
+= [r
'\hypersetup{'] + self
.pdfinfo
+ ['}']
1870 # * document title (with "use_latex_docinfo" also
1871 # 'author', 'organization', 'contact', 'address' and 'date')
1873 self
.use_latex_docinfo
and (self
.author_stack
or self
.date
)):
1874 # with the default template, titledata is written to the preamble
1875 self
.titledata
.append('%%% Title Data')
1876 # \title (empty \title prevents error with \maketitle)
1878 self
.title
.insert(0, '\phantomsection%\n ')
1879 title
= [''.join(self
.title
)] + self
.title_labels
1881 title
+= [r
'\\ % subtitle',
1882 r
'\large{%s}' % ''.join(self
.subtitle
)
1883 ] + self
.subtitle_labels
1884 self
.titledata
.append(r
'\title{%s}' % '%\n '.join(title
))
1885 # \author (empty \author prevents warning with \maketitle)
1886 authors
= ['\\\\\n'.join(author_entry
)
1887 for author_entry
in self
.author_stack
]
1888 self
.titledata
.append(r
'\author{%s}' %
1889 ' \\and\n'.join(authors
))
1890 # \date (empty \date prevents defaulting to \today)
1891 self
.titledata
.append(r
'\date{%s}' % ', '.join(self
.date
))
1892 # \maketitle in the body formats title with LaTeX
1893 self
.body_pre_docinfo
.append('\\maketitle\n')
1896 # TODO insertion point of bibliography should be configurable.
1897 if self
._use
_latex
_citations
and len(self
._bibitems
)>0:
1900 for bi
in self
._bibitems
:
1901 if len(widest_label
)<len(bi
[0]):
1902 widest_label
= bi
[0]
1903 self
.out
.append('\n\\begin{thebibliography}{%s}\n' %
1905 for bi
in self
._bibitems
:
1906 # cite_key: underscores must not be escaped
1907 cite_key
= bi
[0].replace(r
'\_','_')
1908 self
.out
.append('\\bibitem[%s]{%s}{%s}\n' %
1909 (bi
[0], cite_key
, bi
[1]))
1910 self
.out
.append('\\end{thebibliography}\n')
1912 self
.out
.append('\n\\bibliographystyle{%s}\n' %
1914 self
.out
.append('\\bibliography{%s}\n' % self
.bibtex
[1])
1915 # * make sure to generate a toc file if needed for local contents:
1916 if 'minitoc' in self
.requirements
and not self
.has_latex_toc
:
1917 self
.out
.append('\n\\faketableofcontents % for local ToCs\n')
1919 def visit_emphasis(self
, node
):
1920 self
.out
.append('\\emph{')
1922 self
.visit_inline(node
)
1924 def depart_emphasis(self
, node
):
1926 self
.depart_inline(node
)
1927 self
.out
.append('}')
1929 def visit_entry(self
, node
):
1930 self
.active_table
.visit_entry()
1932 # BUG: the following fails, with more than one multirow
1933 # starting in the second column (or later) see
1934 # ../../../test/functional/input/data/latex.txt
1935 if self
.active_table
.get_entry_number() == 1:
1936 # if the first row is a multirow, this actually is the second row.
1937 # this gets hairy if rowspans follow each other.
1938 if self
.active_table
.get_rowspan(0):
1940 while self
.active_table
.get_rowspan(count
):
1942 self
.out
.append(' & ')
1943 self
.active_table
.visit_entry() # increment cell count
1945 self
.out
.append(' & ')
1946 # multirow, multicolumn
1947 # IN WORK BUG TODO HACK continues here
1948 # multirow in LaTeX simply will enlarge the cell over several rows
1949 # (the following n if n is positive, the former if negative).
1950 if 'morerows' in node
and 'morecols' in node
:
1951 raise NotImplementedError('Cells that '
1952 'span multiple rows *and* columns are not supported, sorry.')
1953 if 'morerows' in node
:
1954 self
.requirements
['multirow'] = r
'\usepackage{multirow}'
1955 count
= node
['morerows'] + 1
1956 self
.active_table
.set_rowspan(
1957 self
.active_table
.get_entry_number()-1,count
)
1958 self
.out
.append('\\multirow{%d}{%s}{%%' %
1959 (count
,self
.active_table
.get_column_width()))
1960 self
.context
.append('}')
1961 elif 'morecols' in node
:
1962 # the vertical bar before column is missing if it is the first
1963 # column. the one after always.
1964 if self
.active_table
.get_entry_number() == 1:
1965 bar1
= self
.active_table
.get_vertical_bar()
1968 count
= node
['morecols'] + 1
1969 self
.out
.append('\\multicolumn{%d}{%sp{%s}%s}{' %
1971 self
.active_table
.get_multicolumn_width(
1972 self
.active_table
.get_entry_number(),
1974 self
.active_table
.get_vertical_bar()))
1975 self
.context
.append('}')
1977 self
.context
.append('')
1979 # header / not header
1980 if isinstance(node
.parent
.parent
, nodes
.thead
):
1981 self
.out
.append('\\textbf{%')
1982 self
.context
.append('}')
1983 elif self
.active_table
.is_stub_column():
1984 self
.out
.append('\\textbf{')
1985 self
.context
.append('}')
1987 self
.context
.append('')
1989 def depart_entry(self
, node
):
1990 self
.out
.append(self
.context
.pop()) # header / not header
1991 self
.out
.append(self
.context
.pop()) # multirow/column
1992 # if following row is spanned from above.
1993 if self
.active_table
.get_rowspan(self
.active_table
.get_entry_number()):
1994 self
.out
.append(' & ')
1995 self
.active_table
.visit_entry() # increment cell count
1997 def visit_row(self
, node
):
1998 self
.active_table
.visit_row()
2000 def depart_row(self
, node
):
2001 self
.out
.extend(self
.active_table
.depart_row())
2003 def visit_enumerated_list(self
, node
):
2004 # We create our own enumeration list environment.
2005 # This allows to set the style and starting value
2006 # and unlimited nesting.
2007 enum_style
= {'arabic':'arabic',
2008 'loweralpha':'alph',
2009 'upperalpha':'Alph',
2010 'lowerroman':'roman',
2011 'upperroman':'Roman' }
2013 if 'suffix' in node
:
2014 enum_suffix
= node
['suffix']
2016 if 'prefix' in node
:
2017 enum_prefix
= node
['prefix']
2018 if self
.compound_enumerators
:
2020 if self
.section_prefix_for_enumerators
and self
.section_level
:
2021 for i
in range(self
.section_level
):
2022 pref
+= '%d.' % self
._section
_number
[i
]
2023 pref
= pref
[:-1] + self
.section_enumerator_separator
2025 for ctype
, cname
in self
._enumeration
_counters
:
2026 enum_prefix
+= '\\%s{%s}.' % (ctype
, cname
)
2027 enum_type
= 'arabic'
2028 if 'enumtype' in node
:
2029 enum_type
= node
['enumtype']
2030 if enum_type
in enum_style
:
2031 enum_type
= enum_style
[enum_type
]
2033 counter_name
= 'listcnt%d' % len(self
._enumeration
_counters
)
2034 self
._enumeration
_counters
.append((enum_type
, counter_name
))
2035 # If we haven't used this counter name before, then create a
2036 # new counter; otherwise, reset & reuse the old counter.
2037 if len(self
._enumeration
_counters
) > self
._max
_enumeration
_counters
:
2038 self
._max
_enumeration
_counters
= len(self
._enumeration
_counters
)
2039 self
.out
.append('\\newcounter{%s}\n' % counter_name
)
2041 self
.out
.append('\\setcounter{%s}{0}\n' % counter_name
)
2043 self
.out
.append('\\begin{list}{%s\\%s{%s}%s}\n' %
2044 (enum_prefix
,enum_type
,counter_name
,enum_suffix
))
2045 self
.out
.append('{\n')
2046 self
.out
.append('\\usecounter{%s}\n' % counter_name
)
2047 # set start after usecounter, because it initializes to zero.
2049 self
.out
.append('\\addtocounter{%s}{%d}\n' %
2050 (counter_name
,node
['start']-1))
2051 ## set rightmargin equal to leftmargin
2052 self
.out
.append('\\setlength{\\rightmargin}{\\leftmargin}\n')
2053 self
.out
.append('}\n')
2055 def depart_enumerated_list(self
, node
):
2056 self
.out
.append('\\end{list}\n')
2057 self
._enumeration
_counters
.pop()
2059 def visit_field(self
, node
):
2060 # real output is done in siblings: _argument, _body, _name
2063 def depart_field(self
, node
):
2064 self
.out
.append('\n')
2065 ##self.out.append('%[depart_field]\n')
2067 def visit_field_argument(self
, node
):
2068 self
.out
.append('%[visit_field_argument]\n')
2070 def depart_field_argument(self
, node
):
2071 self
.out
.append('%[depart_field_argument]\n')
2073 def visit_field_body(self
, node
):
2076 def depart_field_body(self
, node
):
2077 if self
.out
is self
.docinfo
:
2078 self
.out
.append(r
'\\')
2080 def visit_field_list(self
, node
):
2081 if self
.out
is not self
.docinfo
:
2082 self
.fallbacks
['fieldlist'] = PreambleCmds
.fieldlist
2083 self
.out
.append('%\n\\begin{DUfieldlist}\n')
2085 def depart_field_list(self
, node
):
2086 if self
.out
is not self
.docinfo
:
2087 self
.out
.append('\\end{DUfieldlist}\n')
2089 def visit_field_name(self
, node
):
2090 if self
.out
is self
.docinfo
:
2091 self
.out
.append('\\textbf{')
2093 # Commands with optional args inside an optional arg must be put
2094 # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
2095 self
.out
.append('\\item[{')
2097 def depart_field_name(self
, node
):
2098 if self
.out
is self
.docinfo
:
2099 self
.out
.append('}: &')
2101 self
.out
.append(':}]')
2103 def visit_figure(self
, node
):
2104 self
.requirements
['float_settings'] = PreambleCmds
.float_settings
2105 # ! the 'align' attribute should set "outer alignment" !
2106 # For "inner alignment" use LaTeX default alignment (similar to HTML)
2107 ## if ('align' not in node.attributes or
2108 ## node.attributes['align'] == 'center'):
2109 ## align = '\n\\centering'
2112 ## # TODO non vertical space for other alignments.
2113 ## align = '\\begin{flush%s}' % node.attributes['align']
2114 ## align_end = '\\end{flush%s}' % node.attributes['align']
2115 ## self.out.append( '\\begin{figure}%s\n' % align )
2116 ## self.context.append( '%s\\end{figure}\n' % align_end )
2117 self
.out
.append('\\begin{figure}')
2119 self
.out
+= ['\n'] + self
.ids_to_labels(node
)
2121 def depart_figure(self
, node
):
2122 self
.out
.append('\\end{figure}\n')
2124 def visit_footer(self
, node
):
2125 self
.push_output_collector([])
2126 self
.out
.append(r
'\newcommand{\DUfooter}{')
2128 def depart_footer(self
, node
):
2129 self
.out
.append('}')
2130 self
.requirements
['~footer'] = ''.join(self
.out
)
2131 self
.pop_output_collector()
2133 def visit_footnote(self
, node
):
2135 backref
= node
['backrefs'][0]
2137 backref
= node
['ids'][0] # no backref, use self-ref instead
2138 if self
.settings
.figure_footnotes
:
2139 self
.requirements
['~fnt_floats'] = PreambleCmds
.footnote_floats
2140 self
.out
.append('\\begin{figure}[b]')
2141 self
.append_hypertargets(node
)
2142 if node
.get('id') == node
.get('name'): # explicite label
2143 self
.out
+= self
.ids_to_labels(node
)
2144 elif self
.docutils_footnotes
:
2145 self
.fallbacks
['footnotes'] = PreambleCmds
.footnotes
2146 num
,text
= node
.astext().split(None,1)
2147 if self
.settings
.footnote_references
== 'brackets':
2149 self
.out
.append('%%\n\\DUfootnotetext{%s}{%s}{%s}{' %
2150 (node
['ids'][0], backref
, self
.encode(num
)))
2151 if node
['ids'] == node
['names']:
2152 self
.out
+= self
.ids_to_labels(node
)
2153 # mask newline to prevent spurious whitespace:
2154 self
.out
.append('%')
2155 ## else: # TODO: "real" LaTeX \footnote{}s
2157 def depart_footnote(self
, node
):
2158 if self
.figure_footnotes
:
2159 self
.out
.append('\\end{figure}\n')
2161 self
.out
.append('}\n')
2163 def visit_footnote_reference(self
, node
):
2166 href
= node
['refid']
2167 elif 'refname' in node
:
2168 href
= self
.document
.nameids
[node
['refname']]
2169 # if not self.docutils_footnotes:
2170 # TODO: insert footnote content at (or near) this place
2171 # print "footnote-ref to", node['refid']
2172 # footnotes = (self.document.footnotes +
2173 # self.document.autofootnotes +
2174 # self.document.symbol_footnotes)
2175 # for footnote in footnotes:
2176 # # print footnote['ids']
2177 # if node.get('refid', '') in footnote['ids']:
2178 # print 'matches', footnote['ids']
2179 format
= self
.settings
.footnote_references
2180 if format
== 'brackets':
2181 self
.append_hypertargets(node
)
2182 self
.out
.append('\\hyperlink{%s}{[' % href
)
2183 self
.context
.append(']}')
2185 self
.fallbacks
['footnotes'] = PreambleCmds
.footnotes
2186 self
.out
.append(r
'\DUfootnotemark{%s}{%s}{' %
2187 (node
['ids'][0], href
))
2188 self
.context
.append('}')
2190 def depart_footnote_reference(self
, node
):
2191 self
.out
.append(self
.context
.pop())
2193 # footnote/citation label
2194 def label_delim(self
, node
, bracket
, superscript
):
2195 if isinstance(node
.parent
, nodes
.footnote
):
2196 if not self
.figure_footnotes
:
2197 raise nodes
.SkipNode
2198 if self
.settings
.footnote_references
== 'brackets':
2199 self
.out
.append(bracket
)
2201 self
.out
.append(superscript
)
2203 assert isinstance(node
.parent
, nodes
.citation
)
2204 if not self
._use
_latex
_citations
:
2205 self
.out
.append(bracket
)
2207 def visit_label(self
, node
):
2208 """footnote or citation label: in brackets or as superscript"""
2209 self
.label_delim(node
, '[', '\\textsuperscript{')
2211 def depart_label(self
, node
):
2212 self
.label_delim(node
, ']', '}')
2214 # elements generated by the framework e.g. section numbers.
2215 def visit_generated(self
, node
):
2218 def depart_generated(self
, node
):
2221 def visit_header(self
, node
):
2222 self
.push_output_collector([])
2223 self
.out
.append(r
'\newcommand{\DUheader}{')
2225 def depart_header(self
, node
):
2226 self
.out
.append('}')
2227 self
.requirements
['~header'] = ''.join(self
.out
)
2228 self
.pop_output_collector()
2230 def to_latex_length(self
, length_str
, pxunit
=None):
2231 """Convert `length_str` with rst lenght to LaTeX length
2233 if pxunit
is not None:
2234 sys
.stderr
.write('deprecation warning: LaTeXTranslator.to_latex_length()'
2235 ' option `pxunit` will be removed.')
2236 match
= re
.match('(\d*\.?\d*)\s*(\S*)', length_str
)
2239 value
, unit
= match
.groups()[:2]
2240 # no unit or "DTP" points (called 'bp' in TeX):
2241 if unit
in ('', 'pt'):
2242 length_str
= '%sbp' % value
2243 # percentage: relate to current line width
2245 length_str
= '%.3f\\linewidth' % (float(value
)/100.0)
2246 elif self
.is_xetex
and unit
== 'px':
2247 # XeTeX does not know the length unit px.
2248 # Use \pdfpxdimen, the macro to set the value of 1 px in pdftex.
2249 # This way, configuring works the same for pdftex and xetex.
2250 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
2251 self
.fallbacks
['px'] = '\n\\DUprovidelength{\\pdfpxdimen}{1bp}\n'
2252 length_str
= r
'%s\pdfpxdimen' % value
2255 def visit_image(self
, node
):
2256 self
.requirements
['graphicx'] = self
.graphicx_package
2257 attrs
= node
.attributes
2258 # Convert image URI to a local file path
2259 imagepath
= urllib
.url2pathname(attrs
['uri']).replace('\\', '/')
2260 # alignment defaults:
2261 if not 'align' in attrs
:
2262 # Set default align of image in a figure to 'center'
2263 if isinstance(node
.parent
, nodes
.figure
):
2264 attrs
['align'] = 'center'
2265 # query 'align-*' class argument
2266 for cls
in node
['classes']:
2267 if cls
.startswith('align-'):
2268 attrs
['align'] = cls
.split('-')[1]
2269 # pre- and postfix (prefix inserted in reverse order)
2272 include_graphics_options
= []
2273 display_style
= ('block-', 'inline-')[self
.is_inline(node
)]
2275 # inline images: by default latex aligns the bottom.
2277 'middle': (r
'\raisebox{-0.5\height}{', '}'),
2278 'top': (r
'\raisebox{-\height}{', '}'),
2279 # block level images:
2280 'center': (r
'\noindent\makebox[\textwidth][c]{', '}'),
2281 'left': (r
'\noindent{', r
'\hfill}'),
2282 'right': (r
'\noindent{\hfill', '}'),}
2283 if 'align' in attrs
:
2285 align_code
= align_codes
[attrs
['align']]
2286 pre
.append(align_code
[0])
2287 post
.append(align_code
[1])
2290 if 'height' in attrs
:
2291 include_graphics_options
.append('height=%s' %
2292 self
.to_latex_length(attrs
['height']))
2293 if 'scale' in attrs
:
2294 include_graphics_options
.append('scale=%f' %
2295 (attrs
['scale'] / 100.0))
2296 if 'width' in attrs
:
2297 include_graphics_options
.append('width=%s' %
2298 self
.to_latex_length(attrs
['width']))
2299 if not self
.is_inline(node
):
2303 self
.out
.extend(pre
)
2305 if include_graphics_options
:
2306 options
= '[%s]' % (','.join(include_graphics_options
))
2307 self
.out
.append('\\includegraphics%s{%s}' % (options
, imagepath
))
2308 self
.out
.extend(post
)
2310 def depart_image(self
, node
):
2312 self
.out
+= self
.ids_to_labels(node
) + ['\n']
2314 def visit_inline(self
, node
): # <span>, i.e. custom roles
2315 # Make a copy to keep ``node['classes']`` True if a
2316 # language argument is popped (used in conditional calls of
2318 classes
= node
['classes'][:]
2319 self
.context
.append('}' * len(classes
))
2320 # handle language specification:
2321 language_tags
= [cls
for cls
in classes
2322 if cls
.startswith('language-')]
2324 language
= self
.babel
.language_name(language_tags
[0][9:])
2326 self
.babel
.otherlanguages
[language
] = True
2327 self
.out
.append(r
'\otherlanguage{%s}{' % language
)
2328 classes
.pop(classes
.index(language_tags
[0]))
2331 # mark up for styling with custom macros
2332 if 'align-center' in classes
:
2333 self
.fallbacks
['align-center'] = PreambleCmds
.align_center
2334 self
.fallbacks
['inline'] = PreambleCmds
.inline
2335 self
.out
+= [r
'\DUrole{%s}{' % cls
for cls
in classes
]
2337 def depart_inline(self
, node
):
2338 self
.out
.append(self
.context
.pop())
2340 def visit_interpreted(self
, node
):
2341 # @@@ Incomplete, pending a proper implementation on the
2342 # Parser/Reader end.
2343 self
.visit_literal(node
)
2345 def depart_interpreted(self
, node
):
2346 self
.depart_literal(node
)
2348 def visit_legend(self
, node
):
2349 self
.fallbacks
['legend'] = PreambleCmds
.legend
2350 self
.out
.append('\\begin{DUlegend}')
2352 def depart_legend(self
, node
):
2353 self
.out
.append('\\end{DUlegend}\n')
2355 def visit_line(self
, node
):
2356 self
.out
.append('\item[] ')
2358 def depart_line(self
, node
):
2359 self
.out
.append('\n')
2361 def visit_line_block(self
, node
):
2362 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
2363 self
.fallbacks
['lineblock'] = PreambleCmds
.lineblock
2364 if isinstance(node
.parent
, nodes
.line_block
):
2365 self
.out
.append('\\item[]\n'
2366 '\\begin{DUlineblock}{\\DUlineblockindent}\n')
2368 self
.out
.append('\n\\begin{DUlineblock}{0em}\n')
2370 self
.visit_inline(node
)
2371 self
.out
.append('\n')
2373 def depart_line_block(self
, node
):
2375 self
.depart_inline(node
)
2376 self
.out
.append('\n')
2377 self
.out
.append('\\end{DUlineblock}\n')
2379 def visit_list_item(self
, node
):
2380 self
.out
.append('\n\\item ')
2382 def depart_list_item(self
, node
):
2385 def visit_literal(self
, node
):
2387 if 'code' in node
.get('classes', []):
2388 self
.requirements
['color'] = PreambleCmds
.color
2389 self
.requirements
['code'] = PreambleCmds
.highlight_rules
2390 self
.out
.append('\\texttt{')
2392 self
.visit_inline(node
)
2394 def depart_literal(self
, node
):
2395 self
.literal
= False
2397 self
.depart_inline(node
)
2398 self
.out
.append('}')
2400 # Literal blocks are used for '::'-prefixed literal-indented
2401 # blocks of text, where the inline markup is not recognized,
2402 # but are also the product of the "parsed-literal" directive,
2403 # where the markup is respected.
2405 # In both cases, we want to use a typewriter/monospaced typeface.
2406 # For "real" literal-blocks, we can use \verbatim, while for all
2407 # the others we must use \mbox or \alltt.
2409 # We can distinguish between the two kinds by the number of
2410 # siblings that compose this node: if it is composed by a
2411 # single element, it's either
2413 # * a parsed-literal that does not contain any markup, or
2414 # * a parsed-literal containing just one markup construct.
2415 def is_plaintext(self
, node
):
2416 """Check whether a node can be typeset verbatim"""
2417 return (len(node
) == 1) and isinstance(node
[0], nodes
.Text
)
2419 def visit_literal_block(self
, node
):
2420 """Render a literal block."""
2421 # environments and packages to typeset literal blocks
2422 packages
= {'listing': r
'\usepackage{moreverb}',
2423 'lstlisting': r
'\usepackage{listings}',
2424 'Verbatim': r
'\usepackage{fancyvrb}',
2426 'verbatimtab': r
'\usepackage{moreverb}'}
2428 if not self
.active_table
.is_open():
2429 # no quote inside tables, to avoid vertical space between
2430 # table border and literal block.
2431 # BUG: fails if normal text preceeds the literal block.
2432 self
.out
.append('%\n\\begin{quote}')
2433 self
.context
.append('\n\\end{quote}\n')
2435 self
.out
.append('\n')
2436 self
.context
.append('\n')
2437 if self
.literal_block_env
!= '' and self
.is_plaintext(node
):
2438 self
.requirements
['literal_block'] = packages
.get(
2439 self
.literal_block_env
, '')
2440 self
.verbatim
= True
2441 self
.out
.append('\\begin{%s}%s\n' % (self
.literal_block_env
,
2442 self
.literal_block_options
))
2445 self
.insert_newline
= True
2446 self
.insert_non_breaking_blanks
= True
2447 self
.out
.append('{\\ttfamily \\raggedright \\noindent\n')
2449 def depart_literal_block(self
, node
):
2451 self
.out
.append('\n\\end{%s}\n' % self
.literal_block_env
)
2452 self
.verbatim
= False
2454 self
.out
.append('\n}')
2455 self
.insert_non_breaking_blanks
= False
2456 self
.insert_newline
= False
2457 self
.literal
= False
2458 self
.out
.append(self
.context
.pop())
2460 ## def visit_meta(self, node):
2461 ## self.out.append('[visit_meta]\n')
2462 # TODO: set keywords for pdf?
2464 # The reStructuredText "meta" directive creates a "pending" node,
2465 # which contains knowledge that the embedded "meta" node can only
2466 # be handled by HTML-compatible writers. The "pending" node is
2467 # resolved by the docutils.transforms.components.Filter transform,
2468 # which checks that the calling writer supports HTML; if it doesn't,
2469 # the "pending" node (and enclosed "meta" node) is removed from the
2471 # --- docutils/docs/peps/pep-0258.html#transformer
2473 ## def depart_meta(self, node):
2474 ## self.out.append('[depart_meta]\n')
2476 def visit_math(self
, node
, math_env
='$'):
2479 self
.visit_inline(node
)
2480 self
.requirements
['amsmath'] = r
'\usepackage{amsmath}'
2481 math_code
= node
.astext().translate(unichar2tex
.uni2tex_table
)
2483 math_code
= '\n'.join([math_code
] + self
.ids_to_labels(node
))
2487 wrapper
= u
'\n'.join(['%%',
2488 r
'\begin{%s}' % math_env
,
2490 r
'\end{%s}' % math_env
])
2491 # print repr(wrapper), repr(math_code)
2492 self
.out
.append(wrapper
% math_code
)
2494 self
.depart_inline(node
)
2495 # Content already processed:
2496 raise nodes
.SkipNode
2498 def depart_math(self
, node
):
2499 pass # never reached
2501 def visit_math_block(self
, node
):
2502 math_env
= pick_math_environment(node
.astext())
2503 self
.visit_math(node
, math_env
=math_env
)
2505 def depart_math_block(self
, node
):
2506 pass # never reached
2508 def visit_option(self
, node
):
2509 if self
.context
[-1]:
2510 # this is not the first option
2511 self
.out
.append(', ')
2513 def depart_option(self
, node
):
2514 # flag that the first option is done.
2515 self
.context
[-1] += 1
2517 def visit_option_argument(self
, node
):
2518 """Append the delimiter betweeen an option and its argument to body."""
2519 self
.out
.append(node
.get('delimiter', ' '))
2521 def depart_option_argument(self
, node
):
2524 def visit_option_group(self
, node
):
2525 self
.out
.append('\n\\item[')
2526 # flag for first option
2527 self
.context
.append(0)
2529 def depart_option_group(self
, node
):
2530 self
.context
.pop() # the flag
2531 self
.out
.append('] ')
2533 def visit_option_list(self
, node
):
2534 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
2535 self
.fallbacks
['optionlist'] = PreambleCmds
.optionlist
2536 self
.out
.append('%\n\\begin{DUoptionlist}\n')
2538 def depart_option_list(self
, node
):
2539 self
.out
.append('\n\\end{DUoptionlist}\n')
2541 def visit_option_list_item(self
, node
):
2544 def depart_option_list_item(self
, node
):
2547 def visit_option_string(self
, node
):
2548 ##self.out.append(self.starttag(node, 'span', '', CLASS='option'))
2551 def depart_option_string(self
, node
):
2552 ##self.out.append('</span>')
2555 def visit_organization(self
, node
):
2556 self
.visit_docinfo_item(node
, 'organization')
2558 def depart_organization(self
, node
):
2559 self
.depart_docinfo_item(node
)
2561 def visit_paragraph(self
, node
):
2562 # insert blank line, if the paragraph is not first in a list item
2563 # nor follows a non-paragraph node in a compound
2564 index
= node
.parent
.index(node
)
2565 if (index
== 0 and (isinstance(node
.parent
, nodes
.list_item
) or
2566 isinstance(node
.parent
, nodes
.description
))):
2568 elif (index
> 0 and isinstance(node
.parent
, nodes
.compound
) and
2569 not isinstance(node
.parent
[index
- 1], nodes
.paragraph
) and
2570 not isinstance(node
.parent
[index
- 1], nodes
.compound
)):
2573 self
.out
.append('\n')
2575 self
.out
+= self
.ids_to_labels(node
) + ['\n']
2577 self
.visit_inline(node
)
2579 def depart_paragraph(self
, node
):
2581 self
.depart_inline(node
)
2582 self
.out
.append('\n')
2584 def visit_problematic(self
, node
):
2585 self
.requirements
['color'] = PreambleCmds
.color
2586 self
.out
.append('%\n')
2587 self
.append_hypertargets(node
)
2588 self
.out
.append(r
'\hyperlink{%s}{\textbf{\color{red}' % node
['refid'])
2590 def depart_problematic(self
, node
):
2591 self
.out
.append('}}')
2593 def visit_raw(self
, node
):
2594 if not 'latex' in node
.get('format', '').split():
2595 raise nodes
.SkipNode
2596 if not self
.is_inline(node
):
2597 self
.out
.append('\n')
2599 self
.visit_inline(node
)
2600 # append "as-is" skipping any LaTeX-encoding
2601 self
.verbatim
= True
2603 def depart_raw(self
, node
):
2604 self
.verbatim
= False
2606 self
.depart_inline(node
)
2607 if not self
.is_inline(node
):
2608 self
.out
.append('\n')
2610 def has_unbalanced_braces(self
, string
):
2611 """Test whether there are unmatched '{' or '}' characters."""
2622 def visit_reference(self
, node
):
2623 # We need to escape #, \, and % if we use the URL in a command.
2624 special_chars
= {ord('#'): ur
'\#',
2628 # external reference (URL)
2629 if 'refuri' in node
:
2630 href
= unicode(node
['refuri']).translate(special_chars
)
2631 # problematic chars double caret and unbalanced braces:
2632 if href
.find('^^') != -1 or self
.has_unbalanced_braces(href
):
2634 'External link "%s" not supported by LaTeX.\n'
2635 ' (Must not contain "^^" or unbalanced braces.)' % href
)
2636 if node
['refuri'] == node
.astext():
2637 self
.out
.append(r
'\url{%s}' % href
)
2638 raise nodes
.SkipNode
2639 self
.out
.append(r
'\href{%s}{' % href
)
2641 # internal reference
2643 href
= node
['refid']
2644 elif 'refname' in node
:
2645 href
= self
.document
.nameids
[node
['refname']]
2647 raise AssertionError('Unknown reference.')
2648 if not self
.is_inline(node
):
2649 self
.out
.append('\n')
2650 self
.out
.append('\\hyperref[%s]{' % href
)
2651 if self
._reference
_label
:
2652 self
.out
.append('\\%s{%s}}' %
2653 (self
._reference
_label
, href
.replace('#', '')))
2654 raise nodes
.SkipNode
2656 def depart_reference(self
, node
):
2657 self
.out
.append('}')
2658 if not self
.is_inline(node
):
2659 self
.out
.append('\n')
2661 def visit_revision(self
, node
):
2662 self
.visit_docinfo_item(node
, 'revision')
2664 def depart_revision(self
, node
):
2665 self
.depart_docinfo_item(node
)
2667 def visit_section(self
, node
):
2668 self
.section_level
+= 1
2669 # Initialize counter for potential subsections:
2670 self
._section
_number
.append(0)
2671 # Counter for this section's level (initialized by parent section):
2672 self
._section
_number
[self
.section_level
- 1] += 1
2674 def depart_section(self
, node
):
2675 # Remove counter for potential subsections:
2676 self
._section
_number
.pop()
2677 self
.section_level
-= 1
2679 def visit_sidebar(self
, node
):
2680 self
.requirements
['color'] = PreambleCmds
.color
2681 self
.fallbacks
['sidebar'] = PreambleCmds
.sidebar
2682 self
.out
.append('\n\\DUsidebar{\n')
2684 def depart_sidebar(self
, node
):
2685 self
.out
.append('}\n')
2687 attribution_formats
= {'dash': (u
'—', ''), # EM DASH
2688 'parentheses': ('(', ')'),
2689 'parens': ('(', ')'),
2692 def visit_attribution(self
, node
):
2693 prefix
, suffix
= self
.attribution_formats
[self
.settings
.attribution
]
2694 self
.out
.append('\\nopagebreak\n\n\\raggedleft ')
2695 self
.out
.append(prefix
)
2696 self
.context
.append(suffix
)
2698 def depart_attribution(self
, node
):
2699 self
.out
.append(self
.context
.pop() + '\n')
2701 def visit_status(self
, node
):
2702 self
.visit_docinfo_item(node
, 'status')
2704 def depart_status(self
, node
):
2705 self
.depart_docinfo_item(node
)
2707 def visit_strong(self
, node
):
2708 self
.out
.append('\\textbf{')
2710 self
.visit_inline(node
)
2712 def depart_strong(self
, node
):
2714 self
.depart_inline(node
)
2715 self
.out
.append('}')
2717 def visit_substitution_definition(self
, node
):
2718 raise nodes
.SkipNode
2720 def visit_substitution_reference(self
, node
):
2721 self
.unimplemented_visit(node
)
2723 def visit_subtitle(self
, node
):
2724 if isinstance(node
.parent
, nodes
.document
):
2725 self
.push_output_collector(self
.subtitle
)
2726 self
.subtitle_labels
+= self
.ids_to_labels(node
, set_anchor
=False)
2727 # section subtitle: "starred" (no number, not in ToC)
2728 elif isinstance(node
.parent
, nodes
.section
):
2729 self
.out
.append(r
'\%s*{' %
2730 self
.d_class
.section(self
.section_level
+ 1))
2732 self
.fallbacks
['subtitle'] = PreambleCmds
.subtitle
2733 self
.out
.append('\n\\DUsubtitle[%s]{' % node
.parent
.tagname
)
2735 def depart_subtitle(self
, node
):
2736 if isinstance(node
.parent
, nodes
.document
):
2737 self
.pop_output_collector()
2739 self
.out
.append('}\n')
2741 def visit_system_message(self
, node
):
2742 self
.requirements
['color'] = PreambleCmds
.color
2743 self
.fallbacks
['title'] = PreambleCmds
.title
2744 node
['classes'] = ['system-message']
2745 self
.visit_admonition(node
)
2746 self
.out
.append('\\DUtitle[system-message]{system-message}\n')
2747 self
.append_hypertargets(node
)
2749 line
= ', line~%s' % node
['line']
2752 self
.out
.append('\n\n{\color{red}%s/%s} in \\texttt{%s}%s\n' %
2753 (node
['type'], node
['level'],
2754 self
.encode(node
['source']), line
))
2755 if len(node
['backrefs']) == 1:
2756 self
.out
.append('\n\\hyperlink{%s}{' % node
['backrefs'][0])
2757 self
.context
.append('}')
2759 backrefs
= ['\\hyperlink{%s}{%d}' % (href
, i
+1)
2760 for (i
, href
) in enumerate(node
['backrefs'])]
2761 self
.context
.append('backrefs: ' + ' '.join(backrefs
))
2763 def depart_system_message(self
, node
):
2764 self
.out
.append(self
.context
.pop())
2765 self
.depart_admonition()
2767 def visit_table(self
, node
):
2768 self
.requirements
['table'] = PreambleCmds
.table
2769 if self
.active_table
.is_open():
2770 self
.table_stack
.append(self
.active_table
)
2771 # nesting longtable does not work (e.g. 2007-04-18)
2772 self
.active_table
= Table(self
,'tabular',self
.settings
.table_style
)
2773 # A longtable moves before \paragraph and \subparagraph
2774 # section titles if it immediately follows them:
2775 if (self
.active_table
._latex
_type
== 'longtable' and
2776 isinstance(node
.parent
, nodes
.section
) and
2777 node
.parent
.index(node
) == 1 and
2778 self
.d_class
.section(self
.section_level
).find('paragraph') != -1):
2779 self
.out
.append('\\leavevmode')
2780 self
.active_table
.open()
2781 for cls
in node
['classes']:
2782 self
.active_table
.set_table_style(cls
)
2783 if self
.active_table
._table
_style
== 'booktabs':
2784 self
.requirements
['booktabs'] = r
'\usepackage{booktabs}'
2785 self
.push_output_collector([])
2787 def depart_table(self
, node
):
2788 # wrap content in the right environment:
2790 self
.pop_output_collector()
2791 self
.out
.append('\n' + self
.active_table
.get_opening())
2793 self
.out
.append(self
.active_table
.get_closing() + '\n')
2794 self
.active_table
.close()
2795 if len(self
.table_stack
)>0:
2796 self
.active_table
= self
.table_stack
.pop()
2798 self
.active_table
.set_table_style(self
.settings
.table_style
)
2799 # Insert hyperlabel after (long)table, as
2800 # other places (beginning, caption) result in LaTeX errors.
2802 self
.out
+= self
.ids_to_labels(node
, set_anchor
=False) + ['\n']
2804 def visit_target(self
, node
):
2805 # Skip indirect targets:
2806 if ('refuri' in node
# external hyperlink
2807 or 'refid' in node
# resolved internal link
2808 or 'refname' in node
): # unresolved internal link
2809 ## self.out.append('%% %s\n' % node) # for debugging
2811 self
.out
.append('%\n')
2812 # do we need an anchor (\phantomsection)?
2813 set_anchor
= not(isinstance(node
.parent
, nodes
.caption
) or
2814 isinstance(node
.parent
, nodes
.title
))
2815 # TODO: where else can/must we omit the \phantomsection?
2816 self
.out
+= self
.ids_to_labels(node
, set_anchor
)
2818 def depart_target(self
, node
):
2821 def visit_tbody(self
, node
):
2822 # BUG write preamble if not yet done (colspecs not [])
2823 # for tables without heads.
2824 if not self
.active_table
.get('preamble written'):
2825 self
.visit_thead(None)
2826 self
.depart_thead(None)
2828 def depart_tbody(self
, node
):
2831 def visit_term(self
, node
):
2832 """definition list term"""
2833 # Commands with optional args inside an optional arg must be put
2834 # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
2835 self
.out
.append('\\item[{')
2837 def depart_term(self
, node
):
2838 # \leavevmode results in a line break if the
2839 # term is followed by an item list.
2840 self
.out
.append('}] \leavevmode ')
2842 def visit_tgroup(self
, node
):
2843 #self.out.append(self.starttag(node, 'colgroup'))
2844 #self.context.append('</colgroup>\n')
2847 def depart_tgroup(self
, node
):
2851 def thead_depth (self
):
2852 return self
._thead
_depth
2854 def visit_thead(self
, node
):
2855 self
._thead
_depth
+= 1
2856 if 1 == self
.thead_depth():
2857 self
.out
.append('{%s}\n' % self
.active_table
.get_colspecs())
2858 self
.active_table
.set('preamble written',1)
2859 self
.out
.append(self
.active_table
.get_caption())
2860 self
.out
.extend(self
.active_table
.visit_thead())
2862 def depart_thead(self
, node
):
2863 if node
is not None:
2864 self
.out
.extend(self
.active_table
.depart_thead())
2865 if self
.active_table
.need_recurse():
2866 node
.walkabout(self
)
2867 self
._thead
_depth
-= 1
2869 def visit_title(self
, node
):
2870 """Append section and other titles."""
2872 if node
.parent
.tagname
== 'document':
2873 self
.push_output_collector(self
.title
)
2874 self
.context
.append('')
2875 self
.pdfinfo
.append(' pdftitle={%s},' %
2876 self
.encode(node
.astext()))
2877 # Topic titles (topic, admonition, sidebar)
2878 elif (isinstance(node
.parent
, nodes
.topic
) or
2879 isinstance(node
.parent
, nodes
.admonition
) or
2880 isinstance(node
.parent
, nodes
.sidebar
)):
2881 self
.fallbacks
['title'] = PreambleCmds
.title
2882 classes
= ','.join(node
.parent
['classes'])
2884 classes
= node
.tagname
2885 self
.out
.append('\\DUtitle[%s]{' % classes
)
2886 self
.context
.append('}\n')
2888 elif isinstance(node
.parent
, nodes
.table
):
2889 self
.push_output_collector(self
.active_table
.caption
)
2890 self
.context
.append('')
2893 if hasattr(PreambleCmds
, 'secnumdepth'):
2894 self
.requirements
['secnumdepth'] = PreambleCmds
.secnumdepth
2895 section_name
= self
.d_class
.section(self
.section_level
)
2896 self
.out
.append('\n\n')
2897 # System messages heading in red:
2898 if ('system-messages' in node
.parent
['classes']):
2899 self
.requirements
['color'] = PreambleCmds
.color
2900 section_title
= self
.encode(node
.astext())
2901 self
.out
.append(r
'\%s[%s]{\color{red}' % (
2902 section_name
,section_title
))
2904 self
.out
.append(r
'\%s{' % section_name
)
2905 if self
.section_level
> len(self
.d_class
.sections
):
2906 # section level not supported by LaTeX
2907 self
.fallbacks
['title'] = PreambleCmds
.title
2908 # self.out.append('\\phantomsection%\n ')
2909 # label and ToC entry:
2911 # add sections with unsupported level to toc and pdfbookmarks?
2912 ## if self.section_level > len(self.d_class.sections):
2913 ## section_title = self.encode(node.astext())
2914 ## bookmark.append(r'\addcontentsline{toc}{%s}{%s}' %
2915 ## (section_name, section_title))
2916 bookmark
+= self
.ids_to_labels(node
.parent
, set_anchor
=False)
2917 self
.context
.append('%\n '.join(bookmark
) + '%\n}\n')
2919 # MAYBE postfix paragraph and subparagraph with \leavemode to
2920 # ensure floats stay in the section and text starts on a new line.
2922 def depart_title(self
, node
):
2923 self
.out
.append(self
.context
.pop())
2924 if (isinstance(node
.parent
, nodes
.table
) or
2925 node
.parent
.tagname
== 'document'):
2926 self
.pop_output_collector()
2928 def minitoc(self
, node
, title
, depth
):
2929 """Generate a local table of contents with LaTeX package minitoc"""
2930 section_name
= self
.d_class
.section(self
.section_level
)
2931 # name-prefix for current section level
2932 minitoc_names
= {'part': 'part', 'chapter': 'mini'}
2933 if 'chapter' not in self
.d_class
.sections
:
2934 minitoc_names
['section'] = 'sect'
2936 minitoc_name
= minitoc_names
[section_name
]
2937 except KeyError: # minitoc only supports part- and toplevel
2938 self
.warn('Skipping local ToC at %s level.\n' % section_name
+
2939 ' Feature not supported with option "use-latex-toc"',
2942 # Requirements/Setup
2943 self
.requirements
['minitoc'] = PreambleCmds
.minitoc
2944 self
.requirements
['minitoc-'+minitoc_name
] = (r
'\do%stoc' %
2946 # depth: (Docutils defaults to unlimited depth)
2947 maxdepth
= len(self
.d_class
.sections
)
2948 self
.requirements
['minitoc-%s-depth' % minitoc_name
] = (
2949 r
'\mtcsetdepth{%stoc}{%d}' % (minitoc_name
, maxdepth
))
2950 # Process 'depth' argument (!Docutils stores a relative depth while
2951 # minitoc expects an absolute depth!):
2952 offset
= {'sect': 1, 'mini': 0, 'part': 0}
2953 if 'chapter' in self
.d_class
.sections
:
2956 self
.out
.append('\\setcounter{%stocdepth}{%d}' %
2957 (minitoc_name
, depth
+ offset
[minitoc_name
]))
2959 self
.out
.append('\\mtcsettitle{%stoc}{%s}\n' % (minitoc_name
, title
))
2960 # the toc-generating command:
2961 self
.out
.append('\\%stoc\n' % minitoc_name
)
2963 def visit_topic(self
, node
):
2964 # Topic nodes can be generic topic, abstract, dedication, or ToC.
2965 # table of contents:
2966 if 'contents' in node
['classes']:
2967 self
.out
.append('\n')
2968 self
.out
+= self
.ids_to_labels(node
)
2969 # add contents to PDF bookmarks sidebar
2970 if isinstance(node
.next_node(), nodes
.title
):
2971 self
.out
.append('\n\\pdfbookmark[%d]{%s}{%s}\n' %
2972 (self
.section_level
+1,
2973 node
.next_node().astext(),
2974 node
.get('ids', ['contents'])[0]
2976 if self
.use_latex_toc
:
2978 if isinstance(node
.next_node(), nodes
.title
):
2979 title
= self
.encode(node
.pop(0).astext())
2980 depth
= node
.get('depth', 0)
2981 if 'local' in node
['classes']:
2982 self
.minitoc(node
, title
, depth
)
2983 self
.context
.append('')
2986 self
.out
.append('\\setcounter{tocdepth}{%d}\n' % depth
)
2987 if title
!= 'Contents':
2988 self
.out
.append('\\renewcommand{\\contentsname}{%s}\n' %
2990 self
.out
.append('\\tableofcontents\n\n')
2991 self
.has_latex_toc
= True
2992 else: # Docutils generated contents list
2993 # set flag for visit_bullet_list() and visit_title()
2994 self
.is_toc_list
= True
2995 self
.context
.append('')
2996 elif ('abstract' in node
['classes'] and
2997 self
.settings
.use_latex_abstract
):
2998 self
.push_output_collector(self
.abstract
)
2999 self
.out
.append('\\begin{abstract}')
3000 self
.context
.append('\\end{abstract}\n')
3001 if isinstance(node
.next_node(), nodes
.title
):
3002 node
.pop(0) # LaTeX provides its own title
3004 self
.fallbacks
['topic'] = PreambleCmds
.topic
3006 if 'abstract' in node
['classes']:
3007 self
.fallbacks
['abstract'] = PreambleCmds
.abstract
3008 self
.push_output_collector(self
.abstract
)
3009 if 'dedication' in node
['classes']:
3010 self
.fallbacks
['dedication'] = PreambleCmds
.dedication
3011 self
.push_output_collector(self
.dedication
)
3012 self
.out
.append('\n\\DUtopic[%s]{\n' % ','.join(node
['classes']))
3013 self
.context
.append('}\n')
3015 def depart_topic(self
, node
):
3016 self
.out
.append(self
.context
.pop())
3017 self
.is_toc_list
= False
3018 if ('abstract' in node
['classes'] or
3019 'dedication' in node
['classes']):
3020 self
.pop_output_collector()
3022 def visit_rubric(self
, node
):
3023 self
.fallbacks
['rubric'] = PreambleCmds
.rubric
3024 self
.out
.append('\n\\DUrubric{')
3025 self
.context
.append('}\n')
3027 def depart_rubric(self
, node
):
3028 self
.out
.append(self
.context
.pop())
3030 def visit_transition(self
, node
):
3031 self
.fallbacks
['transition'] = PreambleCmds
.transition
3032 self
.out
.append('\n\n')
3033 self
.out
.append('%' + '_' * 75 + '\n')
3034 self
.out
.append(r
'\DUtransition')
3035 self
.out
.append('\n\n')
3037 def depart_transition(self
, node
):
3040 def visit_version(self
, node
):
3041 self
.visit_docinfo_item(node
, 'version')
3043 def depart_version(self
, node
):
3044 self
.depart_docinfo_item(node
)
3046 def unimplemented_visit(self
, node
):
3047 raise NotImplementedError('visiting unimplemented node type: %s' %
3048 node
.__class
__.__name
__)
3050 # def unknown_visit(self, node):
3051 # def default_visit(self, node):
3053 # vim: set ts=4 et ai :