3 # Author: Engelbert Gruber <grubert@users.sourceforge.net>
4 # Copyright: This module has been placed in the public domain.
6 """LaTeX2e document tree Writer."""
8 __docformat__
= 'reStructuredText'
10 # code contributions from several people included, thanks to all.
11 # some named: David Abrahams, Julien Letessier, Lele Gaifax, and others.
13 # convention deactivate code by two # i.e. ##.
20 from docutils
import frontend
, nodes
, languages
, writers
, utils
, io
21 from docutils
.transforms
import writer_aux
23 # compatibility module for Python 2.3
24 if not hasattr(string
, 'Template'):
25 import docutils
._string
_template
_compat
26 string
.Template
= docutils
._string
_template
_compat
.Template
28 class Writer(writers
.Writer
):
30 supported
= ('latex','latex2e')
31 """Formats this writer supports."""
33 default_template
= 'default.tex'
34 default_template_path
= os
.path
.dirname(__file__
)
36 default_preamble
= '\n'.join([r
'% PDF Standard Fonts',
37 r
'\usepackage{mathptmx} % Times',
38 r
'\usepackage[scaled=.90]{helvet}',
39 r
'\usepackage{courier}'])
41 'LaTeX-Specific Options',
43 (('Specify documentclass. Default is "article".',
45 {'default': 'article', }),
46 ('Specify document options. Multiple options can be given, '
47 'separated by commas. Default is "a4paper".',
48 ['--documentoptions'],
49 {'default': 'a4paper', }),
50 ('Footnotes with numbers/symbols by Docutils. (default)',
51 ['--docutils-footnotes'],
52 {'default': True, 'action': 'store_true',
53 'validator': frontend
.validate_boolean
}),
54 ('Alias for --docutils-footnotes (deprecated)',
55 ['--use-latex-footnotes'],
56 {'action': 'store_true',
57 'validator': frontend
.validate_boolean
}),
58 ('Use figure floats for footnote text (deprecated)',
59 ['--figure-footnotes'],
60 {'action': 'store_true',
61 'validator': frontend
.validate_boolean
}),
62 ('Format for footnote references: one of "superscript" or '
63 '"brackets". Default is "superscript".',
64 ['--footnote-references'],
65 {'choices': ['superscript', 'brackets'], 'default': 'superscript',
66 'metavar': '<format>',
67 'overrides': 'trim_footnote_reference_space'}),
68 ('Use \\cite command for citations. ',
69 ['--use-latex-citations'],
70 {'default': 0, 'action': 'store_true',
71 'validator': frontend
.validate_boolean
}),
72 ('Use figure floats for citations '
73 '(might get mixed with real figures). (default)',
74 ['--figure-citations'],
75 {'dest': 'use_latex_citations', 'action': 'store_false',
76 'validator': frontend
.validate_boolean
}),
77 ('Format for block quote attributions: one of "dash" (em-dash '
78 'prefix), "parentheses"/"parens", or "none". Default is "dash".',
80 {'choices': ['dash', 'parentheses', 'parens', 'none'],
81 'default': 'dash', 'metavar': '<format>'}),
82 ('Specify LaTeX packages/stylesheets. '
83 ' A style is referenced with \\usepackage if extension is '
84 '".sty" or omitted and with \\input else. '
85 ' Overrides previous --stylesheet and --stylesheet-path settings.',
87 {'default': '', 'metavar': '<file>',
88 'overrides': 'stylesheet_path'}),
89 ('Like --stylesheet, but the path is rewritten '
90 'relative to the output file. ',
91 ['--stylesheet-path'],
92 {'metavar': '<file>', 'overrides': 'stylesheet'}),
93 ('Link to the stylesheet(s) in the output file. (default)',
94 ['--link-stylesheet'],
95 {'dest': 'embed_stylesheet', 'action': 'store_false'}),
96 ('Embed the stylesheet(s) in the output file. '
97 'Stylesheets must be accessible during processing. ',
98 ['--embed-stylesheet'],
99 {'default': 0, 'action': 'store_true',
100 'validator': frontend
.validate_boolean
}),
101 ('Customization by LaTeX code in the preamble. '
102 'Default: select PDF standard fonts (Times, Helvetica, Courier).',
103 ['--latex-preamble'],
104 {'default': default_preamble
}),
105 ('Specify the template file. Default: "%s".' % default_template
,
107 {'default': default_template
, 'metavar': '<file>'}),
108 ('Table of contents by LaTeX. (default) ',
110 {'default': 1, 'action': 'store_true',
111 'validator': frontend
.validate_boolean
}),
112 ('Table of contents by Docutils (without page numbers). ',
113 ['--use-docutils-toc'],
114 {'dest': 'use_latex_toc', 'action': 'store_false',
115 'validator': frontend
.validate_boolean
}),
116 ('Add parts on top of the section hierarchy.',
117 ['--use-part-section'],
118 {'default': 0, 'action': 'store_true',
119 'validator': frontend
.validate_boolean
}),
120 ('Attach author and date to the document info table. (default) ',
121 ['--use-docutils-docinfo'],
122 {'dest': 'use_latex_docinfo', 'action': 'store_false',
123 'validator': frontend
.validate_boolean
}),
124 ('Attach author and date to the document title.',
125 ['--use-latex-docinfo'],
126 {'default': 0, 'action': 'store_true',
127 'validator': frontend
.validate_boolean
}),
128 ("Typeset abstract as topic. (default)",
129 ['--topic-abstract'],
130 {'dest': 'use_latex_abstract', 'action': 'store_false',
131 'validator': frontend
.validate_boolean
}),
132 ("Use LaTeX abstract environment for the document's abstract. ",
133 ['--use-latex-abstract'],
134 {'default': 0, 'action': 'store_true',
135 'validator': frontend
.validate_boolean
}),
136 ('Color of any hyperlinks embedded in text '
137 '(default: "blue", "false" to disable).',
138 ['--hyperlink-color'], {'default': 'blue'}),
139 ('Additional options to the "hyperref" package '
141 ['--hyperref-options'], {'default': ''}),
142 ('Enable compound enumerators for nested enumerated lists '
143 '(e.g. "1.2.a.ii"). Default: disabled.',
144 ['--compound-enumerators'],
145 {'default': None, 'action': 'store_true',
146 'validator': frontend
.validate_boolean
}),
147 ('Disable compound enumerators for nested enumerated lists. '
148 'This is the default.',
149 ['--no-compound-enumerators'],
150 {'action': 'store_false', 'dest': 'compound_enumerators'}),
151 ('Enable section ("." subsection ...) prefixes for compound '
152 'enumerators. This has no effect without --compound-enumerators.'
153 'Default: disabled.',
154 ['--section-prefix-for-enumerators'],
155 {'default': None, 'action': 'store_true',
156 'validator': frontend
.validate_boolean
}),
157 ('Disable section prefixes for compound enumerators. '
158 'This is the default.',
159 ['--no-section-prefix-for-enumerators'],
160 {'action': 'store_false', 'dest': 'section_prefix_for_enumerators'}),
161 ('Set the separator between section number and enumerator '
162 'for compound enumerated lists. Default is "-".',
163 ['--section-enumerator-separator'],
164 {'default': '-', 'metavar': '<char>'}),
165 ('When possibile, use the specified environment for literal-blocks. '
166 'Default is quoting of whitespace and special chars.',
167 ['--literal-block-env'],
169 ('When possibile, use verbatim for literal-blocks. '
170 'Compatibility alias for "--literal-block-env=verbatim".',
171 ['--use-verbatim-when-possible'],
172 {'default': 0, 'action': 'store_true',
173 'validator': frontend
.validate_boolean
}),
174 ('Table style. "standard" with horizontal and vertical lines, '
175 '"booktabs" (LaTeX booktabs style) only horizontal lines '
176 'above and below the table and below the header or "borderless". '
177 'Default: "standard"',
179 {'choices': ['standard', 'booktabs','nolines', 'borderless'],
180 'default': 'standard',
181 'metavar': '<format>'}),
182 ('LaTeX graphicx package option. '
183 'Possible values are "dvips", "pdftex". "auto" includes LaTeX code '
184 'to use "pdftex" if processing with pdf(la)tex and dvips otherwise. '
185 'Default is no option.',
186 ['--graphicx-option'],
188 ('LaTeX font encoding. '
189 'Possible values are "", "T1" (default), "OT1", "LGR,T1" or '
190 'any other combination of options to the `fontenc` package. ',
193 ('Per default the latex-writer puts the reference title into '
194 'hyperreferences. Specify "ref*" or "pageref*" to get the section '
195 'number or the page number.',
196 ['--reference-label'],
197 {'default': None, }),
198 ('Specify style and database for bibtex, for example '
199 '"--use-bibtex=mystyle,mydb1,mydb2".',
201 {'default': None, }),
204 settings_defaults
= {'sectnum_depth': 0 # updated by SectNum transform
206 relative_path_settings
= ('stylesheet_path',)
208 config_section
= 'latex2e writer'
209 config_section_dependencies
= ('writers',)
211 head_parts
= ('head_prefix', 'requirements', 'latex_preamble',
212 'stylesheet', 'fallbacks', 'pdfsetup',
213 'title', 'subtitle', 'titledata')
214 visitor_attributes
= head_parts
+ ('body_pre_docinfo', 'docinfo',
215 'dedication', 'abstract', 'body')
218 """Final translated form of `document`."""
221 writers
.Writer
.__init
__(self
)
222 self
.translator_class
= LaTeXTranslator
224 # Override parent method to add latex-specific transforms
225 def get_transforms(self
):
226 # call the parent class' method
227 transform_list
= writers
.Writer
.get_transforms(self
)
228 # print transform_list
229 # Convert specific admonitions to generic one
230 transform_list
.append(writer_aux
.Admonitions
)
231 # TODO: footnote collection transform
232 # transform_list.append(footnotes.collect)
233 return transform_list
236 visitor
= self
.translator_class(self
.document
)
237 self
.document
.walkabout(visitor
)
239 for part
in self
.visitor_attributes
:
240 setattr(self
, part
, getattr(visitor
, part
))
241 # get template string from file
243 file = open(self
.document
.settings
.template
, 'rb')
245 file = open(os
.path
.join(self
.default_template_path
,
246 self
.document
.settings
.template
), 'rb')
247 template
= string
.Template(unicode(file.read(), 'utf-8'))
250 self
.assemble_parts() # create dictionary of parts
251 self
.output
= template
.substitute(self
.parts
)
253 def assemble_parts(self
):
254 """Assemble the `self.parts` dictionary of output fragments."""
255 writers
.Writer
.assemble_parts(self
)
256 for part
in self
.visitor_attributes
:
257 lines
= getattr(self
, part
)
258 if part
in self
.head_parts
:
260 lines
.append('') # to get a trailing newline
261 self
.parts
[part
] = '\n'.join(lines
)
263 # body contains inline elements, so join without newline
264 self
.parts
[part
] = ''.join(lines
)
268 """Language specifics for LaTeX."""
270 # TeX (babel) language names:
271 # ! not all of these are supported by Docutils!
273 # based on LyX' languages file with adaptions to `BCP 47`_
274 # (http://www.rfc-editor.org/rfc/bcp/bcp47.txt) and
275 # http://www.tug.org/TUGboat/Articles/tb29-3/tb93miklavec.pdf
276 # * the key without subtags is the default
278 # cf. http://docutils.sourceforge.net/docs/howto/i18n.html
279 # http://www.w3.org/International/articles/language-tags/
280 # and http://www.iana.org/assignments/language-subtag-registry
282 # code TeX/Babel-name comment
285 # 'be': 'belarusian',
293 'de': 'ngerman', # new spelling (de_1996)
294 'de_1901': 'german', # old spelling
295 'de_at': 'naustrian',
296 'de_at_1901': 'austrian',
297 'dsb': 'lowersorbian',
298 'el': 'greek', # monotonic (el-monoton)
299 'el_polyton': 'polutonikogreek',
300 'en': 'english', # TeX' default language
301 'en_au': 'australian',
304 'en_nz': 'newzealand',
306 'eo': 'esperanto', # '^' is active
314 'ga': 'irish', # Irish Gaelic
315 # 'grc': # Ancient Greek
316 'grc_ibycus': 'ibycus', # Ibycus encoding
320 'hsb': 'uppersorbian',
323 'id': 'bahasai', # Bahasa (Indonesian)
331 'mn': 'mongolian', # Mongolian, Cyrillic script (mn-cyrl)
332 'ms': 'bahasam', # Bahasa (Malay)
333 'nb': 'norsk', # Norwegian Bokmal
335 'nn': 'nynorsk', # Norwegian Nynorsk
336 'no': 'norsk', # Norwegian Bokmal
341 'ru': 'russian', # '"' is active
342 'se': 'samin', # North Sami
343 # sh-cyrl: Serbo-Croatian, Cyrillic script
344 'sh-latn': 'serbian', # Serbo-Croatian, Latin script
348 # 'sr-cyrl': Serbian, Cyrillic script (sr-cyrl)
349 'sr-latn': 'serbian', # Serbian, Latin script, " active.
355 # zh-latn: Chinese Pinyin
357 warn_msg
= 'Language "%s" not supported by LaTeX (babel)'
359 def __init__(self
, language_code
, reporter
):
360 self
.language_code
= language_code
361 self
.reporter
= reporter
362 self
.language
= self
.get_language(language_code
)
363 self
.otherlanguages
= {}
365 self
.quotes
= ('``', "''")
366 # language dependent configuration:
367 # double quotes are "active" in some languages (e.g. German).
368 # TODO: use \textquotedbl in T1 font encoding?
369 self
.literal_double_quote
= u
'"'
370 if self
.language
in ('ngerman', 'german', 'austrian', 'naustrian',
372 self
.quotes
= (r
'\glqq{}', r
'\grqq{}')
373 self
.literal_double_quote
= ur
'\dq{}'
374 if self
.language
== 'french':
375 self
.quotes
= (r
'\og{}', r
'\fg{}')
376 if self
.language
== 'italian':
377 self
.literal_double_quote
= ur
'{\char`\"}'
380 """Return the babel call with correct options and settings"""
381 languages
= self
.otherlanguages
.keys()
382 languages
.append(self
.language
or 'english')
383 self
.setup
= [r
'\usepackage[%s]{babel}' % ','.join(languages
)]
384 if 'spanish' in languages
:
385 # reset active chars to the original meaning:
387 r
'\addto\shorthandsspanish{\spanishdeactivate{."~<>}}')
388 # or prepend r'\def\spanishoptions{es-noshorthands}'
389 if (languages
[-1] is 'english' and
390 'french' in self
.otherlanguages
.keys()):
391 self
.setup
+= ['% Prevent side-effects if French hyphenation '
392 'patterns are not loaded:',
393 r
'\frenchbsetup{StandardLayout}',
394 r
'\AtBeginDocument{\selectlanguage{%s}'
395 r
'\noextrasfrench}' % self
.language
]
396 return '\n'.join(self
.setup
)
398 def next_quote(self
):
399 q
= self
.quotes
[self
.quote_index
]
400 self
.quote_index
= (self
.quote_index
+1) % 2
403 def quote_quotes(self
,text
):
405 for part
in text
.split('"'):
409 t
+= self
.next_quote() + part
412 def get_language(self
, language_code
):
413 """Return TeX language name for `language_code`"""
414 for tag
in utils
.normalize_language_tag(language_code
):
416 language
= self
.language_codes
[tag
]
421 self
.reporter
.warning(self
.warn_msg
% self
.language_code
)
426 # Building blocks for the latex preamble
427 # --------------------------------------
429 class SortableDict(dict):
430 """Dictionary with additional sorting methods
432 Tip: use key starting with with '_' for sorting before small letters
433 and with '~' for sorting after small letters.
435 def sortedkeys(self
):
436 """Return sorted list of keys"""
441 def sortedvalues(self
):
442 """Return list of values sorted by keys"""
443 return [self
[key
] for key
in self
.sortedkeys()]
448 # A container for LaTeX code snippets that can be
449 # inserted into the preamble if required in the document.
451 # .. The package 'makecmds' would enable shorter definitions using the
452 # \providelength and \provideenvironment commands.
453 # However, it is pretty non-standard (texlive-latex-extra).
455 class PreambleCmds(object):
456 """Building blocks for the latex preamble."""
458 PreambleCmds
.abstract
= r
"""
460 \providecommand*{\DUtitleabstract}[1]{\centerline{\textbf{#1}}}"""
462 PreambleCmds
.admonition
= r
"""
463 % admonition (specially marked topic)
464 \providecommand{\DUadmonition}[2][class-arg]{%
465 % try \DUadmonition#1{#2}:
466 \ifcsname DUadmonition#1\endcsname%
467 \csname DUadmonition#1\endcsname{#2}%
470 \fbox{\parbox{0.9\textwidth}{#2}}
475 PreambleCmds
.align_center
= r
"""
477 \@namedef{DUrolealign-center}{\centering}
481 ## PreambleCmds.caption = r"""% configure caption layout
482 ## \usepackage{caption}
483 ## \captionsetup{singlelinecheck=false}% no exceptions for one-liners"""
485 PreambleCmds
.color
= r
"""\usepackage{color}"""
487 PreambleCmds
.docinfo
= r
"""
488 % docinfo (width of docinfo table)
489 \DUprovidelength{\DUdocinfowidth}{0.9\textwidth}"""
490 # PreambleCmds.docinfo._depends = 'providelength'
492 PreambleCmds
.embedded_package_wrapper
= r
"""\makeatletter
493 %% embedded stylesheet: %s
497 PreambleCmds
.dedication
= r
"""
499 \providecommand{\DUtopicdedication}[1]{\begin{center}#1\end{center}}"""
501 PreambleCmds
.error
= r
"""
502 % error admonition title
503 \providecommand*{\DUtitleerror}[1]{\DUtitle{\color{red}#1}}"""
504 # PreambleCmds.errortitle._depends = 'color'
506 PreambleCmds
.fieldlist
= r
"""
507 % fieldlist environment
508 \ifthenelse{\isundefined{\DUfieldlist}}{
509 \newenvironment{DUfieldlist}%
511 {\enddescription\endquote}
514 PreambleCmds
.float_settings
= r
"""\usepackage{float} % float configuration
515 \floatplacement{figure}{H} % place figures here definitely"""
517 PreambleCmds
.footnotes
= r
"""% numeric or symbol footnotes with hyperlinks
518 \providecommand*{\DUfootnotemark}[3]{%
519 \raisebox{1em}{\hypertarget{#1}{}}%
520 \hyperlink{#2}{\textsuperscript{#3}}%
522 \providecommand{\DUfootnotetext}[4]{%
524 \renewcommand{\thefootnote}{%
525 \protect\raisebox{1em}{\protect\hypertarget{#1}{}}%
526 \protect\hyperlink{#2}{#3}}%
531 PreambleCmds
.footnote_floats
= r
"""% settings for footnotes as floats:
532 \setlength{\floatsep}{0.5em}
533 \setlength{\textfloatsep}{\fill}
534 \addtolength{\textfloatsep}{3em}
535 \renewcommand{\textfraction}{0.5}
536 \renewcommand{\topfraction}{0.5}
537 \renewcommand{\bottomfraction}{0.5}
538 \setcounter{totalnumber}{50}
539 \setcounter{topnumber}{50}
540 \setcounter{bottomnumber}{50}"""
542 PreambleCmds
.graphicx_auto
= r
"""% Check output format
543 \ifx\pdftexversion\undefined
544 \usepackage{graphicx}
546 \usepackage[pdftex]{graphicx}
549 PreambleCmds
.inline
= r
"""
550 % inline markup (custom roles)
551 % \DUrole{#1}{#2} tries \DUrole#1{#2}
552 \providecommand*{\DUrole}[2]{%
553 \ifcsname DUrole#1\endcsname%
554 \csname DUrole#1\endcsname{#2}%
555 \else% backwards compatibility: try \docutilsrole#1{#2}
556 \ifcsname docutilsrole#1\endcsname%
557 \csname docutilsrole#1\endcsname{#2}%
564 PreambleCmds
.legend
= r
"""
566 \ifthenelse{\isundefined{\DUlegend}}{
567 \newenvironment{DUlegend}{\small}{}
570 PreambleCmds
.lineblock
= r
"""
571 % lineblock environment
572 \DUprovidelength{\DUlineblockindent}{2.5em}
573 \ifthenelse{\isundefined{\DUlineblock}}{
574 \newenvironment{DUlineblock}[1]{%
575 \list{}{\setlength{\partopsep}{\parskip}
576 \addtolength{\partopsep}{\baselineskip}
577 \setlength{\topsep}{0pt}
578 \setlength{\itemsep}{0.15\baselineskip}
579 \setlength{\parsep}{0pt}
580 \setlength{\leftmargin}{#1}}
585 # PreambleCmds.lineblock._depends = 'providelength'
587 PreambleCmds
.linking
= r
"""
589 \ifthenelse{\isundefined{\hypersetup}}{
590 \usepackage[%s]{hyperref}
591 \urlstyle{same} %% normal text font (alternatives: tt, rm, sf)
594 PreambleCmds
.minitoc
= r
"""%% local table of contents
595 \usepackage{minitoc}"""
597 PreambleCmds
.optionlist
= r
"""
598 % optionlist environment
599 \providecommand*{\DUoptionlistlabel}[1]{\bf #1 \hfill}
600 \DUprovidelength{\DUoptionlistindent}{3cm}
601 \ifthenelse{\isundefined{\DUoptionlist}}{
602 \newenvironment{DUoptionlist}{%
603 \list{}{\setlength{\labelwidth}{\DUoptionlistindent}
604 \setlength{\rightmargin}{1cm}
605 \setlength{\leftmargin}{\rightmargin}
606 \addtolength{\leftmargin}{\labelwidth}
607 \addtolength{\leftmargin}{\labelsep}
608 \renewcommand{\makelabel}{\DUoptionlistlabel}}
612 # PreambleCmds.optionlist._depends = 'providelength'
614 PreambleCmds
.providelength
= r
"""
615 % providelength (provide a length variable and set default, if it is new)
616 \providecommand*{\DUprovidelength}[2]{
617 \ifthenelse{\isundefined{#1}}{\newlength{#1}\setlength{#1}{#2}}{}
620 PreambleCmds
.rubric
= r
"""
621 % rubric (informal heading)
622 \providecommand*{\DUrubric}[2][class-arg]{%
623 \subsubsection*{\centering\textit{\textmd{#2}}}}"""
625 PreambleCmds
.sidebar
= r
"""
626 % sidebar (text outside the main text flow)
627 \providecommand{\DUsidebar}[2][class-arg]{%
629 \colorbox[gray]{0.80}{\parbox{0.9\textwidth}{#2}}
633 PreambleCmds
.subtitle
= r
"""
634 % subtitle (for topic/sidebar)
635 \providecommand*{\DUsubtitle}[2][class-arg]{\par\emph{#2}\smallskip}"""
637 PreambleCmds
.table
= r
"""\usepackage{longtable}
639 \setlength{\extrarowheight}{2pt}
640 \newlength{\DUtablewidth} % internal use in tables"""
642 # Options [force,almostfull] prevent spurious error messages, see
643 # de.comp.text.tex/2005-12/msg01855
644 PreambleCmds
.textcomp
= """\
645 \\usepackage{textcomp} % text symbol macros"""
647 PreambleCmds
.titlereference
= r
"""
648 % titlereference role
649 \providecommand*{\DUroletitlereference}[1]{\textsl{#1}}"""
651 PreambleCmds
.title
= r
"""
652 % title for topics, admonitions and sidebar
653 \providecommand*{\DUtitle}[2][class-arg]{%
654 % call \DUtitle#1{#2} if it exists:
655 \ifcsname DUtitle#1\endcsname%
656 \csname DUtitle#1\endcsname{#2}%
658 \smallskip\noindent\textbf{#2}\smallskip%
662 PreambleCmds
.topic
= r
"""
663 % topic (quote with heading)
664 \providecommand{\DUtopic}[2][class-arg]{%
665 \ifcsname DUtopic#1\endcsname%
666 \csname DUtopic#1\endcsname{#2}%
668 \begin{quote}#2\end{quote}
672 PreambleCmds
.transition
= r
"""
673 % transition (break, fancybreak, anonymous section)
674 \providecommand*{\DUtransition}[1][class-arg]{%
675 \hspace*{\fill}\hrulefill\hspace*{\fill}
676 \vskip 0.5\baselineskip
680 class DocumentClass(object):
681 """Details of a LaTeX document class."""
683 def __init__(self
, document_class
, with_part
=False):
684 self
.document_class
= document_class
685 self
._with
_part
= with_part
686 self
.sections
= ['section', 'subsection', 'subsubsection',
687 'paragraph', 'subparagraph']
688 if self
.document_class
in ('book', 'memoir', 'report',
689 'scrbook', 'scrreprt'):
690 self
.sections
.insert(0, 'chapter')
692 self
.sections
.insert(0, 'part')
694 def section(self
, level
):
695 """Return the LaTeX section name for section `level`.
697 The name depends on the specific document class.
698 Level is 1,2,3..., as level 0 is the title.
701 if level
<= len(self
.sections
):
702 return self
.sections
[level
-1]
704 return self
.sections
[-1]
708 """Manage a table while traversing.
710 Maybe change to a mixin defining the visit/departs, but then
711 class Table internal variables are in the Translator.
715 :standard: horizontal and vertical lines
716 :booktabs: only horizontal lines (requires "booktabs" LaTeX package)
717 :borderless: no borders around table cells
718 :nolines: alias for borderless
720 def __init__(self
,translator
,latex_type
,table_style
):
721 self
._translator
= translator
722 self
._latex
_type
= latex_type
723 self
._table
_style
= table_style
725 # miscellaneous attributes
737 self
._in
_head
= 0 # maybe context with search
740 self
._col
_specs
= None
746 def set_table_style(self
, table_style
):
747 if not table_style
in ('standard','booktabs','borderless','nolines'):
749 self
._table
_style
= table_style
751 def get_latex_type(self
):
752 return self
._latex
_type
754 def set(self
,attr
,value
):
755 self
._attrs
[attr
] = value
757 if attr
in self
._attrs
:
758 return self
._attrs
[attr
]
761 def get_vertical_bar(self
):
762 if self
._table
_style
== 'standard':
766 # horizontal lines are drawn below a row,
767 def get_opening(self
):
768 if self
._latex
_type
== 'longtable':
769 # otherwise longtable might move before paragraph and subparagraph
770 prefix
= '\\leavevmode\n'
773 prefix
+= '\setlength{\DUtablewidth}{\linewidth}'
774 return '%s\n\\begin{%s}[c]' % (prefix
, self
._latex
_type
)
776 def get_closing(self
):
778 if self
._table
_style
== 'booktabs':
779 line
= '\\bottomrule\n'
780 elif self
._table
_style
== 'standard':
782 return '%s\\end{%s}' % (line
,self
._latex
_type
)
784 def visit_colspec(self
, node
):
785 self
._col
_specs
.append(node
)
786 # "stubs" list is an attribute of the tgroup element:
787 self
.stubs
.append(node
.attributes
.get('stub'))
789 def get_colspecs(self
):
790 """Return column specification for longtable.
792 Assumes reST line length being 80 characters.
793 Table width is hairy.
799 usually gets to narrow, therefore we add 1 (fiddlefactor).
804 # first see if we get too wide.
805 for node
in self
._col
_specs
:
806 colwidth
= float(node
['colwidth']+1) / width
807 total_width
+= colwidth
810 # donot make it full linewidth
812 if total_width
> 1.0:
813 factor
/= total_width
814 bar
= self
.get_vertical_bar()
815 latex_table_spec
= ''
816 for node
in self
._col
_specs
:
817 colwidth
= factor
* float(node
['colwidth']+1) / width
818 self
._col
_width
.append(colwidth
+0.005)
819 self
._rowspan
.append(0)
820 latex_table_spec
+= '%sp{%.3f\\DUtablewidth}' % (bar
, colwidth
+0.005)
821 return latex_table_spec
+bar
823 def get_column_width(self
):
824 """Return columnwidth for current cell (not multicell)."""
825 return '%.2f\\DUtablewidth' % self
._col
_width
[self
._cell
_in
_row
-1]
827 def get_caption(self
):
830 caption
= ''.join(self
.caption
)
831 if 1 == self
._translator
.thead_depth():
832 return r
'\caption{%s}\\' '\n' % caption
833 return r
'\caption[]{%s (... continued)}\\' '\n' % caption
835 def need_recurse(self
):
836 if self
._latex
_type
== 'longtable':
837 return 1 == self
._translator
.thead_depth()
840 def visit_thead(self
):
842 if self
._table
_style
== 'standard':
844 elif self
._table
_style
== 'booktabs':
845 return ['\\toprule\n']
847 def depart_thead(self
):
849 #if self._table_style == 'standard':
850 # a.append('\\hline\n')
851 if self
._table
_style
== 'booktabs':
852 a
.append('\\midrule\n')
853 if self
._latex
_type
== 'longtable':
854 if 1 == self
._translator
.thead_depth():
855 a
.append('\\endfirsthead\n')
857 a
.append('\\endhead\n')
858 a
.append(r
'\multicolumn{%d}{c}' % len(self
._col
_specs
) +
859 r
'{\hfill ... continued on next page} \\')
860 a
.append('\n\\endfoot\n\\endlastfoot\n')
861 # for longtable one could add firsthead, foot and lastfoot
865 self
._cell
_in
_row
= 0
866 def depart_row(self
):
868 self
._cell
_in
_row
= None # remove cell counter
869 for i
in range(len(self
._rowspan
)):
870 if (self
._rowspan
[i
]>0):
871 self
._rowspan
[i
] -= 1
873 if self
._table
_style
== 'standard':
874 rowspans
= [i
+1 for i
in range(len(self
._rowspan
))
875 if (self
._rowspan
[i
]<=0)]
876 if len(rowspans
)==len(self
._rowspan
):
877 res
.append('\\hline\n')
884 c_start
= rowspans
.pop()
887 cline
+= '\\cline{%d-%d}\n' % (c_start
,c_start
)
891 def set_rowspan(self
,cell
,value
):
893 self
._rowspan
[cell
] = value
896 def get_rowspan(self
,cell
):
898 return self
._rowspan
[cell
]
901 def get_entry_number(self
):
902 return self
._cell
_in
_row
903 def visit_entry(self
):
904 self
._cell
_in
_row
+= 1
905 def is_stub_column(self
):
906 if len(self
.stubs
) >= self
._cell
_in
_row
:
907 return self
.stubs
[self
._cell
_in
_row
-1]
911 class LaTeXTranslator(nodes
.NodeVisitor
):
913 # When options are given to the documentclass, latex will pass them
914 # to other packages, as done with babel.
915 # Dummy settings might be taken from document settings
917 # Config setting defaults
918 # -----------------------
920 # TODO: use mixins for different implementations.
921 # list environment for docinfo. else tabularx
922 ## use_optionlist_for_docinfo = False # TODO: NOT YET IN USE
924 # Use compound enumerations (1.A.1.)
925 compound_enumerators
= 0
927 # If using compound enumerations, include section information.
928 section_prefix_for_enumerators
= 0
930 # This is the character that separates the section ("." subsection ...)
931 # prefix from the regular list enumerator.
932 section_enumerator_separator
= '-'
934 # Auxiliary variables
935 # -------------------
937 has_latex_toc
= False # is there a toc in the doc? (needed by minitoc)
938 is_toc_list
= False # is the current bullet_list a ToC?
942 # inside citation reference labels underscores dont need to be escaped
943 inside_citation_reference_label
= False
944 verbatim
= False # do not encode
945 insert_non_breaking_blanks
= False # replace blanks by "~"
946 insert_newline
= False # add latex newline commands
947 literal
= False # literal text (block or inline)
950 def __init__(self
, document
, babel_class
=Babel
):
951 nodes
.NodeVisitor
.__init
__(self
, document
)
954 self
.warn
= self
.document
.reporter
.warning
955 self
.error
= self
.document
.reporter
.error
959 self
.settings
= settings
= document
.settings
960 self
.latex_encoding
= self
.to_latex_encoding(settings
.output_encoding
)
961 self
.use_latex_toc
= settings
.use_latex_toc
962 self
.use_latex_docinfo
= settings
.use_latex_docinfo
963 self
._use
_latex
_citations
= settings
.use_latex_citations
964 self
.embed_stylesheet
= settings
.embed_stylesheet
965 self
._reference
_label
= settings
.reference_label
966 self
.hyperlink_color
= settings
.hyperlink_color
967 self
.compound_enumerators
= settings
.compound_enumerators
968 self
.font_encoding
= getattr(settings
, 'font_encoding', '')
969 self
.section_prefix_for_enumerators
= (
970 settings
.section_prefix_for_enumerators
)
971 self
.section_enumerator_separator
= (
972 settings
.section_enumerator_separator
.replace('_', r
'\_'))
974 self
.literal_block_env
= ''
975 self
.literal_block_options
= ''
976 if settings
.literal_block_env
!= '':
978 self
.literal_block_env
,
979 self
.literal_block_options
,
980 none
) = re
.split('(\w+)(.*)', settings
.literal_block_env
)
981 elif settings
.use_verbatim_when_possible
:
982 self
.literal_block_env
= 'verbatim'
984 if self
.settings
.use_bibtex
:
985 self
.bibtex
= self
.settings
.use_bibtex
.split(',',1)
986 # TODO avoid errors on not declared citations.
989 # language module for Docutils-generated text
990 # (labels, bibliographic_fields, and author_separators)
991 self
.language_module
= languages
.get_language(settings
.language_code
,
993 self
.babel
= babel_class(settings
.language_code
, document
.reporter
)
994 self
.author_separator
= self
.language_module
.author_separators
[0]
995 d_options
= [self
.settings
.documentoptions
]
996 if self
.babel
.language
not in ('english', ''):
997 d_options
.append(self
.babel
.language
)
998 self
.documentoptions
= ','.join(filter(None, d_options
))
999 self
.d_class
= DocumentClass(settings
.documentclass
,
1000 settings
.use_part_section
)
1001 # graphic package options:
1002 if self
.settings
.graphicx_option
== '':
1003 self
.graphicx_package
= r
'\usepackage{graphicx}'
1004 elif self
.settings
.graphicx_option
.lower() == 'auto':
1005 self
.graphicx_package
= PreambleCmds
.graphicx_auto
1007 self
.graphicx_package
= (r
'\usepackage[%s]{graphicx}' %
1008 self
.settings
.graphicx_option
)
1010 self
.docutils_footnotes
= settings
.docutils_footnotes
1011 if settings
.use_latex_footnotes
:
1012 self
.docutils_footnotes
= True
1013 self
.warn('`use_latex_footnotes` is deprecated. '
1014 'The setting has been renamed to `docutils_footnotes` '
1015 'and the alias will be removed in a future version.')
1016 self
.figure_footnotes
= settings
.figure_footnotes
1017 if self
.figure_footnotes
:
1018 self
.docutils_footnotes
= True
1019 self
.warn('The "figure footnotes" workaround/setting is strongly '
1020 'deprecated and will be removed in a future version.')
1022 # Output collection stacks
1023 # ~~~~~~~~~~~~~~~~~~~~~~~~
1026 self
.head_prefix
= [r
'\documentclass[%s]{%s}' %
1027 (self
.documentoptions
, self
.settings
.documentclass
)]
1028 self
.requirements
= SortableDict() # made a list in depart_document()
1029 self
.requirements
['__static'] = r
'\usepackage{ifthen}'
1030 self
.latex_preamble
= [settings
.latex_preamble
]
1031 self
.stylesheet
= []
1032 self
.fallbacks
= SortableDict() # made a list in depart_document()
1033 self
.pdfsetup
= [] # PDF properties (hyperref package)
1036 self
.titledata
= [] # \title, \author, \date
1037 ## self.body_prefix = ['\\begin{document}\n']
1038 self
.body_pre_docinfo
= [] # \maketitle
1040 self
.dedication
= []
1043 ## self.body_suffix = ['\\end{document}\n']
1045 # A heterogenous stack used in conjunction with the tree traversal.
1046 # Make sure that the pops correspond to the pushes:
1050 self
.title_labels
= []
1051 self
.subtitle_labels
= []
1052 # (if use_latex_docinfo: collects lists of
1053 # author/organization/contact/address lines)
1054 self
.author_stack
= []
1057 # PDF properties: pdftitle, pdfauthor
1058 # TODO?: pdfcreator, pdfproducer, pdfsubject, pdfkeywords
1062 # Stack of section counters so that we don't have to use_latex_toc.
1063 # This will grow and shrink as processing occurs.
1064 # Initialized for potential first-level sections.
1065 self
._section
_number
= [0]
1067 # The current stack of enumerations so that we can expand
1068 # them into a compound enumeration.
1069 self
._enumeration
_counters
= []
1070 # The maximum number of enumeration counters we've used.
1071 # If we go beyond this number, we need to create a new
1072 # counter; otherwise, just reuse an old one.
1073 self
._max
_enumeration
_counters
= 0
1077 # object for a table while proccessing.
1078 self
.table_stack
= []
1079 self
.active_table
= Table(self
, 'longtable', settings
.table_style
)
1081 # Where to collect the output of visitor methods (default: body)
1082 self
.out
= self
.body
1083 self
.out_stack
= [] # stack of output collectors
1088 # Docutils' output-encoding => TeX input encoding
1089 if self
.latex_encoding
!= 'ascii':
1090 self
.requirements
['_inputenc'] = (r
'\usepackage[%s]{inputenc}'
1091 % self
.latex_encoding
)
1093 if self
.font_encoding
:
1094 self
.requirements
['_fontenc'] = (r
'\usepackage[%s]{fontenc}' %
1096 # page layout with typearea (if there are relevant document options)
1097 if (settings
.documentclass
.find('scr') == -1 and
1098 (self
.documentoptions
.find('DIV') != -1 or
1099 self
.documentoptions
.find('BCOR') != -1)):
1100 self
.requirements
['typearea'] = r
'\usepackage{typearea}'
1103 # get list of style sheets from settings
1104 styles
= utils
.get_stylesheet_list(settings
)
1105 # adapt path if --stylesheet_path is used
1106 if settings
.stylesheet_path
and not(self
.embed_stylesheet
):
1107 styles
= [utils
.relative_path(settings
._destination
, sheet
)
1108 for sheet
in styles
]
1109 for sheet
in styles
:
1110 (base
, ext
) = os
.path
.splitext(sheet
)
1111 is_package
= ext
in ['.sty', '']
1112 if self
.embed_stylesheet
:
1114 sheet
= base
+ '.sty' # adapt package name
1115 # wrap in \makeatletter, \makeatother
1116 wrapper
= PreambleCmds
.embedded_package_wrapper
1118 wrapper
= '%% embedded stylesheet: %s\n%s'
1119 settings
.record_dependencies
.add(sheet
)
1120 self
.stylesheet
.append(wrapper
%
1121 (sheet
, io
.FileInput(source_path
=sheet
, encoding
='utf-8').read()))
1122 else: # link to style sheet
1124 self
.stylesheet
.append(r
'\usepackage{%s}' % base
)
1126 self
.stylesheet
.append(r
'\input{%s}' % sheet
)
1129 if self
.hyperlink_color
in ('0', 'false', 'False', ''):
1130 self
.hyperref_options
= ''
1132 self
.hyperref_options
= 'colorlinks=true,linkcolor=%s,urlcolor=%s' % (
1133 self
.hyperlink_color
, self
.hyperlink_color
)
1134 if settings
.hyperref_options
:
1135 self
.hyperref_options
+= ',' + settings
.hyperref_options
1138 # include all supported sections in toc and PDF bookmarks
1139 # (or use documentclass-default (as currently))?
1140 ## if self.use_latex_toc:
1141 ## self.requirements['tocdepth'] = (r'\setcounter{tocdepth}{%d}' %
1142 ## len(self.d_class.sections))
1144 # LaTeX section numbering
1145 if not self
.settings
.sectnum_xform
: # section numbering by LaTeX:
1147 # None "sectnum" directive without depth arg -> LaTeX default
1148 # 0 no "sectnum" directive -> no section numbers
1149 # else value of the "depth" argument: translate to LaTeX level
1150 # -1 part (0 with "article" document class)
1151 # 0 chapter (missing in "article" document class)
1157 if settings
.sectnum_depth
is not None:
1158 # limit to supported levels
1159 sectnum_depth
= min(settings
.sectnum_depth
,
1160 len(self
.d_class
.sections
))
1161 # adjust to document class and use_part_section settings
1162 if 'chapter' in self
.d_class
.sections
:
1164 if self
.d_class
.sections
[0] == 'part':
1166 self
.requirements
['sectnum_depth'] = (
1167 r
'\setcounter{secnumdepth}{%d}' % sectnum_depth
)
1168 # start with specified number:
1169 if (hasattr(settings
, 'sectnum_start') and
1170 settings
.sectnum_start
!= 1):
1171 self
.requirements
['sectnum_start'] = (
1172 r
'\setcounter{%s}{%d}' % (self
.d_class
.sections
[0],
1173 settings
.sectnum_start
-1))
1174 # currently ignored (configure in a stylesheet):
1175 ## settings.sectnum_prefix
1176 ## settings.sectnum_suffix
1182 def to_latex_encoding(self
,docutils_encoding
):
1183 """Translate docutils encoding name into LaTeX's.
1185 Default method is remove "-" and "_" chars from docutils_encoding.
1187 tr
= { 'iso-8859-1': 'latin1', # west european
1188 'iso-8859-2': 'latin2', # east european
1189 'iso-8859-3': 'latin3', # esperanto, maltese
1190 'iso-8859-4': 'latin4', # north european, scandinavian, baltic
1191 'iso-8859-5': 'iso88595', # cyrillic (ISO)
1192 'iso-8859-9': 'latin5', # turkish
1193 'iso-8859-15': 'latin9', # latin9, update to latin1.
1194 'mac_cyrillic': 'maccyr', # cyrillic (on Mac)
1195 'windows-1251': 'cp1251', # cyrillic (on Windows)
1196 'koi8-r': 'koi8-r', # cyrillic (Russian)
1197 'koi8-u': 'koi8-u', # cyrillic (Ukrainian)
1198 'windows-1250': 'cp1250', #
1199 'windows-1252': 'cp1252', #
1200 'us-ascii': 'ascii', # ASCII (US)
1201 # unmatched encodings
1203 #'': 'ansinew', # windows 3.1 ansi
1204 #'': 'ascii', # ASCII encoding for the range 32--127.
1205 #'': 'cp437', # dos latin us
1206 #'': 'cp850', # dos latin 1
1207 #'': 'cp852', # dos latin 2
1210 #'iso-8859-6': '' # arabic
1211 #'iso-8859-7': '' # greek
1212 #'iso-8859-8': '' # hebrew
1213 #'iso-8859-10': '' # latin6, more complete iso-8859-4
1215 encoding
= docutils_encoding
.lower()
1218 # convert: latin-1, latin_1, utf-8 and similar things
1219 encoding
= encoding
.replace('_', '').replace('-', '')
1220 # strip the error handler
1221 return encoding
.split(':')[0]
1223 def language_label(self
, docutil_label
):
1224 return self
.language_module
.labels
[docutil_label
]
1226 def ensure_math(self
, text
):
1227 if not hasattr(self
, 'ensure_math_re'):
1228 chars
= { # lnot,pm,twosuperior,threesuperior,mu,onesuperior,times,div
1229 'latin1' : '\xac\xb1\xb2\xb3\xb5\xb9\xd7\xf7' , # ¬±²³µ¹×÷
1230 # TODO?: use texcomp instead.
1232 self
.ensure_math_re
= re
.compile('([%s])' % chars
['latin1'])
1233 text
= self
.ensure_math_re
.sub(r
'\\ensuremath{\1}', text
)
1236 def encode(self
, text
):
1237 """Return text with 'problematic' characters escaped.
1239 Escape the ten special printing characters ``# $ % & ~ _ ^ \ { }``,
1240 square brackets ``[ ]``, double quotes and (in OT1) ``< | >``.
1242 Separate ``-`` (and more in literal text) to prevent input ligatures.
1244 Translate non-supported Unicode characters.
1248 # Separate compound characters, e.g. '--' to '-{}-'.
1249 separate_chars
= '-'
1250 # In monospace-font, we also separate ',,', '``' and "''" and some
1251 # other characters which can't occur in non-literal text.
1253 separate_chars
+= ',`\'"<>'
1254 # LaTeX encoding maps:
1260 ord('~'): ur
'\textasciitilde{}',
1262 ord('^'): ur
'\textasciicircum{}',
1263 ord('\\'): ur
'\textbackslash{}',
1266 # Square brackets are ordinary chars and cannot be escaped with '\',
1267 # so we put them in a group '{[}'. (Alternative: ensure that all
1268 # macros with optional arguments are terminated with {} and text
1269 # inside any optional argument is put in a group ``[{text}]``).
1270 # Commands with optional args inside an optional arg must be put
1271 # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
1275 # Unicode chars that are not recognized by LaTeX's utf8 encoding
1276 unsupported_unicode_chars
= {
1277 0x00A0: ur
'~', # NO-BREAK SPACE
1278 0x00AD: ur
'\-', # SOFT HYPHEN
1280 0x2011: ur
'\hbox{-}', # NON-BREAKING HYPHEN
1281 0x21d4: ur
'$\Leftrightarrow$',
1282 # Docutils footnote symbols:
1283 0x2660: ur
'$\spadesuit$',
1284 0x2663: ur
'$\clubsuit$',
1286 # Unicode chars that are recognized by LaTeX's utf8 encoding
1288 0x200C: ur
'\textcompwordmark', # ZERO WIDTH NON-JOINER
1289 0x2013: ur
'\textendash{}',
1290 0x2014: ur
'\textemdash{}',
1291 0x2018: ur
'\textquoteleft{}',
1292 0x2019: ur
'\textquoteright{}',
1293 0x201A: ur
'\quotesinglbase{}', # SINGLE LOW-9 QUOTATION MARK
1294 0x201C: ur
'\textquotedblleft{}',
1295 0x201D: ur
'\textquotedblright{}',
1296 0x201E: ur
'\quotedblbase{}', # DOUBLE LOW-9 QUOTATION MARK
1297 0x2030: ur
'\textperthousand{}', # PER MILLE SIGN
1298 0x2031: ur
'\textpertenthousand{}', # PER TEN THOUSAND SIGN
1299 0x2039: ur
'\guilsinglleft{}',
1300 0x203A: ur
'\guilsinglright{}',
1301 0x2423: ur
'\textvisiblespace{}', # OPEN BOX
1303 0x2021: ur
'\ddag{}',
1304 0x2026: ur
'\dots{}',
1305 0x2122: ur
'\texttrademark{}',
1307 # Unicode chars that require a feature/package to render
1309 0x2665: ur
'\ding{170}', # black heartsuit
1310 0x2666: ur
'\ding{169}', # black diamondsuit
1312 # recognized with 'utf8', if textcomp is loaded
1314 # Latin-1 Supplement
1315 0x00a2: ur
'\textcent{}', # ¢ CENT SIGN
1316 0x00a4: ur
'\textcurrency{}', # ¤ CURRENCY SYMBOL
1317 0x00a5: ur
'\textyen{}', # ¥ YEN SIGN
1318 0x00a6: ur
'\textbrokenbar{}', # ¦ BROKEN BAR
1319 0x00a7: ur
'\textsection{}', # § SECTION SIGN
1320 0x00a8: ur
'\textasciidieresis{}', # ¨ DIAERESIS
1321 0x00a9: ur
'\textcopyright{}', # © COPYRIGHT SIGN
1322 0x00aa: ur
'\textordfeminine{}', # ª FEMININE ORDINAL INDICATOR
1323 0x00ac: ur
'\textlnot{}', # ¬ NOT SIGN
1324 0x00ae: ur
'\textregistered{}', # ® REGISTERED SIGN
1325 0x00af: ur
'\textasciimacron{}', # ¯ MACRON
1326 0x00b0: ur
'\textdegree{}', # ° DEGREE SIGN
1327 0x00b1: ur
'\textpm{}', # ± PLUS-MINUS SIGN
1328 0x00b2: ur
'\texttwosuperior{}', # ² SUPERSCRIPT TWO
1329 0x00b3: ur
'\textthreesuperior{}', # ³ SUPERSCRIPT THREE
1330 0x00b4: ur
'\textasciiacute{}', # ´ ACUTE ACCENT
1331 0x00b5: ur
'\textmu{}', # µ MICRO SIGN
1332 0x00b6: ur
'\textparagraph{}', # ¶ PILCROW SIGN # not equal to \textpilcrow
1333 0x00b9: ur
'\textonesuperior{}', # ¹ SUPERSCRIPT ONE
1334 0x00ba: ur
'\textordmasculine{}', # º MASCULINE ORDINAL INDICATOR
1335 0x00bc: ur
'\textonequarter{}', # 1/4 FRACTION
1336 0x00bd: ur
'\textonehalf{}', # 1/2 FRACTION
1337 0x00be: ur
'\textthreequarters{}', # 3/4 FRACTION
1338 0x00d7: ur
'\texttimes{}', # × MULTIPLICATION SIGN
1339 0x00f7: ur
'\textdiv{}', # ÷ DIVISION SIGN
1341 0x0192: ur
'\textflorin{}', # LATIN SMALL LETTER F WITH HOOK
1342 0x02b9: ur
'\textasciiacute{}', # MODIFIER LETTER PRIME
1343 0x02ba: ur
'\textacutedbl{}', # MODIFIER LETTER DOUBLE PRIME
1344 0x2016: ur
'\textbardbl{}', # DOUBLE VERTICAL LINE
1345 0x2022: ur
'\textbullet{}', # BULLET
1346 0x2032: ur
'\textasciiacute{}', # PRIME
1347 0x2033: ur
'\textacutedbl{}', # DOUBLE PRIME
1348 0x2035: ur
'\textasciigrave{}', # REVERSED PRIME
1349 0x2036: ur
'\textgravedbl{}', # REVERSED DOUBLE PRIME
1350 0x203b: ur
'\textreferencemark{}', # REFERENCE MARK
1351 0x203d: ur
'\textinterrobang{}', # INTERROBANG
1352 0x2044: ur
'\textfractionsolidus{}', # FRACTION SLASH
1353 0x2045: ur
'\textlquill{}', # LEFT SQUARE BRACKET WITH QUILL
1354 0x2046: ur
'\textrquill{}', # RIGHT SQUARE BRACKET WITH QUILL
1355 0x2052: ur
'\textdiscount{}', # COMMERCIAL MINUS SIGN
1356 0x20a1: ur
'\textcolonmonetary{}', # COLON SIGN
1357 0x20a3: ur
'\textfrenchfranc{}', # FRENCH FRANC SIGN
1358 0x20a4: ur
'\textlira{}', # LIRA SIGN
1359 0x20a6: ur
'\textnaira{}', # NAIRA SIGN
1360 0x20a9: ur
'\textwon{}', # WON SIGN
1361 0x20ab: ur
'\textdong{}', # DONG SIGN
1362 0x20ac: ur
'\texteuro{}', # EURO SIGN
1363 0x20b1: ur
'\textpeso{}', # PESO SIGN
1364 0x20b2: ur
'\textguarani{}', # GUARANI SIGN
1365 0x2103: ur
'\textcelsius{}', # DEGREE CELSIUS
1366 0x2116: ur
'\textnumero{}', # NUMERO SIGN
1367 0x2117: ur
'\textcircledP{}', # SOUND RECORDING COYRIGHT
1368 0x211e: ur
'\textrecipe{}', # PRESCRIPTION TAKE
1369 0x2120: ur
'\textservicemark{}', # SERVICE MARK
1370 0x2122: ur
'\texttrademark{}', # TRADE MARK SIGN
1371 0x2126: ur
'\textohm{}', # OHM SIGN
1372 0x2127: ur
'\textmho{}', # INVERTED OHM SIGN
1373 0x212e: ur
'\textestimated{}', # ESTIMATED SYMBOL
1374 0x2190: ur
'\textleftarrow{}', # LEFTWARDS ARROW
1375 0x2191: ur
'\textuparrow{}', # UPWARDS ARROW
1376 0x2192: ur
'\textrightarrow{}', # RIGHTWARDS ARROW
1377 0x2193: ur
'\textdownarrow{}', # DOWNWARDS ARROW
1378 0x2212: ur
'\textminus{}', # MINUS SIGN
1379 0x2217: ur
'\textasteriskcentered{}', # ASTERISK OPERATOR
1380 0x221a: ur
'\textsurd{}', # SQUARE ROOT
1381 0x2422: ur
'\textblank{}', # BLANK SYMBOL
1382 0x25e6: ur
'\textopenbullet{}', # WHITE BULLET
1383 0x25ef: ur
'\textbigcircle{}', # LARGE CIRCLE
1384 0x266a: ur
'\textmusicalnote{}', # EIGHTH NOTE
1385 0x26ad: ur
'\textmarried{}', # MARRIAGE SYMBOL
1386 0x26ae: ur
'\textdivorced{}', # DIVORCE SYMBOL
1387 0x27e8: ur
'\textlangle{}', # MATHEMATICAL LEFT ANGLE BRACKET
1388 0x27e9: ur
'\textrangle{}', # MATHEMATICAL RIGHT ANGLE BRACKET
1390 # TODO: greek alphabet ... ?
1391 # see also LaTeX codec
1392 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252124
1393 # and unimap.py from TeXML
1395 # set up the translation table:
1396 table
= special_chars
1397 # keep the underscore in citation references
1398 if self
.inside_citation_reference_label
:
1399 del(table
[ord('_')])
1400 # Workarounds for OT1 font-encoding
1401 if self
.font_encoding
in ['OT1', '']:
1402 # * out-of-order characters in cmtt
1404 # replace underscore by underlined blank,
1405 # because this has correct width.
1406 table
[ord('_')] = u
'\\underline{~}'
1407 # the backslash doesn't work, so we use a mirrored slash.
1408 # \reflectbox is provided by graphicx:
1409 self
.requirements
['graphicx'] = self
.graphicx_package
1410 table
[ord('\\')] = ur
'\reflectbox{/}'
1411 # * ``< | >`` come out as different chars (except for cmtt):
1413 table
[ord('|')] = ur
'\textbar{}'
1414 table
[ord('<')] = ur
'\textless{}'
1415 table
[ord('>')] = ur
'\textgreater{}'
1416 if self
.insert_non_breaking_blanks
:
1417 table
[ord(' ')] = ur
'~'
1419 # double quotes are 'active' in some languages
1420 table
[ord('"')] = self
.babel
.literal_double_quote
1422 table
.update(unsupported_unicode_chars
)
1423 table
.update(pifont_chars
)
1424 if not self
.latex_encoding
.startswith('utf8'):
1425 table
.update(unicode_chars
)
1426 table
.update(textcomp_chars
)
1427 # Characters that require a feature/package to render
1429 if ord(ch
) in pifont_chars
:
1430 self
.requirements
['pifont'] = '\\usepackage{pifont}'
1431 if ord(ch
) in textcomp_chars
:
1432 self
.requirements
['textcomp'] = PreambleCmds
.textcomp
1434 text
= text
.translate(table
)
1436 # Break up input ligatures
1437 for char
in separate_chars
* 2:
1438 # Do it twice ("* 2") because otherwise we would replace
1440 text
= text
.replace(char
+ char
, char
+ '{}' + char
)
1441 # Literal line breaks (in address or literal blocks):
1442 if self
.insert_newline
:
1443 lines
= text
.split('\n')
1444 # for blank lines, insert a protected space, to avoid
1445 # ! LaTeX Error: There's no line here to end.
1446 lines
= [line
+ '~'*(not line
.lstrip())
1447 for line
in lines
[:-1]] + lines
[-1:]
1448 text
= '\\\\\n'.join(lines
)
1449 if not self
.literal
:
1450 text
= self
.babel
.quote_quotes(text
)
1451 if self
.literal
and not self
.insert_non_breaking_blanks
:
1452 # preserve runs of spaces but allow wrapping
1453 text
= text
.replace(' ', ' ~')
1454 if not self
.latex_encoding
.startswith('utf8'):
1455 text
= self
.ensure_math(text
)
1458 def attval(self
, text
,
1459 whitespace
=re
.compile('[\n\r\t\v\f]')):
1460 """Cleanse, encode, and return attribute value text."""
1461 return self
.encode(whitespace
.sub(' ', text
))
1463 # TODO: is this used anywhere? -> update (use template) or delete
1464 ## def astext(self):
1465 ## """Assemble document parts and return as string."""
1466 ## head = '\n'.join(self.head_prefix + self.stylesheet + self.head)
1467 ## body = ''.join(self.body_prefix + self.body + self.body_suffix)
1468 ## return head + '\n' + body
1470 def is_inline(self
, node
):
1471 """Check whether a node represents an inline element"""
1472 return isinstance(node
.parent
, nodes
.TextElement
)
1474 def append_hypertargets(self
, node
):
1475 """Append hypertargets for all ids of `node`"""
1476 # hypertarget places the anchor at the target's baseline,
1477 # so we raise it explicitely
1478 self
.out
.append('%\n'.join(['\\raisebox{1em}{\\hypertarget{%s}{}}' %
1479 id for id in node
['ids']]))
1481 def ids_to_labels(self
, node
, set_anchor
=True):
1482 """Return list of label definitions for all ids of `node`
1484 If `set_anchor` is True, an anchor is set with \phantomsection.
1486 labels
= ['\\label{%s}' % id for id in node
.get('ids', [])]
1487 if set_anchor
and labels
:
1488 labels
.insert(0, '\\phantomsection')
1491 def push_output_collector(self
, new_out
):
1492 self
.out_stack
.append(self
.out
)
1495 def pop_output_collector(self
):
1496 self
.out
= self
.out_stack
.pop()
1501 def visit_Text(self
, node
):
1502 self
.out
.append(self
.encode(node
.astext()))
1504 def depart_Text(self
, node
):
1507 def visit_address(self
, node
):
1508 self
.visit_docinfo_item(node
, 'address')
1510 def depart_address(self
, node
):
1511 self
.depart_docinfo_item(node
)
1513 def visit_admonition(self
, node
):
1514 self
.fallbacks
['admonition'] = PreambleCmds
.admonition
1515 if 'error' in node
['classes']:
1516 self
.fallbacks
['error'] = PreambleCmds
.error
1517 # strip the generic 'admonition' from the list of classes
1518 node
['classes'] = [cls
for cls
in node
['classes']
1519 if cls
!= 'admonition']
1520 self
.out
.append('\n\\DUadmonition[%s]{\n' % ','.join(node
['classes']))
1522 def depart_admonition(self
, node
=None):
1523 self
.out
.append('}\n')
1525 def visit_author(self
, node
):
1526 self
.visit_docinfo_item(node
, 'author')
1528 def depart_author(self
, node
):
1529 self
.depart_docinfo_item(node
)
1531 def visit_authors(self
, node
):
1532 # not used: visit_author is called anyway for each author.
1535 def depart_authors(self
, node
):
1538 def visit_block_quote(self
, node
):
1539 self
.out
.append( '%\n\\begin{quote}\n')
1541 self
.visit_inline(node
)
1543 def depart_block_quote(self
, node
):
1545 self
.depart_inline(node
)
1546 self
.out
.append( '\n\\end{quote}\n')
1548 def visit_bullet_list(self
, node
):
1549 if self
.is_toc_list
:
1550 self
.out
.append( '%\n\\begin{list}{}{}\n' )
1552 self
.out
.append( '%\n\\begin{itemize}\n' )
1554 def depart_bullet_list(self
, node
):
1555 if self
.is_toc_list
:
1556 self
.out
.append( '\n\\end{list}\n' )
1558 self
.out
.append( '\n\\end{itemize}\n' )
1560 def visit_superscript(self
, node
):
1561 self
.out
.append(r
'\textsuperscript{')
1563 self
.visit_inline(node
)
1565 def depart_superscript(self
, node
):
1567 self
.depart_inline(node
)
1568 self
.out
.append('}')
1570 def visit_subscript(self
, node
):
1571 self
.out
.append(r
'\textsubscript{') # requires `fixltx2e`
1573 self
.visit_inline(node
)
1575 def depart_subscript(self
, node
):
1577 self
.depart_inline(node
)
1578 self
.out
.append('}')
1580 def visit_caption(self
, node
):
1581 self
.out
.append( '\\caption{' )
1583 def depart_caption(self
, node
):
1584 self
.out
.append('}\n')
1586 def visit_title_reference(self
, node
):
1587 self
.fallbacks
['titlereference'] = PreambleCmds
.titlereference
1588 self
.out
.append(r
'\DUroletitlereference{')
1590 self
.visit_inline(node
)
1592 def depart_title_reference(self
, node
):
1594 self
.depart_inline(node
)
1595 self
.out
.append( '}' )
1597 def visit_citation(self
, node
):
1598 # TODO maybe use cite bibitems
1599 if self
._use
_latex
_citations
:
1600 self
.push_output_collector([])
1602 # TODO: do we need these?
1603 ## self.requirements['~fnt_floats'] = PreambleCmds.footnote_floats
1604 self
.out
.append(r
'\begin{figure}[b]')
1605 self
.append_hypertargets(node
)
1607 def depart_citation(self
, node
):
1608 if self
._use
_latex
_citations
:
1610 text
= ''.join(self
.out
[1:])
1611 self
._bibitems
.append([label
, text
])
1612 self
.pop_output_collector()
1614 self
.out
.append('\\end{figure}\n')
1616 def visit_citation_reference(self
, node
):
1617 if self
._use
_latex
_citations
:
1618 if not self
.inside_citation_reference_label
:
1619 self
.out
.append(r
'\cite{')
1620 self
.inside_citation_reference_label
= 1
1622 assert self
.body
[-1] in (' ', '\n'),\
1623 'unexpected non-whitespace while in reference label'
1628 href
= node
['refid']
1629 elif 'refname' in node
:
1630 href
= self
.document
.nameids
[node
['refname']]
1631 self
.out
.append('[\\hyperlink{%s}{' % href
)
1633 def depart_citation_reference(self
, node
):
1634 if self
._use
_latex
_citations
:
1635 followup_citation
= False
1636 # check for a following citation separated by a space or newline
1637 next_siblings
= node
.traverse(descend
=0, siblings
=1,
1639 if len(next_siblings
) > 1:
1640 next
= next_siblings
[0]
1641 if (isinstance(next
, nodes
.Text
) and
1642 next
.astext() in (' ', '\n')):
1643 if next_siblings
[1].__class
__ == node
.__class
__:
1644 followup_citation
= True
1645 if followup_citation
:
1646 self
.out
.append(',')
1648 self
.out
.append('}')
1649 self
.inside_citation_reference_label
= False
1651 self
.out
.append('}]')
1653 def visit_classifier(self
, node
):
1654 self
.out
.append( '(\\textbf{' )
1656 def depart_classifier(self
, node
):
1657 self
.out
.append( '})\n' )
1659 def visit_colspec(self
, node
):
1660 self
.active_table
.visit_colspec(node
)
1662 def depart_colspec(self
, node
):
1665 def visit_comment(self
, node
):
1666 # Precede every line with a comment sign, wrap in newlines
1667 self
.out
.append('\n%% %s\n' % node
.astext().replace('\n', '\n% '))
1668 raise nodes
.SkipNode
1670 def depart_comment(self
, node
):
1673 def visit_compound(self
, node
):
1676 def depart_compound(self
, node
):
1679 def visit_contact(self
, node
):
1680 self
.visit_docinfo_item(node
, 'contact')
1682 def depart_contact(self
, node
):
1683 self
.depart_docinfo_item(node
)
1685 def visit_container(self
, node
):
1688 def depart_container(self
, node
):
1691 def visit_copyright(self
, node
):
1692 self
.visit_docinfo_item(node
, 'copyright')
1694 def depart_copyright(self
, node
):
1695 self
.depart_docinfo_item(node
)
1697 def visit_date(self
, node
):
1698 self
.visit_docinfo_item(node
, 'date')
1700 def depart_date(self
, node
):
1701 self
.depart_docinfo_item(node
)
1703 def visit_decoration(self
, node
):
1707 def depart_decoration(self
, node
):
1710 def visit_definition(self
, node
):
1713 def depart_definition(self
, node
):
1714 self
.out
.append('\n')
1716 def visit_definition_list(self
, node
):
1717 self
.out
.append( '%\n\\begin{description}\n' )
1719 def depart_definition_list(self
, node
):
1720 self
.out
.append( '\\end{description}\n' )
1722 def visit_definition_list_item(self
, node
):
1725 def depart_definition_list_item(self
, node
):
1728 def visit_description(self
, node
):
1729 self
.out
.append(' ')
1731 def depart_description(self
, node
):
1734 def visit_docinfo(self
, node
):
1735 self
.push_output_collector(self
.docinfo
)
1737 def depart_docinfo(self
, node
):
1738 self
.pop_output_collector()
1739 # Some itmes (e.g. author) end up at other places
1741 # tabularx: automatic width of columns, no page breaks allowed.
1742 self
.requirements
['tabularx'] = r
'\usepackage{tabularx}'
1743 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
1744 self
.fallbacks
['docinfo'] = PreambleCmds
.docinfo
1746 self
.docinfo
.insert(0, '\n% Docinfo\n'
1748 '\\begin{tabularx}{\\DUdocinfowidth}{lX}\n')
1749 self
.docinfo
.append('\\end{tabularx}\n'
1752 def visit_docinfo_item(self
, node
, name
):
1753 if name
== 'author':
1754 self
.pdfauthor
.append(self
.attval(node
.astext()))
1755 if self
.use_latex_docinfo
:
1756 if name
in ('author', 'organization', 'contact', 'address'):
1757 # We attach these to the last author. If any of them precedes
1758 # the first author, put them in a separate "author" group
1759 # (in lack of better semantics).
1760 if name
== 'author' or not self
.author_stack
:
1761 self
.author_stack
.append([])
1762 if name
== 'address': # newlines are meaningful
1763 self
.insert_newline
= True
1764 text
= self
.encode(node
.astext())
1765 self
.insert_newline
= False
1767 text
= self
.attval(node
.astext())
1768 self
.author_stack
[-1].append(text
)
1769 raise nodes
.SkipNode
1770 elif name
== 'date':
1771 self
.date
.append(self
.attval(node
.astext()))
1772 raise nodes
.SkipNode
1773 self
.out
.append('\\textbf{%s}: &\n\t' % self
.language_label(name
))
1774 if name
== 'address':
1775 self
.insert_newline
= 1
1776 self
.out
.append('{\\raggedright\n')
1777 self
.context
.append(' } \\\\\n')
1779 self
.context
.append(' \\\\\n')
1781 def depart_docinfo_item(self
, node
):
1782 self
.out
.append(self
.context
.pop())
1783 # for address we did set insert_newline
1784 self
.insert_newline
= False
1786 def visit_doctest_block(self
, node
):
1787 self
.visit_literal_block(node
)
1789 def depart_doctest_block(self
, node
):
1790 self
.depart_literal_block(node
)
1792 def visit_document(self
, node
):
1794 if (self
.use_latex_docinfo
or len(node
) and
1795 isinstance(node
[0], nodes
.title
)):
1796 self
.title_labels
+= self
.ids_to_labels(node
, set_anchor
=False)
1798 def depart_document(self
, node
):
1799 # Complete header with information gained from walkabout
1801 if (self
.babel
.otherlanguages
or
1802 self
.babel
.language
not in ('', 'english')):
1803 self
.requirements
['babel'] = self
.babel()
1804 # * conditional requirements (before style sheet)
1805 self
.requirements
= self
.requirements
.sortedvalues()
1806 # * coditional fallback definitions (after style sheet)
1807 self
.fallbacks
= self
.fallbacks
.sortedvalues()
1809 self
.pdfsetup
.append(PreambleCmds
.linking
% self
.hyperref_options
)
1811 authors
= self
.author_separator
.join(self
.pdfauthor
)
1812 self
.pdfinfo
.append(' pdfauthor={%s}' % authors
)
1814 self
.pdfsetup
+= [r
'\hypersetup{'] + self
.pdfinfo
+ ['}']
1816 # * document title (with "use_latex_docinfo" also
1817 # 'author', 'organization', 'contact', 'address' and 'date')
1819 self
.use_latex_docinfo
and (self
.author_stack
or self
.date
)):
1820 # with the default template, titledata is written to the preamble
1821 self
.titledata
.append('%%% Title Data')
1822 # \title (empty \title prevents error with \maketitle)
1824 self
.title
.insert(0, '\phantomsection%\n ')
1825 title
= [''.join(self
.title
)] + self
.title_labels
1827 title
+= [r
'\\ % subtitle',
1828 r
'\large{%s}' % ''.join(self
.subtitle
)
1829 ] + self
.subtitle_labels
1830 self
.titledata
.append(r
'\title{%s}' % '%\n '.join(title
))
1831 # \author (empty \author prevents warning with \maketitle)
1832 authors
= ['\\\\\n'.join(author_entry
)
1833 for author_entry
in self
.author_stack
]
1834 self
.titledata
.append(r
'\author{%s}' %
1835 ' \\and\n'.join(authors
))
1836 # \date (empty \date prevents defaulting to \today)
1837 self
.titledata
.append(r
'\date{%s}' % ', '.join(self
.date
))
1838 # \maketitle in the body formats title with LaTeX
1839 self
.body_pre_docinfo
.append('\\maketitle\n')
1842 # TODO insertion point of bibliography should be configurable.
1843 if self
._use
_latex
_citations
and len(self
._bibitems
)>0:
1846 for bi
in self
._bibitems
:
1847 if len(widest_label
)<len(bi
[0]):
1848 widest_label
= bi
[0]
1849 self
.out
.append('\n\\begin{thebibliography}{%s}\n' %
1851 for bi
in self
._bibitems
:
1852 # cite_key: underscores must not be escaped
1853 cite_key
= bi
[0].replace(r
'\_','_')
1854 self
.out
.append('\\bibitem[%s]{%s}{%s}\n' %
1855 (bi
[0], cite_key
, bi
[1]))
1856 self
.out
.append('\\end{thebibliography}\n')
1858 self
.out
.append('\n\\bibliographystyle{%s}\n' %
1860 self
.out
.append('\\bibliography{%s}\n' % self
.bibtex
[1])
1861 # * make sure to generate a toc file if needed for local contents:
1862 if 'minitoc' in self
.requirements
and not self
.has_latex_toc
:
1863 self
.out
.append('\n\\faketableofcontents % for local ToCs\n')
1865 def visit_emphasis(self
, node
):
1866 self
.out
.append('\\emph{')
1868 self
.visit_inline(node
)
1870 def depart_emphasis(self
, node
):
1872 self
.depart_inline(node
)
1873 self
.out
.append('}')
1875 def visit_entry(self
, node
):
1876 self
.active_table
.visit_entry()
1878 # BUG: the following fails, with more than one multirow
1879 # starting in the second column (or later) see
1880 # ../../../test/functional/input/data/latex.txt
1881 if self
.active_table
.get_entry_number() == 1:
1882 # if the first row is a multirow, this actually is the second row.
1883 # this gets hairy if rowspans follow each other.
1884 if self
.active_table
.get_rowspan(0):
1886 while self
.active_table
.get_rowspan(count
):
1888 self
.out
.append(' & ')
1889 self
.active_table
.visit_entry() # increment cell count
1891 self
.out
.append(' & ')
1892 # multirow, multicolumn
1893 # IN WORK BUG TODO HACK continues here
1894 # multirow in LaTeX simply will enlarge the cell over several rows
1895 # (the following n if n is positive, the former if negative).
1896 if 'morerows' in node
and 'morecols' in node
:
1897 raise NotImplementedError('Cells that '
1898 'span multiple rows *and* columns are not supported, sorry.')
1899 if 'morerows' in node
:
1900 self
.requirements
['multirow'] = r
'\usepackage{multirow}'
1901 count
= node
['morerows'] + 1
1902 self
.active_table
.set_rowspan(
1903 self
.active_table
.get_entry_number()-1,count
)
1904 self
.out
.append('\\multirow{%d}{%s}{%%' %
1905 (count
,self
.active_table
.get_column_width()))
1906 self
.context
.append('}')
1907 elif 'morecols' in node
:
1908 # the vertical bar before column is missing if it is the first
1909 # column. the one after always.
1910 if self
.active_table
.get_entry_number() == 1:
1911 bar1
= self
.active_table
.get_vertical_bar()
1914 count
= node
['morecols'] + 1
1915 self
.out
.append('\\multicolumn{%d}{%sl%s}{' %
1916 (count
, bar1
, self
.active_table
.get_vertical_bar()))
1917 self
.context
.append('}')
1919 self
.context
.append('')
1921 # header / not header
1922 if isinstance(node
.parent
.parent
, nodes
.thead
):
1923 self
.out
.append('\\textbf{%')
1924 self
.context
.append('}')
1925 elif self
.active_table
.is_stub_column():
1926 self
.out
.append('\\textbf{')
1927 self
.context
.append('}')
1929 self
.context
.append('')
1931 def depart_entry(self
, node
):
1932 self
.out
.append(self
.context
.pop()) # header / not header
1933 self
.out
.append(self
.context
.pop()) # multirow/column
1934 # if following row is spanned from above.
1935 if self
.active_table
.get_rowspan(self
.active_table
.get_entry_number()):
1936 self
.out
.append(' & ')
1937 self
.active_table
.visit_entry() # increment cell count
1939 def visit_row(self
, node
):
1940 self
.active_table
.visit_row()
1942 def depart_row(self
, node
):
1943 self
.out
.extend(self
.active_table
.depart_row())
1945 def visit_enumerated_list(self
, node
):
1946 # We create our own enumeration list environment.
1947 # This allows to set the style and starting value
1948 # and unlimited nesting.
1949 enum_style
= {'arabic':'arabic',
1950 'loweralpha':'alph',
1951 'upperalpha':'Alph',
1952 'lowerroman':'roman',
1953 'upperroman':'Roman' }
1955 if 'suffix' in node
:
1956 enum_suffix
= node
['suffix']
1958 if 'prefix' in node
:
1959 enum_prefix
= node
['prefix']
1960 if self
.compound_enumerators
:
1962 if self
.section_prefix_for_enumerators
and self
.section_level
:
1963 for i
in range(self
.section_level
):
1964 pref
+= '%d.' % self
._section
_number
[i
]
1965 pref
= pref
[:-1] + self
.section_enumerator_separator
1967 for ctype
, cname
in self
._enumeration
_counters
:
1968 enum_prefix
+= '\\%s{%s}.' % (ctype
, cname
)
1969 enum_type
= 'arabic'
1970 if 'enumtype' in node
:
1971 enum_type
= node
['enumtype']
1972 if enum_type
in enum_style
:
1973 enum_type
= enum_style
[enum_type
]
1975 counter_name
= 'listcnt%d' % len(self
._enumeration
_counters
)
1976 self
._enumeration
_counters
.append((enum_type
, counter_name
))
1977 # If we haven't used this counter name before, then create a
1978 # new counter; otherwise, reset & reuse the old counter.
1979 if len(self
._enumeration
_counters
) > self
._max
_enumeration
_counters
:
1980 self
._max
_enumeration
_counters
= len(self
._enumeration
_counters
)
1981 self
.out
.append('\\newcounter{%s}\n' % counter_name
)
1983 self
.out
.append('\\setcounter{%s}{0}\n' % counter_name
)
1985 self
.out
.append('\\begin{list}{%s\\%s{%s}%s}\n' %
1986 (enum_prefix
,enum_type
,counter_name
,enum_suffix
))
1987 self
.out
.append('{\n')
1988 self
.out
.append('\\usecounter{%s}\n' % counter_name
)
1989 # set start after usecounter, because it initializes to zero.
1991 self
.out
.append('\\addtocounter{%s}{%d}\n' %
1992 (counter_name
,node
['start']-1))
1993 ## set rightmargin equal to leftmargin
1994 self
.out
.append('\\setlength{\\rightmargin}{\\leftmargin}\n')
1995 self
.out
.append('}\n')
1997 def depart_enumerated_list(self
, node
):
1998 self
.out
.append('\\end{list}\n')
1999 self
._enumeration
_counters
.pop()
2001 def visit_field(self
, node
):
2002 # real output is done in siblings: _argument, _body, _name
2005 def depart_field(self
, node
):
2006 self
.out
.append('\n')
2007 ##self.out.append('%[depart_field]\n')
2009 def visit_field_argument(self
, node
):
2010 self
.out
.append('%[visit_field_argument]\n')
2012 def depart_field_argument(self
, node
):
2013 self
.out
.append('%[depart_field_argument]\n')
2015 def visit_field_body(self
, node
):
2018 def depart_field_body(self
, node
):
2019 if self
.out
is self
.docinfo
:
2020 self
.out
.append(r
'\\')
2022 def visit_field_list(self
, node
):
2023 if self
.out
is not self
.docinfo
:
2024 self
.fallbacks
['fieldlist'] = PreambleCmds
.fieldlist
2025 self
.out
.append('%\n\\begin{DUfieldlist}\n')
2027 def depart_field_list(self
, node
):
2028 if self
.out
is not self
.docinfo
:
2029 self
.out
.append('\\end{DUfieldlist}\n')
2031 def visit_field_name(self
, node
):
2032 if self
.out
is self
.docinfo
:
2033 self
.out
.append('\\textbf{')
2035 # Commands with optional args inside an optional arg must be put
2036 # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
2037 self
.out
.append('\\item[{')
2039 def depart_field_name(self
, node
):
2040 if self
.out
is self
.docinfo
:
2041 self
.out
.append('}: &')
2043 self
.out
.append(':}]')
2045 def visit_figure(self
, node
):
2046 self
.requirements
['float_settings'] = PreambleCmds
.float_settings
2047 # ! the 'align' attribute should set "outer alignment" !
2048 # For "inner alignment" use LaTeX default alignment (similar to HTML)
2049 ## if ('align' not in node.attributes or
2050 ## node.attributes['align'] == 'center'):
2051 ## align = '\n\\centering'
2054 ## # TODO non vertical space for other alignments.
2055 ## align = '\\begin{flush%s}' % node.attributes['align']
2056 ## align_end = '\\end{flush%s}' % node.attributes['align']
2057 ## self.out.append( '\\begin{figure}%s\n' % align )
2058 ## self.context.append( '%s\\end{figure}\n' % align_end )
2059 self
.out
.append('\\begin{figure}')
2061 self
.out
+= ['\n'] + self
.ids_to_labels(node
)
2063 def depart_figure(self
, node
):
2064 self
.out
.append('\\end{figure}\n')
2066 def visit_footer(self
, node
):
2067 self
.push_output_collector([])
2068 self
.out
.append(r
'\newcommand{\DUfooter}{')
2070 def depart_footer(self
, node
):
2071 self
.out
.append('}')
2072 self
.requirements
['~footer'] = ''.join(self
.out
)
2073 self
.pop_output_collector()
2075 def visit_footnote(self
, node
):
2077 backref
= node
['backrefs'][0]
2079 backref
= node
['ids'][0] # no backref, use self-ref instead
2080 if self
.settings
.figure_footnotes
:
2081 self
.requirements
['~fnt_floats'] = PreambleCmds
.footnote_floats
2082 self
.out
.append('\\begin{figure}[b]')
2083 self
.append_hypertargets(node
)
2084 if node
.get('id') == node
.get('name'): # explicite label
2085 self
.out
+= self
.ids_to_labels(node
)
2086 elif self
.docutils_footnotes
:
2087 self
.fallbacks
['footnotes'] = PreambleCmds
.footnotes
2088 num
,text
= node
.astext().split(None,1)
2089 if self
.settings
.footnote_references
== 'brackets':
2091 self
.out
.append('%%\n\\DUfootnotetext{%s}{%s}{%s}{' %
2092 (node
['ids'][0], backref
, self
.encode(num
)))
2093 if node
['ids'] == node
['names']:
2094 self
.out
+= self
.ids_to_labels(node
)
2095 # mask newline to prevent spurious whitespace:
2096 self
.out
.append('%')
2097 ## else: # TODO: "real" LaTeX \footnote{}s
2099 def depart_footnote(self
, node
):
2100 if self
.figure_footnotes
:
2101 self
.out
.append('\\end{figure}\n')
2103 self
.out
.append('}\n')
2105 def visit_footnote_reference(self
, node
):
2108 href
= node
['refid']
2109 elif 'refname' in node
:
2110 href
= self
.document
.nameids
[node
['refname']]
2111 # if not self.docutils_footnotes:
2112 # TODO: insert footnote content at (or near) this place
2113 # print "footnote-ref to", node['refid']
2114 # footnotes = (self.document.footnotes +
2115 # self.document.autofootnotes +
2116 # self.document.symbol_footnotes)
2117 # for footnote in footnotes:
2118 # # print footnote['ids']
2119 # if node.get('refid', '') in footnote['ids']:
2120 # print 'matches', footnote['ids']
2121 format
= self
.settings
.footnote_references
2122 if format
== 'brackets':
2123 self
.append_hypertargets(node
)
2124 self
.out
.append('\\hyperlink{%s}{[' % href
)
2125 self
.context
.append(']}')
2127 self
.fallbacks
['footnotes'] = PreambleCmds
.footnotes
2128 self
.out
.append(r
'\DUfootnotemark{%s}{%s}{' %
2129 (node
['ids'][0], href
))
2130 self
.context
.append('}')
2132 def depart_footnote_reference(self
, node
):
2133 self
.out
.append(self
.context
.pop())
2135 # footnote/citation label
2136 def label_delim(self
, node
, bracket
, superscript
):
2137 if isinstance(node
.parent
, nodes
.footnote
):
2138 if not self
.figure_footnotes
:
2139 raise nodes
.SkipNode
2140 if self
.settings
.footnote_references
== 'brackets':
2141 self
.out
.append(bracket
)
2143 self
.out
.append(superscript
)
2145 assert isinstance(node
.parent
, nodes
.citation
)
2146 if not self
._use
_latex
_citations
:
2147 self
.out
.append(bracket
)
2149 def visit_label(self
, node
):
2150 """footnote or citation label: in brackets or as superscript"""
2151 self
.label_delim(node
, '[', '\\textsuperscript{')
2153 def depart_label(self
, node
):
2154 self
.label_delim(node
, ']', '}')
2156 # elements generated by the framework e.g. section numbers.
2157 def visit_generated(self
, node
):
2160 def depart_generated(self
, node
):
2163 def visit_header(self
, node
):
2164 self
.push_output_collector([])
2165 self
.out
.append(r
'\newcommand{\DUheader}{')
2167 def depart_header(self
, node
):
2168 self
.out
.append('}')
2169 self
.requirements
['~header'] = ''.join(self
.out
)
2170 self
.pop_output_collector()
2172 def to_latex_length(self
, length_str
, pxunit
='px'):
2173 """Convert `length_str` with rst lenght to LaTeX length
2175 match
= re
.match('(\d*\.?\d*)\s*(\S*)', length_str
)
2178 value
, unit
= match
.groups()[:2]
2179 # no unit or "DTP" points (called 'bp' in TeX):
2180 if unit
in ('', 'pt'):
2181 length_str
= '%sbp' % value
2182 # percentage: relate to current line width
2184 length_str
= '%.3f\\linewidth' % (float(value
)/100.0)
2185 elif (unit
== 'px') and (pxunit
!= 'px'):
2186 # length unit px not defined in some tex variants (e.g. XeTeX)
2187 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
2188 self
.fallbacks
['px'] = '\n\\DUprovidelength{%s}{1bp}\n' % pxunit
2189 length_str
= '%s%s' % (value
, pxunit
)
2193 def visit_image(self
, node
):
2194 self
.requirements
['graphicx'] = self
.graphicx_package
2195 attrs
= node
.attributes
2196 # Add image URI to dependency list, assuming that it's
2197 # referring to a local file.
2198 self
.settings
.record_dependencies
.add(attrs
['uri'])
2199 # alignment defaults:
2200 if not 'align' in attrs
:
2201 # Set default align of image in a figure to 'center'
2202 if isinstance(node
.parent
, nodes
.figure
):
2203 attrs
['align'] = 'center'
2204 # query 'align-*' class argument
2205 for cls
in node
['classes']:
2206 if cls
.startswith('align-'):
2207 attrs
['align'] = cls
.split('-')[1]
2208 # pre- and postfix (prefix inserted in reverse order)
2211 include_graphics_options
= []
2212 display_style
= ('block-', 'inline-')[self
.is_inline(node
)]
2214 # inline images: by default latex aligns the bottom.
2216 'middle': (r
'\raisebox{-0.5\height}{', '}'),
2217 'top': (r
'\raisebox{-\height}{', '}'),
2218 # block level images:
2219 'center': (r
'\noindent\makebox[\textwidth][c]{', '}'),
2220 'left': (r
'\noindent{', r
'\hfill}'),
2221 'right': (r
'\noindent{\hfill', '}'),}
2222 if 'align' in attrs
:
2224 align_code
= align_codes
[attrs
['align']]
2225 pre
.append(align_code
[0])
2226 post
.append(align_code
[1])
2229 if 'height' in attrs
:
2230 include_graphics_options
.append('height=%s' %
2231 self
.to_latex_length(attrs
['height']))
2232 if 'scale' in attrs
:
2233 include_graphics_options
.append('scale=%f' %
2234 (attrs
['scale'] / 100.0))
2235 if 'width' in attrs
:
2236 include_graphics_options
.append('width=%s' %
2237 self
.to_latex_length(attrs
['width']))
2238 if not self
.is_inline(node
):
2242 self
.out
.extend(pre
)
2244 if include_graphics_options
:
2245 options
= '[%s]' % (','.join(include_graphics_options
))
2246 self
.out
.append('\\includegraphics%s{%s}' % (options
, attrs
['uri']))
2247 self
.out
.extend(post
)
2249 def depart_image(self
, node
):
2251 self
.out
+= self
.ids_to_labels(node
) + ['\n']
2253 def visit_inline(self
, node
): # <span>, i.e. custom roles
2254 # Make a copy to keep ``node['classes']`` True if a
2255 # language argument is popped (used in conditional calls of
2257 classes
= node
['classes'][:]
2258 self
.context
.append('}' * len(classes
))
2259 # handle language specification:
2260 language_tags
= [cls
for cls
in classes
2261 if cls
.startswith('language-')]
2263 language
= self
.babel
.get_language(language_tags
[0][9:])
2265 self
.babel
.otherlanguages
[language
] = True
2266 self
.out
.append(r
'\otherlanguage{%s}{' % language
)
2267 classes
.pop(classes
.index(language_tags
[0]))
2270 # mark up for styling with custom macros
2271 if 'align-center' in classes
:
2272 self
.fallbacks
['align-center'] = PreambleCmds
.align_center
2273 self
.fallbacks
['inline'] = PreambleCmds
.inline
2274 self
.out
+= [r
'\DUrole{%s}{' % cls
for cls
in classes
]
2276 def depart_inline(self
, node
):
2277 self
.out
.append(self
.context
.pop())
2279 def visit_interpreted(self
, node
):
2280 # @@@ Incomplete, pending a proper implementation on the
2281 # Parser/Reader end.
2282 self
.visit_literal(node
)
2284 def depart_interpreted(self
, node
):
2285 self
.depart_literal(node
)
2287 def visit_legend(self
, node
):
2288 self
.fallbacks
['legend'] = PreambleCmds
.legend
2289 self
.out
.append('\\begin{DUlegend}')
2291 def depart_legend(self
, node
):
2292 self
.out
.append('\\end{DUlegend}\n')
2294 def visit_line(self
, node
):
2295 self
.out
.append('\item[] ')
2297 def depart_line(self
, node
):
2298 self
.out
.append('\n')
2300 def visit_line_block(self
, node
):
2301 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
2302 self
.fallbacks
['lineblock'] = PreambleCmds
.lineblock
2303 if isinstance(node
.parent
, nodes
.line_block
):
2304 self
.out
.append('\\item[]\n'
2305 '\\begin{DUlineblock}{\\DUlineblockindent}\n')
2307 self
.out
.append('\n\\begin{DUlineblock}{0em}\n')
2309 self
.visit_inline(node
)
2310 self
.out
.append('\n')
2312 def depart_line_block(self
, node
):
2314 self
.depart_inline(node
)
2315 self
.out
.append('\n')
2316 self
.out
.append('\\end{DUlineblock}\n')
2318 def visit_list_item(self
, node
):
2319 self
.out
.append('\n\\item ')
2321 def depart_list_item(self
, node
):
2324 def visit_literal(self
, node
):
2326 self
.out
.append('\\texttt{')
2328 self
.visit_inline(node
)
2330 def depart_literal(self
, node
):
2331 self
.literal
= False
2333 self
.depart_inline(node
)
2334 self
.out
.append('}')
2336 # Literal blocks are used for '::'-prefixed literal-indented
2337 # blocks of text, where the inline markup is not recognized,
2338 # but are also the product of the "parsed-literal" directive,
2339 # where the markup is respected.
2341 # In both cases, we want to use a typewriter/monospaced typeface.
2342 # For "real" literal-blocks, we can use \verbatim, while for all
2343 # the others we must use \mbox or \alltt.
2345 # We can distinguish between the two kinds by the number of
2346 # siblings that compose this node: if it is composed by a
2347 # single element, it's either
2349 # * a parsed-literal that does not contain any markup, or
2350 # * a parsed-literal containing just one markup construct.
2351 def is_plaintext(self
, node
):
2352 """Check whether a node can be typeset verbatim"""
2353 return (len(node
) == 1) and isinstance(node
[0], nodes
.Text
)
2355 def visit_literal_block(self
, node
):
2356 """Render a literal block."""
2357 # environments and packages to typeset literal blocks
2358 packages
= {'listing': r
'\usepackage{moreverb}',
2359 'lstlisting': r
'\usepackage{listings}',
2360 'Verbatim': r
'\usepackage{fancyvrb}',
2362 'verbatimtab': r
'\usepackage{moreverb}'}
2364 if not self
.active_table
.is_open():
2365 # no quote inside tables, to avoid vertical space between
2366 # table border and literal block.
2367 # BUG: fails if normal text preceeds the literal block.
2368 self
.out
.append('%\n\\begin{quote}')
2369 self
.context
.append('\n\\end{quote}\n')
2371 self
.out
.append('\n')
2372 self
.context
.append('\n')
2373 if self
.literal_block_env
!= '' and self
.is_plaintext(node
):
2374 self
.requirements
['literal_block'] = packages
.get(
2375 self
.literal_block_env
, '')
2376 self
.verbatim
= True
2377 self
.out
.append('\\begin{%s}%s\n' % (self
.literal_block_env
,
2378 self
.literal_block_options
))
2381 self
.insert_newline
= True
2382 self
.insert_non_breaking_blanks
= True
2383 self
.out
.append('{\\ttfamily \\raggedright \\noindent\n')
2385 def depart_literal_block(self
, node
):
2387 self
.out
.append('\n\\end{%s}\n' % self
.literal_block_env
)
2388 self
.verbatim
= False
2390 self
.out
.append('\n}')
2391 self
.insert_non_breaking_blanks
= False
2392 self
.insert_newline
= False
2393 self
.literal
= False
2394 self
.out
.append(self
.context
.pop())
2396 ## def visit_meta(self, node):
2397 ## self.out.append('[visit_meta]\n')
2398 # TODO: set keywords for pdf?
2400 # The reStructuredText "meta" directive creates a "pending" node,
2401 # which contains knowledge that the embedded "meta" node can only
2402 # be handled by HTML-compatible writers. The "pending" node is
2403 # resolved by the docutils.transforms.components.Filter transform,
2404 # which checks that the calling writer supports HTML; if it doesn't,
2405 # the "pending" node (and enclosed "meta" node) is removed from the
2407 # --- docutils/docs/peps/pep-0258.html#transformer
2409 ## def depart_meta(self, node):
2410 ## self.out.append('[depart_meta]\n')
2412 def visit_math(self
, node
):
2414 self
.requirements
['amsmath'] = r
'\usepackage{amsmath}'
2416 self
.visit_inline(node
)
2417 self
.verbatim
= True
2418 self
.out
.append('$')
2420 def depart_math(self
, node
):
2421 self
.verbatim
= False
2422 self
.out
.append('$')
2424 self
.depart_inline(node
)
2426 def multiline_math(self
, code
):
2427 """find out whether `code` is a multi-line equation
2429 This is a very simplified test, looking
2430 for line-breaks (``\\``) outside environments.
2432 # cut out environment content:
2433 chunks
= code
.split(r
'\begin{')
2434 toplevel_code
= ''.join([chunk
.split(r
'\end{')[-1]
2435 for chunk
in chunks
])
2436 return toplevel_code
.find(r
'\\') >= 0
2438 def visit_math_block(self
, node
):
2439 self
.requirements
['amsmath'] = r
'\usepackage{amsmath}'
2441 self
.visit_inline(node
)
2442 math_code
= node
.astext()
2443 if self
.multiline_math(math_code
):
2444 environment
= 'align*'
2446 environment
= 'equation*'
2447 self
.out
.append ('%%\n\\begin{%s}\n' % environment
)
2448 self
.out
.append(math_code
)
2449 self
.out
.append('\n\\end{%s}' % environment
)
2450 # Content already processed:
2451 raise nodes
.SkipNode
2453 def depart_math_block(self
, node
):
2455 self
.depart_inline(node
)
2457 def visit_option(self
, node
):
2458 if self
.context
[-1]:
2459 # this is not the first option
2460 self
.out
.append(', ')
2462 def depart_option(self
, node
):
2463 # flag that the first option is done.
2464 self
.context
[-1] += 1
2466 def visit_option_argument(self
, node
):
2467 """Append the delimiter betweeen an option and its argument to body."""
2468 self
.out
.append(node
.get('delimiter', ' '))
2470 def depart_option_argument(self
, node
):
2473 def visit_option_group(self
, node
):
2474 self
.out
.append('\n\\item[')
2475 # flag for first option
2476 self
.context
.append(0)
2478 def depart_option_group(self
, node
):
2479 self
.context
.pop() # the flag
2480 self
.out
.append('] ')
2482 def visit_option_list(self
, node
):
2483 self
.fallbacks
['_providelength'] = PreambleCmds
.providelength
2484 self
.fallbacks
['optionlist'] = PreambleCmds
.optionlist
2485 self
.out
.append('%\n\\begin{DUoptionlist}\n')
2487 def depart_option_list(self
, node
):
2488 self
.out
.append('\n\\end{DUoptionlist}\n')
2490 def visit_option_list_item(self
, node
):
2493 def depart_option_list_item(self
, node
):
2496 def visit_option_string(self
, node
):
2497 ##self.out.append(self.starttag(node, 'span', '', CLASS='option'))
2500 def depart_option_string(self
, node
):
2501 ##self.out.append('</span>')
2504 def visit_organization(self
, node
):
2505 self
.visit_docinfo_item(node
, 'organization')
2507 def depart_organization(self
, node
):
2508 self
.depart_docinfo_item(node
)
2510 def visit_paragraph(self
, node
):
2511 # insert blank line, if the paragraph is not first in a list item
2512 # nor follows a non-paragraph node in a compound
2513 index
= node
.parent
.index(node
)
2514 if (index
== 0 and (isinstance(node
.parent
, nodes
.list_item
) or
2515 isinstance(node
.parent
, nodes
.description
))):
2517 elif (index
> 0 and isinstance(node
.parent
, nodes
.compound
) and
2518 not isinstance(node
.parent
[index
- 1], nodes
.paragraph
) and
2519 not isinstance(node
.parent
[index
- 1], nodes
.compound
)):
2522 self
.out
.append('\n')
2524 self
.out
+= self
.ids_to_labels(node
) + ['\n']
2526 self
.visit_inline(node
)
2528 def depart_paragraph(self
, node
):
2530 self
.depart_inline(node
)
2531 self
.out
.append('\n')
2533 def visit_problematic(self
, node
):
2534 self
.requirements
['color'] = PreambleCmds
.color
2535 self
.out
.append('%\n')
2536 self
.append_hypertargets(node
)
2537 self
.out
.append(r
'\hyperlink{%s}{\textbf{\color{red}' % node
['refid'])
2539 def depart_problematic(self
, node
):
2540 self
.out
.append('}}')
2542 def visit_raw(self
, node
):
2543 if not 'latex' in node
.get('format', '').split():
2544 raise nodes
.SkipNode
2545 if not self
.is_inline(node
):
2546 self
.out
.append('\n')
2548 self
.visit_inline(node
)
2549 # append "as-is" skipping any LaTeX-encoding
2550 self
.verbatim
= True
2552 def depart_raw(self
, node
):
2553 self
.verbatim
= False
2555 self
.depart_inline(node
)
2556 if not self
.is_inline(node
):
2557 self
.out
.append('\n')
2559 def has_unbalanced_braces(self
, string
):
2560 """Test whether there are unmatched '{' or '}' characters."""
2571 def visit_reference(self
, node
):
2572 # We need to escape #, \, and % if we use the URL in a command.
2573 special_chars
= {ord('#'): ur
'\#',
2577 # external reference (URL)
2578 if 'refuri' in node
:
2579 href
= unicode(node
['refuri']).translate(special_chars
)
2580 # problematic chars double caret and unbalanced braces:
2581 if href
.find('^^') != -1 or self
.has_unbalanced_braces(href
):
2583 'External link "%s" not supported by LaTeX.\n'
2584 ' (Must not contain "^^" or unbalanced braces.)' % href
)
2585 if node
['refuri'] == node
.astext():
2586 self
.out
.append(r
'\url{%s}' % href
)
2587 raise nodes
.SkipNode
2588 self
.out
.append(r
'\href{%s}{' % href
)
2590 # internal reference
2592 href
= node
['refid']
2593 elif 'refname' in node
:
2594 href
= self
.document
.nameids
[node
['refname']]
2596 raise AssertionError('Unknown reference.')
2597 if not self
.is_inline(node
):
2598 self
.out
.append('\n')
2599 self
.out
.append('\\hyperref[%s]{' % href
)
2600 if self
._reference
_label
:
2601 self
.out
.append('\\%s{%s}}' %
2602 (self
._reference
_label
, href
.replace('#', '')))
2603 raise nodes
.SkipNode
2605 def depart_reference(self
, node
):
2606 self
.out
.append('}')
2607 if not self
.is_inline(node
):
2608 self
.out
.append('\n')
2610 def visit_revision(self
, node
):
2611 self
.visit_docinfo_item(node
, 'revision')
2613 def depart_revision(self
, node
):
2614 self
.depart_docinfo_item(node
)
2616 def visit_section(self
, node
):
2617 self
.section_level
+= 1
2618 # Initialize counter for potential subsections:
2619 self
._section
_number
.append(0)
2620 # Counter for this section's level (initialized by parent section):
2621 self
._section
_number
[self
.section_level
- 1] += 1
2623 def depart_section(self
, node
):
2624 # Remove counter for potential subsections:
2625 self
._section
_number
.pop()
2626 self
.section_level
-= 1
2628 def visit_sidebar(self
, node
):
2629 self
.requirements
['color'] = PreambleCmds
.color
2630 self
.fallbacks
['sidebar'] = PreambleCmds
.sidebar
2631 self
.out
.append('\n\\DUsidebar{\n')
2633 def depart_sidebar(self
, node
):
2634 self
.out
.append('}\n')
2636 attribution_formats
= {'dash': (u
'—', ''), # EM DASH
2637 'parentheses': ('(', ')'),
2638 'parens': ('(', ')'),
2641 def visit_attribution(self
, node
):
2642 prefix
, suffix
= self
.attribution_formats
[self
.settings
.attribution
]
2643 self
.out
.append('\\nopagebreak\n\n\\raggedleft ')
2644 self
.out
.append(prefix
)
2645 self
.context
.append(suffix
)
2647 def depart_attribution(self
, node
):
2648 self
.out
.append(self
.context
.pop() + '\n')
2650 def visit_status(self
, node
):
2651 self
.visit_docinfo_item(node
, 'status')
2653 def depart_status(self
, node
):
2654 self
.depart_docinfo_item(node
)
2656 def visit_strong(self
, node
):
2657 self
.out
.append('\\textbf{')
2659 self
.visit_inline(node
)
2661 def depart_strong(self
, node
):
2663 self
.depart_inline(node
)
2664 self
.out
.append('}')
2666 def visit_substitution_definition(self
, node
):
2667 raise nodes
.SkipNode
2669 def visit_substitution_reference(self
, node
):
2670 self
.unimplemented_visit(node
)
2672 def visit_subtitle(self
, node
):
2673 if isinstance(node
.parent
, nodes
.document
):
2674 self
.push_output_collector(self
.subtitle
)
2675 self
.subtitle_labels
+= self
.ids_to_labels(node
, set_anchor
=False)
2676 # section subtitle: "starred" (no number, not in ToC)
2677 elif isinstance(node
.parent
, nodes
.section
):
2678 self
.out
.append(r
'\%s*{' %
2679 self
.d_class
.section(self
.section_level
+ 1))
2681 self
.fallbacks
['subtitle'] = PreambleCmds
.subtitle
2682 self
.out
.append('\n\\DUsubtitle[%s]{' % node
.parent
.tagname
)
2684 def depart_subtitle(self
, node
):
2685 if isinstance(node
.parent
, nodes
.document
):
2686 self
.pop_output_collector()
2688 self
.out
.append('}\n')
2690 def visit_system_message(self
, node
):
2691 self
.requirements
['color'] = PreambleCmds
.color
2692 self
.fallbacks
['title'] = PreambleCmds
.title
2693 node
['classes'] = ['system-message']
2694 self
.visit_admonition(node
)
2695 self
.out
.append('\\DUtitle[system-message]{system-message}\n')
2696 self
.append_hypertargets(node
)
2698 line
= ', line~%s' % node
['line']
2701 self
.out
.append('\n\n{\color{red}%s/%s} in \\texttt{%s}%s\n' %
2702 (node
['type'], node
['level'],
2703 self
.encode(node
['source']), line
))
2704 if len(node
['backrefs']) == 1:
2705 self
.out
.append('\n\\hyperlink{%s}{' % node
['backrefs'][0])
2706 self
.context
.append('}')
2708 backrefs
= ['\\hyperlink{%s}{%d}' % (href
, i
+1)
2709 for (i
, href
) in enumerate(node
['backrefs'])]
2710 self
.context
.append('backrefs: ' + ' '.join(backrefs
))
2712 def depart_system_message(self
, node
):
2713 self
.out
.append(self
.context
.pop())
2714 self
.depart_admonition()
2716 def visit_table(self
, node
):
2717 self
.requirements
['table'] = PreambleCmds
.table
2718 if self
.active_table
.is_open():
2719 self
.table_stack
.append(self
.active_table
)
2720 # nesting longtable does not work (e.g. 2007-04-18)
2721 self
.active_table
= Table(self
,'tabular',self
.settings
.table_style
)
2722 self
.active_table
.open()
2723 for cls
in node
['classes']:
2724 self
.active_table
.set_table_style(cls
)
2725 if self
.active_table
._table
_style
== 'booktabs':
2726 self
.requirements
['booktabs'] = r
'\usepackage{booktabs}'
2727 self
.out
.append('\n' + self
.active_table
.get_opening())
2729 def depart_table(self
, node
):
2730 self
.out
.append(self
.active_table
.get_closing() + '\n')
2731 self
.active_table
.close()
2732 if len(self
.table_stack
)>0:
2733 self
.active_table
= self
.table_stack
.pop()
2735 self
.active_table
.set_table_style(self
.settings
.table_style
)
2736 # Insert hyperlabel after (long)table, as
2737 # other places (beginning, caption) result in LaTeX errors.
2739 self
.out
+= self
.ids_to_labels(node
, set_anchor
=False) + ['\n']
2741 def visit_target(self
, node
):
2742 # Skip indirect targets:
2743 if ('refuri' in node
# external hyperlink
2744 or 'refid' in node
# resolved internal link
2745 or 'refname' in node
): # unresolved internal link
2746 ## self.out.append('%% %s\n' % node) # for debugging
2748 self
.out
.append('%\n')
2749 # do we need an anchor (\phantomsection)?
2750 set_anchor
= not(isinstance(node
.parent
, nodes
.caption
) or
2751 isinstance(node
.parent
, nodes
.title
))
2752 # TODO: where else can/must we omit the \phantomsection?
2753 self
.out
+= self
.ids_to_labels(node
, set_anchor
)
2755 def depart_target(self
, node
):
2758 def visit_tbody(self
, node
):
2759 # BUG write preamble if not yet done (colspecs not [])
2760 # for tables without heads.
2761 if not self
.active_table
.get('preamble written'):
2762 self
.visit_thead(None)
2763 self
.depart_thead(None)
2765 def depart_tbody(self
, node
):
2768 def visit_term(self
, node
):
2769 """definition list term"""
2770 # Commands with optional args inside an optional arg must be put
2771 # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
2772 self
.out
.append('\\item[{')
2774 def depart_term(self
, node
):
2775 # \leavevmode results in a line break if the
2776 # term is followed by an item list.
2777 self
.out
.append('}] \leavevmode ')
2779 def visit_tgroup(self
, node
):
2780 #self.out.append(self.starttag(node, 'colgroup'))
2781 #self.context.append('</colgroup>\n')
2784 def depart_tgroup(self
, node
):
2788 def thead_depth (self
):
2789 return self
._thead
_depth
2791 def visit_thead(self
, node
):
2792 self
._thead
_depth
+= 1
2793 if 1 == self
.thead_depth():
2794 self
.out
.append('{%s}\n' % self
.active_table
.get_colspecs())
2795 self
.active_table
.set('preamble written',1)
2796 self
.out
.append(self
.active_table
.get_caption())
2797 self
.out
.extend(self
.active_table
.visit_thead())
2799 def depart_thead(self
, node
):
2800 if node
is not None:
2801 self
.out
.extend(self
.active_table
.depart_thead())
2802 if self
.active_table
.need_recurse():
2803 node
.walkabout(self
)
2804 self
._thead
_depth
-= 1
2806 def bookmark(self
, node
):
2807 """Return label and pdfbookmark string for titles."""
2809 if self
.settings
.sectnum_xform
: # "starred" section cmd
2810 # add to the toc and pdfbookmarks
2811 section_name
= self
.d_class
.section(max(self
.section_level
, 1))
2812 section_title
= self
.encode(node
.astext())
2813 result
.append(r
'\addcontentsline{toc}{%s}{%s}' %
2814 (section_name
, section_title
))
2815 result
+= self
.ids_to_labels(node
.parent
, set_anchor
=False)
2816 return '%\n '.join(result
) + '%\n'
2818 def visit_title(self
, node
):
2819 """Append section and other titles."""
2821 if node
.parent
.tagname
== 'document':
2822 self
.push_output_collector(self
.title
)
2823 self
.context
.append('')
2824 self
.pdfinfo
.append(' pdftitle={%s},' %
2825 self
.encode(node
.astext()))
2826 # Topic titles (topic, admonition, sidebar)
2827 elif (isinstance(node
.parent
, nodes
.topic
) or
2828 isinstance(node
.parent
, nodes
.admonition
) or
2829 isinstance(node
.parent
, nodes
.sidebar
)):
2830 self
.fallbacks
['title'] = PreambleCmds
.title
2831 classes
= ','.join(node
.parent
['classes'])
2833 classes
= node
.tagname
2834 self
.out
.append('\\DUtitle[%s]{' % classes
)
2835 self
.context
.append('}\n')
2837 elif isinstance(node
.parent
, nodes
.table
):
2838 self
.push_output_collector(self
.active_table
.caption
)
2839 self
.context
.append('')
2842 self
.out
.append('\n\n')
2843 self
.out
.append('%' + '_' * 75)
2844 self
.out
.append('\n\n')
2846 section_name
= self
.d_class
.section(self
.section_level
)
2850 if (self
.settings
.sectnum_xform
# numbering by Docutils
2851 or (self
.section_level
> len(self
.d_class
.sections
))):
2853 pdfanchor
= '\\phantomsection%\n '
2854 self
.out
.append(r
'\%s%s{%s' %
2855 (section_name
, section_star
, pdfanchor
))
2856 # System messages heading in red:
2857 if ('system-messages' in node
.parent
['classes']):
2858 self
.requirements
['color'] = PreambleCmds
.color
2859 self
.out
.append('\color{red}')
2860 # label and ToC entry:
2861 self
.context
.append(self
.bookmark(node
) + '}\n')
2862 # MAYBE postfix paragraph and subparagraph with \leavemode to
2863 # ensure floats stay in the section and text starts on a new line.
2865 def depart_title(self
, node
):
2866 self
.out
.append(self
.context
.pop())
2867 if (isinstance(node
.parent
, nodes
.table
) or
2868 node
.parent
.tagname
== 'document'):
2869 self
.pop_output_collector()
2871 def minitoc(self
, node
, title
, depth
):
2872 """Generate a local table of contents with LaTeX package minitoc"""
2873 section_name
= self
.d_class
.section(self
.section_level
)
2874 # name-prefix for current section level
2875 minitoc_names
= {'part': 'part', 'chapter': 'mini'}
2876 if 'chapter' not in self
.d_class
.sections
:
2877 minitoc_names
['section'] = 'sect'
2879 minitoc_name
= minitoc_names
[section_name
]
2880 except KeyError: # minitoc only supports part- and toplevel
2881 self
.warn('Skipping local ToC at %s level.\n' % section_name
+
2882 ' Feature not supported with option "use-latex-toc"',
2885 # Requirements/Setup
2886 self
.requirements
['minitoc'] = PreambleCmds
.minitoc
2887 self
.requirements
['minitoc-'+minitoc_name
] = (r
'\do%stoc' %
2889 # depth: (Docutils defaults to unlimited depth)
2890 maxdepth
= len(self
.d_class
.sections
)
2891 self
.requirements
['minitoc-%s-depth' % minitoc_name
] = (
2892 r
'\mtcsetdepth{%stoc}{%d}' % (minitoc_name
, maxdepth
))
2893 # Process 'depth' argument (!Docutils stores a relative depth while
2894 # minitoc expects an absolute depth!):
2895 offset
= {'sect': 1, 'mini': 0, 'part': 0}
2896 if 'chapter' in self
.d_class
.sections
:
2899 self
.out
.append('\\setcounter{%stocdepth}{%d}' %
2900 (minitoc_name
, depth
+ offset
[minitoc_name
]))
2902 self
.out
.append('\\mtcsettitle{%stoc}{%s}\n' % (minitoc_name
, title
))
2903 # the toc-generating command:
2904 self
.out
.append('\\%stoc\n' % minitoc_name
)
2906 def visit_topic(self
, node
):
2907 # Topic nodes can be generic topic, abstract, dedication, or ToC.
2908 # table of contents:
2909 if 'contents' in node
['classes']:
2910 self
.out
.append('\n')
2911 self
.out
+= self
.ids_to_labels(node
)
2912 # add contents to PDF bookmarks sidebar
2913 if isinstance(node
.next_node(), nodes
.title
):
2914 self
.out
.append('\n\\pdfbookmark[%d]{%s}{%s}\n' %
2915 (self
.section_level
+1,
2916 node
.next_node().astext(),
2917 node
.get('ids', ['contents'])[0]
2919 if self
.use_latex_toc
:
2921 if isinstance(node
.next_node(), nodes
.title
):
2922 title
= self
.encode(node
.pop(0).astext())
2923 depth
= node
.get('depth', 0)
2924 if 'local' in node
['classes']:
2925 self
.minitoc(node
, title
, depth
)
2926 self
.context
.append('')
2929 self
.out
.append('\\setcounter{tocdepth}{%d}\n' % depth
)
2930 if title
!= 'Contents':
2931 self
.out
.append('\\renewcommand{\\contentsname}{%s}\n' %
2933 self
.out
.append('\\tableofcontents\n\n')
2934 self
.has_latex_toc
= True
2935 else: # Docutils generated contents list
2936 # set flag for visit_bullet_list() and visit_title()
2937 self
.is_toc_list
= True
2938 self
.context
.append('')
2939 elif ('abstract' in node
['classes'] and
2940 self
.settings
.use_latex_abstract
):
2941 self
.push_output_collector(self
.abstract
)
2942 self
.out
.append('\\begin{abstract}')
2943 self
.context
.append('\\end{abstract}\n')
2944 if isinstance(node
.next_node(), nodes
.title
):
2945 node
.pop(0) # LaTeX provides its own title
2947 self
.fallbacks
['topic'] = PreambleCmds
.topic
2949 if 'abstract' in node
['classes']:
2950 self
.fallbacks
['abstract'] = PreambleCmds
.abstract
2951 self
.push_output_collector(self
.abstract
)
2952 if 'dedication' in node
['classes']:
2953 self
.fallbacks
['dedication'] = PreambleCmds
.dedication
2954 self
.push_output_collector(self
.dedication
)
2955 self
.out
.append('\n\\DUtopic[%s]{\n' % ','.join(node
['classes']))
2956 self
.context
.append('}\n')
2958 def depart_topic(self
, node
):
2959 self
.out
.append(self
.context
.pop())
2960 self
.is_toc_list
= False
2961 if ('abstract' in node
['classes'] or
2962 'dedication' in node
['classes']):
2963 self
.pop_output_collector()
2965 def visit_rubric(self
, node
):
2966 self
.fallbacks
['rubric'] = PreambleCmds
.rubric
2967 self
.out
.append('\n\\DUrubric{')
2968 self
.context
.append('}\n')
2970 def depart_rubric(self
, node
):
2971 self
.out
.append(self
.context
.pop())
2973 def visit_transition(self
, node
):
2974 self
.fallbacks
['transition'] = PreambleCmds
.transition
2975 self
.out
.append('\n\n')
2976 self
.out
.append('%' + '_' * 75 + '\n')
2977 self
.out
.append(r
'\DUtransition')
2978 self
.out
.append('\n\n')
2980 def depart_transition(self
, node
):
2983 def visit_version(self
, node
):
2984 self
.visit_docinfo_item(node
, 'version')
2986 def depart_version(self
, node
):
2987 self
.depart_docinfo_item(node
)
2989 def unimplemented_visit(self
, node
):
2990 raise NotImplementedError('visiting unimplemented node type: %s' %
2991 node
.__class
__.__name
__)
2993 # def unknown_visit(self, node):
2994 # def default_visit(self, node):
2996 # vim: set ts=4 et ai :