3 # Author: Engelbert Gruber, Günter Milde
4 # Maintainer: docutils-develop@lists.sourceforge.net
5 # Copyright: This module has been placed in the public domain.
7 """LaTeX2e document tree Writer."""
9 __docformat__
= 'reStructuredText'
11 # code contributions from several people included, thanks to all.
12 # some named: David Abrahams, Julien Letessier, Lele Gaifax, and others.
14 # convention deactivate code by two # i.e. ##.
25 import docutils
.utils
.roman
as roman
26 from docutils
import frontend
, nodes
, languages
, writers
, utils
, io
27 from docutils
.utils
.error_reporting
import SafeString
28 from docutils
.transforms
import writer_aux
29 from docutils
.utils
.math
import pick_math_environment
, unichar2tex
31 class Writer(writers
.Writer
):
33 supported
= ('latex','latex2e')
34 """Formats this writer supports."""
36 default_template
= 'default.tex'
37 default_template_path
= os
.path
.dirname(__file__
)
39 default_preamble
= '\n'.join([r
'% PDF Standard Fonts',
40 r
'\usepackage{mathptmx} % Times',
41 r
'\usepackage[scaled=.90]{helvet}',
42 r
'\usepackage{courier}'])
44 'LaTeX-Specific Options',
46 (('Specify documentclass. Default is "article".',
48 {'default': 'article', }),
49 ('Specify document options. Multiple options can be given, '
50 'separated by commas. Default is "a4paper".',
51 ['--documentoptions'],
52 {'default': 'a4paper', }),
53 ('Footnotes with numbers/symbols by Docutils. (default)',
54 ['--docutils-footnotes'],
55 {'default': True, 'action': 'store_true',
56 'validator': frontend
.validate_boolean
}),
57 ('Alias for --docutils-footnotes (deprecated)',
58 ['--use-latex-footnotes'],
59 {'action': 'store_true',
60 'validator': frontend
.validate_boolean
}),
61 ('Use figure floats for footnote text (deprecated)',
62 ['--figure-footnotes'],
63 {'action': 'store_true',
64 'validator': frontend
.validate_boolean
}),
65 ('Format for footnote references: one of "superscript" or '
66 '"brackets". Default is "superscript".',
67 ['--footnote-references'],
68 {'choices': ['superscript', 'brackets'], 'default': 'superscript',
69 'metavar': '<format>',
70 'overrides': 'trim_footnote_reference_space'}),
71 ('Use \\cite command for citations. ',
72 ['--use-latex-citations'],
73 {'default': 0, 'action': 'store_true',
74 'validator': frontend
.validate_boolean
}),
75 ('Use figure floats for citations '
76 '(might get mixed with real figures). (default)',
77 ['--figure-citations'],
78 {'dest': 'use_latex_citations', 'action': 'store_false',
79 'validator': frontend
.validate_boolean
}),
80 ('Format for block quote attributions: one of "dash" (em-dash '
81 'prefix), "parentheses"/"parens", or "none". Default is "dash".',
83 {'choices': ['dash', 'parentheses', 'parens', 'none'],
84 'default': 'dash', 'metavar': '<format>'}),
85 ('Specify LaTeX packages/stylesheets. '
86 ' A style is referenced with \\usepackage if extension is '
87 '".sty" or omitted and with \\input else. '
88 ' Overrides previous --stylesheet and --stylesheet-path settings.',
90 {'default': '', 'metavar': '<file>',
91 'overrides': 'stylesheet_path',
92 'validator': frontend
.validate_comma_separated_list
}),
93 ('Like --stylesheet, but the path is rewritten '
94 'relative to the output file. ',
95 ['--stylesheet-path'],
96 {'metavar': '<file>', 'overrides': 'stylesheet',
97 'validator': frontend
.validate_comma_separated_list
}),
98 ('Link to the stylesheet(s) in the output file. (default)',
99 ['--link-stylesheet'],
100 {'dest': 'embed_stylesheet', 'action': 'store_false'}),
101 ('Embed the stylesheet(s) in the output file. '
102 'Stylesheets must be accessible during processing. ',
103 ['--embed-stylesheet'],
104 {'default': 0, 'action': 'store_true',
105 'validator': frontend
.validate_boolean
}),
106 ('Customization by LaTeX code in the preamble. '
107 'Default: select PDF standard fonts (Times, Helvetica, Courier).',
108 ['--latex-preamble'],
109 {'default': default_preamble
}),
110 ('Specify the template file. Default: "%s".' % default_template
,
112 {'default': default_template
, 'metavar': '<file>'}),
113 ('Table of contents by LaTeX. (default) ',
115 {'default': 1, 'action': 'store_true',
116 'validator': frontend
.validate_boolean
}),
117 ('Table of contents by Docutils (without page numbers). ',
118 ['--use-docutils-toc'],
119 {'dest': 'use_latex_toc', 'action': 'store_false',
120 'validator': frontend
.validate_boolean
}),
121 ('Add parts on top of the section hierarchy.',
122 ['--use-part-section'],
123 {'default': 0, 'action': 'store_true',
124 'validator': frontend
.validate_boolean
}),
125 ('Attach author and date to the document info table. (default) ',
126 ['--use-docutils-docinfo'],
127 {'dest': 'use_latex_docinfo', 'action': 'store_false',
128 'validator': frontend
.validate_boolean
}),
129 ('Attach author and date to the document title.',
130 ['--use-latex-docinfo'],
131 {'default': 0, 'action': 'store_true',
132 'validator': frontend
.validate_boolean
}),
133 ("Typeset abstract as topic. (default)",
134 ['--topic-abstract'],
135 {'dest': 'use_latex_abstract', 'action': 'store_false',
136 'validator': frontend
.validate_boolean
}),
137 ("Use LaTeX abstract environment for the document's abstract. ",
138 ['--use-latex-abstract'],
139 {'default': 0, 'action': 'store_true',
140 'validator': frontend
.validate_boolean
}),
141 ('Color of any hyperlinks embedded in text '
142 '(default: "blue", "false" to disable).',
143 ['--hyperlink-color'], {'default': 'blue'}),
144 ('Additional options to the "hyperref" package '
146 ['--hyperref-options'], {'default': ''}),
147 ('Enable compound enumerators for nested enumerated lists '
148 '(e.g. "1.2.a.ii"). Default: disabled.',
149 ['--compound-enumerators'],
150 {'default': None, 'action': 'store_true',
151 'validator': frontend
.validate_boolean
}),
152 ('Disable compound enumerators for nested enumerated lists. '
153 'This is the default.',
154 ['--no-compound-enumerators'],
155 {'action': 'store_false', 'dest': 'compound_enumerators'}),
156 ('Enable section ("." subsection ...) prefixes for compound '
157 'enumerators. This has no effect without --compound-enumerators.'
158 'Default: disabled.',
159 ['--section-prefix-for-enumerators'],
160 {'default': None, 'action': 'store_true',
161 'validator': frontend
.validate_boolean
}),
162 ('Disable section prefixes for compound enumerators. '
163 'This is the default.',
164 ['--no-section-prefix-for-enumerators'],
165 {'action': 'store_false', 'dest': 'section_prefix_for_enumerators'}),
166 ('Set the separator between section number and enumerator '
167 'for compound enumerated lists. Default is "-".',
168 ['--section-enumerator-separator'],
169 {'default': '-', 'metavar': '<char>'}),
170 ('When possibile, use the specified environment for literal-blocks. '
171 'Default is quoting of whitespace and special chars.',
172 ['--literal-block-env'],
174 ('When possibile, use verbatim for literal-blocks. '
175 'Compatibility alias for "--literal-block-env=verbatim".',
176 ['--use-verbatim-when-possible'],
177 {'default': 0, 'action': 'store_true',
178 'validator': frontend
.validate_boolean
}),
179 ('Table style. "standard" with horizontal and vertical lines, '
180 '"booktabs" (LaTeX booktabs style) only horizontal lines '
181 'above and below the table and below the header or "borderless". '
182 'Default: "standard"',
184 {'choices': ['standard', 'booktabs','nolines', 'borderless'],
185 'default': 'standard',
186 'metavar': '<format>'}),
187 ('LaTeX graphicx package option. '
188 'Possible values are "dvips", "pdftex". "auto" includes LaTeX code '
189 'to use "pdftex" if processing with pdf(la)tex and dvips otherwise. '
190 'Default is no option.',
191 ['--graphicx-option'],
193 ('LaTeX font encoding. '
194 'Possible values are "", "T1" (default), "OT1", "LGR,T1" or '
195 'any other combination of options to the `fontenc` package. ',
198 ('Per default the latex-writer puts the reference title into '
199 'hyperreferences. Specify "ref*" or "pageref*" to get the section '
200 'number or the page number.',
201 ['--reference-label'],
202 {'default': None, }),
203 ('Specify style and database for bibtex, for example '
204 '"--use-bibtex=mystyle,mydb1,mydb2".',
206 {'default': None, }),
209 settings_defaults
= {'sectnum_depth': 0 # updated by SectNum transform
211 relative_path_settings
= ('stylesheet_path',)
213 config_section
= 'latex2e writer'
214 config_section_dependencies
= ('writers',)
216 head_parts
= ('head_prefix', 'requirements', 'latex_preamble',
217 'stylesheet', 'fallbacks', 'pdfsetup',
218 'title', 'subtitle', 'titledata')
219 visitor_attributes
= head_parts
+ ('body_pre_docinfo', 'docinfo',
220 'dedication', 'abstract', 'body')
223 """Final translated form of `document`."""
226 writers
.Writer
.__init
__(self
)
227 self
.translator_class
= LaTeXTranslator
229 # Override parent method to add latex-specific transforms
230 def get_transforms(self
):
231 return writers
.Writer
.get_transforms(self
) + [
232 # Convert specific admonitions to generic one
233 writer_aux
.Admonitions
,
234 # TODO: footnote collection transform
238 visitor
= self
.translator_class(self
.document
)
239 self
.document
.walkabout(visitor
)
241 for part
in self
.visitor_attributes
:
242 setattr(self
, part
, getattr(visitor
, part
))
243 # get template string from file
245 template_file
= open(self
.document
.settings
.template
, 'rb')
247 template_file
= open(os
.path
.join(self
.default_template_path
,
248 self
.document
.settings
.template
), 'rb')
249 template
= string
.Template(unicode(template_file
.read(), 'utf-8'))
250 template_file
.close()
252 self
.assemble_parts() # create dictionary of parts
253 self
.output
= template
.substitute(self
.parts
)
255 def assemble_parts(self
):
256 """Assemble the `self.parts` dictionary of output fragments."""
257 writers
.Writer
.assemble_parts(self
)
258 for part
in self
.visitor_attributes
:
259 lines
= getattr(self
, part
)
260 if part
in self
.head_parts
:
262 lines
.append('') # to get a trailing newline
263 self
.parts
[part
] = '\n'.join(lines
)
265 # body contains inline elements, so join without newline
266 self
.parts
[part
] = ''.join(lines
)
270 """Language specifics for LaTeX."""
272 # TeX (babel) language names:
273 # ! not all of these are supported by Docutils!
275 # based on LyX' languages file with adaptions to `BCP 47`_
276 # (http://www.rfc-editor.org/rfc/bcp/bcp47.txt) and
277 # http://www.tug.org/TUGboat/Articles/tb29-3/tb93miklavec.pdf
278 # * the key without subtags is the default
280 # cf. http://docutils.sourceforge.net/docs/howto/i18n.html
281 # http://www.w3.org/International/articles/language-tags/
282 # and http://www.iana.org/assignments/language-subtag-registry
284 # code TeX/Babel-name comment
287 # 'be': 'belarusian',
295 'de': 'ngerman', # new spelling (de_1996)
296 'de-1901': 'german', # old spelling
297 'de-AT': 'naustrian',
298 'de-AT-1901': 'austrian',
299 'dsb': 'lowersorbian',
300 'el': 'greek', # monotonic (el-monoton)
301 'el-polyton': 'polutonikogreek',
302 'en': 'english', # TeX' default language
303 'en-AU': 'australian',
306 'en-NZ': 'newzealand',
316 'ga': 'irish', # Irish Gaelic
317 # 'grc': # Ancient Greek
318 'grc-ibycus': 'ibycus', # Ibycus encoding
322 'hsb': 'uppersorbian',
325 'id': 'bahasai', # Bahasa (Indonesian)
333 'mn': 'mongolian', # Mongolian, Cyrillic script (mn-cyrl)
334 'ms': 'bahasam', # Bahasa (Malay)
335 'nb': 'norsk', # Norwegian Bokmal
337 'nn': 'nynorsk', # Norwegian Nynorsk
338 'no': 'norsk', # Norwegian (Bokmal)
344 'se': 'samin', # North Sami
345 # sh-Cyrl: Serbo-Croatian, Cyrillic script
346 'sh-Latn': 'serbian', # Serbo-Croatian, Latin script
350 # 'sr-Cyrl': Serbian, Cyrillic script (sr-cyrl)
351 'sr-Latn': 'serbian', # Serbian, Latin script
357 # zh-Latn: Chinese Pinyin
359 # normalize (downcase) keys
360 language_codes
= dict([(k
.lower(), v
) for (k
,v
) in language_codes
.items()])
362 warn_msg
= 'Language "%s" not supported by LaTeX (babel)'
364 # "Active characters" are shortcuts that start a LaTeX macro and may need
365 # escaping for literals use. Characters that prevent literal use (e.g.
366 # starting accent macros like "a -> ä) will be deactivated if one of the
367 # defining languages is used in the document.
369 # ~ (tilde) -- used in estonian, basque, galician, and old versions of
370 # spanish -- cannot be deactivated as it denotes a no-break space macro,
371 # " (straight quote) -- used in albanian, austrian, basque
372 # brazil, bulgarian, catalan, czech, danish, dutch, estonian,
373 # finnish, galician, german, icelandic, italian, latin, naustrian,
374 # ngerman, norsk, nynorsk, polish, portuges, russian, serbian, slovak,
375 # slovene, spanish, swedish, ukrainian, and uppersorbian --
376 # is escaped as ``\textquotedbl``.
377 active_chars
= {# TeX/Babel-name: active characters to deactivate
378 # 'breton': ':;!?' # ensure whitespace
381 # 'french': ':;!?' # ensure whitespace
382 'galician': '.<>', # also '~"'
383 # 'magyar': '`', # for special hyphenation cases
384 'spanish': '.<>', # old versions also '~'
385 # 'turkish': ':!=' # ensure whitespace
388 def __init__(self
, language_code
, reporter
=None):
389 self
.reporter
= reporter
390 self
.language
= self
.language_name(language_code
)
391 self
.otherlanguages
= {}
394 """Return the babel call with correct options and settings"""
395 languages
= sorted(self
.otherlanguages
.keys())
396 languages
.append(self
.language
or 'english')
397 self
.setup
= [r
'\usepackage[%s]{babel}' % ','.join(languages
)]
398 # Deactivate "active characters"
400 for c
in ''.join([self
.active_chars
.get(l
, '') for l
in languages
]):
401 if c
not in shorthands
:
404 self
.setup
.append(r
'\AtBeginDocument{\shorthandoff{%s}}'
405 % ''.join(shorthands
))
406 # Including '~' in shorthandoff prevents its use as no-break space
407 if 'galician' in languages
:
408 self
.setup
.append(r
'\deactivatetilden % restore ~ in Galician')
409 if 'estonian' in languages
:
410 self
.setup
.extend([r
'\makeatletter',
411 r
' \addto\extrasestonian{\bbl@deactivate{~}}',
413 if 'basque' in languages
:
414 self
.setup
.extend([r
'\makeatletter',
415 r
' \addto\extrasbasque{\bbl@deactivate{~}}',
417 if (languages
[-1] == 'english' and
418 'french' in self
.otherlanguages
.keys()):
419 self
.setup
+= ['% Prevent side-effects if French hyphenation '
420 'patterns are not loaded:',
421 r
'\frenchbsetup{StandardLayout}',
422 r
'\AtBeginDocument{\selectlanguage{%s}'
423 r
'\noextrasfrench}' % self
.language
]
424 return '\n'.join(self
.setup
)
426 def language_name(self
, language_code
):
427 """Return TeX language name for `language_code`"""
428 for tag
in utils
.normalize_language_tag(language_code
):
430 return self
.language_codes
[tag
]
433 if self
.reporter
is not None:
434 self
.reporter
.warning(self
.warn_msg
% language_code
)
437 def get_language(self
):
438 # Obsolete, kept for backwards compatibility with Sphinx
442 # Building blocks for the latex preamble
443 # --------------------------------------
445 class SortableDict(dict):
446 """Dictionary with additional sorting methods
448 Tip: use key starting with with '_' for sorting before small letters
449 and with '~' for sorting after small letters.
451 def sortedkeys(self
):
452 """Return sorted list of keys"""
457 def sortedvalues(self
):
458 """Return list of values sorted by keys"""
459 return [self
[key
] for key
in self
.sortedkeys()]
464 # A container for LaTeX code snippets that can be
465 # inserted into the preamble if required in the document.
467 # .. The package 'makecmds' would enable shorter definitions using the
468 # \providelength and \provideenvironment commands.
469 # However, it is pretty non-standard (texlive-latex-extra).
471 class PreambleCmds(object):
472 """Building blocks for the latex preamble."""
474 PreambleCmds
.abstract
= r
"""
476 \providecommand*{\DUtitleabstract}[1]{\centerline{\textbf{#1}}}"""
478 PreambleCmds
.admonition
= r
"""
479 % admonition (specially marked topic)
480 \providecommand{\DUadmonition}[2][class-arg]{%
481 % try \DUadmonition#1{#2}:
482 \ifcsname DUadmonition#1\endcsname%
483 \csname DUadmonition#1\endcsname{#2}%
486 \fbox{\parbox{0.9\textwidth}{#2}}
491 PreambleCmds
.align_center
= r
"""
493 \@namedef{DUrolealign-center}{\centering}
497 ## PreambleCmds.caption = r"""% configure caption layout
498 ## \usepackage{caption}
499 ## \captionsetup{singlelinecheck=false}% no exceptions for one-liners"""
501 PreambleCmds
.color
= r
"""\usepackage{color}"""
503 PreambleCmds
.docinfo
= r
"""
504 % docinfo (width of docinfo table)
505 \DUprovidelength{\DUdocinfowidth}{0.9\textwidth}"""
506 # PreambleCmds.docinfo._depends = 'providelength'
508 PreambleCmds
.dedication
= r
"""
510 \providecommand{\DUtopicdedication}[1]{\begin{center}#1\end{center}}"""
512 PreambleCmds
.error
= r
"""
513 % error admonition title
514 \providecommand*{\DUtitleerror}[1]{\DUtitle{\color{red}#1}}"""
515 # PreambleCmds.errortitle._depends = 'color'
517 PreambleCmds
.fieldlist
= r
"""
518 % fieldlist environment
519 \ifthenelse{\isundefined{\DUfieldlist}}{
520 \newenvironment{DUfieldlist}%
522 {\enddescription\endquote}
525 PreambleCmds
.float_settings
= r
"""\usepackage{float} % float configuration
526 \floatplacement{figure}{H} % place figures here definitely"""
528 PreambleCmds
.footnotes
= r
"""% numeric or symbol footnotes with hyperlinks
529 \providecommand*{\DUfootnotemark}[3]{%
530 \raisebox{1em}{\hypertarget{#1}{}}%
531 \hyperlink{#2}{\textsuperscript{#3}}%
533 \providecommand{\DUfootnotetext}[4]{%
535 \renewcommand{\thefootnote}{%
536 \protect\raisebox{1em}{\protect\hypertarget{#1}{}}%
537 \protect\hyperlink{#2}{#3}}%
542 PreambleCmds
.footnote_floats
= r
"""% settings for footnotes as floats:
543 \setlength{\floatsep}{0.5em}
544 \setlength{\textfloatsep}{\fill}
545 \addtolength{\textfloatsep}{3em}
546 \renewcommand{\textfraction}{0.5}
547 \renewcommand{\topfraction}{0.5}
548 \renewcommand{\bottomfraction}{0.5}
549 \setcounter{totalnumber}{50}
550 \setcounter{topnumber}{50}
551 \setcounter{bottomnumber}{50}"""
553 PreambleCmds
.graphicx_auto
= r
"""% Check output format
554 \ifx\pdftexversion\undefined
555 \usepackage{graphicx}
557 \usepackage[pdftex]{graphicx}
560 PreambleCmds
.highlight_rules
= r
"""% basic code highlight:
561 \providecommand*\DUrolecomment[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
562 \providecommand*\DUroledeleted[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
563 \providecommand*\DUrolekeyword[1]{\textbf{#1}}
564 \providecommand*\DUrolestring[1]{\textit{#1}}"""
566 PreambleCmds
.inline
= r
"""
567 % inline markup (custom roles)
568 % \DUrole{#1}{#2} tries \DUrole#1{#2}
569 \providecommand*{\DUrole}[2]{%
570 \ifcsname DUrole#1\endcsname%
571 \csname DUrole#1\endcsname{#2}%
572 \else% backwards compatibility: try \docutilsrole#1{#2}
573 \ifcsname docutilsrole#1\endcsname%
574 \csname docutilsrole#1\endcsname{#2}%
581 PreambleCmds
.legend
= r
"""
583 \ifthenelse{\isundefined{\DUlegend}}{
584 \newenvironment{DUlegend}{\small}{}
587 PreambleCmds
.lineblock
= r
"""
588 % lineblock environment
589 \DUprovidelength{\DUlineblockindent}{2.5em}
590 \ifthenelse{\isundefined{\DUlineblock}}{
591 \newenvironment{DUlineblock}[1]{%
592 \list{}{\setlength{\partopsep}{\parskip}
593 \addtolength{\partopsep}{\baselineskip}
594 \setlength{\topsep}{0pt}
595 \setlength{\itemsep}{0.15\baselineskip}
596 \setlength{\parsep}{0pt}
597 \setlength{\leftmargin}{#1}}
602 # PreambleCmds.lineblock._depends = 'providelength'
604 PreambleCmds
.linking
= r
"""
606 \ifthenelse{\isundefined{\hypersetup}}{
607 \usepackage[%s]{hyperref}
608 \urlstyle{same} %% normal text font (alternatives: tt, rm, sf)
611 PreambleCmds
.minitoc
= r
"""%% local table of contents
612 \usepackage{minitoc}"""
614 PreambleCmds
.optionlist
= r
"""
615 % optionlist environment
616 \providecommand*{\DUoptionlistlabel}[1]{\bf #1 \hfill}
617 \DUprovidelength{\DUoptionlistindent}{3cm}
618 \ifthenelse{\isundefined{\DUoptionlist}}{
619 \newenvironment{DUoptionlist}{%
620 \list{}{\setlength{\labelwidth}{\DUoptionlistindent}
621 \setlength{\rightmargin}{1cm}
622 \setlength{\leftmargin}{\rightmargin}
623 \addtolength{\leftmargin}{\labelwidth}
624 \addtolength{\leftmargin}{\labelsep}
625 \renewcommand{\makelabel}{\DUoptionlistlabel}}
629 # PreambleCmds.optionlist._depends = 'providelength'
631 PreambleCmds
.providelength
= r
"""
632 % providelength (provide a length variable and set default, if it is new)
633 \providecommand*{\DUprovidelength}[2]{
634 \ifthenelse{\isundefined{#1}}{\newlength{#1}\setlength{#1}{#2}}{}
637 PreambleCmds
.rubric
= r
"""
638 % rubric (informal heading)
639 \providecommand*{\DUrubric}[2][class-arg]{%
640 \subsubsection*{\centering\textit{\textmd{#2}}}}"""
642 PreambleCmds
.sidebar
= r
"""
643 % sidebar (text outside the main text flow)
644 \providecommand{\DUsidebar}[2][class-arg]{%
646 \colorbox[gray]{0.80}{\parbox{0.9\textwidth}{#2}}
650 PreambleCmds
.subtitle
= r
"""
651 % subtitle (for topic/sidebar)
652 \providecommand*{\DUsubtitle}[2][class-arg]{\par\emph{#2}\smallskip}"""
654 PreambleCmds
.table
= r
"""\usepackage{longtable,ltcaption,array}
655 \setlength{\extrarowheight}{2pt}
656 \newlength{\DUtablewidth} % internal use in tables"""
658 # Options [force,almostfull] prevent spurious error messages, see
659 # de.comp.text.tex/2005-12/msg01855
660 PreambleCmds
.textcomp
= """\
661 \\usepackage{textcomp} % text symbol macros"""
663 PreambleCmds
.titlereference
= r
"""
664 % titlereference role
665 \providecommand*{\DUroletitlereference}[1]{\textsl{#1}}"""
667 PreambleCmds
.title
= r
"""
668 % title for topics, admonitions, unsupported section levels, and sidebar
669 \providecommand*{\DUtitle}[2][class-arg]{%
670 % call \DUtitle#1{#2} if it exists:
671 \ifcsname DUtitle#1\endcsname%
672 \csname DUtitle#1\endcsname{#2}%
674 \smallskip\noindent\textbf{#2}\smallskip%
678 PreambleCmds
.topic
= r
"""
679 % topic (quote with heading)
680 \providecommand{\DUtopic}[2][class-arg]{%
681 \ifcsname DUtopic#1\endcsname%
682 \csname DUtopic#1\endcsname{#2}%
684 \begin{quote}#2\end{quote}
688 PreambleCmds
.transition
= r
"""
689 % transition (break, fancybreak, anonymous section)
690 \providecommand*{\DUtransition}[1][class-arg]{%
691 \hspace*{\fill}\hrulefill\hspace*{\fill}
692 \vskip 0.5\baselineskip
696 # LaTeX encoding maps
697 # -------------------
700 class CharMaps(object):
701 """LaTeX representations for active and Unicode characters."""
703 # characters that always need escaping:
709 ord('~'): ur
'\textasciitilde{}',
711 ord('^'): ur
'\textasciicircum{}',
712 ord('\\'): ur
'\textbackslash{}',
715 # straight double quotes are 'active' in many languages
716 ord('"'): ur
'\textquotedbl{}',
717 # Square brackets are ordinary chars and cannot be escaped with '\',
718 # so we put them in a group '{[}'. (Alternative: ensure that all
719 # macros with optional arguments are terminated with {} and text
720 # inside any optional argument is put in a group ``[{text}]``).
721 # Commands with optional args inside an optional arg must be put in a
722 # group, e.g. ``\item[{\hyperref[label]{text}}]``.
725 # the soft hyphen is unknown in 8-bit text
726 # and not properly handled by XeTeX
727 0x00AD: ur
'\-', # SOFT HYPHEN
729 # Unicode chars that are not recognized by LaTeX's utf8 encoding
730 unsupported_unicode
= {
731 0x00A0: ur
'~', # NO-BREAK SPACE
732 # TODO: ensure white space also at the beginning of a line?
733 # 0x00A0: ur'\leavevmode\nobreak\vadjust{}~'
734 0x2008: ur
'\,', # PUNCTUATION SPACE
735 0x2011: ur
'\hbox{-}', # NON-BREAKING HYPHEN
736 0x202F: ur
'\,', # NARROW NO-BREAK SPACE
737 0x21d4: ur
'$\Leftrightarrow$',
738 # Docutils footnote symbols:
739 0x2660: ur
'$\spadesuit$',
740 0x2663: ur
'$\clubsuit$',
742 # Unicode chars that are recognized by LaTeX's utf8 encoding
743 utf8_supported_unicode
= {
744 0x00AB: ur
'\guillemotleft', # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
745 0x00bb: ur
'\guillemotright', # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
746 0x200C: ur
'\textcompwordmark', # ZERO WIDTH NON-JOINER
747 0x2013: ur
'\textendash{}',
748 0x2014: ur
'\textemdash{}',
749 0x2018: ur
'\textquoteleft{}',
750 0x2019: ur
'\textquoteright{}',
751 0x201A: ur
'\quotesinglbase{}', # SINGLE LOW-9 QUOTATION MARK
752 0x201C: ur
'\textquotedblleft{}',
753 0x201D: ur
'\textquotedblright{}',
754 0x201E: ur
'\quotedblbase{}', # DOUBLE LOW-9 QUOTATION MARK
755 0x2030: ur
'\textperthousand{}', # PER MILLE SIGN
756 0x2031: ur
'\textpertenthousand{}', # PER TEN THOUSAND SIGN
757 0x2039: ur
'\guilsinglleft{}',
758 0x203A: ur
'\guilsinglright{}',
759 0x2423: ur
'\textvisiblespace{}', # OPEN BOX
763 0x2122: ur
'\texttrademark{}',
765 # recognized with 'utf8', if textcomp is loaded
768 0x00a2: ur
'\textcent{}', # ¢ CENT SIGN
769 0x00a4: ur
'\textcurrency{}', # ¤ CURRENCY SYMBOL
770 0x00a5: ur
'\textyen{}', # ¥ YEN SIGN
771 0x00a6: ur
'\textbrokenbar{}', # ¦ BROKEN BAR
772 0x00a7: ur
'\textsection{}', # § SECTION SIGN
773 0x00a8: ur
'\textasciidieresis{}', # ¨ DIAERESIS
774 0x00a9: ur
'\textcopyright{}', # © COPYRIGHT SIGN
775 0x00aa: ur
'\textordfeminine{}', # ª FEMININE ORDINAL INDICATOR
776 0x00ac: ur
'\textlnot{}', # ¬ NOT SIGN
777 0x00ae: ur
'\textregistered{}', # ® REGISTERED SIGN
778 0x00af: ur
'\textasciimacron{}', # ¯ MACRON
779 0x00b0: ur
'\textdegree{}', # ° DEGREE SIGN
780 0x00b1: ur
'\textpm{}', # ± PLUS-MINUS SIGN
781 0x00b2: ur
'\texttwosuperior{}', # ² SUPERSCRIPT TWO
782 0x00b3: ur
'\textthreesuperior{}', # ³ SUPERSCRIPT THREE
783 0x00b4: ur
'\textasciiacute{}', # ´ ACUTE ACCENT
784 0x00b5: ur
'\textmu{}', # µ MICRO SIGN
785 0x00b6: ur
'\textparagraph{}', # ¶ PILCROW SIGN # != \textpilcrow
786 0x00b9: ur
'\textonesuperior{}', # ¹ SUPERSCRIPT ONE
787 0x00ba: ur
'\textordmasculine{}', # º MASCULINE ORDINAL INDICATOR
788 0x00bc: ur
'\textonequarter{}', # 1/4 FRACTION
789 0x00bd: ur
'\textonehalf{}', # 1/2 FRACTION
790 0x00be: ur
'\textthreequarters{}', # 3/4 FRACTION
791 0x00d7: ur
'\texttimes{}', # × MULTIPLICATION SIGN
792 0x00f7: ur
'\textdiv{}', # ÷ DIVISION SIGN
794 0x0192: ur
'\textflorin{}', # LATIN SMALL LETTER F WITH HOOK
795 0x02b9: ur
'\textasciiacute{}', # MODIFIER LETTER PRIME
796 0x02ba: ur
'\textacutedbl{}', # MODIFIER LETTER DOUBLE PRIME
797 0x2016: ur
'\textbardbl{}', # DOUBLE VERTICAL LINE
798 0x2022: ur
'\textbullet{}', # BULLET
799 0x2032: ur
'\textasciiacute{}', # PRIME
800 0x2033: ur
'\textacutedbl{}', # DOUBLE PRIME
801 0x2035: ur
'\textasciigrave{}', # REVERSED PRIME
802 0x2036: ur
'\textgravedbl{}', # REVERSED DOUBLE PRIME
803 0x203b: ur
'\textreferencemark{}', # REFERENCE MARK
804 0x203d: ur
'\textinterrobang{}', # INTERROBANG
805 0x2044: ur
'\textfractionsolidus{}', # FRACTION SLASH
806 0x2045: ur
'\textlquill{}', # LEFT SQUARE BRACKET WITH QUILL
807 0x2046: ur
'\textrquill{}', # RIGHT SQUARE BRACKET WITH QUILL
808 0x2052: ur
'\textdiscount{}', # COMMERCIAL MINUS SIGN
809 0x20a1: ur
'\textcolonmonetary{}', # COLON SIGN
810 0x20a3: ur
'\textfrenchfranc{}', # FRENCH FRANC SIGN
811 0x20a4: ur
'\textlira{}', # LIRA SIGN
812 0x20a6: ur
'\textnaira{}', # NAIRA SIGN
813 0x20a9: ur
'\textwon{}', # WON SIGN
814 0x20ab: ur
'\textdong{}', # DONG SIGN
815 0x20ac: ur
'\texteuro{}', # EURO SIGN
816 0x20b1: ur
'\textpeso{}', # PESO SIGN
817 0x20b2: ur
'\textguarani{}', # GUARANI SIGN
818 0x2103: ur
'\textcelsius{}', # DEGREE CELSIUS
819 0x2116: ur
'\textnumero{}', # NUMERO SIGN
820 0x2117: ur
'\textcircledP{}', # SOUND RECORDING COYRIGHT
821 0x211e: ur
'\textrecipe{}', # PRESCRIPTION TAKE
822 0x2120: ur
'\textservicemark{}', # SERVICE MARK
823 0x2122: ur
'\texttrademark{}', # TRADE MARK SIGN
824 0x2126: ur
'\textohm{}', # OHM SIGN
825 0x2127: ur
'\textmho{}', # INVERTED OHM SIGN
826 0x212e: ur
'\textestimated{}', # ESTIMATED SYMBOL
827 0x2190: ur
'\textleftarrow{}', # LEFTWARDS ARROW
828 0x2191: ur
'\textuparrow{}', # UPWARDS ARROW
829 0x2192: ur
'\textrightarrow{}', # RIGHTWARDS ARROW
830 0x2193: ur
'\textdownarrow{}', # DOWNWARDS ARROW
831 0x2212: ur
'\textminus{}', # MINUS SIGN
832 0x2217: ur
'\textasteriskcentered{}', # ASTERISK OPERATOR
833 0x221a: ur
'\textsurd{}', # SQUARE ROOT
834 0x2422: ur
'\textblank{}', # BLANK SYMBOL
835 0x25e6: ur
'\textopenbullet{}', # WHITE BULLET
836 0x25ef: ur
'\textbigcircle{}', # LARGE CIRCLE
837 0x266a: ur
'\textmusicalnote{}', # EIGHTH NOTE
838 0x26ad: ur
'\textmarried{}', # MARRIAGE SYMBOL
839 0x26ae: ur
'\textdivorced{}', # DIVORCE SYMBOL
840 0x27e8: ur
'\textlangle{}', # MATHEMATICAL LEFT ANGLE BRACKET
841 0x27e9: ur
'\textrangle{}', # MATHEMATICAL RIGHT ANGLE BRACKET
843 # Unicode chars that require a feature/package to render
845 0x2665: ur
'\ding{170}', # black heartsuit
846 0x2666: ur
'\ding{169}', # black diamondsuit
847 0x2713: ur
'\ding{51}', # check mark
848 0x2717: ur
'\ding{55}', # check mark
850 # TODO: greek alphabet ... ?
851 # see also LaTeX codec
852 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252124
853 # and unimap.py from TeXML
856 class DocumentClass(object):
857 """Details of a LaTeX document class."""
859 def __init__(self
, document_class
, with_part
=False):
860 self
.document_class
= document_class
861 self
._with
_part
= with_part
862 self
.sections
= ['section', 'subsection', 'subsubsection',
863 'paragraph', 'subparagraph']
864 if self
.document_class
in ('book', 'memoir', 'report',
865 'scrbook', 'scrreprt'):
866 self
.sections
.insert(0, 'chapter')
868 self
.sections
.insert(0, 'part')
870 def section(self
, level
):
871 """Return the LaTeX section name for section `level`.
873 The name depends on the specific document class.
874 Level is 1,2,3..., as level 0 is the title.
876 if level
<= len(self
.sections
):
877 return self
.sections
[level
-1]
878 else: # unsupported levels
879 return 'DUtitle[section%s]' % roman
.toRoman(level
)
882 """Manage a table while traversing.
884 Maybe change to a mixin defining the visit/departs, but then
885 class Table internal variables are in the Translator.
889 :standard: horizontal and vertical lines
890 :booktabs: only horizontal lines (requires "booktabs" LaTeX package)
891 :borderless: no borders around table cells
892 :nolines: alias for borderless
894 def __init__(self
,translator
,latex_type
,table_style
):
895 self
._translator
= translator
896 self
._latex
_type
= latex_type
897 self
._table
_style
= table_style
899 # miscellaneous attributes
911 self
._in
_head
= False # maybe context with search
914 self
._col
_specs
= None
921 def set_table_style(self
, table_style
):
922 if not table_style
in ('standard','booktabs','borderless','nolines'):
924 self
._table
_style
= table_style
926 def get_latex_type(self
):
927 if self
._latex
_type
== 'longtable' and not self
.caption
:
928 # do not advance the "table" counter (requires "ltcaption" package)
930 return self
._latex
_type
932 def set(self
,attr
,value
):
933 self
._attrs
[attr
] = value
935 if attr
in self
._attrs
:
936 return self
._attrs
[attr
]
939 def get_vertical_bar(self
):
940 if self
._table
_style
== 'standard':
944 # horizontal lines are drawn below a row,
945 def get_opening(self
):
946 return '\n'.join([r
'\setlength{\DUtablewidth}{\linewidth}',
947 r
'\begin{%s}[c]' % self
.get_latex_type()])
949 def get_closing(self
):
951 if self
._table
_style
== 'booktabs':
952 closing
.append(r
'\bottomrule')
953 # elif self._table_style == 'standard':
954 # closing.append(r'\hline')
955 closing
.append(r
'\end{%s}' % self
.get_latex_type())
956 return '\n'.join(closing
)
958 def visit_colspec(self
, node
):
959 self
._col
_specs
.append(node
)
960 # "stubs" list is an attribute of the tgroup element:
961 self
.stubs
.append(node
.attributes
.get('stub'))
963 def get_colspecs(self
):
964 """Return column specification for longtable.
966 Assumes reST line length being 80 characters.
967 Table width is hairy.
973 usually gets to narrow, therefore we add 1 (fiddlefactor).
978 # first see if we get too wide.
979 for node
in self
._col
_specs
:
980 colwidth
= float(node
['colwidth']+1) / width
981 total_width
+= colwidth
984 # donot make it full linewidth
986 if total_width
> 1.0:
987 factor
/= total_width
988 bar
= self
.get_vertical_bar()
989 latex_table_spec
= ''
990 for node
in self
._col
_specs
:
991 colwidth
= factor
* float(node
['colwidth']+1) / width
992 self
._col
_width
.append(colwidth
+0.005)
993 self
._rowspan
.append(0)
994 latex_table_spec
+= '%sp{%.3f\\DUtablewidth}' % (bar
, colwidth
+0.005)
995 return latex_table_spec
+bar
997 def get_column_width(self
):
998 """Return columnwidth for current cell (not multicell)."""
999 return '%.2f\\DUtablewidth' % self
._col
_width
[self
._cell
_in
_row
-1]
1001 def get_multicolumn_width(self
, start
, len_
):
1002 """Return sum of columnwidths for multicell."""
1003 mc_width
= sum([width
1004 for width
in ([self
._col
_width
[start
+ co
- 1]
1005 for co
in range (len_
)])])
1006 return '%.2f\\DUtablewidth' % mc_width
1008 def get_caption(self
):
1009 if not self
.caption
:
1011 caption
= ''.join(self
.caption
)
1012 if 1 == self
._translator
.thead_depth():
1013 return r
'\caption{%s}\\' '\n' % caption
1014 return r
'\caption[]{%s (... continued)}\\' '\n' % caption
1016 def need_recurse(self
):
1017 if self
._latex
_type
== 'longtable':
1018 return 1 == self
._translator
.thead_depth()
1021 def visit_thead(self
):
1023 if self
._table
_style
== 'standard':
1024 return ['\\hline\n']
1025 elif self
._table
_style
== 'booktabs':
1026 return ['\\toprule\n']
1029 def depart_thead(self
):
1031 #if self._table_style == 'standard':
1032 # a.append('\\hline\n')
1033 if self
._table
_style
== 'booktabs':
1034 a
.append('\\midrule\n')
1035 if self
._latex
_type
== 'longtable':
1036 if 1 == self
._translator
.thead_depth():
1037 a
.append('\\endfirsthead\n')
1039 a
.append('\\endhead\n')
1040 a
.append(r
'\multicolumn{%d}{c}' % len(self
._col
_specs
) +
1041 r
'{\hfill ... continued on next page} \\')
1042 a
.append('\n\\endfoot\n\\endlastfoot\n')
1043 # for longtable one could add firsthead, foot and lastfoot
1046 def visit_row(self
):
1047 self
._cell
_in
_row
= 0
1048 def depart_row(self
):
1050 self
._cell
_in
_row
= None # remove cell counter
1051 for i
in range(len(self
._rowspan
)):
1052 if (self
._rowspan
[i
]>0):
1053 self
._rowspan
[i
] -= 1
1055 if self
._table
_style
== 'standard':
1056 rowspans
= [i
+1 for i
in range(len(self
._rowspan
))
1057 if (self
._rowspan
[i
]<=0)]
1058 if len(rowspans
)==len(self
._rowspan
):
1059 res
.append('\\hline\n')
1066 c_start
= rowspans
.pop()
1069 cline
+= '\\cline{%d-%d}\n' % (c_start
,c_start
)
1073 def set_rowspan(self
,cell
,value
):
1075 self
._rowspan
[cell
] = value
1078 def get_rowspan(self
,cell
):
1080 return self
._rowspan
[cell
]
1083 def get_entry_number(self
):
1084 return self
._cell
_in
_row
1085 def visit_entry(self
):
1086 self
._cell
_in
_row
+= 1
1087 def is_stub_column(self
):
1088 if len(self
.stubs
) >= self
._cell
_in
_row
:
1089 return self
.stubs
[self
._cell
_in
_row
-1]
1093 class LaTeXTranslator(nodes
.NodeVisitor
):
1095 # When options are given to the documentclass, latex will pass them
1096 # to other packages, as done with babel.
1097 # Dummy settings might be taken from document settings
1099 # Write code for typesetting with 8-bit tex/pdftex (vs. xetex/luatex) engine
1100 # overwritten by the XeTeX writer
1103 # Config setting defaults
1104 # -----------------------
1106 # TODO: use mixins for different implementations.
1107 # list environment for docinfo. else tabularx
1108 ## use_optionlist_for_docinfo = False # TODO: NOT YET IN USE
1110 # Use compound enumerations (1.A.1.)
1111 compound_enumerators
= False
1113 # If using compound enumerations, include section information.
1114 section_prefix_for_enumerators
= False
1116 # This is the character that separates the section ("." subsection ...)
1117 # prefix from the regular list enumerator.
1118 section_enumerator_separator
= '-'
1120 # Auxiliary variables
1121 # -------------------
1123 has_latex_toc
= False # is there a toc in the doc? (needed by minitoc)
1124 is_toc_list
= False # is the current bullet_list a ToC?
1127 # Flags to encode():
1128 # inside citation reference labels underscores dont need to be escaped
1129 inside_citation_reference_label
= False
1130 verbatim
= False # do not encode
1131 insert_non_breaking_blanks
= False # replace blanks by "~"
1132 insert_newline
= False # add latex newline commands
1133 literal
= False # literal text (block or inline)
1136 def __init__(self
, document
, babel_class
=Babel
):
1137 nodes
.NodeVisitor
.__init
__(self
, document
)
1140 self
.warn
= self
.document
.reporter
.warning
1141 self
.error
= self
.document
.reporter
.error
1145 self
.settings
= settings
= document
.settings
1146 self
.latex_encoding
= self
.to_latex_encoding(settings
.output_encoding
)
1147 self
.use_latex_toc
= settings
.use_latex_toc
1148 self
.use_latex_docinfo
= settings
.use_latex_docinfo
1149 self
._use
_latex
_citations
= settings
.use_latex_citations
1150 self
._reference
_label
= settings
.reference_label
1151 self
.hyperlink_color
= settings
.hyperlink_color
1152 self
.compound_enumerators
= settings
.compound_enumerators
1153 self
.font_encoding
= getattr(settings
, 'font_encoding', '')
1154 self
.section_prefix_for_enumerators
= (
1155 settings
.section_prefix_for_enumerators
)
1156 self
.section_enumerator_separator
= (
1157 settings
.section_enumerator_separator
.replace('_', r
'\_'))
1159 self
.literal_block_env
= ''
1160 self
.literal_block_options
= ''
1161 if settings
.literal_block_env
!= '':
1163 self
.literal_block_env
,
1164 self
.literal_block_options
,
1165 none
) = re
.split('(\w+)(.*)', settings
.literal_block_env
)
1166 elif settings
.use_verbatim_when_possible
:
1167 self
.literal_block_env
= 'verbatim'
1169 if self
.settings
.use_bibtex
:
1170 self
.bibtex
= self
.settings
.use_bibtex
.split(',',1)
1171 # TODO avoid errors on not declared citations.
1174 # language module for Docutils-generated text
1175 # (labels, bibliographic_fields, and author_separators)
1176 self
.language_module
= languages
.get_language(settings
.language_code
,
1178 self
.babel
= babel_class(settings
.language_code
, document
.reporter
)
1179 self
.author_separator
= self
.language_module
.author_separators
[0]
1180 d_options
= [self
.settings
.documentoptions
]
1181 if self
.babel
.language
not in ('english', ''):
1182 d_options
.append(self
.babel
.language
)
1183 self
.documentoptions
= ','.join(filter(None, d_options
))
1184 self
.d_class
= DocumentClass(settings
.documentclass
,
1185 settings
.use_part_section
)
1186 # graphic package options:
1187 if self
.settings
.graphicx_option
== '':
1188 self
.graphicx_package
= r
'\usepackage{graphicx}'
1189 elif self
.settings
.graphicx_option
.lower() == 'auto':
1190 self
.graphicx_package
= PreambleCmds
.graphicx_auto
1192 self
.graphicx_package
= (r
'\usepackage[%s]{graphicx}' %
1193 self
.settings
.graphicx_option
)
1195 self
.docutils_footnotes
= settings
.docutils_footnotes
1196 if settings
.use_latex_footnotes
:
1197 self
.docutils_footnotes
= True
1198 self
.warn('`use_latex_footnotes` is deprecated. '
1199 'The setting has been renamed to `docutils_footnotes` '
1200 'and the alias will be removed in a future version.')
1201 self
.figure_footnotes
= settings
.figure_footnotes
1202 if self
.figure_footnotes
:
1203 self
.docutils_footnotes
= True
1204 self
.warn('The "figure footnotes" workaround/setting is strongly '
1205 'deprecated and will be removed in a future version.')
1207 # Output collection stacks
1208 # ~~~~~~~~~~~~~~~~~~~~~~~~
1211 self
.head_prefix
= [r
'\documentclass[%s]{%s}' %
1212 (self
.documentoptions
, self
.settings
.documentclass
)]
1213 self
.requirements
= SortableDict() # made a list in depart_document()
1214 self
.requirements
['__static'] = r
'\usepackage{ifthen}'
1215 self
.latex_preamble
= [settings
.latex_preamble
]
1216 self
.fallbacks
= SortableDict() # made a list in depart_document()
1217 self
.pdfsetup
= [] # PDF properties (hyperref package)
1220 self
.titledata
= [] # \title, \author, \date
1221 ## self.body_prefix = ['\\begin{document}\n']
1222 self
.body_pre_docinfo
= [] # \maketitle
1224 self
.dedication
= []
1227 ## self.body_suffix = ['\\end{document}\n']
1229 # A heterogenous stack used in conjunction with the tree traversal.
1230 # Make sure that the pops correspond to the pushes:
1234 self
.title_labels
= []
1235 self
.subtitle_labels
= []
1236 # (if use_latex_docinfo: collects lists of
1237 # author/organization/contact/address lines)
1238 self
.author_stack
= []
1241 # PDF properties: pdftitle, pdfauthor
1242 # TODO?: pdfcreator, pdfproducer, pdfsubject, pdfkeywords
1246 # Stack of section counters so that we don't have to use_latex_toc.
1247 # This will grow and shrink as processing occurs.
1248 # Initialized for potential first-level sections.
1249 self
._section
_number
= [0]
1251 # The current stack of enumerations so that we can expand
1252 # them into a compound enumeration.
1253 self
._enumeration
_counters
= []
1254 # The maximum number of enumeration counters we've used.
1255 # If we go beyond this number, we need to create a new
1256 # counter; otherwise, just reuse an old one.
1257 self
._max
_enumeration
_counters
= 0
1261 # object for a table while proccessing.
1262 self
.table_stack
= []
1263 self
.active_table
= Table(self
, 'longtable', settings
.table_style
)
1265 # Where to collect the output of visitor methods (default: body)
1266 self
.out
= self
.body
1267 self
.out_stack
= [] # stack of output collectors
1272 # Docutils' output-encoding => TeX input encoding
1273 if self
.latex_encoding
!= 'ascii':
1274 self
.requirements
['_inputenc'] = (r
'\usepackage[%s]{inputenc}'
1275 % self
.latex_encoding
)
1277 if not self
.is_xetex
:
1278 if self
.font_encoding
:
1279 self
.requirements
['_fontenc'] = (r
'\usepackage[%s]{fontenc}' %
1281 # ensure \textquotedbl is defined:
1282 for enc
in self
.font_encoding
.split(','):
1285 self
.requirements
['_textquotedblOT1'] = (
1286 r
'\DeclareTextSymbol{\textquotedbl}{OT1}{`\"}')
1287 elif enc
not in ('T1', 'T2A', 'T2B', 'T2C', 'T4', 'T5'):
1288 self
.requirements
['_textquotedbl'] = (
1289 r
'\DeclareTextSymbolDefault{\textquotedbl}{T1}')
1290 # page layout with typearea (if there are relevant document options)
1291 if (settings
.documentclass
.find('scr') == -1 and
1292 (self
.documentoptions
.find('DIV') != -1 or
1293 self
.documentoptions
.find('BCOR') != -1)):
1294 self
.requirements
['typearea'] = r
'\usepackage{typearea}'
1297 # (the name `self.stylesheet` is singular because only one
1298 # stylesheet was supported before Docutils 0.6).
1299 self
.stylesheet
= [self
.stylesheet_call(path
)
1300 for path
in utils
.get_stylesheet_list(settings
)]
1303 if self
.hyperlink_color
in ('0', 'false', 'False', ''):
1304 self
.hyperref_options
= ''
1306 self
.hyperref_options
= 'colorlinks=true,linkcolor=%s,urlcolor=%s' % (
1307 self
.hyperlink_color
, self
.hyperlink_color
)
1308 if settings
.hyperref_options
:
1309 self
.hyperref_options
+= ',' + settings
.hyperref_options
1312 # include all supported sections in toc and PDF bookmarks
1313 # (or use documentclass-default (as currently))?
1314 ## if self.use_latex_toc:
1315 ## self.requirements['tocdepth'] = (r'\setcounter{tocdepth}{%d}' %
1316 ## len(self.d_class.sections))
1319 if settings
.sectnum_xform
: # section numbering by Docutils
1320 PreambleCmds
.secnumdepth
= r
'\setcounter{secnumdepth}{0}'
1321 else: # section numbering by LaTeX:
1322 secnumdepth
= settings
.sectnum_depth
1323 # Possible values of settings.sectnum_depth:
1324 # None "sectnum" directive without depth arg -> LaTeX default
1325 # 0 no "sectnum" directive -> no section numbers
1326 # >0 value of "depth" argument -> translate to LaTeX levels:
1327 # -1 part (0 with "article" document class)
1328 # 0 chapter (missing in "article" document class)
1334 if secnumdepth
is not None:
1335 # limit to supported levels
1336 secnumdepth
= min(secnumdepth
, len(self
.d_class
.sections
))
1337 # adjust to document class and use_part_section settings
1338 if 'chapter' in self
.d_class
.sections
:
1340 if self
.d_class
.sections
[0] == 'part':
1342 PreambleCmds
.secnumdepth
= \
1343 r
'\setcounter{secnumdepth}{%d}' % secnumdepth
1345 # start with specified number:
1346 if (hasattr(settings
, 'sectnum_start') and
1347 settings
.sectnum_start
!= 1):
1348 self
.requirements
['sectnum_start'] = (
1349 r
'\setcounter{%s}{%d}' % (self
.d_class
.sections
[0],
1350 settings
.sectnum_start
-1))
1351 # TODO: currently ignored (configure in a stylesheet):
1352 ## settings.sectnum_prefix
1353 ## settings.sectnum_suffix
1358 def stylesheet_call(self
, path
):
1359 """Return code to reference or embed stylesheet file `path`"""
1360 # is it a package (no extension or *.sty) or "normal" tex code:
1361 (base
, ext
) = os
.path
.splitext(path
)
1362 is_package
= ext
in ['.sty', '']
1363 # Embed content of style file:
1364 if self
.settings
.embed_stylesheet
:
1366 path
= base
+ '.sty' # ensure extension
1368 content
= io
.FileInput(source_path
=path
,
1369 encoding
='utf-8').read()
1370 self
.settings
.record_dependencies
.add(path
)
1371 except IOError, err
:
1372 msg
= u
"Cannot embed stylesheet '%s':\n %s." % (
1373 path
, SafeString(err
.strerror
))
1374 self
.document
.reporter
.error(msg
)
1375 return '% ' + msg
.replace('\n', '\n% ')
1377 content
= '\n'.join([r
'\makeatletter',
1380 return '%% embedded stylesheet: %s\n%s' % (path
, content
)
1381 # Link to style file:
1383 path
= base
# drop extension
1384 cmd
= r
'\usepackage{%s}'
1387 if self
.settings
.stylesheet_path
:
1388 # adapt path relative to output (cf. config.html#stylesheet-path)
1389 path
= utils
.relative_path(self
.settings
._destination
, path
)
1392 def to_latex_encoding(self
,docutils_encoding
):
1393 """Translate docutils encoding name into LaTeX's.
1395 Default method is remove "-" and "_" chars from docutils_encoding.
1397 tr
= { 'iso-8859-1': 'latin1', # west european
1398 'iso-8859-2': 'latin2', # east european
1399 'iso-8859-3': 'latin3', # esperanto, maltese
1400 'iso-8859-4': 'latin4', # north european, scandinavian, baltic
1401 'iso-8859-5': 'iso88595', # cyrillic (ISO)
1402 'iso-8859-9': 'latin5', # turkish
1403 'iso-8859-15': 'latin9', # latin9, update to latin1.
1404 'mac_cyrillic': 'maccyr', # cyrillic (on Mac)
1405 'windows-1251': 'cp1251', # cyrillic (on Windows)
1406 'koi8-r': 'koi8-r', # cyrillic (Russian)
1407 'koi8-u': 'koi8-u', # cyrillic (Ukrainian)
1408 'windows-1250': 'cp1250', #
1409 'windows-1252': 'cp1252', #
1410 'us-ascii': 'ascii', # ASCII (US)
1411 # unmatched encodings
1413 #'': 'ansinew', # windows 3.1 ansi
1414 #'': 'ascii', # ASCII encoding for the range 32--127.
1415 #'': 'cp437', # dos latin us
1416 #'': 'cp850', # dos latin 1
1417 #'': 'cp852', # dos latin 2
1420 #'iso-8859-6': '' # arabic
1421 #'iso-8859-7': '' # greek
1422 #'iso-8859-8': '' # hebrew
1423 #'iso-8859-10': '' # latin6, more complete iso-8859-4
1425 encoding
= docutils_encoding
.lower()
1428 # drop hyphen or low-line from "latin-1", "latin_1", "utf-8" and similar
1429 encoding
= encoding
.replace('_', '').replace('-', '')
1430 # strip the error handler
1431 return encoding
.split(':')[0]
1433 def language_label(self
, docutil_label
):
1434 return self
.language_module
.labels
[docutil_label
]
1436 def encode(self
, text
):
1437 """Return text with 'problematic' characters escaped.
1439 * Escape the ten special printing characters ``# $ % & ~ _ ^ \ { }``,
1440 square brackets ``[ ]``, double quotes and (in OT1) ``< | >``.
1441 * Translate non-supported Unicode characters.
1442 * Separate ``-`` (and more in literal text) to prevent input ligatures.
1447 # Set up the translation table:
1448 table
= CharMaps
.special
.copy()
1449 # keep the underscore in citation references
1450 if self
.inside_citation_reference_label
:
1451 del(table
[ord('_')])
1452 # Workarounds for OT1 font-encoding
1453 if self
.font_encoding
in ['OT1', ''] and not self
.is_xetex
:
1454 # * out-of-order characters in cmtt
1456 # replace underscore by underlined blank,
1457 # because this has correct width.
1458 table
[ord('_')] = u
'\\underline{~}'
1459 # the backslash doesn't work, so we use a mirrored slash.
1460 # \reflectbox is provided by graphicx:
1461 self
.requirements
['graphicx'] = self
.graphicx_package
1462 table
[ord('\\')] = ur
'\reflectbox{/}'
1463 # * ``< | >`` come out as different chars (except for cmtt):
1465 table
[ord('|')] = ur
'\textbar{}'
1466 table
[ord('<')] = ur
'\textless{}'
1467 table
[ord('>')] = ur
'\textgreater{}'
1468 if self
.insert_non_breaking_blanks
:
1469 table
[ord(' ')] = ur
'~'
1470 # Unicode replacements for 8-bit tex engines (not required with XeTeX/LuaTeX):
1471 if not self
.is_xetex
:
1472 table
.update(CharMaps
.unsupported_unicode
)
1473 if not self
.latex_encoding
.startswith('utf8'):
1474 table
.update(CharMaps
.utf8_supported_unicode
)
1475 table
.update(CharMaps
.textcomp
)
1476 table
.update(CharMaps
.pifont
)
1477 # Characters that require a feature/package to render
1478 if [True for ch
in text
if ord(ch
) in CharMaps
.textcomp
]:
1479 self
.requirements
['textcomp'] = PreambleCmds
.textcomp
1480 if [True for ch
in text
if ord(ch
) in CharMaps
.pifont
]:
1481 self
.requirements
['pifont'] = '\\usepackage{pifont}'
1483 text
= text
.translate(table
)
1485 # Break up input ligatures e.g. '--' to '-{}-'.
1486 if not self
.is_xetex
: # Not required with xetex/luatex
1487 separate_chars
= '-'
1488 # In monospace-font, we also separate ',,', '``' and "''" and some
1489 # other characters which can't occur in non-literal text.
1491 separate_chars
+= ',`\'"<>'
1492 for char
in separate_chars
* 2:
1493 # Do it twice ("* 2") because otherwise we would replace
1495 text
= text
.replace(char
+ char
, char
+ '{}' + char
)
1497 # Literal line breaks (in address or literal blocks):
1498 if self
.insert_newline
:
1499 lines
= text
.split('\n')
1500 # Add a protected space to blank lines (except the last)
1501 # to avoid ``! LaTeX Error: There's no line here to end.``
1502 for i
, line
in enumerate(lines
[:-1]):
1503 if not line
.lstrip():
1505 text
= (r
'\\' + '\n').join(lines
)
1506 if self
.literal
and not self
.insert_non_breaking_blanks
:
1507 # preserve runs of spaces but allow wrapping
1508 text
= text
.replace(' ', ' ~')
1511 def attval(self
, text
,
1512 whitespace
=re
.compile('[\n\r\t\v\f]')):
1513 """Cleanse, encode, and return attribute value text."""
1514 return self
.encode(whitespace
.sub(' ', text
))
1516 # TODO: is this used anywhere? -> update (use template) or delete
1517 ## def astext(self):
1518 ## """Assemble document parts and return as string."""
1519 ## head = '\n'.join(self.head_prefix + self.stylesheet + self.head)
1520 ## body = ''.join(self.body_prefix + self.body + self.body_suffix)
1521 ## return head + '\n' + body
1523 def is_inline(self
, node
):
1524 """Check whether a node represents an inline element"""
1525 return isinstance(node
.parent
, nodes
.TextElement
)
1527 def append_hypertargets(self
, node
):
1528 """Append hypertargets for all ids of `node`"""
1529 # hypertarget places the anchor at the target's baseline,
1530 # so we raise it explicitely
1531 self
.out
.append('%\n'.join(['\\raisebox{1em}{\\hypertarget{%s}{}}' %
1532 id for id in node
['ids']]))
1534 def ids_to_labels(self
, node
, set_anchor
=True):
1535 """Return list of label definitions for all ids of `node`
1537 If `set_anchor` is True, an anchor is set with \phantomsection.
1539 labels
= ['\\label{%s}' % id for id in node
.get('ids', [])]
1540 if set_anchor
and labels
:
1541 labels
.insert(0, '\\phantomsection')
1544 def push_output_collector(self
, new_out
):
1545 self
.out_stack
.append(self
.out
)
1548 def pop_output_collector(self
):
1549 self
.out
= self
.out_stack
.pop()
1554 def visit_Text(self
, node
):
1555 self
.out
.append(self
.encode(node
.astext()))
1557 def depart_Text(self
, node
):
1560 def visit_abbreviation(self
, node
):
1561 node
['classes'].insert(0, 'abbreviation')
1562 self
.visit_inline(node
)
1564 def depart_abbreviation(self
, node
):
1565 self
.depart_inline(node
)
1567 def visit_acronym(self
, node
):
1568 node
['classes'].insert(0, 'acronym')
1569 self
.visit_inline(node
)
1571 def depart_acronym(self
, node
):
1572 self
.depart_inline(node
)
1574 def visit_address(self
, node
):
1575 self
.visit_docinfo_item(node
, 'address')
1577 def depart_address(self
, node
):
1578 self
.depart_docinfo_item(node
)
1580 def visit_admonition(self
, node
):
1581 self
.fallbacks
['admonition'] = PreambleCmds
.admonition
1582 if 'error' in node
['classes']:
1583 self
.fallbacks
['error'] = PreambleCmds
.error
1584 # strip the generic 'admonition' from the list of classes
1585 node
['classes'] = [cls
for cls
in node
['classes']
1586 if cls
!= 'admonition']
1587 self
.out
.append('\n\\DUadmonition[%s]{\n' % ','.join(node
['classes']))
1589 def depart_admonition(self
, node
=None):
1590 self
.out
.append('}\n')
1592 def visit_author(self
, node
):
1593 self
.visit_docinfo_item(node
, 'author')
1595 def depart_author(self
, node
):
1596 self
.depart_docinfo_item(node
)
1598 def visit_authors(self
, node
):
1599 # not used: visit_author is called anyway for each author.
1602 def depart_authors(self
, node
):
1605 def visit_block_quote(self
, node
):
1606 self
.out
.append( '%\n\\begin{quote}\n')
1608 self
.visit_inline(node
)
1610 def depart_block_quote(self
, node
):
1612 self
.depart_inline(node
)
1613 self
.out
.append( '\n\\end{quote}\n')
1615 def visit_bullet_list(self
, node
):
1616 if self
.is_toc_list
:
1617 self
.out
.append( '%\n\\begin{list}{}{}\n' )
1619 self
.out
.append( '%\n\\begin{itemize}\n' )
1620 # if node['classes']:
1621 # self.visit_inline(node)
1623 def depart_bullet_list(self
, node
):
1624 # if node['classes']:
1625 # self.depart_inline(node)
1626 if self
.is_toc_list
:
1627 self
.out
.append( '\n\\end{list}\n' )
1629 self
.out
.append( '\n\\end{itemize}\n' )
1631 def visit_superscript(self
, node
):
1632 self
.out
.append(r
'\textsuperscript{')
1634 self
.visit_inline(node
)
1636 def depart_superscript(self
, node
):
1638 self
.depart_inline(node
)
1639 self
.out
.append('}')
1641 def visit_subscript(self
, node
):
1642 self
.out
.append(r
'\textsubscript{') # requires `fixltx2e`
1644 self
.visit_inline(node
)
1646 def depart_subscript(self
, node
):
1648 self
.depart_inline(node
)
1649 self
.out
.append('}')
1651 def visit_caption(self
, node
):
1652 self
.out
.append( '\\caption{' )
1654 def depart_caption(self
, node
):
1655 self
.out
.append('}\n')
1657 def visit_title_reference(self
, node
):
1658 self
.fallbacks
['titlereference'] = PreambleCmds
.titlereference
1659 self
.out
.append(r
'\DUroletitlereference{')
1661 self
.visit_inline(node
)
1663 def depart_title_reference(self
, node
):
1665 self
.depart_inline(node
)
1666 self
.out
.append( '}' )
1668 def visit_citation(self
, node
):
1669 # TODO maybe use cite bibitems
1670 if self
._use
_latex
_citations
:
1671 self
.push_output_collector([])
1673 # TODO: do we need these?
1674 ## self.requirements['~fnt_floats'] = PreambleCmds.footnote_floats
1675 self
.out
.append(r
'\begin{figure}[b]')
1676 self
.append_hypertargets(node
)
1678 def depart_citation(self
, node
):
1679 if self
._use
_latex
_citations
:
1681 text
= ''.join(self
.out
[1:])
1682 self
._bibitems
.append([label
, text
])
1683 self
.pop_output_collector()
1685 self
.out
.append('\\end{figure}\n')
1687 def visit_citation_reference(self
, node
):
1688 if self
._use
_latex
_citations
:
1689 if not self
.inside_citation_reference_label
:
1690 self
.out
.append(r
'\cite{')
1691 self
.inside_citation_reference_label
= 1
1693 assert self
.body
[-1] in (' ', '\n'),\
1694 'unexpected non-whitespace while in reference label'
1699 href
= node
['refid']
1700 elif 'refname' in node
:
1701 href
= self
.document
.nameids
[node
['refname']]
1702 self
.out
.append('\\hyperlink{%s}{[' % href
)
1704 def depart_citation_reference(self
, node
):
1705 if self
._use
_latex
_citations
:
1706 followup_citation
= False
1707 # check for a following citation separated by a space or newline
1708 next_siblings
= node
.traverse(descend
=False, siblings
=True,
1710 if len(next_siblings
) > 1:
1711 next
= next_siblings
[0]
1712 if (isinstance(next
, nodes
.Text
) and
1713 next
.astext() in (' ', '\n')):
1714 if next_siblings
[1].__class
__ == node
.__class
__:
1715 followup_citation
= True
1716 if followup_citation
:
1717 self
.out
.append(',')
1719 self
.out
.append('}')
1720 self
.inside_citation_reference_label
= False
1722 self
.out
.append(']}')
1724 def visit_classifier(self
, node
):
1725 self
.out
.append( '(\\textbf{' )
1727 def depart_classifier(self
, node
):
1728 self
.out
.append( '})\n' )
1730 def visit_colspec(self
, node
):
1731 self
.active_table
.visit_colspec(node
)
1733 def depart_colspec(self
, node
):
1736 def visit_comment(self
, node
):
1737 # Precede every line with a comment sign, wrap in newlines
1738 self
.out
.append('\n%% %s\n' % node
.astext().replace('\n', '\n% '))
1739 raise nodes
.SkipNode
1741 def depart_comment(self
, node
):
1744 def visit_compound(self
, node
):
1747 def depart_compound(self
, node
):
1750 def visit_contact(self
, node
):
1751 self
.visit_docinfo_item(node
, 'contact')
1753 def depart_contact(self
, node
):
1754 self
.depart_docinfo_item(node
)
1756 def visit_container(self
, node
):
1759 def depart_container(self
, node
):
1762 def visit_copyright(self
, node
):
1763 self
.visit_docinfo_item(node
, 'copyright')
1765 def depart_copyright(self
, node
):
1766 self
.depart_docinfo_item(node
)
1768 def visit_date(self
, node
):
1769 self
.visit_docinfo_item(node
, 'date')
1771 def depart_date(self
, node
):
1772 self
.depart_docinfo_item(node
)
1774 def visit_decoration(self
, node
):
1778 def depart_decoration(self
, node
):
1781 def visit_definition(self
, node
):
1784 def depart_definition(self
, node
):
1785 self
.out
.append('\n')
1787 def visit_definition_list(self
, node
):
1788 self
.out
.append( '%\n\\begin{description}\n' )
1790 def depart_definition_list(self
, node
):
1791 self
.out
.append( '\\end{description}\n' )
1793 def visit_definition_list_item(self
, node
):
1796 def depart_definition_list_item(self
, node
):
1799 def visit_description(self
, node
):
1800 self
.out
.append(' ')
1802 def depart_description(self
, node
):
1805 def visit_docinfo(self
, node
):
1806 self
.push_output_collector(self
.docinfo
)
1808 def depart_docinfo(self
, node
):
1809 self
.pop_output_collector()
1810 # Some itmes (e.g. author) end up at other places
1812 # tabularx: automatic width of columns, no page breaks allowed.
1813 self
.requirements
['tabularx'] = r
'\usepackage{tabularx}'
1814 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
1815 self
.fallbacks
['docinfo'] = PreambleCmds
.docinfo
1817 self
.docinfo
.insert(0, '\n% Docinfo\n'
1819 '\\begin{tabularx}{\\DUdocinfowidth}{lX}\n')
1820 self
.docinfo
.append('\\end{tabularx}\n'
1823 def visit_docinfo_item(self
, node
, name
):
1824 if name
== 'author':
1825 self
.pdfauthor
.append(self
.attval(node
.astext()))
1826 if self
.use_latex_docinfo
:
1827 if name
in ('author', 'organization', 'contact', 'address'):
1828 # We attach these to the last author. If any of them precedes
1829 # the first author, put them in a separate "author" group
1830 # (in lack of better semantics).
1831 if name
== 'author' or not self
.author_stack
:
1832 self
.author_stack
.append([])
1833 if name
== 'address': # newlines are meaningful
1834 self
.insert_newline
= True
1835 text
= self
.encode(node
.astext())
1836 self
.insert_newline
= False
1838 text
= self
.attval(node
.astext())
1839 self
.author_stack
[-1].append(text
)
1840 raise nodes
.SkipNode
1841 elif name
== 'date':
1842 self
.date
.append(self
.attval(node
.astext()))
1843 raise nodes
.SkipNode
1844 self
.out
.append('\\textbf{%s}: &\n\t' % self
.language_label(name
))
1845 if name
== 'address':
1846 self
.insert_newline
= 1
1847 self
.out
.append('{\\raggedright\n')
1848 self
.context
.append(' } \\\\\n')
1850 self
.context
.append(' \\\\\n')
1852 def depart_docinfo_item(self
, node
):
1853 self
.out
.append(self
.context
.pop())
1854 # for address we did set insert_newline
1855 self
.insert_newline
= False
1857 def visit_doctest_block(self
, node
):
1858 self
.visit_literal_block(node
)
1860 def depart_doctest_block(self
, node
):
1861 self
.depart_literal_block(node
)
1863 def visit_document(self
, node
):
1865 if (self
.use_latex_docinfo
or len(node
) and
1866 isinstance(node
[0], nodes
.title
)):
1867 self
.title_labels
+= self
.ids_to_labels(node
, set_anchor
=False)
1869 def depart_document(self
, node
):
1870 # Complete header with information gained from walkabout
1872 if (self
.babel
.otherlanguages
or
1873 self
.babel
.language
not in ('', 'english')):
1874 self
.requirements
['babel'] = self
.babel()
1875 # * conditional requirements (before style sheet)
1876 self
.requirements
= self
.requirements
.sortedvalues()
1877 # * coditional fallback definitions (after style sheet)
1878 self
.fallbacks
= self
.fallbacks
.sortedvalues()
1880 self
.pdfsetup
.append(PreambleCmds
.linking
% self
.hyperref_options
)
1882 authors
= self
.author_separator
.join(self
.pdfauthor
)
1883 self
.pdfinfo
.append(' pdfauthor={%s}' % authors
)
1885 self
.pdfsetup
+= [r
'\hypersetup{'] + self
.pdfinfo
+ ['}']
1887 # * document title (with "use_latex_docinfo" also
1888 # 'author', 'organization', 'contact', 'address' and 'date')
1890 self
.use_latex_docinfo
and (self
.author_stack
or self
.date
)):
1891 # with the default template, titledata is written to the preamble
1892 self
.titledata
.append('%%% Title Data')
1893 # \title (empty \title prevents error with \maketitle)
1895 self
.title
.insert(0, '\phantomsection%\n ')
1896 title
= [''.join(self
.title
)] + self
.title_labels
1898 title
+= [r
'\\ % subtitle',
1899 r
'\large{%s}' % ''.join(self
.subtitle
)
1900 ] + self
.subtitle_labels
1901 self
.titledata
.append(r
'\title{%s}' % '%\n '.join(title
))
1902 # \author (empty \author prevents warning with \maketitle)
1903 authors
= ['\\\\\n'.join(author_entry
)
1904 for author_entry
in self
.author_stack
]
1905 self
.titledata
.append(r
'\author{%s}' %
1906 ' \\and\n'.join(authors
))
1907 # \date (empty \date prevents defaulting to \today)
1908 self
.titledata
.append(r
'\date{%s}' % ', '.join(self
.date
))
1909 # \maketitle in the body formats title with LaTeX
1910 self
.body_pre_docinfo
.append('\\maketitle\n')
1913 # TODO insertion point of bibliography should be configurable.
1914 if self
._use
_latex
_citations
and len(self
._bibitems
)>0:
1917 for bi
in self
._bibitems
:
1918 if len(widest_label
)<len(bi
[0]):
1919 widest_label
= bi
[0]
1920 self
.out
.append('\n\\begin{thebibliography}{%s}\n' %
1922 for bi
in self
._bibitems
:
1923 # cite_key: underscores must not be escaped
1924 cite_key
= bi
[0].replace(r
'\_','_')
1925 self
.out
.append('\\bibitem[%s]{%s}{%s}\n' %
1926 (bi
[0], cite_key
, bi
[1]))
1927 self
.out
.append('\\end{thebibliography}\n')
1929 self
.out
.append('\n\\bibliographystyle{%s}\n' %
1931 self
.out
.append('\\bibliography{%s}\n' % self
.bibtex
[1])
1932 # * make sure to generate a toc file if needed for local contents:
1933 if 'minitoc' in self
.requirements
and not self
.has_latex_toc
:
1934 self
.out
.append('\n\\faketableofcontents % for local ToCs\n')
1936 def visit_emphasis(self
, node
):
1937 self
.out
.append('\\emph{')
1939 self
.visit_inline(node
)
1941 def depart_emphasis(self
, node
):
1943 self
.depart_inline(node
)
1944 self
.out
.append('}')
1946 def visit_entry(self
, node
):
1947 self
.active_table
.visit_entry()
1949 # BUG: the following fails, with more than one multirow
1950 # starting in the second column (or later) see
1951 # ../../../test/functional/input/data/latex.txt
1952 if self
.active_table
.get_entry_number() == 1:
1953 # if the first row is a multirow, this actually is the second row.
1954 # this gets hairy if rowspans follow each other.
1955 if self
.active_table
.get_rowspan(0):
1957 while self
.active_table
.get_rowspan(count
):
1959 self
.out
.append(' & ')
1960 self
.active_table
.visit_entry() # increment cell count
1962 self
.out
.append(' & ')
1963 # multirow, multicolumn
1964 # IN WORK BUG TODO HACK continues here
1965 # multirow in LaTeX simply will enlarge the cell over several rows
1966 # (the following n if n is positive, the former if negative).
1967 if 'morerows' in node
and 'morecols' in node
:
1968 raise NotImplementedError('Cells that '
1969 'span multiple rows *and* columns are not supported, sorry.')
1970 if 'morerows' in node
:
1971 self
.requirements
['multirow'] = r
'\usepackage{multirow}'
1972 count
= node
['morerows'] + 1
1973 self
.active_table
.set_rowspan(
1974 self
.active_table
.get_entry_number()-1,count
)
1975 self
.out
.append('\\multirow{%d}{%s}{%%' %
1976 (count
,self
.active_table
.get_column_width()))
1977 self
.context
.append('}')
1978 elif 'morecols' in node
:
1979 # the vertical bar before column is missing if it is the first
1980 # column. the one after always.
1981 if self
.active_table
.get_entry_number() == 1:
1982 bar1
= self
.active_table
.get_vertical_bar()
1985 count
= node
['morecols'] + 1
1986 self
.out
.append('\\multicolumn{%d}{%sp{%s}%s}{' %
1988 self
.active_table
.get_multicolumn_width(
1989 self
.active_table
.get_entry_number(),
1991 self
.active_table
.get_vertical_bar()))
1992 self
.context
.append('}')
1994 self
.context
.append('')
1996 # header / not header
1997 if isinstance(node
.parent
.parent
, nodes
.thead
):
1998 self
.out
.append('\\textbf{%')
1999 self
.context
.append('}')
2000 elif self
.active_table
.is_stub_column():
2001 self
.out
.append('\\textbf{')
2002 self
.context
.append('}')
2004 self
.context
.append('')
2006 def depart_entry(self
, node
):
2007 self
.out
.append(self
.context
.pop()) # header / not header
2008 self
.out
.append(self
.context
.pop()) # multirow/column
2009 # if following row is spanned from above.
2010 if self
.active_table
.get_rowspan(self
.active_table
.get_entry_number()):
2011 self
.out
.append(' & ')
2012 self
.active_table
.visit_entry() # increment cell count
2014 def visit_row(self
, node
):
2015 self
.active_table
.visit_row()
2017 def depart_row(self
, node
):
2018 self
.out
.extend(self
.active_table
.depart_row())
2020 def visit_enumerated_list(self
, node
):
2021 # We create our own enumeration list environment.
2022 # This allows to set the style and starting value
2023 # and unlimited nesting.
2024 enum_style
= {'arabic':'arabic',
2025 'loweralpha':'alph',
2026 'upperalpha':'Alph',
2027 'lowerroman':'roman',
2028 'upperroman':'Roman' }
2030 if 'suffix' in node
:
2031 enum_suffix
= node
['suffix']
2033 if 'prefix' in node
:
2034 enum_prefix
= node
['prefix']
2035 if self
.compound_enumerators
:
2037 if self
.section_prefix_for_enumerators
and self
.section_level
:
2038 for i
in range(self
.section_level
):
2039 pref
+= '%d.' % self
._section
_number
[i
]
2040 pref
= pref
[:-1] + self
.section_enumerator_separator
2042 for ctype
, cname
in self
._enumeration
_counters
:
2043 enum_prefix
+= '\\%s{%s}.' % (ctype
, cname
)
2044 enum_type
= 'arabic'
2045 if 'enumtype' in node
:
2046 enum_type
= node
['enumtype']
2047 if enum_type
in enum_style
:
2048 enum_type
= enum_style
[enum_type
]
2050 counter_name
= 'listcnt%d' % len(self
._enumeration
_counters
)
2051 self
._enumeration
_counters
.append((enum_type
, counter_name
))
2052 # If we haven't used this counter name before, then create a
2053 # new counter; otherwise, reset & reuse the old counter.
2054 if len(self
._enumeration
_counters
) > self
._max
_enumeration
_counters
:
2055 self
._max
_enumeration
_counters
= len(self
._enumeration
_counters
)
2056 self
.out
.append('\\newcounter{%s}\n' % counter_name
)
2058 self
.out
.append('\\setcounter{%s}{0}\n' % counter_name
)
2060 self
.out
.append('\\begin{list}{%s\\%s{%s}%s}\n' %
2061 (enum_prefix
,enum_type
,counter_name
,enum_suffix
))
2062 self
.out
.append('{\n')
2063 self
.out
.append('\\usecounter{%s}\n' % counter_name
)
2064 # set start after usecounter, because it initializes to zero.
2066 self
.out
.append('\\addtocounter{%s}{%d}\n' %
2067 (counter_name
,node
['start']-1))
2068 ## set rightmargin equal to leftmargin
2069 self
.out
.append('\\setlength{\\rightmargin}{\\leftmargin}\n')
2070 self
.out
.append('}\n')
2072 def depart_enumerated_list(self
, node
):
2073 self
.out
.append('\\end{list}\n')
2074 self
._enumeration
_counters
.pop()
2076 def visit_field(self
, node
):
2077 # real output is done in siblings: _argument, _body, _name
2080 def depart_field(self
, node
):
2081 self
.out
.append('\n')
2082 ##self.out.append('%[depart_field]\n')
2084 def visit_field_argument(self
, node
):
2085 self
.out
.append('%[visit_field_argument]\n')
2087 def depart_field_argument(self
, node
):
2088 self
.out
.append('%[depart_field_argument]\n')
2090 def visit_field_body(self
, node
):
2093 def depart_field_body(self
, node
):
2094 if self
.out
is self
.docinfo
:
2095 self
.out
.append(r
'\\')
2097 def visit_field_list(self
, node
):
2098 if self
.out
is not self
.docinfo
:
2099 self
.fallbacks
['fieldlist'] = PreambleCmds
.fieldlist
2100 self
.out
.append('%\n\\begin{DUfieldlist}\n')
2102 def depart_field_list(self
, node
):
2103 if self
.out
is not self
.docinfo
:
2104 self
.out
.append('\\end{DUfieldlist}\n')
2106 def visit_field_name(self
, node
):
2107 if self
.out
is self
.docinfo
:
2108 self
.out
.append('\\textbf{')
2110 # Commands with optional args inside an optional arg must be put
2111 # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
2112 self
.out
.append('\\item[{')
2114 def depart_field_name(self
, node
):
2115 if self
.out
is self
.docinfo
:
2116 self
.out
.append('}: &')
2118 self
.out
.append(':}]')
2120 def visit_figure(self
, node
):
2121 self
.requirements
['float_settings'] = PreambleCmds
.float_settings
2122 # ! the 'align' attribute should set "outer alignment" !
2123 # For "inner alignment" use LaTeX default alignment (similar to HTML)
2124 ## if ('align' not in node.attributes or
2125 ## node.attributes['align'] == 'center'):
2126 ## align = '\n\\centering'
2129 ## # TODO non vertical space for other alignments.
2130 ## align = '\\begin{flush%s}' % node.attributes['align']
2131 ## align_end = '\\end{flush%s}' % node.attributes['align']
2132 ## self.out.append( '\\begin{figure}%s\n' % align )
2133 ## self.context.append( '%s\\end{figure}\n' % align_end )
2134 self
.out
.append('\\begin{figure}')
2136 self
.out
+= ['\n'] + self
.ids_to_labels(node
)
2138 def depart_figure(self
, node
):
2139 self
.out
.append('\\end{figure}\n')
2141 def visit_footer(self
, node
):
2142 self
.push_output_collector([])
2143 self
.out
.append(r
'\newcommand{\DUfooter}{')
2145 def depart_footer(self
, node
):
2146 self
.out
.append('}')
2147 self
.requirements
['~footer'] = ''.join(self
.out
)
2148 self
.pop_output_collector()
2150 def visit_footnote(self
, node
):
2152 backref
= node
['backrefs'][0]
2154 backref
= node
['ids'][0] # no backref, use self-ref instead
2155 if self
.settings
.figure_footnotes
:
2156 self
.requirements
['~fnt_floats'] = PreambleCmds
.footnote_floats
2157 self
.out
.append('\\begin{figure}[b]')
2158 self
.append_hypertargets(node
)
2159 if node
.get('id') == node
.get('name'): # explicite label
2160 self
.out
+= self
.ids_to_labels(node
)
2161 elif self
.docutils_footnotes
:
2162 self
.fallbacks
['footnotes'] = PreambleCmds
.footnotes
2163 num
,text
= node
.astext().split(None,1)
2164 if self
.settings
.footnote_references
== 'brackets':
2166 self
.out
.append('%%\n\\DUfootnotetext{%s}{%s}{%s}{' %
2167 (node
['ids'][0], backref
, self
.encode(num
)))
2168 if node
['ids'] == node
['names']:
2169 self
.out
+= self
.ids_to_labels(node
)
2170 # mask newline to prevent spurious whitespace:
2171 self
.out
.append('%')
2172 ## else: # TODO: "real" LaTeX \footnote{}s
2174 def depart_footnote(self
, node
):
2175 if self
.figure_footnotes
:
2176 self
.out
.append('\\end{figure}\n')
2178 self
.out
.append('}\n')
2180 def visit_footnote_reference(self
, node
):
2183 href
= node
['refid']
2184 elif 'refname' in node
:
2185 href
= self
.document
.nameids
[node
['refname']]
2186 # if not self.docutils_footnotes:
2187 # TODO: insert footnote content at (or near) this place
2188 # print "footnote-ref to", node['refid']
2189 # footnotes = (self.document.footnotes +
2190 # self.document.autofootnotes +
2191 # self.document.symbol_footnotes)
2192 # for footnote in footnotes:
2193 # # print footnote['ids']
2194 # if node.get('refid', '') in footnote['ids']:
2195 # print 'matches', footnote['ids']
2196 format
= self
.settings
.footnote_references
2197 if format
== 'brackets':
2198 self
.append_hypertargets(node
)
2199 self
.out
.append('\\hyperlink{%s}{[' % href
)
2200 self
.context
.append(']}')
2202 self
.fallbacks
['footnotes'] = PreambleCmds
.footnotes
2203 self
.out
.append(r
'\DUfootnotemark{%s}{%s}{' %
2204 (node
['ids'][0], href
))
2205 self
.context
.append('}')
2207 def depart_footnote_reference(self
, node
):
2208 self
.out
.append(self
.context
.pop())
2210 # footnote/citation label
2211 def label_delim(self
, node
, bracket
, superscript
):
2212 if isinstance(node
.parent
, nodes
.footnote
):
2213 if not self
.figure_footnotes
:
2214 raise nodes
.SkipNode
2215 if self
.settings
.footnote_references
== 'brackets':
2216 self
.out
.append(bracket
)
2218 self
.out
.append(superscript
)
2220 assert isinstance(node
.parent
, nodes
.citation
)
2221 if not self
._use
_latex
_citations
:
2222 self
.out
.append(bracket
)
2224 def visit_label(self
, node
):
2225 """footnote or citation label: in brackets or as superscript"""
2226 self
.label_delim(node
, '[', '\\textsuperscript{')
2228 def depart_label(self
, node
):
2229 self
.label_delim(node
, ']', '}')
2231 # elements generated by the framework e.g. section numbers.
2232 def visit_generated(self
, node
):
2235 def depart_generated(self
, node
):
2238 def visit_header(self
, node
):
2239 self
.push_output_collector([])
2240 self
.out
.append(r
'\newcommand{\DUheader}{')
2242 def depart_header(self
, node
):
2243 self
.out
.append('}')
2244 self
.requirements
['~header'] = ''.join(self
.out
)
2245 self
.pop_output_collector()
2247 def to_latex_length(self
, length_str
, pxunit
=None):
2248 """Convert `length_str` with rst lenght to LaTeX length
2250 if pxunit
is not None:
2251 sys
.stderr
.write('deprecation warning: LaTeXTranslator.to_latex_length()'
2252 ' option `pxunit` will be removed.')
2253 match
= re
.match('(\d*\.?\d*)\s*(\S*)', length_str
)
2256 value
, unit
= match
.groups()[:2]
2257 # no unit or "DTP" points (called 'bp' in TeX):
2258 if unit
in ('', 'pt'):
2259 length_str
= '%sbp' % value
2260 # percentage: relate to current line width
2262 length_str
= '%.3f\\linewidth' % (float(value
)/100.0)
2263 elif self
.is_xetex
and unit
== 'px':
2264 # XeTeX does not know the length unit px.
2265 # Use \pdfpxdimen, the macro to set the value of 1 px in pdftex.
2266 # This way, configuring works the same for pdftex and xetex.
2267 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
2268 self
.fallbacks
['px'] = '\n\\DUprovidelength{\\pdfpxdimen}{1bp}\n'
2269 length_str
= r
'%s\pdfpxdimen' % value
2272 def visit_image(self
, node
):
2273 self
.requirements
['graphicx'] = self
.graphicx_package
2274 attrs
= node
.attributes
2275 # Convert image URI to a local file path
2276 imagepath
= urllib
.url2pathname(attrs
['uri']).replace('\\', '/')
2277 # alignment defaults:
2278 if not 'align' in attrs
:
2279 # Set default align of image in a figure to 'center'
2280 if isinstance(node
.parent
, nodes
.figure
):
2281 attrs
['align'] = 'center'
2282 # query 'align-*' class argument
2283 for cls
in node
['classes']:
2284 if cls
.startswith('align-'):
2285 attrs
['align'] = cls
.split('-')[1]
2286 # pre- and postfix (prefix inserted in reverse order)
2289 include_graphics_options
= []
2290 display_style
= ('block-', 'inline-')[self
.is_inline(node
)]
2292 # inline images: by default latex aligns the bottom.
2294 'middle': (r
'\raisebox{-0.5\height}{', '}'),
2295 'top': (r
'\raisebox{-\height}{', '}'),
2296 # block level images:
2297 'center': (r
'\noindent\makebox[\textwidth][c]{', '}'),
2298 'left': (r
'\noindent{', r
'\hfill}'),
2299 'right': (r
'\noindent{\hfill', '}'),}
2300 if 'align' in attrs
:
2302 align_code
= align_codes
[attrs
['align']]
2303 pre
.append(align_code
[0])
2304 post
.append(align_code
[1])
2307 if 'height' in attrs
:
2308 include_graphics_options
.append('height=%s' %
2309 self
.to_latex_length(attrs
['height']))
2310 if 'scale' in attrs
:
2311 include_graphics_options
.append('scale=%f' %
2312 (attrs
['scale'] / 100.0))
2313 if 'width' in attrs
:
2314 include_graphics_options
.append('width=%s' %
2315 self
.to_latex_length(attrs
['width']))
2316 if not self
.is_inline(node
):
2320 self
.out
.extend(pre
)
2322 if include_graphics_options
:
2323 options
= '[%s]' % (','.join(include_graphics_options
))
2324 self
.out
.append('\\includegraphics%s{%s}' % (options
, imagepath
))
2325 self
.out
.extend(post
)
2327 def depart_image(self
, node
):
2329 self
.out
+= self
.ids_to_labels(node
) + ['\n']
2331 def visit_inline(self
, node
): # <span>, i.e. custom roles
2332 # Make a copy to keep ``node['classes']`` True if a
2333 # language argument is popped (used in conditional calls of
2335 classes
= node
['classes'][:]
2336 self
.context
.append('}' * len(classes
))
2337 # handle language specification:
2338 language_tags
= [cls
for cls
in classes
2339 if cls
.startswith('language-')]
2341 language
= self
.babel
.language_name(language_tags
[0][9:])
2343 self
.babel
.otherlanguages
[language
] = True
2344 self
.out
.append(r
'\foreignlanguage{%s}{' % language
)
2345 classes
.pop(classes
.index(language_tags
[0]))
2348 # mark up for styling with custom macros
2349 if 'align-center' in classes
:
2350 self
.fallbacks
['align-center'] = PreambleCmds
.align_center
2351 self
.fallbacks
['inline'] = PreambleCmds
.inline
2352 self
.out
+= [r
'\DUrole{%s}{' % cls
for cls
in classes
]
2354 def depart_inline(self
, node
):
2355 self
.out
.append(self
.context
.pop())
2357 def visit_interpreted(self
, node
):
2358 # @@@ Incomplete, pending a proper implementation on the
2359 # Parser/Reader end.
2360 self
.visit_literal(node
)
2362 def depart_interpreted(self
, node
):
2363 self
.depart_literal(node
)
2365 def visit_legend(self
, node
):
2366 self
.fallbacks
['legend'] = PreambleCmds
.legend
2367 self
.out
.append('\\begin{DUlegend}')
2369 def depart_legend(self
, node
):
2370 self
.out
.append('\\end{DUlegend}\n')
2372 def visit_line(self
, node
):
2373 self
.out
.append('\item[] ')
2375 def depart_line(self
, node
):
2376 self
.out
.append('\n')
2378 def visit_line_block(self
, node
):
2379 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
2380 self
.fallbacks
['lineblock'] = PreambleCmds
.lineblock
2381 if isinstance(node
.parent
, nodes
.line_block
):
2382 self
.out
.append('\\item[]\n'
2383 '\\begin{DUlineblock}{\\DUlineblockindent}\n')
2385 self
.out
.append('\n\\begin{DUlineblock}{0em}\n')
2387 self
.visit_inline(node
)
2388 self
.out
.append('\n')
2390 def depart_line_block(self
, node
):
2392 self
.depart_inline(node
)
2393 self
.out
.append('\n')
2394 self
.out
.append('\\end{DUlineblock}\n')
2396 def visit_list_item(self
, node
):
2397 self
.out
.append('\n\\item ')
2399 def depart_list_item(self
, node
):
2402 def visit_literal(self
, node
):
2404 if 'code' in node
.get('classes', []):
2405 self
.requirements
['color'] = PreambleCmds
.color
2406 self
.requirements
['code'] = PreambleCmds
.highlight_rules
2407 self
.out
.append('\\texttt{')
2409 self
.visit_inline(node
)
2411 def depart_literal(self
, node
):
2412 self
.literal
= False
2414 self
.depart_inline(node
)
2415 self
.out
.append('}')
2417 # Literal blocks are used for '::'-prefixed literal-indented
2418 # blocks of text, where the inline markup is not recognized,
2419 # but are also the product of the "parsed-literal" directive,
2420 # where the markup is respected.
2422 # In both cases, we want to use a typewriter/monospaced typeface.
2423 # For "real" literal-blocks, we can use \verbatim, while for all
2424 # the others we must use \mbox or \alltt.
2426 # We can distinguish between the two kinds by the number of
2427 # siblings that compose this node: if it is composed by a
2428 # single element, it's either
2430 # * a parsed-literal that does not contain any markup, or
2431 # * a parsed-literal containing just one markup construct.
2432 def is_plaintext(self
, node
):
2433 """Check whether a node can be typeset verbatim"""
2434 return (len(node
) == 1) and isinstance(node
[0], nodes
.Text
)
2436 def visit_literal_block(self
, node
):
2437 """Render a literal block."""
2438 # environments and packages to typeset literal blocks
2439 packages
= {'listing': r
'\usepackage{moreverb}',
2440 'lstlisting': r
'\usepackage{listings}',
2441 'Verbatim': r
'\usepackage{fancyvrb}',
2443 'verbatimtab': r
'\usepackage{moreverb}'}
2445 if not self
.active_table
.is_open():
2446 # no quote inside tables, to avoid vertical space between
2447 # table border and literal block.
2448 # BUG: fails if normal text preceeds the literal block.
2449 self
.out
.append('%\n\\begin{quote}')
2450 self
.context
.append('\n\\end{quote}\n')
2452 self
.out
.append('\n')
2453 self
.context
.append('\n')
2454 if self
.literal_block_env
!= '' and self
.is_plaintext(node
):
2455 self
.requirements
['literal_block'] = packages
.get(
2456 self
.literal_block_env
, '')
2457 self
.verbatim
= True
2458 self
.out
.append('\\begin{%s}%s\n' % (self
.literal_block_env
,
2459 self
.literal_block_options
))
2462 self
.insert_newline
= True
2463 self
.insert_non_breaking_blanks
= True
2464 self
.out
.append('{\\ttfamily \\raggedright \\noindent\n')
2466 def depart_literal_block(self
, node
):
2468 self
.out
.append('\n\\end{%s}\n' % self
.literal_block_env
)
2469 self
.verbatim
= False
2471 self
.out
.append('\n}')
2472 self
.insert_non_breaking_blanks
= False
2473 self
.insert_newline
= False
2474 self
.literal
= False
2475 self
.out
.append(self
.context
.pop())
2477 ## def visit_meta(self, node):
2478 ## self.out.append('[visit_meta]\n')
2479 # TODO: set keywords for pdf?
2481 # The reStructuredText "meta" directive creates a "pending" node,
2482 # which contains knowledge that the embedded "meta" node can only
2483 # be handled by HTML-compatible writers. The "pending" node is
2484 # resolved by the docutils.transforms.components.Filter transform,
2485 # which checks that the calling writer supports HTML; if it doesn't,
2486 # the "pending" node (and enclosed "meta" node) is removed from the
2488 # --- docutils/docs/peps/pep-0258.html#transformer
2490 ## def depart_meta(self, node):
2491 ## self.out.append('[depart_meta]\n')
2493 def visit_math(self
, node
, math_env
='$'):
2496 self
.visit_inline(node
)
2497 self
.requirements
['amsmath'] = r
'\usepackage{amsmath}'
2498 math_code
= node
.astext().translate(unichar2tex
.uni2tex_table
)
2500 math_code
= '\n'.join([math_code
] + self
.ids_to_labels(node
))
2504 wrapper
= u
'\n'.join(['%%',
2505 r
'\begin{%s}' % math_env
,
2507 r
'\end{%s}' % math_env
])
2508 # print repr(wrapper), repr(math_code)
2509 self
.out
.append(wrapper
% math_code
)
2511 self
.depart_inline(node
)
2512 # Content already processed:
2513 raise nodes
.SkipNode
2515 def depart_math(self
, node
):
2516 pass # never reached
2518 def visit_math_block(self
, node
):
2519 math_env
= pick_math_environment(node
.astext())
2520 self
.visit_math(node
, math_env
=math_env
)
2522 def depart_math_block(self
, node
):
2523 pass # never reached
2525 def visit_option(self
, node
):
2526 if self
.context
[-1]:
2527 # this is not the first option
2528 self
.out
.append(', ')
2530 def depart_option(self
, node
):
2531 # flag that the first option is done.
2532 self
.context
[-1] += 1
2534 def visit_option_argument(self
, node
):
2535 """Append the delimiter betweeen an option and its argument to body."""
2536 self
.out
.append(node
.get('delimiter', ' '))
2538 def depart_option_argument(self
, node
):
2541 def visit_option_group(self
, node
):
2542 self
.out
.append('\n\\item[')
2543 # flag for first option
2544 self
.context
.append(0)
2546 def depart_option_group(self
, node
):
2547 self
.context
.pop() # the flag
2548 self
.out
.append('] ')
2550 def visit_option_list(self
, node
):
2551 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
2552 self
.fallbacks
['optionlist'] = PreambleCmds
.optionlist
2553 self
.out
.append('%\n\\begin{DUoptionlist}\n')
2555 def depart_option_list(self
, node
):
2556 self
.out
.append('\n\\end{DUoptionlist}\n')
2558 def visit_option_list_item(self
, node
):
2561 def depart_option_list_item(self
, node
):
2564 def visit_option_string(self
, node
):
2565 ##self.out.append(self.starttag(node, 'span', '', CLASS='option'))
2568 def depart_option_string(self
, node
):
2569 ##self.out.append('</span>')
2572 def visit_organization(self
, node
):
2573 self
.visit_docinfo_item(node
, 'organization')
2575 def depart_organization(self
, node
):
2576 self
.depart_docinfo_item(node
)
2578 def visit_paragraph(self
, node
):
2579 # insert blank line, if the paragraph is not first in a list item
2580 # nor follows a non-paragraph node in a compound
2581 index
= node
.parent
.index(node
)
2582 if (index
== 0 and (isinstance(node
.parent
, nodes
.list_item
) or
2583 isinstance(node
.parent
, nodes
.description
))):
2585 elif (index
> 0 and isinstance(node
.parent
, nodes
.compound
) and
2586 not isinstance(node
.parent
[index
- 1], nodes
.paragraph
) and
2587 not isinstance(node
.parent
[index
- 1], nodes
.compound
)):
2590 self
.out
.append('\n')
2592 self
.out
+= self
.ids_to_labels(node
) + ['\n']
2594 self
.visit_inline(node
)
2596 def depart_paragraph(self
, node
):
2598 self
.depart_inline(node
)
2599 self
.out
.append('\n')
2601 def visit_problematic(self
, node
):
2602 self
.requirements
['color'] = PreambleCmds
.color
2603 self
.out
.append('%\n')
2604 self
.append_hypertargets(node
)
2605 self
.out
.append(r
'\hyperlink{%s}{\textbf{\color{red}' % node
['refid'])
2607 def depart_problematic(self
, node
):
2608 self
.out
.append('}}')
2610 def visit_raw(self
, node
):
2611 if not 'latex' in node
.get('format', '').split():
2612 raise nodes
.SkipNode
2613 if not self
.is_inline(node
):
2614 self
.out
.append('\n')
2616 self
.visit_inline(node
)
2617 # append "as-is" skipping any LaTeX-encoding
2618 self
.verbatim
= True
2620 def depart_raw(self
, node
):
2621 self
.verbatim
= False
2623 self
.depart_inline(node
)
2624 if not self
.is_inline(node
):
2625 self
.out
.append('\n')
2627 def has_unbalanced_braces(self
, string
):
2628 """Test whether there are unmatched '{' or '}' characters."""
2639 def visit_reference(self
, node
):
2640 # We need to escape #, \, and % if we use the URL in a command.
2641 special_chars
= {ord('#'): ur
'\#',
2645 # external reference (URL)
2646 if 'refuri' in node
:
2647 href
= unicode(node
['refuri']).translate(special_chars
)
2648 # problematic chars double caret and unbalanced braces:
2649 if href
.find('^^') != -1 or self
.has_unbalanced_braces(href
):
2651 'External link "%s" not supported by LaTeX.\n'
2652 ' (Must not contain "^^" or unbalanced braces.)' % href
)
2653 if node
['refuri'] == node
.astext():
2654 self
.out
.append(r
'\url{%s}' % href
)
2655 raise nodes
.SkipNode
2656 self
.out
.append(r
'\href{%s}{' % href
)
2658 # internal reference
2660 href
= node
['refid']
2661 elif 'refname' in node
:
2662 href
= self
.document
.nameids
[node
['refname']]
2664 raise AssertionError('Unknown reference.')
2665 if not self
.is_inline(node
):
2666 self
.out
.append('\n')
2667 self
.out
.append('\\hyperref[%s]{' % href
)
2668 if self
._reference
_label
:
2669 self
.out
.append('\\%s{%s}}' %
2670 (self
._reference
_label
, href
.replace('#', '')))
2671 raise nodes
.SkipNode
2673 def depart_reference(self
, node
):
2674 self
.out
.append('}')
2675 if not self
.is_inline(node
):
2676 self
.out
.append('\n')
2678 def visit_revision(self
, node
):
2679 self
.visit_docinfo_item(node
, 'revision')
2681 def depart_revision(self
, node
):
2682 self
.depart_docinfo_item(node
)
2684 def visit_section(self
, node
):
2685 self
.section_level
+= 1
2686 # Initialize counter for potential subsections:
2687 self
._section
_number
.append(0)
2688 # Counter for this section's level (initialized by parent section):
2689 self
._section
_number
[self
.section_level
- 1] += 1
2691 def depart_section(self
, node
):
2692 # Remove counter for potential subsections:
2693 self
._section
_number
.pop()
2694 self
.section_level
-= 1
2696 def visit_sidebar(self
, node
):
2697 self
.requirements
['color'] = PreambleCmds
.color
2698 self
.fallbacks
['sidebar'] = PreambleCmds
.sidebar
2699 self
.out
.append('\n\\DUsidebar{\n')
2701 def depart_sidebar(self
, node
):
2702 self
.out
.append('}\n')
2704 attribution_formats
= {'dash': (u
'—', ''), # EM DASH
2705 'parentheses': ('(', ')'),
2706 'parens': ('(', ')'),
2709 def visit_attribution(self
, node
):
2710 prefix
, suffix
= self
.attribution_formats
[self
.settings
.attribution
]
2711 self
.out
.append('\\nopagebreak\n\n\\raggedleft ')
2712 self
.out
.append(prefix
)
2713 self
.context
.append(suffix
)
2715 def depart_attribution(self
, node
):
2716 self
.out
.append(self
.context
.pop() + '\n')
2718 def visit_status(self
, node
):
2719 self
.visit_docinfo_item(node
, 'status')
2721 def depart_status(self
, node
):
2722 self
.depart_docinfo_item(node
)
2724 def visit_strong(self
, node
):
2725 self
.out
.append('\\textbf{')
2727 self
.visit_inline(node
)
2729 def depart_strong(self
, node
):
2731 self
.depart_inline(node
)
2732 self
.out
.append('}')
2734 def visit_substitution_definition(self
, node
):
2735 raise nodes
.SkipNode
2737 def visit_substitution_reference(self
, node
):
2738 self
.unimplemented_visit(node
)
2740 def visit_subtitle(self
, node
):
2741 if isinstance(node
.parent
, nodes
.document
):
2742 self
.push_output_collector(self
.subtitle
)
2743 self
.subtitle_labels
+= self
.ids_to_labels(node
, set_anchor
=False)
2744 # section subtitle: "starred" (no number, not in ToC)
2745 elif isinstance(node
.parent
, nodes
.section
):
2746 self
.out
.append(r
'\%s*{' %
2747 self
.d_class
.section(self
.section_level
+ 1))
2749 self
.fallbacks
['subtitle'] = PreambleCmds
.subtitle
2750 self
.out
.append('\n\\DUsubtitle[%s]{' % node
.parent
.tagname
)
2752 def depart_subtitle(self
, node
):
2753 if isinstance(node
.parent
, nodes
.document
):
2754 self
.pop_output_collector()
2756 self
.out
.append('}\n')
2758 def visit_system_message(self
, node
):
2759 self
.requirements
['color'] = PreambleCmds
.color
2760 self
.fallbacks
['title'] = PreambleCmds
.title
2761 node
['classes'] = ['system-message']
2762 self
.visit_admonition(node
)
2763 self
.out
.append('\\DUtitle[system-message]{system-message}\n')
2764 self
.append_hypertargets(node
)
2766 line
= ', line~%s' % node
['line']
2769 self
.out
.append('\n\n{\color{red}%s/%s} in \\texttt{%s}%s\n' %
2770 (node
['type'], node
['level'],
2771 self
.encode(node
['source']), line
))
2772 if len(node
['backrefs']) == 1:
2773 self
.out
.append('\n\\hyperlink{%s}{' % node
['backrefs'][0])
2774 self
.context
.append('}')
2776 backrefs
= ['\\hyperlink{%s}{%d}' % (href
, i
+1)
2777 for (i
, href
) in enumerate(node
['backrefs'])]
2778 self
.context
.append('backrefs: ' + ' '.join(backrefs
))
2780 def depart_system_message(self
, node
):
2781 self
.out
.append(self
.context
.pop())
2782 self
.depart_admonition()
2784 def visit_table(self
, node
):
2785 self
.requirements
['table'] = PreambleCmds
.table
2786 if self
.active_table
.is_open():
2787 self
.table_stack
.append(self
.active_table
)
2788 # nesting longtable does not work (e.g. 2007-04-18)
2789 self
.active_table
= Table(self
,'tabular',self
.settings
.table_style
)
2790 # A longtable moves before \paragraph and \subparagraph
2791 # section titles if it immediately follows them:
2792 if (self
.active_table
._latex
_type
== 'longtable' and
2793 isinstance(node
.parent
, nodes
.section
) and
2794 node
.parent
.index(node
) == 1 and
2795 self
.d_class
.section(self
.section_level
).find('paragraph') != -1):
2796 self
.out
.append('\\leavevmode')
2797 self
.active_table
.open()
2798 for cls
in node
['classes']:
2799 self
.active_table
.set_table_style(cls
)
2800 if self
.active_table
._table
_style
== 'booktabs':
2801 self
.requirements
['booktabs'] = r
'\usepackage{booktabs}'
2802 self
.push_output_collector([])
2804 def depart_table(self
, node
):
2805 # wrap content in the right environment:
2807 self
.pop_output_collector()
2808 self
.out
.append('\n' + self
.active_table
.get_opening())
2810 self
.out
.append(self
.active_table
.get_closing() + '\n')
2811 self
.active_table
.close()
2812 if len(self
.table_stack
)>0:
2813 self
.active_table
= self
.table_stack
.pop()
2815 self
.active_table
.set_table_style(self
.settings
.table_style
)
2816 # Insert hyperlabel after (long)table, as
2817 # other places (beginning, caption) result in LaTeX errors.
2819 self
.out
+= self
.ids_to_labels(node
, set_anchor
=False) + ['\n']
2821 def visit_target(self
, node
):
2822 # Skip indirect targets:
2823 if ('refuri' in node
# external hyperlink
2824 or 'refid' in node
# resolved internal link
2825 or 'refname' in node
): # unresolved internal link
2826 ## self.out.append('%% %s\n' % node) # for debugging
2828 self
.out
.append('%\n')
2829 # do we need an anchor (\phantomsection)?
2830 set_anchor
= not(isinstance(node
.parent
, nodes
.caption
) or
2831 isinstance(node
.parent
, nodes
.title
))
2832 # TODO: where else can/must we omit the \phantomsection?
2833 self
.out
+= self
.ids_to_labels(node
, set_anchor
)
2835 def depart_target(self
, node
):
2838 def visit_tbody(self
, node
):
2839 # BUG write preamble if not yet done (colspecs not [])
2840 # for tables without heads.
2841 if not self
.active_table
.get('preamble written'):
2842 self
.visit_thead(None)
2843 self
.depart_thead(None)
2845 def depart_tbody(self
, node
):
2848 def visit_term(self
, node
):
2849 """definition list term"""
2850 # Commands with optional args inside an optional arg must be put
2851 # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
2852 self
.out
.append('\\item[{')
2854 def depart_term(self
, node
):
2855 # \leavevmode results in a line break if the
2856 # term is followed by an item list.
2857 self
.out
.append('}] \leavevmode ')
2859 def visit_tgroup(self
, node
):
2860 #self.out.append(self.starttag(node, 'colgroup'))
2861 #self.context.append('</colgroup>\n')
2864 def depart_tgroup(self
, node
):
2868 def thead_depth (self
):
2869 return self
._thead
_depth
2871 def visit_thead(self
, node
):
2872 self
._thead
_depth
+= 1
2873 if 1 == self
.thead_depth():
2874 self
.out
.append('{%s}\n' % self
.active_table
.get_colspecs())
2875 self
.active_table
.set('preamble written',1)
2876 self
.out
.append(self
.active_table
.get_caption())
2877 self
.out
.extend(self
.active_table
.visit_thead())
2879 def depart_thead(self
, node
):
2880 if node
is not None:
2881 self
.out
.extend(self
.active_table
.depart_thead())
2882 if self
.active_table
.need_recurse():
2883 node
.walkabout(self
)
2884 self
._thead
_depth
-= 1
2886 def visit_title(self
, node
):
2887 """Append section and other titles."""
2889 if node
.parent
.tagname
== 'document':
2890 self
.push_output_collector(self
.title
)
2891 self
.context
.append('')
2892 self
.pdfinfo
.append(' pdftitle={%s},' %
2893 self
.encode(node
.astext()))
2894 # Topic titles (topic, admonition, sidebar)
2895 elif (isinstance(node
.parent
, nodes
.topic
) or
2896 isinstance(node
.parent
, nodes
.admonition
) or
2897 isinstance(node
.parent
, nodes
.sidebar
)):
2898 self
.fallbacks
['title'] = PreambleCmds
.title
2899 classes
= ','.join(node
.parent
['classes'])
2901 classes
= node
.tagname
2902 self
.out
.append('\\DUtitle[%s]{' % classes
)
2903 self
.context
.append('}\n')
2905 elif isinstance(node
.parent
, nodes
.table
):
2906 self
.push_output_collector(self
.active_table
.caption
)
2907 self
.context
.append('')
2910 if hasattr(PreambleCmds
, 'secnumdepth'):
2911 self
.requirements
['secnumdepth'] = PreambleCmds
.secnumdepth
2912 section_name
= self
.d_class
.section(self
.section_level
)
2913 self
.out
.append('\n\n')
2914 # System messages heading in red:
2915 if ('system-messages' in node
.parent
['classes']):
2916 self
.requirements
['color'] = PreambleCmds
.color
2917 section_title
= self
.encode(node
.astext())
2918 self
.out
.append(r
'\%s[%s]{\color{red}' % (
2919 section_name
,section_title
))
2921 self
.out
.append(r
'\%s{' % section_name
)
2922 if self
.section_level
> len(self
.d_class
.sections
):
2923 # section level not supported by LaTeX
2924 self
.fallbacks
['title'] = PreambleCmds
.title
2925 # self.out.append('\\phantomsection%\n ')
2926 # label and ToC entry:
2928 # add sections with unsupported level to toc and pdfbookmarks?
2929 ## if self.section_level > len(self.d_class.sections):
2930 ## section_title = self.encode(node.astext())
2931 ## bookmark.append(r'\addcontentsline{toc}{%s}{%s}' %
2932 ## (section_name, section_title))
2933 bookmark
+= self
.ids_to_labels(node
.parent
, set_anchor
=False)
2934 self
.context
.append('%\n '.join(bookmark
) + '%\n}\n')
2936 # MAYBE postfix paragraph and subparagraph with \leavemode to
2937 # ensure floats stay in the section and text starts on a new line.
2939 def depart_title(self
, node
):
2940 self
.out
.append(self
.context
.pop())
2941 if (isinstance(node
.parent
, nodes
.table
) or
2942 node
.parent
.tagname
== 'document'):
2943 self
.pop_output_collector()
2945 def minitoc(self
, node
, title
, depth
):
2946 """Generate a local table of contents with LaTeX package minitoc"""
2947 section_name
= self
.d_class
.section(self
.section_level
)
2948 # name-prefix for current section level
2949 minitoc_names
= {'part': 'part', 'chapter': 'mini'}
2950 if 'chapter' not in self
.d_class
.sections
:
2951 minitoc_names
['section'] = 'sect'
2953 minitoc_name
= minitoc_names
[section_name
]
2954 except KeyError: # minitoc only supports part- and toplevel
2955 self
.warn('Skipping local ToC at %s level.\n' % section_name
+
2956 ' Feature not supported with option "use-latex-toc"',
2959 # Requirements/Setup
2960 self
.requirements
['minitoc'] = PreambleCmds
.minitoc
2961 self
.requirements
['minitoc-'+minitoc_name
] = (r
'\do%stoc' %
2963 # depth: (Docutils defaults to unlimited depth)
2964 maxdepth
= len(self
.d_class
.sections
)
2965 self
.requirements
['minitoc-%s-depth' % minitoc_name
] = (
2966 r
'\mtcsetdepth{%stoc}{%d}' % (minitoc_name
, maxdepth
))
2967 # Process 'depth' argument (!Docutils stores a relative depth while
2968 # minitoc expects an absolute depth!):
2969 offset
= {'sect': 1, 'mini': 0, 'part': 0}
2970 if 'chapter' in self
.d_class
.sections
:
2973 self
.out
.append('\\setcounter{%stocdepth}{%d}' %
2974 (minitoc_name
, depth
+ offset
[minitoc_name
]))
2976 self
.out
.append('\\mtcsettitle{%stoc}{%s}\n' % (minitoc_name
, title
))
2977 # the toc-generating command:
2978 self
.out
.append('\\%stoc\n' % minitoc_name
)
2980 def visit_topic(self
, node
):
2981 # Topic nodes can be generic topic, abstract, dedication, or ToC.
2982 # table of contents:
2983 if 'contents' in node
['classes']:
2984 self
.out
.append('\n')
2985 self
.out
+= self
.ids_to_labels(node
)
2986 # add contents to PDF bookmarks sidebar
2987 if isinstance(node
.next_node(), nodes
.title
):
2988 self
.out
.append('\n\\pdfbookmark[%d]{%s}{%s}\n' %
2989 (self
.section_level
+1,
2990 node
.next_node().astext(),
2991 node
.get('ids', ['contents'])[0]
2993 if self
.use_latex_toc
:
2995 if isinstance(node
.next_node(), nodes
.title
):
2996 title
= self
.encode(node
.pop(0).astext())
2997 depth
= node
.get('depth', 0)
2998 if 'local' in node
['classes']:
2999 self
.minitoc(node
, title
, depth
)
3000 self
.context
.append('')
3003 self
.out
.append('\\setcounter{tocdepth}{%d}\n' % depth
)
3004 if title
!= 'Contents':
3005 self
.out
.append('\\renewcommand{\\contentsname}{%s}\n' %
3007 self
.out
.append('\\tableofcontents\n\n')
3008 self
.has_latex_toc
= True
3009 else: # Docutils generated contents list
3010 # set flag for visit_bullet_list() and visit_title()
3011 self
.is_toc_list
= True
3012 self
.context
.append('')
3013 elif ('abstract' in node
['classes'] and
3014 self
.settings
.use_latex_abstract
):
3015 self
.push_output_collector(self
.abstract
)
3016 self
.out
.append('\\begin{abstract}')
3017 self
.context
.append('\\end{abstract}\n')
3018 if isinstance(node
.next_node(), nodes
.title
):
3019 node
.pop(0) # LaTeX provides its own title
3021 self
.fallbacks
['topic'] = PreambleCmds
.topic
3023 if 'abstract' in node
['classes']:
3024 self
.fallbacks
['abstract'] = PreambleCmds
.abstract
3025 self
.push_output_collector(self
.abstract
)
3026 if 'dedication' in node
['classes']:
3027 self
.fallbacks
['dedication'] = PreambleCmds
.dedication
3028 self
.push_output_collector(self
.dedication
)
3029 self
.out
.append('\n\\DUtopic[%s]{\n' % ','.join(node
['classes']))
3030 self
.context
.append('}\n')
3032 def depart_topic(self
, node
):
3033 self
.out
.append(self
.context
.pop())
3034 self
.is_toc_list
= False
3035 if ('abstract' in node
['classes'] or
3036 'dedication' in node
['classes']):
3037 self
.pop_output_collector()
3039 def visit_rubric(self
, node
):
3040 self
.fallbacks
['rubric'] = PreambleCmds
.rubric
3041 self
.out
.append('\n\\DUrubric{')
3042 self
.context
.append('}\n')
3044 def depart_rubric(self
, node
):
3045 self
.out
.append(self
.context
.pop())
3047 def visit_transition(self
, node
):
3048 self
.fallbacks
['transition'] = PreambleCmds
.transition
3049 self
.out
.append('\n\n')
3050 self
.out
.append('%' + '_' * 75 + '\n')
3051 self
.out
.append(r
'\DUtransition')
3052 self
.out
.append('\n\n')
3054 def depart_transition(self
, node
):
3057 def visit_version(self
, node
):
3058 self
.visit_docinfo_item(node
, 'version')
3060 def depart_version(self
, node
):
3061 self
.depart_docinfo_item(node
)
3063 def unimplemented_visit(self
, node
):
3064 raise NotImplementedError('visiting unimplemented node type: %s' %
3065 node
.__class
__.__name
__)
3067 # def unknown_visit(self, node):
3068 # def default_visit(self, node):
3070 # vim: set ts=4 et ai :