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[,file,...]>',
91 'overrides': 'stylesheet_path',
92 'validator': frontend
.validate_comma_separated_list
}),
93 ('Comma separated list of LaTeX packages/stylesheets. '
94 'Relative paths are expanded if a matching file is found in '
95 'the --stylesheet-dirs. With --link-stylesheet, '
96 'the path is rewritten relative to the output *.tex file. ',
97 ['--stylesheet-path'],
98 {'metavar': '<file[,file,...]>', 'overrides': 'stylesheet',
99 'validator': frontend
.validate_comma_separated_list
}),
100 ('Link to the stylesheet(s) in the output file. (default)',
101 ['--link-stylesheet'],
102 {'dest': 'embed_stylesheet', 'action': 'store_false'}),
103 ('Embed the stylesheet(s) in the output file. '
104 'Stylesheets must be accessible during processing. ',
105 ['--embed-stylesheet'],
106 {'default': 0, 'action': 'store_true',
107 'validator': frontend
.validate_boolean
}),
108 ('Comma-separated list of directories where stylesheets are found. '
109 'Used by --stylesheet-path when expanding relative path arguments. '
111 ['--stylesheet-dirs'],
112 {'metavar': '<dir[,dir,...]>',
113 'validator': frontend
.validate_comma_separated_list
,
115 ('Customization by LaTeX code in the preamble. '
116 'Default: select PDF standard fonts (Times, Helvetica, Courier).',
117 ['--latex-preamble'],
118 {'default': default_preamble
}),
119 ('Specify the template file. Default: "%s".' % default_template
,
121 {'default': default_template
, 'metavar': '<file>'}),
122 ('Table of contents by LaTeX. (default) ',
124 {'default': 1, 'action': 'store_true',
125 'validator': frontend
.validate_boolean
}),
126 ('Table of contents by Docutils (without page numbers). ',
127 ['--use-docutils-toc'],
128 {'dest': 'use_latex_toc', 'action': 'store_false',
129 'validator': frontend
.validate_boolean
}),
130 ('Add parts on top of the section hierarchy.',
131 ['--use-part-section'],
132 {'default': 0, 'action': 'store_true',
133 'validator': frontend
.validate_boolean
}),
134 ('Attach author and date to the document info table. (default) ',
135 ['--use-docutils-docinfo'],
136 {'dest': 'use_latex_docinfo', 'action': 'store_false',
137 'validator': frontend
.validate_boolean
}),
138 ('Attach author and date to the document title.',
139 ['--use-latex-docinfo'],
140 {'default': 0, 'action': 'store_true',
141 'validator': frontend
.validate_boolean
}),
142 ("Typeset abstract as topic. (default)",
143 ['--topic-abstract'],
144 {'dest': 'use_latex_abstract', 'action': 'store_false',
145 'validator': frontend
.validate_boolean
}),
146 ("Use LaTeX abstract environment for the document's abstract. ",
147 ['--use-latex-abstract'],
148 {'default': 0, 'action': 'store_true',
149 'validator': frontend
.validate_boolean
}),
150 ('Color of any hyperlinks embedded in text '
151 '(default: "blue", "false" to disable).',
152 ['--hyperlink-color'], {'default': 'blue'}),
153 ('Additional options to the "hyperref" package '
155 ['--hyperref-options'], {'default': ''}),
156 ('Enable compound enumerators for nested enumerated lists '
157 '(e.g. "1.2.a.ii"). Default: disabled.',
158 ['--compound-enumerators'],
159 {'default': None, 'action': 'store_true',
160 'validator': frontend
.validate_boolean
}),
161 ('Disable compound enumerators for nested enumerated lists. '
162 'This is the default.',
163 ['--no-compound-enumerators'],
164 {'action': 'store_false', 'dest': 'compound_enumerators'}),
165 ('Enable section ("." subsection ...) prefixes for compound '
166 'enumerators. This has no effect without --compound-enumerators.'
167 'Default: disabled.',
168 ['--section-prefix-for-enumerators'],
169 {'default': None, 'action': 'store_true',
170 'validator': frontend
.validate_boolean
}),
171 ('Disable section prefixes for compound enumerators. '
172 'This is the default.',
173 ['--no-section-prefix-for-enumerators'],
174 {'action': 'store_false', 'dest': 'section_prefix_for_enumerators'}),
175 ('Set the separator between section number and enumerator '
176 'for compound enumerated lists. Default is "-".',
177 ['--section-enumerator-separator'],
178 {'default': '-', 'metavar': '<char>'}),
179 ('When possibile, use the specified environment for literal-blocks. '
180 'Default is quoting of whitespace and special chars.',
181 ['--literal-block-env'],
183 ('When possibile, use verbatim for literal-blocks. '
184 'Compatibility alias for "--literal-block-env=verbatim".',
185 ['--use-verbatim-when-possible'],
186 {'default': 0, 'action': 'store_true',
187 'validator': frontend
.validate_boolean
}),
188 ('Table style. "standard" with horizontal and vertical lines, '
189 '"booktabs" (LaTeX booktabs style) only horizontal lines '
190 'above and below the table and below the header or "borderless". '
191 'Default: "standard"',
193 {'choices': ['standard', 'booktabs','nolines', 'borderless'],
194 'default': 'standard',
195 'metavar': '<format>'}),
196 ('LaTeX graphicx package option. '
197 'Possible values are "dvips", "pdftex". "auto" includes LaTeX code '
198 'to use "pdftex" if processing with pdf(la)tex and dvips otherwise. '
199 'Default is no option.',
200 ['--graphicx-option'],
202 ('LaTeX font encoding. '
203 'Possible values are "", "T1" (default), "OT1", "LGR,T1" or '
204 'any other combination of options to the `fontenc` package. ',
207 ('Per default the latex-writer puts the reference title into '
208 'hyperreferences. Specify "ref*" or "pageref*" to get the section '
209 'number or the page number.',
210 ['--reference-label'],
211 {'default': None, }),
212 ('Specify style and database for bibtex, for example '
213 '"--use-bibtex=mystyle,mydb1,mydb2".',
215 {'default': None, }),
218 settings_defaults
= {'sectnum_depth': 0 # updated by SectNum transform
220 relative_path_settings
= ('stylesheet_path',)
222 config_section
= 'latex2e writer'
223 config_section_dependencies
= ('writers',)
225 head_parts
= ('head_prefix', 'requirements', 'latex_preamble',
226 'stylesheet', 'fallbacks', 'pdfsetup',
227 'title', 'subtitle', 'titledata')
228 visitor_attributes
= head_parts
+ ('body_pre_docinfo', 'docinfo',
229 'dedication', 'abstract', 'body')
232 """Final translated form of `document`."""
235 writers
.Writer
.__init
__(self
)
236 self
.translator_class
= LaTeXTranslator
238 # Override parent method to add latex-specific transforms
239 def get_transforms(self
):
240 return writers
.Writer
.get_transforms(self
) + [
241 # Convert specific admonitions to generic one
242 writer_aux
.Admonitions
,
243 # TODO: footnote collection transform
247 visitor
= self
.translator_class(self
.document
)
248 self
.document
.walkabout(visitor
)
250 for part
in self
.visitor_attributes
:
251 setattr(self
, part
, getattr(visitor
, part
))
252 # get template string from file
254 template_file
= open(self
.document
.settings
.template
, 'rb')
256 template_file
= open(os
.path
.join(self
.default_template_path
,
257 self
.document
.settings
.template
), 'rb')
258 template
= string
.Template(unicode(template_file
.read(), 'utf-8'))
259 template_file
.close()
261 self
.assemble_parts() # create dictionary of parts
262 self
.output
= template
.substitute(self
.parts
)
264 def assemble_parts(self
):
265 """Assemble the `self.parts` dictionary of output fragments."""
266 writers
.Writer
.assemble_parts(self
)
267 for part
in self
.visitor_attributes
:
268 lines
= getattr(self
, part
)
269 if part
in self
.head_parts
:
271 lines
.append('') # to get a trailing newline
272 self
.parts
[part
] = '\n'.join(lines
)
274 # body contains inline elements, so join without newline
275 self
.parts
[part
] = ''.join(lines
)
279 """Language specifics for LaTeX."""
281 # TeX (babel) language names:
282 # ! not all of these are supported by Docutils!
284 # based on LyX' languages file with adaptions to `BCP 47`_
285 # (http://www.rfc-editor.org/rfc/bcp/bcp47.txt) and
286 # http://www.tug.org/TUGboat/Articles/tb29-3/tb93miklavec.pdf
287 # * the key without subtags is the default
289 # cf. http://docutils.sourceforge.net/docs/howto/i18n.html
290 # http://www.w3.org/International/articles/language-tags/
291 # and http://www.iana.org/assignments/language-subtag-registry
293 # code TeX/Babel-name comment
296 # 'be': 'belarusian',
304 'de': 'ngerman', # new spelling (de_1996)
305 'de-1901': 'german', # old spelling
306 'de-AT': 'naustrian',
307 'de-AT-1901': 'austrian',
308 'dsb': 'lowersorbian',
309 'el': 'greek', # monotonic (el-monoton)
310 'el-polyton': 'polutonikogreek',
311 'en': 'english', # TeX' default language
312 'en-AU': 'australian',
315 'en-NZ': 'newzealand',
325 'ga': 'irish', # Irish Gaelic
326 # 'grc': # Ancient Greek
327 'grc-ibycus': 'ibycus', # Ibycus encoding
331 'hsb': 'uppersorbian',
334 'id': 'bahasai', # Bahasa (Indonesian)
342 'mn': 'mongolian', # Mongolian, Cyrillic script (mn-cyrl)
343 'ms': 'bahasam', # Bahasa (Malay)
344 'nb': 'norsk', # Norwegian Bokmal
346 'nn': 'nynorsk', # Norwegian Nynorsk
347 'no': 'norsk', # Norwegian (Bokmal)
353 'se': 'samin', # North Sami
354 # sh-Cyrl: Serbo-Croatian, Cyrillic script
355 'sh-Latn': 'serbian', # Serbo-Croatian, Latin script
359 # 'sr-Cyrl': Serbian, Cyrillic script (sr-cyrl)
360 'sr-Latn': 'serbian', # Serbian, Latin script
366 # zh-Latn: Chinese Pinyin
368 # normalize (downcase) keys
369 language_codes
= dict([(k
.lower(), v
) for (k
,v
) in language_codes
.items()])
371 warn_msg
= 'Language "%s" not supported by LaTeX (babel)'
373 # "Active characters" are shortcuts that start a LaTeX macro and may need
374 # escaping for literals use. Characters that prevent literal use (e.g.
375 # starting accent macros like "a -> ä) will be deactivated if one of the
376 # defining languages is used in the document.
378 # ~ (tilde) -- used in estonian, basque, galician, and old versions of
379 # spanish -- cannot be deactivated as it denotes a no-break space macro,
380 # " (straight quote) -- used in albanian, austrian, basque
381 # brazil, bulgarian, catalan, czech, danish, dutch, estonian,
382 # finnish, galician, german, icelandic, italian, latin, naustrian,
383 # ngerman, norsk, nynorsk, polish, portuges, russian, serbian, slovak,
384 # slovene, spanish, swedish, ukrainian, and uppersorbian --
385 # is escaped as ``\textquotedbl``.
386 active_chars
= {# TeX/Babel-name: active characters to deactivate
387 # 'breton': ':;!?' # ensure whitespace
390 # 'french': ':;!?' # ensure whitespace
391 'galician': '.<>', # also '~"'
392 # 'magyar': '`', # for special hyphenation cases
393 'spanish': '.<>', # old versions also '~'
394 # 'turkish': ':!=' # ensure whitespace
397 def __init__(self
, language_code
, reporter
=None):
398 self
.reporter
= reporter
399 self
.language
= self
.language_name(language_code
)
400 self
.otherlanguages
= {}
403 """Return the babel call with correct options and settings"""
404 languages
= sorted(self
.otherlanguages
.keys())
405 languages
.append(self
.language
or 'english')
406 self
.setup
= [r
'\usepackage[%s]{babel}' % ','.join(languages
)]
407 # Deactivate "active characters"
409 for c
in ''.join([self
.active_chars
.get(l
, '') for l
in languages
]):
410 if c
not in shorthands
:
413 self
.setup
.append(r
'\AtBeginDocument{\shorthandoff{%s}}'
414 % ''.join(shorthands
))
415 # Including '~' in shorthandoff prevents its use as no-break space
416 if 'galician' in languages
:
417 self
.setup
.append(r
'\deactivatetilden % restore ~ in Galician')
418 if 'estonian' in languages
:
419 self
.setup
.extend([r
'\makeatletter',
420 r
' \addto\extrasestonian{\bbl@deactivate{~}}',
422 if 'basque' in languages
:
423 self
.setup
.extend([r
'\makeatletter',
424 r
' \addto\extrasbasque{\bbl@deactivate{~}}',
426 if (languages
[-1] == 'english' and
427 'french' in self
.otherlanguages
.keys()):
428 self
.setup
+= ['% Prevent side-effects if French hyphenation '
429 'patterns are not loaded:',
430 r
'\frenchbsetup{StandardLayout}',
431 r
'\AtBeginDocument{\selectlanguage{%s}'
432 r
'\noextrasfrench}' % self
.language
]
433 return '\n'.join(self
.setup
)
435 def language_name(self
, language_code
):
436 """Return TeX language name for `language_code`"""
437 for tag
in utils
.normalize_language_tag(language_code
):
439 return self
.language_codes
[tag
]
442 if self
.reporter
is not None:
443 self
.reporter
.warning(self
.warn_msg
% language_code
)
446 def get_language(self
):
447 # Obsolete, kept for backwards compatibility with Sphinx
451 # Building blocks for the latex preamble
452 # --------------------------------------
454 class SortableDict(dict):
455 """Dictionary with additional sorting methods
457 Tip: use key starting with with '_' for sorting before small letters
458 and with '~' for sorting after small letters.
460 def sortedkeys(self
):
461 """Return sorted list of keys"""
466 def sortedvalues(self
):
467 """Return list of values sorted by keys"""
468 return [self
[key
] for key
in self
.sortedkeys()]
473 # A container for LaTeX code snippets that can be
474 # inserted into the preamble if required in the document.
476 # .. The package 'makecmds' would enable shorter definitions using the
477 # \providelength and \provideenvironment commands.
478 # However, it is pretty non-standard (texlive-latex-extra).
480 class PreambleCmds(object):
481 """Building blocks for the latex preamble."""
483 PreambleCmds
.abstract
= r
"""
485 \providecommand*{\DUtitleabstract}[1]{\centerline{\textbf{#1}}}"""
487 PreambleCmds
.admonition
= r
"""
488 % admonition (specially marked topic)
489 \providecommand{\DUadmonition}[2][class-arg]{%
490 % try \DUadmonition#1{#2}:
491 \ifcsname DUadmonition#1\endcsname%
492 \csname DUadmonition#1\endcsname{#2}%
495 \fbox{\parbox{0.9\textwidth}{#2}}
500 PreambleCmds
.align_center
= r
"""
502 \@namedef{DUrolealign-center}{\centering}
506 ## PreambleCmds.caption = r"""% configure caption layout
507 ## \usepackage{caption}
508 ## \captionsetup{singlelinecheck=false}% no exceptions for one-liners"""
510 PreambleCmds
.color
= r
"""\usepackage{color}"""
512 PreambleCmds
.docinfo
= r
"""
513 % docinfo (width of docinfo table)
514 \DUprovidelength{\DUdocinfowidth}{0.9\textwidth}"""
515 # PreambleCmds.docinfo._depends = 'providelength'
517 PreambleCmds
.dedication
= r
"""
519 \providecommand{\DUtopicdedication}[1]{\begin{center}#1\end{center}}"""
521 PreambleCmds
.error
= r
"""
522 % error admonition title
523 \providecommand*{\DUtitleerror}[1]{\DUtitle{\color{red}#1}}"""
524 # PreambleCmds.errortitle._depends = 'color'
526 PreambleCmds
.fieldlist
= r
"""
527 % fieldlist environment
528 \ifthenelse{\isundefined{\DUfieldlist}}{
529 \newenvironment{DUfieldlist}%
531 {\enddescription\endquote}
534 PreambleCmds
.float_settings
= r
"""\usepackage{float} % float configuration
535 \floatplacement{figure}{H} % place figures here definitely"""
537 PreambleCmds
.footnotes
= r
"""% numeric or symbol footnotes with hyperlinks
538 \providecommand*{\DUfootnotemark}[3]{%
539 \raisebox{1em}{\hypertarget{#1}{}}%
540 \hyperlink{#2}{\textsuperscript{#3}}%
542 \providecommand{\DUfootnotetext}[4]{%
544 \renewcommand{\thefootnote}{%
545 \protect\raisebox{1em}{\protect\hypertarget{#1}{}}%
546 \protect\hyperlink{#2}{#3}}%
551 PreambleCmds
.footnote_floats
= r
"""% settings for footnotes as floats:
552 \setlength{\floatsep}{0.5em}
553 \setlength{\textfloatsep}{\fill}
554 \addtolength{\textfloatsep}{3em}
555 \renewcommand{\textfraction}{0.5}
556 \renewcommand{\topfraction}{0.5}
557 \renewcommand{\bottomfraction}{0.5}
558 \setcounter{totalnumber}{50}
559 \setcounter{topnumber}{50}
560 \setcounter{bottomnumber}{50}"""
562 PreambleCmds
.graphicx_auto
= r
"""% Check output format
563 \ifx\pdftexversion\undefined
564 \usepackage{graphicx}
566 \usepackage[pdftex]{graphicx}
569 PreambleCmds
.highlight_rules
= r
"""% basic code highlight:
570 \providecommand*\DUrolecomment[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
571 \providecommand*\DUroledeleted[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
572 \providecommand*\DUrolekeyword[1]{\textbf{#1}}
573 \providecommand*\DUrolestring[1]{\textit{#1}}"""
575 PreambleCmds
.inline
= r
"""
576 % inline markup (custom roles)
577 % \DUrole{#1}{#2} tries \DUrole#1{#2}
578 \providecommand*{\DUrole}[2]{%
579 \ifcsname DUrole#1\endcsname%
580 \csname DUrole#1\endcsname{#2}%
581 \else% backwards compatibility: try \docutilsrole#1{#2}
582 \ifcsname docutilsrole#1\endcsname%
583 \csname docutilsrole#1\endcsname{#2}%
590 PreambleCmds
.legend
= r
"""
592 \ifthenelse{\isundefined{\DUlegend}}{
593 \newenvironment{DUlegend}{\small}{}
596 PreambleCmds
.lineblock
= r
"""
597 % lineblock environment
598 \DUprovidelength{\DUlineblockindent}{2.5em}
599 \ifthenelse{\isundefined{\DUlineblock}}{
600 \newenvironment{DUlineblock}[1]{%
601 \list{}{\setlength{\partopsep}{\parskip}
602 \addtolength{\partopsep}{\baselineskip}
603 \setlength{\topsep}{0pt}
604 \setlength{\itemsep}{0.15\baselineskip}
605 \setlength{\parsep}{0pt}
606 \setlength{\leftmargin}{#1}}
611 # PreambleCmds.lineblock._depends = 'providelength'
613 PreambleCmds
.linking
= r
"""
615 \ifthenelse{\isundefined{\hypersetup}}{
616 \usepackage[%s]{hyperref}
617 \urlstyle{same} %% normal text font (alternatives: tt, rm, sf)
620 PreambleCmds
.minitoc
= r
"""%% local table of contents
621 \usepackage{minitoc}"""
623 PreambleCmds
.optionlist
= r
"""
624 % optionlist environment
625 \providecommand*{\DUoptionlistlabel}[1]{\bf #1 \hfill}
626 \DUprovidelength{\DUoptionlistindent}{3cm}
627 \ifthenelse{\isundefined{\DUoptionlist}}{
628 \newenvironment{DUoptionlist}{%
629 \list{}{\setlength{\labelwidth}{\DUoptionlistindent}
630 \setlength{\rightmargin}{1cm}
631 \setlength{\leftmargin}{\rightmargin}
632 \addtolength{\leftmargin}{\labelwidth}
633 \addtolength{\leftmargin}{\labelsep}
634 \renewcommand{\makelabel}{\DUoptionlistlabel}}
638 # PreambleCmds.optionlist._depends = 'providelength'
640 PreambleCmds
.providelength
= r
"""
641 % providelength (provide a length variable and set default, if it is new)
642 \providecommand*{\DUprovidelength}[2]{
643 \ifthenelse{\isundefined{#1}}{\newlength{#1}\setlength{#1}{#2}}{}
646 PreambleCmds
.rubric
= r
"""
647 % rubric (informal heading)
648 \providecommand*{\DUrubric}[2][class-arg]{%
649 \subsubsection*{\centering\textit{\textmd{#2}}}}"""
651 PreambleCmds
.sidebar
= r
"""
652 % sidebar (text outside the main text flow)
653 \providecommand{\DUsidebar}[2][class-arg]{%
655 \colorbox[gray]{0.80}{\parbox{0.9\textwidth}{#2}}
659 PreambleCmds
.subtitle
= r
"""
660 % subtitle (for topic/sidebar)
661 \providecommand*{\DUsubtitle}[2][class-arg]{\par\emph{#2}\smallskip}"""
663 PreambleCmds
.table
= r
"""\usepackage{longtable,ltcaption,array}
664 \setlength{\extrarowheight}{2pt}
665 \newlength{\DUtablewidth} % internal use in tables"""
667 # Options [force,almostfull] prevent spurious error messages, see
668 # de.comp.text.tex/2005-12/msg01855
669 PreambleCmds
.textcomp
= """\
670 \\usepackage{textcomp} % text symbol macros"""
672 PreambleCmds
.titlereference
= r
"""
673 % titlereference role
674 \providecommand*{\DUroletitlereference}[1]{\textsl{#1}}"""
676 PreambleCmds
.title
= r
"""
677 % title for topics, admonitions, unsupported section levels, and sidebar
678 \providecommand*{\DUtitle}[2][class-arg]{%
679 % call \DUtitle#1{#2} if it exists:
680 \ifcsname DUtitle#1\endcsname%
681 \csname DUtitle#1\endcsname{#2}%
683 \smallskip\noindent\textbf{#2}\smallskip%
687 PreambleCmds
.topic
= r
"""
688 % topic (quote with heading)
689 \providecommand{\DUtopic}[2][class-arg]{%
690 \ifcsname DUtopic#1\endcsname%
691 \csname DUtopic#1\endcsname{#2}%
693 \begin{quote}#2\end{quote}
697 PreambleCmds
.transition
= r
"""
698 % transition (break, fancybreak, anonymous section)
699 \providecommand*{\DUtransition}[1][class-arg]{%
700 \hspace*{\fill}\hrulefill\hspace*{\fill}
701 \vskip 0.5\baselineskip
705 # LaTeX encoding maps
706 # -------------------
709 class CharMaps(object):
710 """LaTeX representations for active and Unicode characters."""
712 # characters that always need escaping:
718 ord('~'): ur
'\textasciitilde{}',
720 ord('^'): ur
'\textasciicircum{}',
721 ord('\\'): ur
'\textbackslash{}',
724 # straight double quotes are 'active' in many languages
725 ord('"'): ur
'\textquotedbl{}',
726 # Square brackets are ordinary chars and cannot be escaped with '\',
727 # so we put them in a group '{[}'. (Alternative: ensure that all
728 # macros with optional arguments are terminated with {} and text
729 # inside any optional argument is put in a group ``[{text}]``).
730 # Commands with optional args inside an optional arg must be put in a
731 # group, e.g. ``\item[{\hyperref[label]{text}}]``.
734 # the soft hyphen is unknown in 8-bit text
735 # and not properly handled by XeTeX
736 0x00AD: ur
'\-', # SOFT HYPHEN
738 # Unicode chars that are not recognized by LaTeX's utf8 encoding
739 unsupported_unicode
= {
740 0x00A0: ur
'~', # NO-BREAK SPACE
741 # TODO: ensure white space also at the beginning of a line?
742 # 0x00A0: ur'\leavevmode\nobreak\vadjust{}~'
743 0x2008: ur
'\,', # PUNCTUATION SPACE
744 0x2011: ur
'\hbox{-}', # NON-BREAKING HYPHEN
745 0x202F: ur
'\,', # NARROW NO-BREAK SPACE
746 0x21d4: ur
'$\Leftrightarrow$',
747 # Docutils footnote symbols:
748 0x2660: ur
'$\spadesuit$',
749 0x2663: ur
'$\clubsuit$',
751 # Unicode chars that are recognized by LaTeX's utf8 encoding
752 utf8_supported_unicode
= {
753 0x00AB: ur
'\guillemotleft', # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
754 0x00bb: ur
'\guillemotright', # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
755 0x200C: ur
'\textcompwordmark', # ZERO WIDTH NON-JOINER
756 0x2013: ur
'\textendash{}',
757 0x2014: ur
'\textemdash{}',
758 0x2018: ur
'\textquoteleft{}',
759 0x2019: ur
'\textquoteright{}',
760 0x201A: ur
'\quotesinglbase{}', # SINGLE LOW-9 QUOTATION MARK
761 0x201C: ur
'\textquotedblleft{}',
762 0x201D: ur
'\textquotedblright{}',
763 0x201E: ur
'\quotedblbase{}', # DOUBLE LOW-9 QUOTATION MARK
764 0x2030: ur
'\textperthousand{}', # PER MILLE SIGN
765 0x2031: ur
'\textpertenthousand{}', # PER TEN THOUSAND SIGN
766 0x2039: ur
'\guilsinglleft{}',
767 0x203A: ur
'\guilsinglright{}',
768 0x2423: ur
'\textvisiblespace{}', # OPEN BOX
772 0x2122: ur
'\texttrademark{}',
774 # recognized with 'utf8', if textcomp is loaded
777 0x00a2: ur
'\textcent{}', # ¢ CENT SIGN
778 0x00a4: ur
'\textcurrency{}', # ¤ CURRENCY SYMBOL
779 0x00a5: ur
'\textyen{}', # ¥ YEN SIGN
780 0x00a6: ur
'\textbrokenbar{}', # ¦ BROKEN BAR
781 0x00a7: ur
'\textsection{}', # § SECTION SIGN
782 0x00a8: ur
'\textasciidieresis{}', # ¨ DIAERESIS
783 0x00a9: ur
'\textcopyright{}', # © COPYRIGHT SIGN
784 0x00aa: ur
'\textordfeminine{}', # ª FEMININE ORDINAL INDICATOR
785 0x00ac: ur
'\textlnot{}', # ¬ NOT SIGN
786 0x00ae: ur
'\textregistered{}', # ® REGISTERED SIGN
787 0x00af: ur
'\textasciimacron{}', # ¯ MACRON
788 0x00b0: ur
'\textdegree{}', # ° DEGREE SIGN
789 0x00b1: ur
'\textpm{}', # ± PLUS-MINUS SIGN
790 0x00b2: ur
'\texttwosuperior{}', # ² SUPERSCRIPT TWO
791 0x00b3: ur
'\textthreesuperior{}', # ³ SUPERSCRIPT THREE
792 0x00b4: ur
'\textasciiacute{}', # ´ ACUTE ACCENT
793 0x00b5: ur
'\textmu{}', # µ MICRO SIGN
794 0x00b6: ur
'\textparagraph{}', # ¶ PILCROW SIGN # != \textpilcrow
795 0x00b9: ur
'\textonesuperior{}', # ¹ SUPERSCRIPT ONE
796 0x00ba: ur
'\textordmasculine{}', # º MASCULINE ORDINAL INDICATOR
797 0x00bc: ur
'\textonequarter{}', # 1/4 FRACTION
798 0x00bd: ur
'\textonehalf{}', # 1/2 FRACTION
799 0x00be: ur
'\textthreequarters{}', # 3/4 FRACTION
800 0x00d7: ur
'\texttimes{}', # × MULTIPLICATION SIGN
801 0x00f7: ur
'\textdiv{}', # ÷ DIVISION SIGN
803 0x0192: ur
'\textflorin{}', # LATIN SMALL LETTER F WITH HOOK
804 0x02b9: ur
'\textasciiacute{}', # MODIFIER LETTER PRIME
805 0x02ba: ur
'\textacutedbl{}', # MODIFIER LETTER DOUBLE PRIME
806 0x2016: ur
'\textbardbl{}', # DOUBLE VERTICAL LINE
807 0x2022: ur
'\textbullet{}', # BULLET
808 0x2032: ur
'\textasciiacute{}', # PRIME
809 0x2033: ur
'\textacutedbl{}', # DOUBLE PRIME
810 0x2035: ur
'\textasciigrave{}', # REVERSED PRIME
811 0x2036: ur
'\textgravedbl{}', # REVERSED DOUBLE PRIME
812 0x203b: ur
'\textreferencemark{}', # REFERENCE MARK
813 0x203d: ur
'\textinterrobang{}', # INTERROBANG
814 0x2044: ur
'\textfractionsolidus{}', # FRACTION SLASH
815 0x2045: ur
'\textlquill{}', # LEFT SQUARE BRACKET WITH QUILL
816 0x2046: ur
'\textrquill{}', # RIGHT SQUARE BRACKET WITH QUILL
817 0x2052: ur
'\textdiscount{}', # COMMERCIAL MINUS SIGN
818 0x20a1: ur
'\textcolonmonetary{}', # COLON SIGN
819 0x20a3: ur
'\textfrenchfranc{}', # FRENCH FRANC SIGN
820 0x20a4: ur
'\textlira{}', # LIRA SIGN
821 0x20a6: ur
'\textnaira{}', # NAIRA SIGN
822 0x20a9: ur
'\textwon{}', # WON SIGN
823 0x20ab: ur
'\textdong{}', # DONG SIGN
824 0x20ac: ur
'\texteuro{}', # EURO SIGN
825 0x20b1: ur
'\textpeso{}', # PESO SIGN
826 0x20b2: ur
'\textguarani{}', # GUARANI SIGN
827 0x2103: ur
'\textcelsius{}', # DEGREE CELSIUS
828 0x2116: ur
'\textnumero{}', # NUMERO SIGN
829 0x2117: ur
'\textcircledP{}', # SOUND RECORDING COYRIGHT
830 0x211e: ur
'\textrecipe{}', # PRESCRIPTION TAKE
831 0x2120: ur
'\textservicemark{}', # SERVICE MARK
832 0x2122: ur
'\texttrademark{}', # TRADE MARK SIGN
833 0x2126: ur
'\textohm{}', # OHM SIGN
834 0x2127: ur
'\textmho{}', # INVERTED OHM SIGN
835 0x212e: ur
'\textestimated{}', # ESTIMATED SYMBOL
836 0x2190: ur
'\textleftarrow{}', # LEFTWARDS ARROW
837 0x2191: ur
'\textuparrow{}', # UPWARDS ARROW
838 0x2192: ur
'\textrightarrow{}', # RIGHTWARDS ARROW
839 0x2193: ur
'\textdownarrow{}', # DOWNWARDS ARROW
840 0x2212: ur
'\textminus{}', # MINUS SIGN
841 0x2217: ur
'\textasteriskcentered{}', # ASTERISK OPERATOR
842 0x221a: ur
'\textsurd{}', # SQUARE ROOT
843 0x2422: ur
'\textblank{}', # BLANK SYMBOL
844 0x25e6: ur
'\textopenbullet{}', # WHITE BULLET
845 0x25ef: ur
'\textbigcircle{}', # LARGE CIRCLE
846 0x266a: ur
'\textmusicalnote{}', # EIGHTH NOTE
847 0x26ad: ur
'\textmarried{}', # MARRIAGE SYMBOL
848 0x26ae: ur
'\textdivorced{}', # DIVORCE SYMBOL
849 0x27e8: ur
'\textlangle{}', # MATHEMATICAL LEFT ANGLE BRACKET
850 0x27e9: ur
'\textrangle{}', # MATHEMATICAL RIGHT ANGLE BRACKET
852 # Unicode chars that require a feature/package to render
854 0x2665: ur
'\ding{170}', # black heartsuit
855 0x2666: ur
'\ding{169}', # black diamondsuit
856 0x2713: ur
'\ding{51}', # check mark
857 0x2717: ur
'\ding{55}', # check mark
859 # TODO: greek alphabet ... ?
860 # see also LaTeX codec
861 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252124
862 # and unimap.py from TeXML
865 class DocumentClass(object):
866 """Details of a LaTeX document class."""
868 def __init__(self
, document_class
, with_part
=False):
869 self
.document_class
= document_class
870 self
._with
_part
= with_part
871 self
.sections
= ['section', 'subsection', 'subsubsection',
872 'paragraph', 'subparagraph']
873 if self
.document_class
in ('book', 'memoir', 'report',
874 'scrbook', 'scrreprt'):
875 self
.sections
.insert(0, 'chapter')
877 self
.sections
.insert(0, 'part')
879 def section(self
, level
):
880 """Return the LaTeX section name for section `level`.
882 The name depends on the specific document class.
883 Level is 1,2,3..., as level 0 is the title.
885 if level
<= len(self
.sections
):
886 return self
.sections
[level
-1]
887 else: # unsupported levels
888 return 'DUtitle[section%s]' % roman
.toRoman(level
)
891 """Manage a table while traversing.
893 Maybe change to a mixin defining the visit/departs, but then
894 class Table internal variables are in the Translator.
898 :standard: horizontal and vertical lines
899 :booktabs: only horizontal lines (requires "booktabs" LaTeX package)
900 :borderless: no borders around table cells
901 :nolines: alias for borderless
903 def __init__(self
,translator
,latex_type
,table_style
):
904 self
._translator
= translator
905 self
._latex
_type
= latex_type
906 self
._table
_style
= table_style
908 # miscellaneous attributes
920 self
._in
_head
= False # maybe context with search
923 self
._col
_specs
= None
930 def set_table_style(self
, table_style
):
931 if not table_style
in ('standard','booktabs','borderless','nolines'):
933 self
._table
_style
= table_style
935 def get_latex_type(self
):
936 if self
._latex
_type
== 'longtable' and not self
.caption
:
937 # do not advance the "table" counter (requires "ltcaption" package)
939 return self
._latex
_type
941 def set(self
,attr
,value
):
942 self
._attrs
[attr
] = value
944 if attr
in self
._attrs
:
945 return self
._attrs
[attr
]
948 def get_vertical_bar(self
):
949 if self
._table
_style
== 'standard':
953 # horizontal lines are drawn below a row,
954 def get_opening(self
):
955 return '\n'.join([r
'\setlength{\DUtablewidth}{\linewidth}',
956 r
'\begin{%s}[c]' % self
.get_latex_type()])
958 def get_closing(self
):
960 if self
._table
_style
== 'booktabs':
961 closing
.append(r
'\bottomrule')
962 # elif self._table_style == 'standard':
963 # closing.append(r'\hline')
964 closing
.append(r
'\end{%s}' % self
.get_latex_type())
965 return '\n'.join(closing
)
967 def visit_colspec(self
, node
):
968 self
._col
_specs
.append(node
)
969 # "stubs" list is an attribute of the tgroup element:
970 self
.stubs
.append(node
.attributes
.get('stub'))
972 def get_colspecs(self
):
973 """Return column specification for longtable.
975 Assumes reST line length being 80 characters.
976 Table width is hairy.
982 usually gets to narrow, therefore we add 1 (fiddlefactor).
987 # first see if we get too wide.
988 for node
in self
._col
_specs
:
989 colwidth
= float(node
['colwidth']+1) / width
990 total_width
+= colwidth
993 # donot make it full linewidth
995 if total_width
> 1.0:
996 factor
/= total_width
997 bar
= self
.get_vertical_bar()
998 latex_table_spec
= ''
999 for node
in self
._col
_specs
:
1000 colwidth
= factor
* float(node
['colwidth']+1) / width
1001 self
._col
_width
.append(colwidth
+0.005)
1002 self
._rowspan
.append(0)
1003 latex_table_spec
+= '%sp{%.3f\\DUtablewidth}' % (bar
, colwidth
+0.005)
1004 return latex_table_spec
+bar
1006 def get_column_width(self
):
1007 """Return columnwidth for current cell (not multicell)."""
1008 return '%.2f\\DUtablewidth' % self
._col
_width
[self
._cell
_in
_row
-1]
1010 def get_multicolumn_width(self
, start
, len_
):
1011 """Return sum of columnwidths for multicell."""
1012 mc_width
= sum([width
1013 for width
in ([self
._col
_width
[start
+ co
- 1]
1014 for co
in range (len_
)])])
1015 return '%.2f\\DUtablewidth' % mc_width
1017 def get_caption(self
):
1018 if not self
.caption
:
1020 caption
= ''.join(self
.caption
)
1021 if 1 == self
._translator
.thead_depth():
1022 return r
'\caption{%s}\\' '\n' % caption
1023 return r
'\caption[]{%s (... continued)}\\' '\n' % caption
1025 def need_recurse(self
):
1026 if self
._latex
_type
== 'longtable':
1027 return 1 == self
._translator
.thead_depth()
1030 def visit_thead(self
):
1032 if self
._table
_style
== 'standard':
1033 return ['\\hline\n']
1034 elif self
._table
_style
== 'booktabs':
1035 return ['\\toprule\n']
1038 def depart_thead(self
):
1040 #if self._table_style == 'standard':
1041 # a.append('\\hline\n')
1042 if self
._table
_style
== 'booktabs':
1043 a
.append('\\midrule\n')
1044 if self
._latex
_type
== 'longtable':
1045 if 1 == self
._translator
.thead_depth():
1046 a
.append('\\endfirsthead\n')
1048 a
.append('\\endhead\n')
1049 a
.append(r
'\multicolumn{%d}{c}' % len(self
._col
_specs
) +
1050 r
'{\hfill ... continued on next page} \\')
1051 a
.append('\n\\endfoot\n\\endlastfoot\n')
1052 # for longtable one could add firsthead, foot and lastfoot
1055 def visit_row(self
):
1056 self
._cell
_in
_row
= 0
1057 def depart_row(self
):
1059 self
._cell
_in
_row
= None # remove cell counter
1060 for i
in range(len(self
._rowspan
)):
1061 if (self
._rowspan
[i
]>0):
1062 self
._rowspan
[i
] -= 1
1064 if self
._table
_style
== 'standard':
1065 rowspans
= [i
+1 for i
in range(len(self
._rowspan
))
1066 if (self
._rowspan
[i
]<=0)]
1067 if len(rowspans
)==len(self
._rowspan
):
1068 res
.append('\\hline\n')
1075 c_start
= rowspans
.pop()
1078 cline
+= '\\cline{%d-%d}\n' % (c_start
,c_start
)
1082 def set_rowspan(self
,cell
,value
):
1084 self
._rowspan
[cell
] = value
1087 def get_rowspan(self
,cell
):
1089 return self
._rowspan
[cell
]
1092 def get_entry_number(self
):
1093 return self
._cell
_in
_row
1094 def visit_entry(self
):
1095 self
._cell
_in
_row
+= 1
1096 def is_stub_column(self
):
1097 if len(self
.stubs
) >= self
._cell
_in
_row
:
1098 return self
.stubs
[self
._cell
_in
_row
-1]
1102 class LaTeXTranslator(nodes
.NodeVisitor
):
1104 # When options are given to the documentclass, latex will pass them
1105 # to other packages, as done with babel.
1106 # Dummy settings might be taken from document settings
1108 # Write code for typesetting with 8-bit tex/pdftex (vs. xetex/luatex) engine
1109 # overwritten by the XeTeX writer
1112 # Config setting defaults
1113 # -----------------------
1115 # TODO: use mixins for different implementations.
1116 # list environment for docinfo. else tabularx
1117 ## use_optionlist_for_docinfo = False # TODO: NOT YET IN USE
1119 # Use compound enumerations (1.A.1.)
1120 compound_enumerators
= False
1122 # If using compound enumerations, include section information.
1123 section_prefix_for_enumerators
= False
1125 # This is the character that separates the section ("." subsection ...)
1126 # prefix from the regular list enumerator.
1127 section_enumerator_separator
= '-'
1129 # Auxiliary variables
1130 # -------------------
1132 has_latex_toc
= False # is there a toc in the doc? (needed by minitoc)
1133 is_toc_list
= False # is the current bullet_list a ToC?
1136 # Flags to encode():
1137 # inside citation reference labels underscores dont need to be escaped
1138 inside_citation_reference_label
= False
1139 verbatim
= False # do not encode
1140 insert_non_breaking_blanks
= False # replace blanks by "~"
1141 insert_newline
= False # add latex newline commands
1142 literal
= False # literal text (block or inline)
1145 def __init__(self
, document
, babel_class
=Babel
):
1146 nodes
.NodeVisitor
.__init
__(self
, document
)
1149 self
.warn
= self
.document
.reporter
.warning
1150 self
.error
= self
.document
.reporter
.error
1154 self
.settings
= settings
= document
.settings
1155 self
.latex_encoding
= self
.to_latex_encoding(settings
.output_encoding
)
1156 self
.use_latex_toc
= settings
.use_latex_toc
1157 self
.use_latex_docinfo
= settings
.use_latex_docinfo
1158 self
._use
_latex
_citations
= settings
.use_latex_citations
1159 self
._reference
_label
= settings
.reference_label
1160 self
.hyperlink_color
= settings
.hyperlink_color
1161 self
.compound_enumerators
= settings
.compound_enumerators
1162 self
.font_encoding
= getattr(settings
, 'font_encoding', '')
1163 self
.section_prefix_for_enumerators
= (
1164 settings
.section_prefix_for_enumerators
)
1165 self
.section_enumerator_separator
= (
1166 settings
.section_enumerator_separator
.replace('_', r
'\_'))
1168 self
.literal_block_env
= ''
1169 self
.literal_block_options
= ''
1170 if settings
.literal_block_env
!= '':
1172 self
.literal_block_env
,
1173 self
.literal_block_options
,
1174 none
) = re
.split('(\w+)(.*)', settings
.literal_block_env
)
1175 elif settings
.use_verbatim_when_possible
:
1176 self
.literal_block_env
= 'verbatim'
1178 if self
.settings
.use_bibtex
:
1179 self
.bibtex
= self
.settings
.use_bibtex
.split(',',1)
1180 # TODO avoid errors on not declared citations.
1183 # language module for Docutils-generated text
1184 # (labels, bibliographic_fields, and author_separators)
1185 self
.language_module
= languages
.get_language(settings
.language_code
,
1187 self
.babel
= babel_class(settings
.language_code
, document
.reporter
)
1188 self
.author_separator
= self
.language_module
.author_separators
[0]
1189 d_options
= [self
.settings
.documentoptions
]
1190 if self
.babel
.language
not in ('english', ''):
1191 d_options
.append(self
.babel
.language
)
1192 self
.documentoptions
= ','.join(filter(None, d_options
))
1193 self
.d_class
= DocumentClass(settings
.documentclass
,
1194 settings
.use_part_section
)
1195 # graphic package options:
1196 if self
.settings
.graphicx_option
== '':
1197 self
.graphicx_package
= r
'\usepackage{graphicx}'
1198 elif self
.settings
.graphicx_option
.lower() == 'auto':
1199 self
.graphicx_package
= PreambleCmds
.graphicx_auto
1201 self
.graphicx_package
= (r
'\usepackage[%s]{graphicx}' %
1202 self
.settings
.graphicx_option
)
1204 self
.docutils_footnotes
= settings
.docutils_footnotes
1205 if settings
.use_latex_footnotes
:
1206 self
.docutils_footnotes
= True
1207 self
.warn('`use_latex_footnotes` is deprecated. '
1208 'The setting has been renamed to `docutils_footnotes` '
1209 'and the alias will be removed in a future version.')
1210 self
.figure_footnotes
= settings
.figure_footnotes
1211 if self
.figure_footnotes
:
1212 self
.docutils_footnotes
= True
1213 self
.warn('The "figure footnotes" workaround/setting is strongly '
1214 'deprecated and will be removed in a future version.')
1216 # Output collection stacks
1217 # ~~~~~~~~~~~~~~~~~~~~~~~~
1220 self
.head_prefix
= [r
'\documentclass[%s]{%s}' %
1221 (self
.documentoptions
, self
.settings
.documentclass
)]
1222 self
.requirements
= SortableDict() # made a list in depart_document()
1223 self
.requirements
['__static'] = r
'\usepackage{ifthen}'
1224 self
.latex_preamble
= [settings
.latex_preamble
]
1225 self
.fallbacks
= SortableDict() # made a list in depart_document()
1226 self
.pdfsetup
= [] # PDF properties (hyperref package)
1229 self
.titledata
= [] # \title, \author, \date
1230 ## self.body_prefix = ['\\begin{document}\n']
1231 self
.body_pre_docinfo
= [] # \maketitle
1233 self
.dedication
= []
1236 ## self.body_suffix = ['\\end{document}\n']
1238 # A heterogenous stack used in conjunction with the tree traversal.
1239 # Make sure that the pops correspond to the pushes:
1243 self
.title_labels
= []
1244 self
.subtitle_labels
= []
1245 # (if use_latex_docinfo: collects lists of
1246 # author/organization/contact/address lines)
1247 self
.author_stack
= []
1250 # PDF properties: pdftitle, pdfauthor
1251 # TODO?: pdfcreator, pdfproducer, pdfsubject, pdfkeywords
1255 # Stack of section counters so that we don't have to use_latex_toc.
1256 # This will grow and shrink as processing occurs.
1257 # Initialized for potential first-level sections.
1258 self
._section
_number
= [0]
1260 # The current stack of enumerations so that we can expand
1261 # them into a compound enumeration.
1262 self
._enumeration
_counters
= []
1263 # The maximum number of enumeration counters we've used.
1264 # If we go beyond this number, we need to create a new
1265 # counter; otherwise, just reuse an old one.
1266 self
._max
_enumeration
_counters
= 0
1270 # object for a table while proccessing.
1271 self
.table_stack
= []
1272 self
.active_table
= Table(self
, 'longtable', settings
.table_style
)
1274 # Where to collect the output of visitor methods (default: body)
1275 self
.out
= self
.body
1276 self
.out_stack
= [] # stack of output collectors
1281 # Docutils' output-encoding => TeX input encoding
1282 if self
.latex_encoding
!= 'ascii':
1283 self
.requirements
['_inputenc'] = (r
'\usepackage[%s]{inputenc}'
1284 % self
.latex_encoding
)
1286 if not self
.is_xetex
:
1287 if self
.font_encoding
:
1288 self
.requirements
['_fontenc'] = (r
'\usepackage[%s]{fontenc}' %
1290 # ensure \textquotedbl is defined:
1291 for enc
in self
.font_encoding
.split(','):
1294 self
.requirements
['_textquotedblOT1'] = (
1295 r
'\DeclareTextSymbol{\textquotedbl}{OT1}{`\"}')
1296 elif enc
not in ('T1', 'T2A', 'T2B', 'T2C', 'T4', 'T5'):
1297 self
.requirements
['_textquotedbl'] = (
1298 r
'\DeclareTextSymbolDefault{\textquotedbl}{T1}')
1299 # page layout with typearea (if there are relevant document options)
1300 if (settings
.documentclass
.find('scr') == -1 and
1301 (self
.documentoptions
.find('DIV') != -1 or
1302 self
.documentoptions
.find('BCOR') != -1)):
1303 self
.requirements
['typearea'] = r
'\usepackage{typearea}'
1306 # (the name `self.stylesheet` is singular because only one
1307 # stylesheet was supported before Docutils 0.6).
1308 self
.stylesheet
= [self
.stylesheet_call(path
)
1309 for path
in utils
.get_stylesheet_list(settings
)]
1312 if self
.hyperlink_color
in ('0', 'false', 'False', ''):
1313 self
.hyperref_options
= ''
1315 self
.hyperref_options
= 'colorlinks=true,linkcolor=%s,urlcolor=%s' % (
1316 self
.hyperlink_color
, self
.hyperlink_color
)
1317 if settings
.hyperref_options
:
1318 self
.hyperref_options
+= ',' + settings
.hyperref_options
1321 # include all supported sections in toc and PDF bookmarks
1322 # (or use documentclass-default (as currently))?
1323 ## if self.use_latex_toc:
1324 ## self.requirements['tocdepth'] = (r'\setcounter{tocdepth}{%d}' %
1325 ## len(self.d_class.sections))
1328 if settings
.sectnum_xform
: # section numbering by Docutils
1329 PreambleCmds
.secnumdepth
= r
'\setcounter{secnumdepth}{0}'
1330 else: # section numbering by LaTeX:
1331 secnumdepth
= settings
.sectnum_depth
1332 # Possible values of settings.sectnum_depth:
1333 # None "sectnum" directive without depth arg -> LaTeX default
1334 # 0 no "sectnum" directive -> no section numbers
1335 # >0 value of "depth" argument -> translate to LaTeX levels:
1336 # -1 part (0 with "article" document class)
1337 # 0 chapter (missing in "article" document class)
1343 if secnumdepth
is not None:
1344 # limit to supported levels
1345 secnumdepth
= min(secnumdepth
, len(self
.d_class
.sections
))
1346 # adjust to document class and use_part_section settings
1347 if 'chapter' in self
.d_class
.sections
:
1349 if self
.d_class
.sections
[0] == 'part':
1351 PreambleCmds
.secnumdepth
= \
1352 r
'\setcounter{secnumdepth}{%d}' % secnumdepth
1354 # start with specified number:
1355 if (hasattr(settings
, 'sectnum_start') and
1356 settings
.sectnum_start
!= 1):
1357 self
.requirements
['sectnum_start'] = (
1358 r
'\setcounter{%s}{%d}' % (self
.d_class
.sections
[0],
1359 settings
.sectnum_start
-1))
1360 # TODO: currently ignored (configure in a stylesheet):
1361 ## settings.sectnum_prefix
1362 ## settings.sectnum_suffix
1367 def stylesheet_call(self
, path
):
1368 """Return code to reference or embed stylesheet file `path`"""
1369 # is it a package (no extension or *.sty) or "normal" tex code:
1370 (base
, ext
) = os
.path
.splitext(path
)
1371 is_package
= ext
in ['.sty', '']
1372 # Embed content of style file:
1373 if self
.settings
.embed_stylesheet
:
1375 path
= base
+ '.sty' # ensure extension
1377 content
= io
.FileInput(source_path
=path
,
1378 encoding
='utf-8').read()
1379 self
.settings
.record_dependencies
.add(path
)
1380 except IOError, err
:
1381 msg
= u
"Cannot embed stylesheet '%s':\n %s." % (
1382 path
, SafeString(err
.strerror
))
1383 self
.document
.reporter
.error(msg
)
1384 return '% ' + msg
.replace('\n', '\n% ')
1386 content
= '\n'.join([r
'\makeatletter',
1389 return '%% embedded stylesheet: %s\n%s' % (path
, content
)
1390 # Link to style file:
1392 path
= base
# drop extension
1393 cmd
= r
'\usepackage{%s}'
1396 if self
.settings
.stylesheet_path
:
1397 # adapt path relative to output (cf. config.html#stylesheet-path)
1398 path
= utils
.relative_path(self
.settings
._destination
, path
)
1401 def to_latex_encoding(self
,docutils_encoding
):
1402 """Translate docutils encoding name into LaTeX's.
1404 Default method is remove "-" and "_" chars from docutils_encoding.
1406 tr
= { 'iso-8859-1': 'latin1', # west european
1407 'iso-8859-2': 'latin2', # east european
1408 'iso-8859-3': 'latin3', # esperanto, maltese
1409 'iso-8859-4': 'latin4', # north european, scandinavian, baltic
1410 'iso-8859-5': 'iso88595', # cyrillic (ISO)
1411 'iso-8859-9': 'latin5', # turkish
1412 'iso-8859-15': 'latin9', # latin9, update to latin1.
1413 'mac_cyrillic': 'maccyr', # cyrillic (on Mac)
1414 'windows-1251': 'cp1251', # cyrillic (on Windows)
1415 'koi8-r': 'koi8-r', # cyrillic (Russian)
1416 'koi8-u': 'koi8-u', # cyrillic (Ukrainian)
1417 'windows-1250': 'cp1250', #
1418 'windows-1252': 'cp1252', #
1419 'us-ascii': 'ascii', # ASCII (US)
1420 # unmatched encodings
1422 #'': 'ansinew', # windows 3.1 ansi
1423 #'': 'ascii', # ASCII encoding for the range 32--127.
1424 #'': 'cp437', # dos latin us
1425 #'': 'cp850', # dos latin 1
1426 #'': 'cp852', # dos latin 2
1429 #'iso-8859-6': '' # arabic
1430 #'iso-8859-7': '' # greek
1431 #'iso-8859-8': '' # hebrew
1432 #'iso-8859-10': '' # latin6, more complete iso-8859-4
1434 encoding
= docutils_encoding
.lower()
1437 # drop hyphen or low-line from "latin-1", "latin_1", "utf-8" and similar
1438 encoding
= encoding
.replace('_', '').replace('-', '')
1439 # strip the error handler
1440 return encoding
.split(':')[0]
1442 def language_label(self
, docutil_label
):
1443 return self
.language_module
.labels
[docutil_label
]
1445 def encode(self
, text
):
1446 """Return text with 'problematic' characters escaped.
1448 * Escape the ten special printing characters ``# $ % & ~ _ ^ \ { }``,
1449 square brackets ``[ ]``, double quotes and (in OT1) ``< | >``.
1450 * Translate non-supported Unicode characters.
1451 * Separate ``-`` (and more in literal text) to prevent input ligatures.
1456 # Set up the translation table:
1457 table
= CharMaps
.special
.copy()
1458 # keep the underscore in citation references
1459 if self
.inside_citation_reference_label
:
1460 del(table
[ord('_')])
1461 # Workarounds for OT1 font-encoding
1462 if self
.font_encoding
in ['OT1', ''] and not self
.is_xetex
:
1463 # * out-of-order characters in cmtt
1465 # replace underscore by underlined blank,
1466 # because this has correct width.
1467 table
[ord('_')] = u
'\\underline{~}'
1468 # the backslash doesn't work, so we use a mirrored slash.
1469 # \reflectbox is provided by graphicx:
1470 self
.requirements
['graphicx'] = self
.graphicx_package
1471 table
[ord('\\')] = ur
'\reflectbox{/}'
1472 # * ``< | >`` come out as different chars (except for cmtt):
1474 table
[ord('|')] = ur
'\textbar{}'
1475 table
[ord('<')] = ur
'\textless{}'
1476 table
[ord('>')] = ur
'\textgreater{}'
1477 if self
.insert_non_breaking_blanks
:
1478 table
[ord(' ')] = ur
'~'
1479 # Unicode replacements for 8-bit tex engines (not required with XeTeX/LuaTeX):
1480 if not self
.is_xetex
:
1481 table
.update(CharMaps
.unsupported_unicode
)
1482 if not self
.latex_encoding
.startswith('utf8'):
1483 table
.update(CharMaps
.utf8_supported_unicode
)
1484 table
.update(CharMaps
.textcomp
)
1485 table
.update(CharMaps
.pifont
)
1486 # Characters that require a feature/package to render
1487 if [True for ch
in text
if ord(ch
) in CharMaps
.textcomp
]:
1488 self
.requirements
['textcomp'] = PreambleCmds
.textcomp
1489 if [True for ch
in text
if ord(ch
) in CharMaps
.pifont
]:
1490 self
.requirements
['pifont'] = '\\usepackage{pifont}'
1492 text
= text
.translate(table
)
1494 # Break up input ligatures e.g. '--' to '-{}-'.
1495 if not self
.is_xetex
: # Not required with xetex/luatex
1496 separate_chars
= '-'
1497 # In monospace-font, we also separate ',,', '``' and "''" and some
1498 # other characters which can't occur in non-literal text.
1500 separate_chars
+= ',`\'"<>'
1501 for char
in separate_chars
* 2:
1502 # Do it twice ("* 2") because otherwise we would replace
1504 text
= text
.replace(char
+ char
, char
+ '{}' + char
)
1506 # Literal line breaks (in address or literal blocks):
1507 if self
.insert_newline
:
1508 lines
= text
.split('\n')
1509 # Add a protected space to blank lines (except the last)
1510 # to avoid ``! LaTeX Error: There's no line here to end.``
1511 for i
, line
in enumerate(lines
[:-1]):
1512 if not line
.lstrip():
1514 text
= (r
'\\' + '\n').join(lines
)
1515 if self
.literal
and not self
.insert_non_breaking_blanks
:
1516 # preserve runs of spaces but allow wrapping
1517 text
= text
.replace(' ', ' ~')
1520 def attval(self
, text
,
1521 whitespace
=re
.compile('[\n\r\t\v\f]')):
1522 """Cleanse, encode, and return attribute value text."""
1523 return self
.encode(whitespace
.sub(' ', text
))
1525 # TODO: is this used anywhere? -> update (use template) or delete
1526 ## def astext(self):
1527 ## """Assemble document parts and return as string."""
1528 ## head = '\n'.join(self.head_prefix + self.stylesheet + self.head)
1529 ## body = ''.join(self.body_prefix + self.body + self.body_suffix)
1530 ## return head + '\n' + body
1532 def is_inline(self
, node
):
1533 """Check whether a node represents an inline element"""
1534 return isinstance(node
.parent
, nodes
.TextElement
)
1536 def append_hypertargets(self
, node
):
1537 """Append hypertargets for all ids of `node`"""
1538 # hypertarget places the anchor at the target's baseline,
1539 # so we raise it explicitely
1540 self
.out
.append('%\n'.join(['\\raisebox{1em}{\\hypertarget{%s}{}}' %
1541 id for id in node
['ids']]))
1543 def ids_to_labels(self
, node
, set_anchor
=True):
1544 """Return list of label definitions for all ids of `node`
1546 If `set_anchor` is True, an anchor is set with \phantomsection.
1548 labels
= ['\\label{%s}' % id for id in node
.get('ids', [])]
1549 if set_anchor
and labels
:
1550 labels
.insert(0, '\\phantomsection')
1553 def push_output_collector(self
, new_out
):
1554 self
.out_stack
.append(self
.out
)
1557 def pop_output_collector(self
):
1558 self
.out
= self
.out_stack
.pop()
1563 def visit_Text(self
, node
):
1564 self
.out
.append(self
.encode(node
.astext()))
1566 def depart_Text(self
, node
):
1569 def visit_abbreviation(self
, node
):
1570 node
['classes'].insert(0, 'abbreviation')
1571 self
.visit_inline(node
)
1573 def depart_abbreviation(self
, node
):
1574 self
.depart_inline(node
)
1576 def visit_acronym(self
, node
):
1577 node
['classes'].insert(0, 'acronym')
1578 self
.visit_inline(node
)
1580 def depart_acronym(self
, node
):
1581 self
.depart_inline(node
)
1583 def visit_address(self
, node
):
1584 self
.visit_docinfo_item(node
, 'address')
1586 def depart_address(self
, node
):
1587 self
.depart_docinfo_item(node
)
1589 def visit_admonition(self
, node
):
1590 self
.fallbacks
['admonition'] = PreambleCmds
.admonition
1591 if 'error' in node
['classes']:
1592 self
.fallbacks
['error'] = PreambleCmds
.error
1593 # strip the generic 'admonition' from the list of classes
1594 node
['classes'] = [cls
for cls
in node
['classes']
1595 if cls
!= 'admonition']
1596 self
.out
.append('\n\\DUadmonition[%s]{\n' % ','.join(node
['classes']))
1598 def depart_admonition(self
, node
=None):
1599 self
.out
.append('}\n')
1601 def visit_author(self
, node
):
1602 self
.visit_docinfo_item(node
, 'author')
1604 def depart_author(self
, node
):
1605 self
.depart_docinfo_item(node
)
1607 def visit_authors(self
, node
):
1608 # not used: visit_author is called anyway for each author.
1611 def depart_authors(self
, node
):
1614 def visit_block_quote(self
, node
):
1615 self
.out
.append( '%\n\\begin{quote}\n')
1617 self
.visit_inline(node
)
1619 def depart_block_quote(self
, node
):
1621 self
.depart_inline(node
)
1622 self
.out
.append( '\n\\end{quote}\n')
1624 def visit_bullet_list(self
, node
):
1625 if self
.is_toc_list
:
1626 self
.out
.append( '%\n\\begin{list}{}{}\n' )
1628 self
.out
.append( '%\n\\begin{itemize}\n' )
1629 # if node['classes']:
1630 # self.visit_inline(node)
1632 def depart_bullet_list(self
, node
):
1633 # if node['classes']:
1634 # self.depart_inline(node)
1635 if self
.is_toc_list
:
1636 self
.out
.append( '\n\\end{list}\n' )
1638 self
.out
.append( '\n\\end{itemize}\n' )
1640 def visit_superscript(self
, node
):
1641 self
.out
.append(r
'\textsuperscript{')
1643 self
.visit_inline(node
)
1645 def depart_superscript(self
, node
):
1647 self
.depart_inline(node
)
1648 self
.out
.append('}')
1650 def visit_subscript(self
, node
):
1651 self
.out
.append(r
'\textsubscript{') # requires `fixltx2e`
1653 self
.visit_inline(node
)
1655 def depart_subscript(self
, node
):
1657 self
.depart_inline(node
)
1658 self
.out
.append('}')
1660 def visit_caption(self
, node
):
1661 self
.out
.append( '\\caption{' )
1663 def depart_caption(self
, node
):
1664 self
.out
.append('}\n')
1666 def visit_title_reference(self
, node
):
1667 self
.fallbacks
['titlereference'] = PreambleCmds
.titlereference
1668 self
.out
.append(r
'\DUroletitlereference{')
1670 self
.visit_inline(node
)
1672 def depart_title_reference(self
, node
):
1674 self
.depart_inline(node
)
1675 self
.out
.append( '}' )
1677 def visit_citation(self
, node
):
1678 # TODO maybe use cite bibitems
1679 if self
._use
_latex
_citations
:
1680 self
.push_output_collector([])
1682 # TODO: do we need these?
1683 ## self.requirements['~fnt_floats'] = PreambleCmds.footnote_floats
1684 self
.out
.append(r
'\begin{figure}[b]')
1685 self
.append_hypertargets(node
)
1687 def depart_citation(self
, node
):
1688 if self
._use
_latex
_citations
:
1690 text
= ''.join(self
.out
[1:])
1691 self
._bibitems
.append([label
, text
])
1692 self
.pop_output_collector()
1694 self
.out
.append('\\end{figure}\n')
1696 def visit_citation_reference(self
, node
):
1697 if self
._use
_latex
_citations
:
1698 if not self
.inside_citation_reference_label
:
1699 self
.out
.append(r
'\cite{')
1700 self
.inside_citation_reference_label
= 1
1702 assert self
.body
[-1] in (' ', '\n'),\
1703 'unexpected non-whitespace while in reference label'
1708 href
= node
['refid']
1709 elif 'refname' in node
:
1710 href
= self
.document
.nameids
[node
['refname']]
1711 self
.out
.append('\\hyperlink{%s}{[' % href
)
1713 def depart_citation_reference(self
, node
):
1714 if self
._use
_latex
_citations
:
1715 followup_citation
= False
1716 # check for a following citation separated by a space or newline
1717 next_siblings
= node
.traverse(descend
=False, siblings
=True,
1719 if len(next_siblings
) > 1:
1720 next
= next_siblings
[0]
1721 if (isinstance(next
, nodes
.Text
) and
1722 next
.astext() in (' ', '\n')):
1723 if next_siblings
[1].__class
__ == node
.__class
__:
1724 followup_citation
= True
1725 if followup_citation
:
1726 self
.out
.append(',')
1728 self
.out
.append('}')
1729 self
.inside_citation_reference_label
= False
1731 self
.out
.append(']}')
1733 def visit_classifier(self
, node
):
1734 self
.out
.append( '(\\textbf{' )
1736 def depart_classifier(self
, node
):
1737 self
.out
.append( '})\n' )
1739 def visit_colspec(self
, node
):
1740 self
.active_table
.visit_colspec(node
)
1742 def depart_colspec(self
, node
):
1745 def visit_comment(self
, node
):
1746 # Precede every line with a comment sign, wrap in newlines
1747 self
.out
.append('\n%% %s\n' % node
.astext().replace('\n', '\n% '))
1748 raise nodes
.SkipNode
1750 def depart_comment(self
, node
):
1753 def visit_compound(self
, node
):
1756 def depart_compound(self
, node
):
1759 def visit_contact(self
, node
):
1760 self
.visit_docinfo_item(node
, 'contact')
1762 def depart_contact(self
, node
):
1763 self
.depart_docinfo_item(node
)
1765 def visit_container(self
, node
):
1768 def depart_container(self
, node
):
1771 def visit_copyright(self
, node
):
1772 self
.visit_docinfo_item(node
, 'copyright')
1774 def depart_copyright(self
, node
):
1775 self
.depart_docinfo_item(node
)
1777 def visit_date(self
, node
):
1778 self
.visit_docinfo_item(node
, 'date')
1780 def depart_date(self
, node
):
1781 self
.depart_docinfo_item(node
)
1783 def visit_decoration(self
, node
):
1787 def depart_decoration(self
, node
):
1790 def visit_definition(self
, node
):
1793 def depart_definition(self
, node
):
1794 self
.out
.append('\n')
1796 def visit_definition_list(self
, node
):
1797 self
.out
.append( '%\n\\begin{description}\n' )
1799 def depart_definition_list(self
, node
):
1800 self
.out
.append( '\\end{description}\n' )
1802 def visit_definition_list_item(self
, node
):
1805 def depart_definition_list_item(self
, node
):
1808 def visit_description(self
, node
):
1809 self
.out
.append(' ')
1811 def depart_description(self
, node
):
1814 def visit_docinfo(self
, node
):
1815 self
.push_output_collector(self
.docinfo
)
1817 def depart_docinfo(self
, node
):
1818 self
.pop_output_collector()
1819 # Some itmes (e.g. author) end up at other places
1821 # tabularx: automatic width of columns, no page breaks allowed.
1822 self
.requirements
['tabularx'] = r
'\usepackage{tabularx}'
1823 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
1824 self
.fallbacks
['docinfo'] = PreambleCmds
.docinfo
1826 self
.docinfo
.insert(0, '\n% Docinfo\n'
1828 '\\begin{tabularx}{\\DUdocinfowidth}{lX}\n')
1829 self
.docinfo
.append('\\end{tabularx}\n'
1832 def visit_docinfo_item(self
, node
, name
):
1833 if name
== 'author':
1834 self
.pdfauthor
.append(self
.attval(node
.astext()))
1835 if self
.use_latex_docinfo
:
1836 if name
in ('author', 'organization', 'contact', 'address'):
1837 # We attach these to the last author. If any of them precedes
1838 # the first author, put them in a separate "author" group
1839 # (in lack of better semantics).
1840 if name
== 'author' or not self
.author_stack
:
1841 self
.author_stack
.append([])
1842 if name
== 'address': # newlines are meaningful
1843 self
.insert_newline
= True
1844 text
= self
.encode(node
.astext())
1845 self
.insert_newline
= False
1847 text
= self
.attval(node
.astext())
1848 self
.author_stack
[-1].append(text
)
1849 raise nodes
.SkipNode
1850 elif name
== 'date':
1851 self
.date
.append(self
.attval(node
.astext()))
1852 raise nodes
.SkipNode
1853 self
.out
.append('\\textbf{%s}: &\n\t' % self
.language_label(name
))
1854 if name
== 'address':
1855 self
.insert_newline
= 1
1856 self
.out
.append('{\\raggedright\n')
1857 self
.context
.append(' } \\\\\n')
1859 self
.context
.append(' \\\\\n')
1861 def depart_docinfo_item(self
, node
):
1862 self
.out
.append(self
.context
.pop())
1863 # for address we did set insert_newline
1864 self
.insert_newline
= False
1866 def visit_doctest_block(self
, node
):
1867 self
.visit_literal_block(node
)
1869 def depart_doctest_block(self
, node
):
1870 self
.depart_literal_block(node
)
1872 def visit_document(self
, node
):
1874 if (self
.use_latex_docinfo
or len(node
) and
1875 isinstance(node
[0], nodes
.title
)):
1876 self
.title_labels
+= self
.ids_to_labels(node
, set_anchor
=False)
1878 def depart_document(self
, node
):
1879 # Complete header with information gained from walkabout
1881 if (self
.babel
.otherlanguages
or
1882 self
.babel
.language
not in ('', 'english')):
1883 self
.requirements
['babel'] = self
.babel()
1884 # * conditional requirements (before style sheet)
1885 self
.requirements
= self
.requirements
.sortedvalues()
1886 # * coditional fallback definitions (after style sheet)
1887 self
.fallbacks
= self
.fallbacks
.sortedvalues()
1889 self
.pdfsetup
.append(PreambleCmds
.linking
% self
.hyperref_options
)
1891 authors
= self
.author_separator
.join(self
.pdfauthor
)
1892 self
.pdfinfo
.append(' pdfauthor={%s}' % authors
)
1894 self
.pdfsetup
+= [r
'\hypersetup{'] + self
.pdfinfo
+ ['}']
1896 # * document title (with "use_latex_docinfo" also
1897 # 'author', 'organization', 'contact', 'address' and 'date')
1899 self
.use_latex_docinfo
and (self
.author_stack
or self
.date
)):
1900 # with the default template, titledata is written to the preamble
1901 self
.titledata
.append('%%% Title Data')
1902 # \title (empty \title prevents error with \maketitle)
1904 self
.title
.insert(0, '\phantomsection%\n ')
1905 title
= [''.join(self
.title
)] + self
.title_labels
1907 title
+= [r
'\\ % subtitle',
1908 r
'\large{%s}' % ''.join(self
.subtitle
)
1909 ] + self
.subtitle_labels
1910 self
.titledata
.append(r
'\title{%s}' % '%\n '.join(title
))
1911 # \author (empty \author prevents warning with \maketitle)
1912 authors
= ['\\\\\n'.join(author_entry
)
1913 for author_entry
in self
.author_stack
]
1914 self
.titledata
.append(r
'\author{%s}' %
1915 ' \\and\n'.join(authors
))
1916 # \date (empty \date prevents defaulting to \today)
1917 self
.titledata
.append(r
'\date{%s}' % ', '.join(self
.date
))
1918 # \maketitle in the body formats title with LaTeX
1919 self
.body_pre_docinfo
.append('\\maketitle\n')
1922 # TODO insertion point of bibliography should be configurable.
1923 if self
._use
_latex
_citations
and len(self
._bibitems
)>0:
1926 for bi
in self
._bibitems
:
1927 if len(widest_label
)<len(bi
[0]):
1928 widest_label
= bi
[0]
1929 self
.out
.append('\n\\begin{thebibliography}{%s}\n' %
1931 for bi
in self
._bibitems
:
1932 # cite_key: underscores must not be escaped
1933 cite_key
= bi
[0].replace(r
'\_','_')
1934 self
.out
.append('\\bibitem[%s]{%s}{%s}\n' %
1935 (bi
[0], cite_key
, bi
[1]))
1936 self
.out
.append('\\end{thebibliography}\n')
1938 self
.out
.append('\n\\bibliographystyle{%s}\n' %
1940 self
.out
.append('\\bibliography{%s}\n' % self
.bibtex
[1])
1941 # * make sure to generate a toc file if needed for local contents:
1942 if 'minitoc' in self
.requirements
and not self
.has_latex_toc
:
1943 self
.out
.append('\n\\faketableofcontents % for local ToCs\n')
1945 def visit_emphasis(self
, node
):
1946 self
.out
.append('\\emph{')
1948 self
.visit_inline(node
)
1950 def depart_emphasis(self
, node
):
1952 self
.depart_inline(node
)
1953 self
.out
.append('}')
1955 def visit_entry(self
, node
):
1956 self
.active_table
.visit_entry()
1958 # BUG: the following fails, with more than one multirow
1959 # starting in the second column (or later) see
1960 # ../../../test/functional/input/data/latex.txt
1961 if self
.active_table
.get_entry_number() == 1:
1962 # if the first row is a multirow, this actually is the second row.
1963 # this gets hairy if rowspans follow each other.
1964 if self
.active_table
.get_rowspan(0):
1966 while self
.active_table
.get_rowspan(count
):
1968 self
.out
.append(' & ')
1969 self
.active_table
.visit_entry() # increment cell count
1971 self
.out
.append(' & ')
1972 # multirow, multicolumn
1973 # IN WORK BUG TODO HACK continues here
1974 # multirow in LaTeX simply will enlarge the cell over several rows
1975 # (the following n if n is positive, the former if negative).
1976 if 'morerows' in node
and 'morecols' in node
:
1977 raise NotImplementedError('Cells that '
1978 'span multiple rows *and* columns are not supported, sorry.')
1979 if 'morerows' in node
:
1980 self
.requirements
['multirow'] = r
'\usepackage{multirow}'
1981 count
= node
['morerows'] + 1
1982 self
.active_table
.set_rowspan(
1983 self
.active_table
.get_entry_number()-1,count
)
1984 # TODO why does multirow end on % ? needs to be checked for below
1985 self
.out
.append('\\multirow{%d}{%s}{%%' %
1986 (count
,self
.active_table
.get_column_width()))
1987 self
.context
.append('}')
1988 elif 'morecols' in node
:
1989 # the vertical bar before column is missing if it is the first
1990 # column. the one after always.
1991 if self
.active_table
.get_entry_number() == 1:
1992 bar1
= self
.active_table
.get_vertical_bar()
1995 count
= node
['morecols'] + 1
1996 self
.out
.append('\\multicolumn{%d}{%sp{%s}%s}{' %
1998 self
.active_table
.get_multicolumn_width(
1999 self
.active_table
.get_entry_number(),
2001 self
.active_table
.get_vertical_bar()))
2002 self
.context
.append('}')
2004 self
.context
.append('')
2006 # header / not header
2007 if isinstance(node
.parent
.parent
, nodes
.thead
):
2008 if self
.out
[-1].endswith("%"):
2009 self
.out
.append("\n")
2010 self
.out
.append('\\textbf{%')
2011 self
.context
.append('}')
2012 elif self
.active_table
.is_stub_column():
2013 if self
.out
[-1].endswith("%"):
2014 self
.out
.append("\n")
2015 self
.out
.append('\\textbf{')
2016 self
.context
.append('}')
2018 self
.context
.append('')
2020 def depart_entry(self
, node
):
2021 self
.out
.append(self
.context
.pop()) # header / not header
2022 self
.out
.append(self
.context
.pop()) # multirow/column
2023 # if following row is spanned from above.
2024 if self
.active_table
.get_rowspan(self
.active_table
.get_entry_number()):
2025 self
.out
.append(' & ')
2026 self
.active_table
.visit_entry() # increment cell count
2028 def visit_row(self
, node
):
2029 self
.active_table
.visit_row()
2031 def depart_row(self
, node
):
2032 self
.out
.extend(self
.active_table
.depart_row())
2034 def visit_enumerated_list(self
, node
):
2035 # We create our own enumeration list environment.
2036 # This allows to set the style and starting value
2037 # and unlimited nesting.
2038 enum_style
= {'arabic':'arabic',
2039 'loweralpha':'alph',
2040 'upperalpha':'Alph',
2041 'lowerroman':'roman',
2042 'upperroman':'Roman' }
2044 if 'suffix' in node
:
2045 enum_suffix
= node
['suffix']
2047 if 'prefix' in node
:
2048 enum_prefix
= node
['prefix']
2049 if self
.compound_enumerators
:
2051 if self
.section_prefix_for_enumerators
and self
.section_level
:
2052 for i
in range(self
.section_level
):
2053 pref
+= '%d.' % self
._section
_number
[i
]
2054 pref
= pref
[:-1] + self
.section_enumerator_separator
2056 for ctype
, cname
in self
._enumeration
_counters
:
2057 enum_prefix
+= '\\%s{%s}.' % (ctype
, cname
)
2058 enum_type
= 'arabic'
2059 if 'enumtype' in node
:
2060 enum_type
= node
['enumtype']
2061 if enum_type
in enum_style
:
2062 enum_type
= enum_style
[enum_type
]
2064 counter_name
= 'listcnt%d' % len(self
._enumeration
_counters
)
2065 self
._enumeration
_counters
.append((enum_type
, counter_name
))
2066 # If we haven't used this counter name before, then create a
2067 # new counter; otherwise, reset & reuse the old counter.
2068 if len(self
._enumeration
_counters
) > self
._max
_enumeration
_counters
:
2069 self
._max
_enumeration
_counters
= len(self
._enumeration
_counters
)
2070 self
.out
.append('\\newcounter{%s}\n' % counter_name
)
2072 self
.out
.append('\\setcounter{%s}{0}\n' % counter_name
)
2074 self
.out
.append('\\begin{list}{%s\\%s{%s}%s}\n' %
2075 (enum_prefix
,enum_type
,counter_name
,enum_suffix
))
2076 self
.out
.append('{\n')
2077 self
.out
.append('\\usecounter{%s}\n' % counter_name
)
2078 # set start after usecounter, because it initializes to zero.
2080 self
.out
.append('\\addtocounter{%s}{%d}\n' %
2081 (counter_name
,node
['start']-1))
2082 ## set rightmargin equal to leftmargin
2083 self
.out
.append('\\setlength{\\rightmargin}{\\leftmargin}\n')
2084 self
.out
.append('}\n')
2086 def depart_enumerated_list(self
, node
):
2087 self
.out
.append('\\end{list}\n')
2088 self
._enumeration
_counters
.pop()
2090 def visit_field(self
, node
):
2091 # real output is done in siblings: _argument, _body, _name
2094 def depart_field(self
, node
):
2095 self
.out
.append('\n')
2096 ##self.out.append('%[depart_field]\n')
2098 def visit_field_argument(self
, node
):
2099 self
.out
.append('%[visit_field_argument]\n')
2101 def depart_field_argument(self
, node
):
2102 self
.out
.append('%[depart_field_argument]\n')
2104 def visit_field_body(self
, node
):
2107 def depart_field_body(self
, node
):
2108 if self
.out
is self
.docinfo
:
2109 self
.out
.append(r
'\\')
2111 def visit_field_list(self
, node
):
2112 if self
.out
is not self
.docinfo
:
2113 self
.fallbacks
['fieldlist'] = PreambleCmds
.fieldlist
2114 self
.out
.append('%\n\\begin{DUfieldlist}\n')
2116 def depart_field_list(self
, node
):
2117 if self
.out
is not self
.docinfo
:
2118 self
.out
.append('\\end{DUfieldlist}\n')
2120 def visit_field_name(self
, node
):
2121 if self
.out
is self
.docinfo
:
2122 self
.out
.append('\\textbf{')
2124 # Commands with optional args inside an optional arg must be put
2125 # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
2126 self
.out
.append('\\item[{')
2128 def depart_field_name(self
, node
):
2129 if self
.out
is self
.docinfo
:
2130 self
.out
.append('}: &')
2132 self
.out
.append(':}]')
2134 def visit_figure(self
, node
):
2135 self
.requirements
['float_settings'] = PreambleCmds
.float_settings
2136 # ! the 'align' attribute should set "outer alignment" !
2137 # For "inner alignment" use LaTeX default alignment (similar to HTML)
2138 ## if ('align' not in node.attributes or
2139 ## node.attributes['align'] == 'center'):
2140 ## align = '\n\\centering'
2143 ## # TODO non vertical space for other alignments.
2144 ## align = '\\begin{flush%s}' % node.attributes['align']
2145 ## align_end = '\\end{flush%s}' % node.attributes['align']
2146 ## self.out.append( '\\begin{figure}%s\n' % align )
2147 ## self.context.append( '%s\\end{figure}\n' % align_end )
2148 self
.out
.append('\\begin{figure}')
2150 self
.out
+= ['\n'] + self
.ids_to_labels(node
)
2152 def depart_figure(self
, node
):
2153 self
.out
.append('\\end{figure}\n')
2155 def visit_footer(self
, node
):
2156 self
.push_output_collector([])
2157 self
.out
.append(r
'\newcommand{\DUfooter}{')
2159 def depart_footer(self
, node
):
2160 self
.out
.append('}')
2161 self
.requirements
['~footer'] = ''.join(self
.out
)
2162 self
.pop_output_collector()
2164 def visit_footnote(self
, node
):
2166 backref
= node
['backrefs'][0]
2168 backref
= node
['ids'][0] # no backref, use self-ref instead
2169 if self
.settings
.figure_footnotes
:
2170 self
.requirements
['~fnt_floats'] = PreambleCmds
.footnote_floats
2171 self
.out
.append('\\begin{figure}[b]')
2172 self
.append_hypertargets(node
)
2173 if node
.get('id') == node
.get('name'): # explicite label
2174 self
.out
+= self
.ids_to_labels(node
)
2175 elif self
.docutils_footnotes
:
2176 self
.fallbacks
['footnotes'] = PreambleCmds
.footnotes
2177 num
,text
= node
.astext().split(None,1)
2178 if self
.settings
.footnote_references
== 'brackets':
2180 self
.out
.append('%%\n\\DUfootnotetext{%s}{%s}{%s}{' %
2181 (node
['ids'][0], backref
, self
.encode(num
)))
2182 if node
['ids'] == node
['names']:
2183 self
.out
+= self
.ids_to_labels(node
)
2184 # mask newline to prevent spurious whitespace:
2185 self
.out
.append('%')
2186 ## else: # TODO: "real" LaTeX \footnote{}s
2188 def depart_footnote(self
, node
):
2189 if self
.figure_footnotes
:
2190 self
.out
.append('\\end{figure}\n')
2192 self
.out
.append('}\n')
2194 def visit_footnote_reference(self
, node
):
2197 href
= node
['refid']
2198 elif 'refname' in node
:
2199 href
= self
.document
.nameids
[node
['refname']]
2200 # if not self.docutils_footnotes:
2201 # TODO: insert footnote content at (or near) this place
2202 # print "footnote-ref to", node['refid']
2203 # footnotes = (self.document.footnotes +
2204 # self.document.autofootnotes +
2205 # self.document.symbol_footnotes)
2206 # for footnote in footnotes:
2207 # # print footnote['ids']
2208 # if node.get('refid', '') in footnote['ids']:
2209 # print 'matches', footnote['ids']
2210 format
= self
.settings
.footnote_references
2211 if format
== 'brackets':
2212 self
.append_hypertargets(node
)
2213 self
.out
.append('\\hyperlink{%s}{[' % href
)
2214 self
.context
.append(']}')
2216 self
.fallbacks
['footnotes'] = PreambleCmds
.footnotes
2217 self
.out
.append(r
'\DUfootnotemark{%s}{%s}{' %
2218 (node
['ids'][0], href
))
2219 self
.context
.append('}')
2221 def depart_footnote_reference(self
, node
):
2222 self
.out
.append(self
.context
.pop())
2224 # footnote/citation label
2225 def label_delim(self
, node
, bracket
, superscript
):
2226 if isinstance(node
.parent
, nodes
.footnote
):
2227 if not self
.figure_footnotes
:
2228 raise nodes
.SkipNode
2229 if self
.settings
.footnote_references
== 'brackets':
2230 self
.out
.append(bracket
)
2232 self
.out
.append(superscript
)
2234 assert isinstance(node
.parent
, nodes
.citation
)
2235 if not self
._use
_latex
_citations
:
2236 self
.out
.append(bracket
)
2238 def visit_label(self
, node
):
2239 """footnote or citation label: in brackets or as superscript"""
2240 self
.label_delim(node
, '[', '\\textsuperscript{')
2242 def depart_label(self
, node
):
2243 self
.label_delim(node
, ']', '}')
2245 # elements generated by the framework e.g. section numbers.
2246 def visit_generated(self
, node
):
2249 def depart_generated(self
, node
):
2252 def visit_header(self
, node
):
2253 self
.push_output_collector([])
2254 self
.out
.append(r
'\newcommand{\DUheader}{')
2256 def depart_header(self
, node
):
2257 self
.out
.append('}')
2258 self
.requirements
['~header'] = ''.join(self
.out
)
2259 self
.pop_output_collector()
2261 def to_latex_length(self
, length_str
, pxunit
=None):
2262 """Convert `length_str` with rst lenght to LaTeX length
2264 if pxunit
is not None:
2265 sys
.stderr
.write('deprecation warning: LaTeXTranslator.to_latex_length()'
2266 ' option `pxunit` will be removed.')
2267 match
= re
.match('(\d*\.?\d*)\s*(\S*)', length_str
)
2270 value
, unit
= match
.groups()[:2]
2271 # no unit or "DTP" points (called 'bp' in TeX):
2272 if unit
in ('', 'pt'):
2273 length_str
= '%sbp' % value
2274 # percentage: relate to current line width
2276 length_str
= '%.3f\\linewidth' % (float(value
)/100.0)
2277 elif self
.is_xetex
and unit
== 'px':
2278 # XeTeX does not know the length unit px.
2279 # Use \pdfpxdimen, the macro to set the value of 1 px in pdftex.
2280 # This way, configuring works the same for pdftex and xetex.
2281 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
2282 self
.fallbacks
['px'] = '\n\\DUprovidelength{\\pdfpxdimen}{1bp}\n'
2283 length_str
= r
'%s\pdfpxdimen' % value
2286 def visit_image(self
, node
):
2287 self
.requirements
['graphicx'] = self
.graphicx_package
2288 attrs
= node
.attributes
2289 # Convert image URI to a local file path
2290 imagepath
= urllib
.url2pathname(attrs
['uri']).replace('\\', '/')
2291 # alignment defaults:
2292 if not 'align' in attrs
:
2293 # Set default align of image in a figure to 'center'
2294 if isinstance(node
.parent
, nodes
.figure
):
2295 attrs
['align'] = 'center'
2296 # query 'align-*' class argument
2297 for cls
in node
['classes']:
2298 if cls
.startswith('align-'):
2299 attrs
['align'] = cls
.split('-')[1]
2300 # pre- and postfix (prefix inserted in reverse order)
2303 include_graphics_options
= []
2304 display_style
= ('block-', 'inline-')[self
.is_inline(node
)]
2306 # inline images: by default latex aligns the bottom.
2308 'middle': (r
'\raisebox{-0.5\height}{', '}'),
2309 'top': (r
'\raisebox{-\height}{', '}'),
2310 # block level images:
2311 'center': (r
'\noindent\makebox[\textwidth][c]{', '}'),
2312 'left': (r
'\noindent{', r
'\hfill}'),
2313 'right': (r
'\noindent{\hfill', '}'),}
2314 if 'align' in attrs
:
2316 align_code
= align_codes
[attrs
['align']]
2317 pre
.append(align_code
[0])
2318 post
.append(align_code
[1])
2321 if 'height' in attrs
:
2322 include_graphics_options
.append('height=%s' %
2323 self
.to_latex_length(attrs
['height']))
2324 if 'scale' in attrs
:
2325 include_graphics_options
.append('scale=%f' %
2326 (attrs
['scale'] / 100.0))
2327 if 'width' in attrs
:
2328 include_graphics_options
.append('width=%s' %
2329 self
.to_latex_length(attrs
['width']))
2330 if not self
.is_inline(node
):
2334 self
.out
.extend(pre
)
2336 if include_graphics_options
:
2337 options
= '[%s]' % (','.join(include_graphics_options
))
2338 self
.out
.append('\\includegraphics%s{%s}' % (options
, imagepath
))
2339 self
.out
.extend(post
)
2341 def depart_image(self
, node
):
2343 self
.out
+= self
.ids_to_labels(node
) + ['\n']
2345 def visit_inline(self
, node
): # <span>, i.e. custom roles
2346 # Make a copy to keep ``node['classes']`` True if a
2347 # language argument is popped (used in conditional calls of
2349 classes
= node
['classes'][:]
2350 self
.context
.append('}' * len(classes
))
2351 # handle language specification:
2352 language_tags
= [cls
for cls
in classes
2353 if cls
.startswith('language-')]
2355 language
= self
.babel
.language_name(language_tags
[0][9:])
2357 self
.babel
.otherlanguages
[language
] = True
2358 self
.out
.append(r
'\foreignlanguage{%s}{' % language
)
2359 classes
.pop(classes
.index(language_tags
[0]))
2362 # mark up for styling with custom macros
2363 if 'align-center' in classes
:
2364 self
.fallbacks
['align-center'] = PreambleCmds
.align_center
2365 self
.fallbacks
['inline'] = PreambleCmds
.inline
2366 self
.out
+= [r
'\DUrole{%s}{' % cls
for cls
in classes
]
2368 def depart_inline(self
, node
):
2369 self
.out
.append(self
.context
.pop())
2371 def visit_interpreted(self
, node
):
2372 # @@@ Incomplete, pending a proper implementation on the
2373 # Parser/Reader end.
2374 self
.visit_literal(node
)
2376 def depart_interpreted(self
, node
):
2377 self
.depart_literal(node
)
2379 def visit_legend(self
, node
):
2380 self
.fallbacks
['legend'] = PreambleCmds
.legend
2381 self
.out
.append('\\begin{DUlegend}')
2383 def depart_legend(self
, node
):
2384 self
.out
.append('\\end{DUlegend}\n')
2386 def visit_line(self
, node
):
2387 self
.out
.append('\item[] ')
2389 def depart_line(self
, node
):
2390 self
.out
.append('\n')
2392 def visit_line_block(self
, node
):
2393 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
2394 self
.fallbacks
['lineblock'] = PreambleCmds
.lineblock
2395 if isinstance(node
.parent
, nodes
.line_block
):
2396 self
.out
.append('\\item[]\n'
2397 '\\begin{DUlineblock}{\\DUlineblockindent}\n')
2399 self
.out
.append('\n\\begin{DUlineblock}{0em}\n')
2401 self
.visit_inline(node
)
2402 self
.out
.append('\n')
2404 def depart_line_block(self
, node
):
2406 self
.depart_inline(node
)
2407 self
.out
.append('\n')
2408 self
.out
.append('\\end{DUlineblock}\n')
2410 def visit_list_item(self
, node
):
2411 self
.out
.append('\n\\item ')
2413 def depart_list_item(self
, node
):
2416 def visit_literal(self
, node
):
2418 if 'code' in node
.get('classes', []):
2419 self
.requirements
['color'] = PreambleCmds
.color
2420 self
.requirements
['code'] = PreambleCmds
.highlight_rules
2421 self
.out
.append('\\texttt{')
2423 self
.visit_inline(node
)
2425 def depart_literal(self
, node
):
2426 self
.literal
= False
2428 self
.depart_inline(node
)
2429 self
.out
.append('}')
2431 # Literal blocks are used for '::'-prefixed literal-indented
2432 # blocks of text, where the inline markup is not recognized,
2433 # but are also the product of the "parsed-literal" directive,
2434 # where the markup is respected.
2436 # In both cases, we want to use a typewriter/monospaced typeface.
2437 # For "real" literal-blocks, we can use \verbatim, while for all
2438 # the others we must use \mbox or \alltt.
2440 # We can distinguish between the two kinds by the number of
2441 # siblings that compose this node: if it is composed by a
2442 # single element, it's either
2444 # * a parsed-literal that does not contain any markup, or
2445 # * a parsed-literal containing just one markup construct.
2446 def is_plaintext(self
, node
):
2447 """Check whether a node can be typeset verbatim"""
2448 return (len(node
) == 1) and isinstance(node
[0], nodes
.Text
)
2450 def visit_literal_block(self
, node
):
2451 """Render a literal block."""
2452 # environments and packages to typeset literal blocks
2453 packages
= {'listing': r
'\usepackage{moreverb}',
2454 'lstlisting': r
'\usepackage{listings}',
2455 'Verbatim': r
'\usepackage{fancyvrb}',
2457 'verbatimtab': r
'\usepackage{moreverb}'}
2459 if not self
.active_table
.is_open():
2460 # no quote inside tables, to avoid vertical space between
2461 # table border and literal block.
2462 # BUG: fails if normal text preceeds the literal block.
2463 self
.out
.append('%\n\\begin{quote}')
2464 self
.context
.append('\n\\end{quote}\n')
2466 self
.out
.append('\n')
2467 self
.context
.append('\n')
2468 if self
.literal_block_env
!= '' and self
.is_plaintext(node
):
2469 self
.requirements
['literal_block'] = packages
.get(
2470 self
.literal_block_env
, '')
2471 self
.verbatim
= True
2472 self
.out
.append('\\begin{%s}%s\n' % (self
.literal_block_env
,
2473 self
.literal_block_options
))
2476 self
.insert_newline
= True
2477 self
.insert_non_breaking_blanks
= True
2478 self
.out
.append('{\\ttfamily \\raggedright \\noindent\n')
2480 def depart_literal_block(self
, node
):
2482 self
.out
.append('\n\\end{%s}\n' % self
.literal_block_env
)
2483 self
.verbatim
= False
2485 self
.out
.append('\n}')
2486 self
.insert_non_breaking_blanks
= False
2487 self
.insert_newline
= False
2488 self
.literal
= False
2489 self
.out
.append(self
.context
.pop())
2491 ## def visit_meta(self, node):
2492 ## self.out.append('[visit_meta]\n')
2493 # TODO: set keywords for pdf?
2495 # The reStructuredText "meta" directive creates a "pending" node,
2496 # which contains knowledge that the embedded "meta" node can only
2497 # be handled by HTML-compatible writers. The "pending" node is
2498 # resolved by the docutils.transforms.components.Filter transform,
2499 # which checks that the calling writer supports HTML; if it doesn't,
2500 # the "pending" node (and enclosed "meta" node) is removed from the
2502 # --- docutils/docs/peps/pep-0258.html#transformer
2504 ## def depart_meta(self, node):
2505 ## self.out.append('[depart_meta]\n')
2507 def visit_math(self
, node
, math_env
='$'):
2510 self
.visit_inline(node
)
2511 self
.requirements
['amsmath'] = r
'\usepackage{amsmath}'
2512 math_code
= node
.astext().translate(unichar2tex
.uni2tex_table
)
2514 math_code
= '\n'.join([math_code
] + self
.ids_to_labels(node
))
2518 wrapper
= u
'\n'.join(['%%',
2519 r
'\begin{%s}' % math_env
,
2521 r
'\end{%s}' % math_env
])
2522 # print repr(wrapper), repr(math_code)
2523 self
.out
.append(wrapper
% math_code
)
2525 self
.depart_inline(node
)
2526 # Content already processed:
2527 raise nodes
.SkipNode
2529 def depart_math(self
, node
):
2530 pass # never reached
2532 def visit_math_block(self
, node
):
2533 math_env
= pick_math_environment(node
.astext())
2534 self
.visit_math(node
, math_env
=math_env
)
2536 def depart_math_block(self
, node
):
2537 pass # never reached
2539 def visit_option(self
, node
):
2540 if self
.context
[-1]:
2541 # this is not the first option
2542 self
.out
.append(', ')
2544 def depart_option(self
, node
):
2545 # flag that the first option is done.
2546 self
.context
[-1] += 1
2548 def visit_option_argument(self
, node
):
2549 """Append the delimiter betweeen an option and its argument to body."""
2550 self
.out
.append(node
.get('delimiter', ' '))
2552 def depart_option_argument(self
, node
):
2555 def visit_option_group(self
, node
):
2556 self
.out
.append('\n\\item[')
2557 # flag for first option
2558 self
.context
.append(0)
2560 def depart_option_group(self
, node
):
2561 self
.context
.pop() # the flag
2562 self
.out
.append('] ')
2564 def visit_option_list(self
, node
):
2565 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
2566 self
.fallbacks
['optionlist'] = PreambleCmds
.optionlist
2567 self
.out
.append('%\n\\begin{DUoptionlist}\n')
2569 def depart_option_list(self
, node
):
2570 self
.out
.append('\n\\end{DUoptionlist}\n')
2572 def visit_option_list_item(self
, node
):
2575 def depart_option_list_item(self
, node
):
2578 def visit_option_string(self
, node
):
2579 ##self.out.append(self.starttag(node, 'span', '', CLASS='option'))
2582 def depart_option_string(self
, node
):
2583 ##self.out.append('</span>')
2586 def visit_organization(self
, node
):
2587 self
.visit_docinfo_item(node
, 'organization')
2589 def depart_organization(self
, node
):
2590 self
.depart_docinfo_item(node
)
2592 def visit_paragraph(self
, node
):
2593 # insert blank line, if the paragraph is not first in a list item
2594 # nor follows a non-paragraph node in a compound
2595 index
= node
.parent
.index(node
)
2596 if (index
== 0 and (isinstance(node
.parent
, nodes
.list_item
) or
2597 isinstance(node
.parent
, nodes
.description
))):
2599 elif (index
> 0 and isinstance(node
.parent
, nodes
.compound
) and
2600 not isinstance(node
.parent
[index
- 1], nodes
.paragraph
) and
2601 not isinstance(node
.parent
[index
- 1], nodes
.compound
)):
2604 self
.out
.append('\n')
2606 self
.out
+= self
.ids_to_labels(node
) + ['\n']
2608 self
.visit_inline(node
)
2610 def depart_paragraph(self
, node
):
2612 self
.depart_inline(node
)
2613 self
.out
.append('\n')
2615 def visit_problematic(self
, node
):
2616 self
.requirements
['color'] = PreambleCmds
.color
2617 self
.out
.append('%\n')
2618 self
.append_hypertargets(node
)
2619 self
.out
.append(r
'\hyperlink{%s}{\textbf{\color{red}' % node
['refid'])
2621 def depart_problematic(self
, node
):
2622 self
.out
.append('}}')
2624 def visit_raw(self
, node
):
2625 if not 'latex' in node
.get('format', '').split():
2626 raise nodes
.SkipNode
2627 if not self
.is_inline(node
):
2628 self
.out
.append('\n')
2630 self
.visit_inline(node
)
2631 # append "as-is" skipping any LaTeX-encoding
2632 self
.verbatim
= True
2634 def depart_raw(self
, node
):
2635 self
.verbatim
= False
2637 self
.depart_inline(node
)
2638 if not self
.is_inline(node
):
2639 self
.out
.append('\n')
2641 def has_unbalanced_braces(self
, string
):
2642 """Test whether there are unmatched '{' or '}' characters."""
2653 def visit_reference(self
, node
):
2654 # We need to escape #, \, and % if we use the URL in a command.
2655 special_chars
= {ord('#'): ur
'\#',
2659 # external reference (URL)
2660 if 'refuri' in node
:
2661 href
= unicode(node
['refuri']).translate(special_chars
)
2662 # problematic chars double caret and unbalanced braces:
2663 if href
.find('^^') != -1 or self
.has_unbalanced_braces(href
):
2665 'External link "%s" not supported by LaTeX.\n'
2666 ' (Must not contain "^^" or unbalanced braces.)' % href
)
2667 if node
['refuri'] == node
.astext():
2668 self
.out
.append(r
'\url{%s}' % href
)
2669 raise nodes
.SkipNode
2670 self
.out
.append(r
'\href{%s}{' % href
)
2672 # internal reference
2674 href
= node
['refid']
2675 elif 'refname' in node
:
2676 href
= self
.document
.nameids
[node
['refname']]
2678 raise AssertionError('Unknown reference.')
2679 if not self
.is_inline(node
):
2680 self
.out
.append('\n')
2681 self
.out
.append('\\hyperref[%s]{' % href
)
2682 if self
._reference
_label
:
2683 self
.out
.append('\\%s{%s}}' %
2684 (self
._reference
_label
, href
.replace('#', '')))
2685 raise nodes
.SkipNode
2687 def depart_reference(self
, node
):
2688 self
.out
.append('}')
2689 if not self
.is_inline(node
):
2690 self
.out
.append('\n')
2692 def visit_revision(self
, node
):
2693 self
.visit_docinfo_item(node
, 'revision')
2695 def depart_revision(self
, node
):
2696 self
.depart_docinfo_item(node
)
2698 def visit_section(self
, node
):
2699 self
.section_level
+= 1
2700 # Initialize counter for potential subsections:
2701 self
._section
_number
.append(0)
2702 # Counter for this section's level (initialized by parent section):
2703 self
._section
_number
[self
.section_level
- 1] += 1
2705 def depart_section(self
, node
):
2706 # Remove counter for potential subsections:
2707 self
._section
_number
.pop()
2708 self
.section_level
-= 1
2710 def visit_sidebar(self
, node
):
2711 self
.requirements
['color'] = PreambleCmds
.color
2712 self
.fallbacks
['sidebar'] = PreambleCmds
.sidebar
2713 self
.out
.append('\n\\DUsidebar{\n')
2715 def depart_sidebar(self
, node
):
2716 self
.out
.append('}\n')
2718 attribution_formats
= {'dash': (u
'—', ''), # EM DASH
2719 'parentheses': ('(', ')'),
2720 'parens': ('(', ')'),
2723 def visit_attribution(self
, node
):
2724 prefix
, suffix
= self
.attribution_formats
[self
.settings
.attribution
]
2725 self
.out
.append('\\nopagebreak\n\n\\raggedleft ')
2726 self
.out
.append(prefix
)
2727 self
.context
.append(suffix
)
2729 def depart_attribution(self
, node
):
2730 self
.out
.append(self
.context
.pop() + '\n')
2732 def visit_status(self
, node
):
2733 self
.visit_docinfo_item(node
, 'status')
2735 def depart_status(self
, node
):
2736 self
.depart_docinfo_item(node
)
2738 def visit_strong(self
, node
):
2739 self
.out
.append('\\textbf{')
2741 self
.visit_inline(node
)
2743 def depart_strong(self
, node
):
2745 self
.depart_inline(node
)
2746 self
.out
.append('}')
2748 def visit_substitution_definition(self
, node
):
2749 raise nodes
.SkipNode
2751 def visit_substitution_reference(self
, node
):
2752 self
.unimplemented_visit(node
)
2754 def visit_subtitle(self
, node
):
2755 if isinstance(node
.parent
, nodes
.document
):
2756 self
.push_output_collector(self
.subtitle
)
2757 self
.subtitle_labels
+= self
.ids_to_labels(node
, set_anchor
=False)
2758 # section subtitle: "starred" (no number, not in ToC)
2759 elif isinstance(node
.parent
, nodes
.section
):
2760 self
.out
.append(r
'\%s*{' %
2761 self
.d_class
.section(self
.section_level
+ 1))
2763 self
.fallbacks
['subtitle'] = PreambleCmds
.subtitle
2764 self
.out
.append('\n\\DUsubtitle[%s]{' % node
.parent
.tagname
)
2766 def depart_subtitle(self
, node
):
2767 if isinstance(node
.parent
, nodes
.document
):
2768 self
.pop_output_collector()
2770 self
.out
.append('}\n')
2772 def visit_system_message(self
, node
):
2773 self
.requirements
['color'] = PreambleCmds
.color
2774 self
.fallbacks
['title'] = PreambleCmds
.title
2775 node
['classes'] = ['system-message']
2776 self
.visit_admonition(node
)
2777 self
.out
.append('\\DUtitle[system-message]{system-message}\n')
2778 self
.append_hypertargets(node
)
2780 line
= ', line~%s' % node
['line']
2783 self
.out
.append('\n\n{\color{red}%s/%s} in \\texttt{%s}%s\n' %
2784 (node
['type'], node
['level'],
2785 self
.encode(node
['source']), line
))
2786 if len(node
['backrefs']) == 1:
2787 self
.out
.append('\n\\hyperlink{%s}{' % node
['backrefs'][0])
2788 self
.context
.append('}')
2790 backrefs
= ['\\hyperlink{%s}{%d}' % (href
, i
+1)
2791 for (i
, href
) in enumerate(node
['backrefs'])]
2792 self
.context
.append('backrefs: ' + ' '.join(backrefs
))
2794 def depart_system_message(self
, node
):
2795 self
.out
.append(self
.context
.pop())
2796 self
.depart_admonition()
2798 def visit_table(self
, node
):
2799 self
.requirements
['table'] = PreambleCmds
.table
2800 if self
.active_table
.is_open():
2801 self
.table_stack
.append(self
.active_table
)
2802 # nesting longtable does not work (e.g. 2007-04-18)
2803 self
.active_table
= Table(self
,'tabular',self
.settings
.table_style
)
2804 # A longtable moves before \paragraph and \subparagraph
2805 # section titles if it immediately follows them:
2806 if (self
.active_table
._latex
_type
== 'longtable' and
2807 isinstance(node
.parent
, nodes
.section
) and
2808 node
.parent
.index(node
) == 1 and
2809 self
.d_class
.section(self
.section_level
).find('paragraph') != -1):
2810 self
.out
.append('\\leavevmode')
2811 self
.active_table
.open()
2812 for cls
in node
['classes']:
2813 self
.active_table
.set_table_style(cls
)
2814 if self
.active_table
._table
_style
== 'booktabs':
2815 self
.requirements
['booktabs'] = r
'\usepackage{booktabs}'
2816 self
.push_output_collector([])
2818 def depart_table(self
, node
):
2819 # wrap content in the right environment:
2821 self
.pop_output_collector()
2822 self
.out
.append('\n' + self
.active_table
.get_opening())
2824 self
.out
.append(self
.active_table
.get_closing() + '\n')
2825 self
.active_table
.close()
2826 if len(self
.table_stack
)>0:
2827 self
.active_table
= self
.table_stack
.pop()
2829 self
.active_table
.set_table_style(self
.settings
.table_style
)
2830 # Insert hyperlabel after (long)table, as
2831 # other places (beginning, caption) result in LaTeX errors.
2833 self
.out
+= self
.ids_to_labels(node
, set_anchor
=False) + ['\n']
2835 def visit_target(self
, node
):
2836 # Skip indirect targets:
2837 if ('refuri' in node
# external hyperlink
2838 or 'refid' in node
# resolved internal link
2839 or 'refname' in node
): # unresolved internal link
2840 ## self.out.append('%% %s\n' % node) # for debugging
2842 self
.out
.append('%\n')
2843 # do we need an anchor (\phantomsection)?
2844 set_anchor
= not(isinstance(node
.parent
, nodes
.caption
) or
2845 isinstance(node
.parent
, nodes
.title
))
2846 # TODO: where else can/must we omit the \phantomsection?
2847 self
.out
+= self
.ids_to_labels(node
, set_anchor
)
2849 def depart_target(self
, node
):
2852 def visit_tbody(self
, node
):
2853 # BUG write preamble if not yet done (colspecs not [])
2854 # for tables without heads.
2855 if not self
.active_table
.get('preamble written'):
2856 self
.visit_thead(None)
2857 self
.depart_thead(None)
2859 def depart_tbody(self
, node
):
2862 def visit_term(self
, node
):
2863 """definition list term"""
2864 # Commands with optional args inside an optional arg must be put
2865 # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
2866 self
.out
.append('\\item[{')
2868 def depart_term(self
, node
):
2869 # \leavevmode results in a line break if the
2870 # term is followed by an item list.
2871 self
.out
.append('}] \leavevmode ')
2873 def visit_tgroup(self
, node
):
2874 #self.out.append(self.starttag(node, 'colgroup'))
2875 #self.context.append('</colgroup>\n')
2878 def depart_tgroup(self
, node
):
2882 def thead_depth (self
):
2883 return self
._thead
_depth
2885 def visit_thead(self
, node
):
2886 self
._thead
_depth
+= 1
2887 if 1 == self
.thead_depth():
2888 self
.out
.append('{%s}\n' % self
.active_table
.get_colspecs())
2889 self
.active_table
.set('preamble written',1)
2890 self
.out
.append(self
.active_table
.get_caption())
2891 self
.out
.extend(self
.active_table
.visit_thead())
2893 def depart_thead(self
, node
):
2894 if node
is not None:
2895 self
.out
.extend(self
.active_table
.depart_thead())
2896 if self
.active_table
.need_recurse():
2897 node
.walkabout(self
)
2898 self
._thead
_depth
-= 1
2900 def visit_title(self
, node
):
2901 """Append section and other titles."""
2903 if node
.parent
.tagname
== 'document':
2904 self
.push_output_collector(self
.title
)
2905 self
.context
.append('')
2906 self
.pdfinfo
.append(' pdftitle={%s},' %
2907 self
.encode(node
.astext()))
2908 # Topic titles (topic, admonition, sidebar)
2909 elif (isinstance(node
.parent
, nodes
.topic
) or
2910 isinstance(node
.parent
, nodes
.admonition
) or
2911 isinstance(node
.parent
, nodes
.sidebar
)):
2912 self
.fallbacks
['title'] = PreambleCmds
.title
2913 classes
= ','.join(node
.parent
['classes'])
2915 classes
= node
.tagname
2916 self
.out
.append('\\DUtitle[%s]{' % classes
)
2917 self
.context
.append('}\n')
2919 elif isinstance(node
.parent
, nodes
.table
):
2920 self
.push_output_collector(self
.active_table
.caption
)
2921 self
.context
.append('')
2924 if hasattr(PreambleCmds
, 'secnumdepth'):
2925 self
.requirements
['secnumdepth'] = PreambleCmds
.secnumdepth
2926 section_name
= self
.d_class
.section(self
.section_level
)
2927 self
.out
.append('\n\n')
2928 # System messages heading in red:
2929 if ('system-messages' in node
.parent
['classes']):
2930 self
.requirements
['color'] = PreambleCmds
.color
2931 section_title
= self
.encode(node
.astext())
2932 self
.out
.append(r
'\%s[%s]{\color{red}' % (
2933 section_name
,section_title
))
2935 self
.out
.append(r
'\%s{' % section_name
)
2936 if self
.section_level
> len(self
.d_class
.sections
):
2937 # section level not supported by LaTeX
2938 self
.fallbacks
['title'] = PreambleCmds
.title
2939 # self.out.append('\\phantomsection%\n ')
2940 # label and ToC entry:
2942 # add sections with unsupported level to toc and pdfbookmarks?
2943 ## if self.section_level > len(self.d_class.sections):
2944 ## section_title = self.encode(node.astext())
2945 ## bookmark.append(r'\addcontentsline{toc}{%s}{%s}' %
2946 ## (section_name, section_title))
2947 bookmark
+= self
.ids_to_labels(node
.parent
, set_anchor
=False)
2948 self
.context
.append('%\n '.join(bookmark
) + '%\n}\n')
2950 # MAYBE postfix paragraph and subparagraph with \leavemode to
2951 # ensure floats stay in the section and text starts on a new line.
2953 def depart_title(self
, node
):
2954 self
.out
.append(self
.context
.pop())
2955 if (isinstance(node
.parent
, nodes
.table
) or
2956 node
.parent
.tagname
== 'document'):
2957 self
.pop_output_collector()
2959 def minitoc(self
, node
, title
, depth
):
2960 """Generate a local table of contents with LaTeX package minitoc"""
2961 section_name
= self
.d_class
.section(self
.section_level
)
2962 # name-prefix for current section level
2963 minitoc_names
= {'part': 'part', 'chapter': 'mini'}
2964 if 'chapter' not in self
.d_class
.sections
:
2965 minitoc_names
['section'] = 'sect'
2967 minitoc_name
= minitoc_names
[section_name
]
2968 except KeyError: # minitoc only supports part- and toplevel
2969 self
.warn('Skipping local ToC at %s level.\n' % section_name
+
2970 ' Feature not supported with option "use-latex-toc"',
2973 # Requirements/Setup
2974 self
.requirements
['minitoc'] = PreambleCmds
.minitoc
2975 self
.requirements
['minitoc-'+minitoc_name
] = (r
'\do%stoc' %
2977 # depth: (Docutils defaults to unlimited depth)
2978 maxdepth
= len(self
.d_class
.sections
)
2979 self
.requirements
['minitoc-%s-depth' % minitoc_name
] = (
2980 r
'\mtcsetdepth{%stoc}{%d}' % (minitoc_name
, maxdepth
))
2981 # Process 'depth' argument (!Docutils stores a relative depth while
2982 # minitoc expects an absolute depth!):
2983 offset
= {'sect': 1, 'mini': 0, 'part': 0}
2984 if 'chapter' in self
.d_class
.sections
:
2987 self
.out
.append('\\setcounter{%stocdepth}{%d}' %
2988 (minitoc_name
, depth
+ offset
[minitoc_name
]))
2990 self
.out
.append('\\mtcsettitle{%stoc}{%s}\n' % (minitoc_name
, title
))
2991 # the toc-generating command:
2992 self
.out
.append('\\%stoc\n' % minitoc_name
)
2994 def visit_topic(self
, node
):
2995 # Topic nodes can be generic topic, abstract, dedication, or ToC.
2996 # table of contents:
2997 if 'contents' in node
['classes']:
2998 self
.out
.append('\n')
2999 self
.out
+= self
.ids_to_labels(node
)
3000 # add contents to PDF bookmarks sidebar
3001 if isinstance(node
.next_node(), nodes
.title
):
3002 self
.out
.append('\n\\pdfbookmark[%d]{%s}{%s}\n' %
3003 (self
.section_level
+1,
3004 node
.next_node().astext(),
3005 node
.get('ids', ['contents'])[0]
3007 if self
.use_latex_toc
:
3009 if isinstance(node
.next_node(), nodes
.title
):
3010 title
= self
.encode(node
.pop(0).astext())
3011 depth
= node
.get('depth', 0)
3012 if 'local' in node
['classes']:
3013 self
.minitoc(node
, title
, depth
)
3014 self
.context
.append('')
3017 self
.out
.append('\\setcounter{tocdepth}{%d}\n' % depth
)
3018 if title
!= 'Contents':
3019 self
.out
.append('\\renewcommand{\\contentsname}{%s}\n' %
3021 self
.out
.append('\\tableofcontents\n\n')
3022 self
.has_latex_toc
= True
3023 else: # Docutils generated contents list
3024 # set flag for visit_bullet_list() and visit_title()
3025 self
.is_toc_list
= True
3026 self
.context
.append('')
3027 elif ('abstract' in node
['classes'] and
3028 self
.settings
.use_latex_abstract
):
3029 self
.push_output_collector(self
.abstract
)
3030 self
.out
.append('\\begin{abstract}')
3031 self
.context
.append('\\end{abstract}\n')
3032 if isinstance(node
.next_node(), nodes
.title
):
3033 node
.pop(0) # LaTeX provides its own title
3035 self
.fallbacks
['topic'] = PreambleCmds
.topic
3037 if 'abstract' in node
['classes']:
3038 self
.fallbacks
['abstract'] = PreambleCmds
.abstract
3039 self
.push_output_collector(self
.abstract
)
3040 if 'dedication' in node
['classes']:
3041 self
.fallbacks
['dedication'] = PreambleCmds
.dedication
3042 self
.push_output_collector(self
.dedication
)
3043 self
.out
.append('\n\\DUtopic[%s]{\n' % ','.join(node
['classes']))
3044 self
.context
.append('}\n')
3046 def depart_topic(self
, node
):
3047 self
.out
.append(self
.context
.pop())
3048 self
.is_toc_list
= False
3049 if ('abstract' in node
['classes'] or
3050 'dedication' in node
['classes']):
3051 self
.pop_output_collector()
3053 def visit_rubric(self
, node
):
3054 self
.fallbacks
['rubric'] = PreambleCmds
.rubric
3055 self
.out
.append('\n\\DUrubric{')
3056 self
.context
.append('}\n')
3058 def depart_rubric(self
, node
):
3059 self
.out
.append(self
.context
.pop())
3061 def visit_transition(self
, node
):
3062 self
.fallbacks
['transition'] = PreambleCmds
.transition
3063 self
.out
.append('\n\n')
3064 self
.out
.append('%' + '_' * 75 + '\n')
3065 self
.out
.append(r
'\DUtransition')
3066 self
.out
.append('\n\n')
3068 def depart_transition(self
, node
):
3071 def visit_version(self
, node
):
3072 self
.visit_docinfo_item(node
, 'version')
3074 def depart_version(self
, node
):
3075 self
.depart_docinfo_item(node
)
3077 def unimplemented_visit(self
, node
):
3078 raise NotImplementedError('visiting unimplemented node type: %s' %
3079 node
.__class
__.__name
__)
3081 # def unknown_visit(self, node):
3082 # def default_visit(self, node):
3084 # vim: set ts=4 et ai :