/code/docutils/writers/latex2e/__init__.py
Python | 2831 lines | 2788 code | 10 blank | 33 comment | 6 complexity | 9448a05dcbf80b67e0b1f31151009321 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- # -*- coding: utf8 -*-
- # $Id: __init__.py 6385 2010-08-13 12:17:01Z milde $
- # Author: Engelbert Gruber <grubert@users.sourceforge.net>
- # Copyright: This module has been placed in the public domain.
- """LaTeX2e document tree Writer."""
- __docformat__ = 'reStructuredText'
- # code contributions from several people included, thanks to all.
- # some named: David Abrahams, Julien Letessier, Lele Gaifax, and others.
- #
- # convention deactivate code by two # i.e. ##.
- import sys
- import os
- import time
- import re
- import string
- from docutils import frontend, nodes, languages, writers, utils, io
- from docutils.transforms import writer_aux
- # compatibility module for Python 2.3
- if not hasattr(string, 'Template'):
- import docutils._string_template_compat
- string.Template = docutils._string_template_compat.Template
- class Writer(writers.Writer):
- supported = ('latex','latex2e')
- """Formats this writer supports."""
- default_template = 'default.tex'
- default_template_path = os.path.dirname(__file__)
- default_preamble = '\n'.join([r'% PDF Standard Fonts',
- r'\usepackage{mathptmx} % Times',
- r'\usepackage[scaled=.90]{helvet}',
- r'\usepackage{courier}'])
- settings_spec = (
- 'LaTeX-Specific Options',
- None,
- (('Specify documentclass. Default is "article".',
- ['--documentclass'],
- {'default': 'article', }),
- ('Specify document options. Multiple options can be given, '
- 'separated by commas. Default is "a4paper".',
- ['--documentoptions'],
- {'default': 'a4paper', }),
- ('Footnotes with numbers/symbols by Docutils. (default)',
- ['--docutils-footnotes'],
- {'default': True, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Alias for --docutils-footnotes (deprecated)',
- ['--use-latex-footnotes'],
- {'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Use figure floats for footnote text (deprecated)',
- ['--figure-footnotes'],
- {'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Format for footnote references: one of "superscript" or '
- '"brackets". Default is "superscript".',
- ['--footnote-references'],
- {'choices': ['superscript', 'brackets'], 'default': 'superscript',
- 'metavar': '<format>',
- 'overrides': 'trim_footnote_reference_space'}),
- ('Use \\cite command for citations. ',
- ['--use-latex-citations'],
- {'default': 0, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Use figure floats for citations '
- '(might get mixed with real figures). (default)',
- ['--figure-citations'],
- {'dest': 'use_latex_citations', 'action': 'store_false',
- 'validator': frontend.validate_boolean}),
- ('Format for block quote attributions: one of "dash" (em-dash '
- 'prefix), "parentheses"/"parens", or "none". Default is "dash".',
- ['--attribution'],
- {'choices': ['dash', 'parentheses', 'parens', 'none'],
- 'default': 'dash', 'metavar': '<format>'}),
- ('Specify LaTeX packages/stylesheets. '
- ' A style is referenced with \\usepackage if extension is '
- '".sty" or omitted and with \\input else. '
- ' Overrides previous --stylesheet and --stylesheet-path settings.',
- ['--stylesheet'],
- {'default': '', 'metavar': '<file>',
- 'overrides': 'stylesheet_path'}),
- ('Like --stylesheet, but the path is rewritten '
- 'relative to the output file. ',
- ['--stylesheet-path'],
- {'metavar': '<file>', 'overrides': 'stylesheet'}),
- ('Link to the stylesheet(s) in the output file. (default)',
- ['--link-stylesheet'],
- {'dest': 'embed_stylesheet', 'action': 'store_false'}),
- ('Embed the stylesheet(s) in the output file. '
- 'Stylesheets must be accessible during processing. ',
- ['--embed-stylesheet'],
- {'default': 0, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Customization by LaTeX code in the preamble. '
- 'Default: select PDF standard fonts (Times, Helvetica, Courier).',
- ['--latex-preamble'],
- {'default': default_preamble}),
- ('Specify the template file. Default: "%s".' % default_template,
- ['--template'],
- {'default': default_template, 'metavar': '<file>'}),
- ('Table of contents by LaTeX. (default) ',
- ['--use-latex-toc'],
- {'default': 1, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Table of contents by Docutils (without page numbers). ',
- ['--use-docutils-toc'],
- {'dest': 'use_latex_toc', 'action': 'store_false',
- 'validator': frontend.validate_boolean}),
- ('Add parts on top of the section hierarchy.',
- ['--use-part-section'],
- {'default': 0, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Attach author and date to the document info table. (default) ',
- ['--use-docutils-docinfo'],
- {'dest': 'use_latex_docinfo', 'action': 'store_false',
- 'validator': frontend.validate_boolean}),
- ('Attach author and date to the document title.',
- ['--use-latex-docinfo'],
- {'default': 0, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ("Typeset abstract as topic. (default)",
- ['--topic-abstract'],
- {'dest': 'use_latex_abstract', 'action': 'store_false',
- 'validator': frontend.validate_boolean}),
- ("Use LaTeX abstract environment for the document's abstract. ",
- ['--use-latex-abstract'],
- {'default': 0, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Color of any hyperlinks embedded in text '
- '(default: "blue", "0" to disable).',
- ['--hyperlink-color'], {'default': 'blue'}),
- ('Enable compound enumerators for nested enumerated lists '
- '(e.g. "1.2.a.ii"). Default: disabled.',
- ['--compound-enumerators'],
- {'default': None, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Disable compound enumerators for nested enumerated lists. '
- 'This is the default.',
- ['--no-compound-enumerators'],
- {'action': 'store_false', 'dest': 'compound_enumerators'}),
- ('Enable section ("." subsection ...) prefixes for compound '
- 'enumerators. This has no effect without --compound-enumerators.'
- 'Default: disabled.',
- ['--section-prefix-for-enumerators'],
- {'default': None, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Disable section prefixes for compound enumerators. '
- 'This is the default.',
- ['--no-section-prefix-for-enumerators'],
- {'action': 'store_false', 'dest': 'section_prefix_for_enumerators'}),
- ('Set the separator between section number and enumerator '
- 'for compound enumerated lists. Default is "-".',
- ['--section-enumerator-separator'],
- {'default': '-', 'metavar': '<char>'}),
- ('When possibile, use the specified environment for literal-blocks. '
- 'Default is quoting of whitespace and special chars.',
- ['--literal-block-env'],
- {'default': ''}),
- ('When possibile, use verbatim for literal-blocks. '
- 'Compatibility alias for "--literal-block-env=verbatim".',
- ['--use-verbatim-when-possible'],
- {'default': 0, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Table style. "standard" with horizontal and vertical lines, '
- '"booktabs" (LaTeX booktabs style) only horizontal lines '
- 'above and below the table and below the header or "borderless". '
- 'Default: "standard"',
- ['--table-style'],
- {'choices': ['standard', 'booktabs','nolines', 'borderless'],
- 'default': 'standard',
- 'metavar': '<format>'}),
- ('LaTeX graphicx package option. '
- 'Possible values are "dvips", "pdftex". "auto" includes LaTeX code '
- 'to use "pdftex" if processing with pdf(la)tex and dvips otherwise. '
- 'Default is no option.',
- ['--graphicx-option'],
- {'default': ''}),
- ('LaTeX font encoding. '
- 'Possible values are "", "T1" (default), "OT1", "LGR,T1" or '
- 'any other combination of options to the `fontenc` package. ',
- ['--font-encoding'],
- {'default': 'T1'}),
- ('Per default the latex-writer puts the reference title into '
- 'hyperreferences. Specify "ref*" or "pageref*" to get the section '
- 'number or the page number.',
- ['--reference-label'],
- {'default': None, }),
- ('Specify style and database for bibtex, for example '
- '"--use-bibtex=mystyle,mydb1,mydb2".',
- ['--use-bibtex'],
- {'default': None, }),
- ),)
- settings_defaults = {'sectnum_depth': 0 # updated by SectNum transform
- }
- relative_path_settings = ('stylesheet_path',)
- config_section = 'latex2e writer'
- config_section_dependencies = ('writers',)
- head_parts = ('head_prefix', 'requirements', 'latex_preamble',
- 'stylesheet', 'fallbacks', 'pdfsetup', 'title', 'subtitle')
- visitor_attributes = head_parts + ('body_pre_docinfo', 'docinfo',
- 'dedication', 'abstract', 'body')
- output = None
- """Final translated form of `document`."""
- def __init__(self):
- writers.Writer.__init__(self)
- self.translator_class = LaTeXTranslator
- # Override parent method to add latex-specific transforms
- def get_transforms(self):
- # call the parent class' method
- transform_list = writers.Writer.get_transforms(self)
- # print transform_list
- # Convert specific admonitions to generic one
- transform_list.append(writer_aux.Admonitions)
- # TODO: footnote collection transform
- # transform_list.append(footnotes.collect)
- return transform_list
- def translate(self):
- visitor = self.translator_class(self.document)
- self.document.walkabout(visitor)
- # copy parts
- for part in self.visitor_attributes:
- setattr(self, part, getattr(visitor, part))
- # get template string from file
- try:
- file = open(self.document.settings.template, 'rb')
- except IOError:
- file = open(os.path.join(os.path.dirname(__file__),
- self.document.settings.template), 'rb')
- template = string.Template(unicode(file.read(), 'utf-8'))
- file.close()
- # fill template
- self.assemble_parts() # create dictionary of parts
- self.output = template.substitute(self.parts)
- def assemble_parts(self):
- """Assemble the `self.parts` dictionary of output fragments."""
- writers.Writer.assemble_parts(self)
- for part in self.visitor_attributes:
- lines = getattr(self, part)
- if part in self.head_parts:
- if lines:
- lines.append('') # to get a trailing newline
- self.parts[part] = '\n'.join(lines)
- else:
- # body contains inline elements, so join without newline
- self.parts[part] = ''.join(lines)
- class Babel(object):
- """Language specifics for LaTeX."""
- # country code by a.schlock.
- # partly manually converted from iso and babel stuff, dialects and some
- _ISO639_TO_BABEL = {
- 'no': 'norsk', #XXX added by hand ( forget about nynorsk?)
- 'gd': 'scottish', #XXX added by hand
- 'hu': 'magyar', #XXX added by hand
- 'pt': 'portuguese',#XXX added by hand
- 'sl': 'slovenian',
- 'af': 'afrikaans',
- 'bg': 'bulgarian',
- 'br': 'breton',
- 'ca': 'catalan',
- 'cs': 'czech',
- 'cy': 'welsh',
- 'da': 'danish',
- 'fr': 'french',
- # french, francais, canadien, acadian
- 'de': 'ngerman', #XXX rather than german
- # ngerman, naustrian, german, germanb, austrian
- 'el': 'greek',
- 'en': 'english',
- # english, USenglish, american, UKenglish, british, canadian
- 'eo': 'esperanto',
- 'es': 'spanish',
- 'et': 'estonian',
- 'eu': 'basque',
- 'fi': 'finnish',
- 'ga': 'irish',
- 'gl': 'galician',
- 'he': 'hebrew',
- 'hr': 'croatian',
- 'hu': 'hungarian',
- 'is': 'icelandic',
- 'it': 'italian',
- 'la': 'latin',
- 'nl': 'dutch',
- 'pl': 'polish',
- 'pt': 'portuguese',
- 'ro': 'romanian',
- 'ru': 'russian',
- 'sk': 'slovak',
- 'sr': 'serbian',
- 'sv': 'swedish',
- 'tr': 'turkish',
- 'uk': 'ukrainian'
- }
- def __init__(self, lang):
- self.language = lang
- self.quote_index = 0
- self.quotes = ('``', "''")
- self.setup = '' # language dependent configuration code
- # double quotes are "active" in some languages (e.g. German).
- # TODO: use \textquotedbl in OT1 font encoding?
- self.literal_double_quote = u'"'
- if self.language.startswith('de'):
- self.quotes = (r'\glqq{}', r'\grqq{}')
- self.literal_double_quote = ur'\dq{}'
- if self.language.startswith('it'):
- self.literal_double_quote = ur'{\char`\"}'
- if self.language.startswith('es'):
- # reset tilde ~ to the original binding (nobreakspace):
- self.setup = ('\n'
- r'\addto\shorthandsspanish{\spanishdeactivate{."~<>}}')
- def next_quote(self):
- q = self.quotes[self.quote_index]
- self.quote_index = (self.quote_index+1) % 2
- return q
- def quote_quotes(self,text):
- t = None
- for part in text.split('"'):
- if t == None:
- t = part
- else:
- t += self.next_quote() + part
- return t
- def get_language(self):
- lang = self.language.split('_')[0] # filter dialects
- return self._ISO639_TO_BABEL.get(lang, "")
- # Building blocks for the latex preamble
- # --------------------------------------
- class SortableDict(dict):
- """Dictionary with additional sorting methods
- Tip: use key starting with with '_' for sorting before small letters
- and with '~' for sorting after small letters.
- """
- def sortedkeys(self):
- """Return sorted list of keys"""
- keys = self.keys()
- keys.sort()
- return keys
- def sortedvalues(self):
- """Return list of values sorted by keys"""
- return [self[key] for key in self.sortedkeys()]
- # PreambleCmds
- # `````````````
- # A container for LaTeX code snippets that can be
- # inserted into the preamble if required in the document.
- #
- # .. The package 'makecmds' would enable shorter definitions using the
- # \providelength and \provideenvironment commands.
- # However, it is pretty non-standard (texlive-latex-extra).
- class PreambleCmds(object):
- """Building blocks for the latex preamble."""
- PreambleCmds.abstract = r"""
- % abstract title
- \providecommand*{\DUtitleabstract}[1]{\centerline{\textbf{#1}}}"""
- PreambleCmds.admonition = r"""
- % admonition (specially marked topic)
- \providecommand{\DUadmonition}[2][class-arg]{%
- % try \DUadmonition#1{#2}:
- \ifcsname DUadmonition#1\endcsname%
- \csname DUadmonition#1\endcsname{#2}%
- \else
- \begin{center}
- \fbox{\parbox{0.9\textwidth}{#2}}
- \end{center}
- \fi
- }"""
- ## PreambleCmds.caption = r"""% configure caption layout
- ## \usepackage{caption}
- ## \captionsetup{singlelinecheck=false}% no exceptions for one-liners"""
- PreambleCmds.color = r"""\usepackage{color}"""
- PreambleCmds.docinfo = r"""
- % docinfo (width of docinfo table)
- \DUprovidelength{\DUdocinfowidth}{0.9\textwidth}"""
- # PreambleCmds.docinfo._depends = 'providelength'
- PreambleCmds.embedded_package_wrapper = r"""\makeatletter
- %% embedded stylesheet: %s
- %s
- \makeatother"""
- PreambleCmds.dedication = r"""
- % dedication topic
- \providecommand{\DUtopicdedication}[1]{\begin{center}#1\end{center}}"""
- PreambleCmds.error = r"""
- % error admonition title
- \providecommand*{\DUtitleerror}[1]{\DUtitle{\color{red}#1}}"""
- # PreambleCmds.errortitle._depends = 'color'
- PreambleCmds.fieldlist = r"""
- % fieldlist environment
- \ifthenelse{\isundefined{\DUfieldlist}}{
- \newenvironment{DUfieldlist}%
- {\quote\description}
- {\enddescription\endquote}
- }{}"""
- PreambleCmds.float_settings = r"""\usepackage{float} % float configuration
- \floatplacement{figure}{H} % place figures here definitely"""
- PreambleCmds.footnotes = r"""% numeric or symbol footnotes with hyperlinks
- \providecommand*{\DUfootnotemark}[3]{%
- \raisebox{1em}{\hypertarget{#1}{}}%
- \hyperlink{#2}{\textsuperscript{#3}}%
- }
- \providecommand{\DUfootnotetext}[4]{%
- \begingroup%
- \renewcommand{\thefootnote}{%
- \protect\raisebox{1em}{\protect\hypertarget{#1}{}}%
- \protect\hyperlink{#2}{#3}}%
- \footnotetext{#4}%
- \endgroup%
- }"""
- PreambleCmds.footnote_floats = r"""% settings for footnotes as floats:
- \setlength{\floatsep}{0.5em}
- \setlength{\textfloatsep}{\fill}
- \addtolength{\textfloatsep}{3em}
- \renewcommand{\textfraction}{0.5}
- \renewcommand{\topfraction}{0.5}
- \renewcommand{\bottomfraction}{0.5}
- \setcounter{totalnumber}{50}
- \setcounter{topnumber}{50}
- \setcounter{bottomnumber}{50}"""
- PreambleCmds.graphicx_auto = r"""% Check output format
- \ifx\pdftexversion\undefined
- \usepackage{graphicx}
- \else
- \usepackage[pdftex]{graphicx}
- \fi'))"""
- PreambleCmds.inline = r"""
- % inline markup (custom roles)
- % \DUrole{#1}{#2} tries \DUrole#1{#2}
- \providecommand*{\DUrole}[2]{%
- \ifcsname DUrole#1\endcsname%
- \csname DUrole#1\endcsname{#2}%
- \else% backwards compatibility: try \docutilsrole#1{#2}
- \ifcsname docutilsrole#1\endcsname%
- \csname docutilsrole#1\endcsname{#2}%
- \else%
- #2%
- \fi%
- \fi%
- }"""
- PreambleCmds.legend = r"""
- % legend environment
- \ifthenelse{\isundefined{\DUlegend}}{
- \newenvironment{DUlegend}{\small}{}
- }{}"""
- PreambleCmds.lineblock = r"""
- % lineblock environment
- \DUprovidelength{\DUlineblockindent}{2.5em}
- \ifthenelse{\isundefined{\DUlineblock}}{
- \newenvironment{DUlineblock}[1]{%
- \list{}{\setlength{\partopsep}{\parskip}
- \addtolength{\partopsep}{\baselineskip}
- \setlength{\topsep}{0pt}
- \setlength{\itemsep}{0.15\baselineskip}
- \setlength{\parsep}{0pt}
- \setlength{\leftmargin}{#1}}
- \raggedright
- }
- {\endlist}
- }{}"""
- # PreambleCmds.lineblock._depends = 'providelength'
- PreambleCmds.linking = r"""
- %% hyperlinks:
- \ifthenelse{\isundefined{\hypersetup}}{
- \usepackage[unicode,colorlinks=%s,linkcolor=%s,urlcolor=%s]{hyperref}
- \urlstyle{same} %% normal text font (alternatives: tt, rm, sf)
- }{}"""
- PreambleCmds.minitoc = r"""%% local table of contents
- \usepackage{minitoc}"""
- PreambleCmds.optionlist = r"""
- % optionlist environment
- \providecommand*{\DUoptionlistlabel}[1]{\bf #1 \hfill}
- \DUprovidelength{\DUoptionlistindent}{3cm}
- \ifthenelse{\isundefined{\DUoptionlist}}{
- \newenvironment{DUoptionlist}{%
- \list{}{\setlength{\labelwidth}{\DUoptionlistindent}
- \setlength{\rightmargin}{1cm}
- \setlength{\leftmargin}{\rightmargin}
- \addtolength{\leftmargin}{\labelwidth}
- \addtolength{\leftmargin}{\labelsep}
- \renewcommand{\makelabel}{\DUoptionlistlabel}}
- }
- {\endlist}
- }{}"""
- # PreambleCmds.optionlist._depends = 'providelength'
- PreambleCmds.providelength = r"""
- % providelength (provide a length variable and set default, if it is new)
- \providecommand*{\DUprovidelength}[2]{
- \ifthenelse{\isundefined{#1}}{\newlength{#1}\setlength{#1}{#2}}{}
- }"""
- PreambleCmds.rubric = r"""
- % rubric (informal heading)
- \providecommand*{\DUrubric}[2][class-arg]{%
- \subsubsection*{\centering\textit{\textmd{#2}}}}"""
- PreambleCmds.sidebar = r"""
- % sidebar (text outside the main text flow)
- \providecommand{\DUsidebar}[2][class-arg]{%
- \begin{center}
- \colorbox[gray]{0.80}{\parbox{0.9\textwidth}{#2}}
- \end{center}
- }"""
- PreambleCmds.subtitle = r"""
- % subtitle (for topic/sidebar)
- \providecommand*{\DUsubtitle}[2][class-arg]{\par\emph{#2}\smallskip}"""
- PreambleCmds.table = r"""\usepackage{longtable}
- \usepackage{array}
- \setlength{\extrarowheight}{2pt}
- \newlength{\DUtablewidth} % internal use in tables"""
- # Options [force,almostfull] prevent spurious error messages, see
- # de.comp.text.tex/2005-12/msg01855
- PreambleCmds.textcomp = """\
- \\usepackage{textcomp} % text symbol macros"""
- PreambleCmds.documenttitle = r"""
- %% Document title
- \title{%s}
- \author{%s}
- \date{%s}
- \maketitle
- """
- PreambleCmds.titlereference = r"""
- % titlereference role
- \providecommand*{\DUroletitlereference}[1]{\textsl{#1}}"""
- PreambleCmds.title = r"""
- % title for topics, admonitions and sidebar
- \providecommand*{\DUtitle}[2][class-arg]{%
- % call \DUtitle#1{#2} if it exists:
- \ifcsname DUtitle#1\endcsname%
- \csname DUtitle#1\endcsname{#2}%
- \else
- \smallskip\noindent\textbf{#2}\smallskip%
- \fi
- }"""
- PreambleCmds.topic = r"""
- % topic (quote with heading)
- \providecommand{\DUtopic}[2][class-arg]{%
- \ifcsname DUtopic#1\endcsname%
- \csname DUtopic#1\endcsname{#2}%
- \else
- \begin{quote}#2\end{quote}
- \fi
- }"""
- PreambleCmds.transition = r"""
- % transition (break, fancybreak, anonymous section)
- \providecommand*{\DUtransition}[1][class-arg]{%
- \hspace*{\fill}\hrulefill\hspace*{\fill}
- \vskip 0.5\baselineskip
- }"""
- class DocumentClass(object):
- """Details of a LaTeX document class."""
- def __init__(self, document_class, with_part=False):
- self.document_class = document_class
- self._with_part = with_part
- self.sections = ['section', 'subsection', 'subsubsection',
- 'paragraph', 'subparagraph']
- if self.document_class in ('book', 'memoir', 'report',
- 'scrbook', 'scrreprt'):
- self.sections.insert(0, 'chapter')
- if self._with_part:
- self.sections.insert(0, 'part')
- def section(self, level):
- """Return the LaTeX section name for section `level`.
- The name depends on the specific document class.
- Level is 1,2,3..., as level 0 is the title.
- """
- if level <= len(self.sections):
- return self.sections[level-1]
- else:
- return self.sections[-1]
- class Table(object):
- """Manage a table while traversing.
- Maybe change to a mixin defining the visit/departs, but then
- class Table internal variables are in the Translator.
- Table style might be
- :standard: horizontal and vertical lines
- :booktabs: only horizontal lines (requires "booktabs" LaTeX package)
- :borderless: no borders around table cells
- :nolines: alias for borderless
- """
- def __init__(self,translator,latex_type,table_style):
- self._translator = translator
- self._latex_type = latex_type
- self._table_style = table_style
- self._open = 0
- # miscellaneous attributes
- self._attrs = {}
- self._col_width = []
- self._rowspan = []
- self.stubs = []
- self._in_thead = 0
- def open(self):
- self._open = 1
- self._col_specs = []
- self.caption = []
- self._attrs = {}
- self._in_head = 0 # maybe context with search
- def close(self):
- self._open = 0
- self._col_specs = None
- self.caption = []
- self._attrs = {}
- self.stubs = []
- def is_open(self):
- return self._open
- def set_table_style(self, table_style):
- if not table_style in ('standard','booktabs','borderless','nolines'):
- return
- self._table_style = table_style
- def get_latex_type(self):
- return self._latex_type
- def set(self,attr,value):
- self._attrs[attr] = value
- def get(self,attr):
- if attr in self._attrs:
- return self._attrs[attr]
- return None
- def get_vertical_bar(self):
- if self._table_style == 'standard':
- return '|'
- return ''
- # horizontal lines are drawn below a row,
- def get_opening(self):
- if self._latex_type == 'longtable':
- # otherwise longtable might move before paragraph and subparagraph
- prefix = '\\leavevmode\n'
- else:
- prefix = ''
- prefix += '\setlength{\DUtablewidth}{\linewidth}'
- return '%s\n\\begin{%s}[c]' % (prefix, self._latex_type)
- def get_closing(self):
- line = ''
- if self._table_style == 'booktabs':
- line = '\\bottomrule\n'
- elif self._table_style == 'standard':
- lines = '\\hline\n'
- return '%s\\end{%s}' % (line,self._latex_type)
- def visit_colspec(self, node):
- self._col_specs.append(node)
- # "stubs" list is an attribute of the tgroup element:
- self.stubs.append(node.attributes.get('stub'))
- def get_colspecs(self):
- """Return column specification for longtable.
- Assumes reST line length being 80 characters.
- Table width is hairy.
- === ===
- ABC DEF
- === ===
- usually gets to narrow, therefore we add 1 (fiddlefactor).
- """
- width = 80
- total_width = 0.0
- # first see if we get too wide.
- for node in self._col_specs:
- colwidth = float(node['colwidth']+1) / width
- total_width += colwidth
- self._col_width = []
- self._rowspan = []
- # donot make it full linewidth
- factor = 0.93
- if total_width > 1.0:
- factor /= total_width
- bar = self.get_vertical_bar()
- latex_table_spec = ''
- for node in self._col_specs:
- colwidth = factor * float(node['colwidth']+1) / width
- self._col_width.append(colwidth+0.005)
- self._rowspan.append(0)
- latex_table_spec += '%sp{%.3f\\DUtablewidth}' % (bar, colwidth+0.005)
- return latex_table_spec+bar
- def get_column_width(self):
- """Return columnwidth for current cell (not multicell)."""
- return '%.2f\\DUtablewidth' % self._col_width[self._cell_in_row-1]
- def get_caption(self):
- if not self.caption:
- return ''
- caption = ''.join(self.caption)
- if 1 == self._translator.thead_depth():
- return r'\caption{%s}\\' '\n' % caption
- return r'\caption[]{%s (... continued)}\\' '\n' % caption
- def need_recurse(self):
- if self._latex_type == 'longtable':
- return 1 == self._translator.thead_depth()
- return 0
- def visit_thead(self):
- self._in_thead += 1
- if self._table_style == 'standard':
- return ['\\hline\n']
- elif self._table_style == 'booktabs':
- return ['\\toprule\n']
- return []
- def depart_thead(self):
- a = []
- #if self._table_style == 'standard':
- # a.append('\\hline\n')
- if self._table_style == 'booktabs':
- a.append('\\midrule\n')
- if self._latex_type == 'longtable':
- if 1 == self._translator.thead_depth():
- a.append('\\endfirsthead\n')
- else:
- a.append('\\endhead\n')
- a.append(r'\multicolumn{%d}{c}' % len(self._col_specs) +
- r'{\hfill ... continued on next page} \\')
- a.append('\n\\endfoot\n\\endlastfoot\n')
- # for longtable one could add firsthead, foot and lastfoot
- self._in_thead -= 1
- return a
- def visit_row(self):
- self._cell_in_row = 0
- def depart_row(self):
- res = [' \\\\\n']
- self._cell_in_row = None # remove cell counter
- for i in range(len(self._rowspan)):
- if (self._rowspan[i]>0):
- self._rowspan[i] -= 1
- if self._table_style == 'standard':
- rowspans = [i+1 for i in range(len(self._rowspan))
- if (self._rowspan[i]<=0)]
- if len(rowspans)==len(self._rowspan):
- res.append('\\hline\n')
- else:
- cline = ''
- rowspans.reverse()
- # TODO merge clines
- while 1:
- try:
- c_start = rowspans.pop()
- except:
- break
- cline += '\\cline{%d-%d}\n' % (c_start,c_start)
- res.append(cline)
- return res
- def set_rowspan(self,cell,value):
- try:
- self._rowspan[cell] = value
- except:
- pass
- def get_rowspan(self,cell):
- try:
- return self._rowspan[cell]
- except:
- return 0
- def get_entry_number(self):
- return self._cell_in_row
- def visit_entry(self):
- self._cell_in_row += 1
- def is_stub_column(self):
- if len(self.stubs) >= self._cell_in_row:
- return self.stubs[self._cell_in_row-1]
- return False
- class LaTeXTranslator(nodes.NodeVisitor):
- # When options are given to the documentclass, latex will pass them
- # to other packages, as done with babel.
- # Dummy settings might be taken from document settings
- # Config setting defaults
- # -----------------------
- # TODO: use mixins for different implementations.
- # list environment for docinfo. else tabularx
- ## use_optionlist_for_docinfo = False # TODO: NOT YET IN USE
- # Use compound enumerations (1.A.1.)
- compound_enumerators = 0
- # If using compound enumerations, include section information.
- section_prefix_for_enumerators = 0
- # This is the character that separates the section ("." subsection ...)
- # prefix from the regular list enumerator.
- section_enumerator_separator = '-'
- # default link color
- hyperlink_color = 'blue'
- # Auxiliary variables
- # -------------------
- has_latex_toc = False # is there a toc in the doc? (needed by minitoc)
- is_toc_list = False # is the current bullet_list a ToC?
- section_level = 0
- # Flags to encode():
- # inside citation reference labels underscores dont need to be escaped
- inside_citation_reference_label = False
- verbatim = False # do not encode
- insert_non_breaking_blanks = False # replace blanks by "~"
- insert_newline = False # add latex newline commands
- literal = False # literal text (block or inline)
- def __init__(self, document):
- nodes.NodeVisitor.__init__(self, document)
- # Reporter
- # ~~~~~~~~
- self.warn = self.document.reporter.warning
- self.error = self.document.reporter.error
- # Settings
- # ~~~~~~~~
- self.settings = settings = document.settings
- self.latex_encoding = self.to_latex_encoding(settings.output_encoding)
- self.use_latex_toc = settings.use_latex_toc
- self.use_latex_docinfo = settings.use_latex_docinfo
- self._use_latex_citations = settings.use_latex_citations
- self.embed_stylesheet = settings.embed_stylesheet
- self._reference_label = settings.reference_label
- self.hyperlink_color = settings.hyperlink_color
- self.compound_enumerators = settings.compound_enumerators
- self.font_encoding = settings.font_encoding
- self.section_prefix_for_enumerators = (
- settings.section_prefix_for_enumerators)
- self.section_enumerator_separator = (
- settings.section_enumerator_separator.replace('_', '\\_'))
- # literal blocks:
- self.literal_block_env = ''
- self.literal_block_options = ''
- if settings.literal_block_env != '':
- (none,
- self.literal_block_env,
- self.literal_block_options,
- none ) = re.split('(\w+)(.*)', settings.literal_block_env)
- elif settings.use_verbatim_when_possible:
- self.literal_block_env = 'verbatim'
- #
- if self.settings.use_bibtex:
- self.bibtex = self.settings.use_bibtex.split(',',1)
- # TODO avoid errors on not declared citations.
- else:
- self.bibtex = None
- # language:
- # (labels, bibliographic_fields, and author_separators)
- self.language = languages.get_language(settings.language_code)
- self.babel = Babel(settings.language_code)
- self.author_separator = self.language.author_separators[0]
- self.d_options = [self.settings.documentoptions,
- self.babel.get_language()]
- self.d_options = ','.join([opt for opt in self.d_options if opt])
- self.d_class = DocumentClass(settings.documentclass,
- settings.use_part_section)
- # graphic package options:
- if self.settings.graphicx_option == '':
- self.graphicx_package = r'\usepackage{graphicx}'
- elif self.settings.graphicx_option.lower() == 'auto':
- self.graphicx_package = PreambleCmds.graphicx_auto
- else:
- self.graphicx_package = (r'\usepackage[%s]{graphicx}' %
- self.settings.graphicx_option)
- # footnotes:
- self.docutils_footnotes = settings.docutils_footnotes
- if settings.use_latex_footnotes:
- self.docutils_footnotes = True
- self.warn('`use_latex_footnotes` is deprecated. '
- 'The setting has been renamed to `docutils_footnotes` '
- 'and the alias will be removed in a future version.')
- self.figure_footnotes = settings.figure_footnotes
- if self.figure_footnotes:
- self.docutils_footnotes = True
- self.warn('The "figure footnotes" workaround/setting is strongly '
- 'deprecated and will be removed in a future version.')
- # Output collection stacks
- # ~~~~~~~~~~~~~~~~~~~~~~~~
- # Document parts
- self.head_prefix = [r'\documentclass[%s]{%s}' %
- (self.d_options, self.settings.documentclass)]
- self.requirements = SortableDict() # made a list in depart_document()
- self.latex_preamble = [settings.latex_preamble]
- self.stylesheet = []
- self.fallbacks = SortableDict() # made a list in depart_document()
- self.pdfsetup = [] # PDF properties (hyperref package)
- self.title = []
- self.subtitle = []
- ## self.body_prefix = ['\\begin{document}\n']
- self.body_pre_docinfo = [] # title data and \maketitle
- self.docinfo = []
- self.dedication = []
- self.abstract = []
- self.body = []
- ## self.body_suffix = ['\\end{document}\n']
- # A heterogenous stack used in conjunction with the tree traversal.
- # Make sure that the pops correspond to the pushes:
- self.context = []
- # Title metadata:
- self.title_labels = []
- self.subtitle_labels = []
- # (if use_latex_docinfo: collects lists of
- # author/organization/contact/address lines)
- self.author_stack = []
- # date (the default supresses the "auto-date" feature of \maketitle)
- self.date = []
- # PDF properties: pdftitle, pdfauthor
- # TODO?: pdfcreator, pdfproducer, pdfsubject, pdfkeywords
- self.pdfinfo = []
- self.pdfauthor = []
- # Stack of section counters so that we don't have to use_latex_toc.
- # This will grow and shrink as processing occurs.
- # Initialized for potential first-level sections.
- self._section_number = [0]
- # The current stack of enumerations so that we can expand
- # them into a compound enumeration.
- self._enumeration_counters = []
- # The maximum number of enumeration counters we've used.
- # If we go beyond this number, we need to create a new
- # counter; otherwise, just reuse an old one.
- self._max_enumeration_counters = 0
- self._bibitems = []
- # object for a table while proccessing.
- self.table_stack = []
- self.active_table = Table(self, 'longtable', settings.table_style)
- # Where to collect the output of visitor methods (default: body)
- self.out = self.body
- self.out_stack = [] # stack of output collectors
- # Process settings
- # ~~~~~~~~~~~~~~~~
- # Static requirements
- # TeX font encoding
- if self.font_encoding:
- encodings = [r'\usepackage[%s]{fontenc}' % self.font_encoding]
- else:
- encodings = [r'%\usepackage[OT1]{fontenc}'] # just a comment
- # Docutils' output-encoding => TeX input encoding:
- if self.latex_encoding != 'ascii':
- encodings.append(r'\usepackage[%s]{inputenc}'
- % self.latex_encoding)
- self.requirements['_static'] = '\n'.join(
- encodings + [
- r'\usepackage{ifthen}',
- # multi-language support (language is in document options)
- '\\usepackage{babel}%s' % self.babel.setup,
- ])
- # page layout with typearea (if there are relevant document options)
- if (settings.documentclass.find('scr') == -1 and
- (self.d_options.find('DIV') != -1 or
- self.d_options.find('BCOR') != -1)):
- self.requirements['typearea'] = r'\usepackage{typearea}'
- # Stylesheets
- # get list of style sheets from settings
- styles = utils.get_stylesheet_list(settings)
- # adapt path if --stylesheet_path is used
- if settings.stylesheet_path and not(self.embed_stylesheet):
- styles = [utils.relative_path(settings._destination, sheet)
- for sheet in styles]
- for sheet in styles:
- (base, ext) = os.path.splitext(sheet)
- is_package = ext in ['.sty', '']
- if self.embed_stylesheet:
- if is_package:
- sheet = base + '.sty' # adapt package name
- # wrap in \makeatletter, \makeatother
- wrapper = PreambleCmds.embedded_package_wrapper
- else:
- wrapper = '%% embedded stylesheet: %s\n%s'
- settings.record_dependencies.add(sheet)
- self.stylesheet.append(wrapper %
- (sheet, io.FileInput(source_path=sheet, encoding='utf-8').read()))
- else: # link to style sheet
- if is_package:
- self.stylesheet.append(r'\usepackage{%s}' % base)
- else:
- self.stylesheet.append(r'\input{%s}' % sheet)
- # PDF setup
- if self.hyperlink_color == '0':
- self.hyperlink_color = 'black'
- self.colorlinks = 'false'
- else:
- self.colorlinks = 'true'
- # LaTeX Toc
- # include all supported sections in toc and PDF bookmarks
- # (or use documentclass-default (as currently))?
- ## if self.use_latex_toc:
- ## self.requirements['tocdepth'] = (r'\setcounter{tocdepth}{%d}' %
- ## len(self.d_class.sections))
- # LaTeX section numbering
- if not self.settings.sectnum_xform: # section numbering by LaTeX:
- # sectnum_depth:
- # None "sectnum" directive without depth arg -> LaTeX default
- # 0 no "sectnum" directive -> no section numbers
- # else value of the "depth" argument: translate to LaTeX level
- # -1 part (0 with "article" document class)
- # 0 chapter (missing in "article" document class)
- # 1 section
- # 2 subsection
- # 3 subsubsection
- # 4 paragraph
- # 5 subparagraph
- if settings.sectnum_depth is not None:
- # limit to supported levels
- sectnum_depth = min(settings.sectnum_depth,
- len(self.d_class.sections))
- # adjust to document class and use_part_section settings
- if 'chapter' in self.d_class.sections:
- sectnum_depth -= 1
- if self.d_class.sections[0] == 'part':
- sectnum_depth -= 1
- self.requirements['sectnum_depth'] = (
- r'\setcounter{secnumdepth}{%d}' % sectnum_depth)
- # start with specified number:
- if (hasattr(settings, 'sectnum_start') and
- settings.sectnum_start != 1):
- self.requirements['sectnum_start'] = (
- r'\setcounter{%s}{%d}' % (self.d_class.sections[0],
- settings.sectnum_start-1))
- # currently ignored (configure in a stylesheet):
- ## settings.sectnum_prefix
- ## settings.sectnum_suffix
- # Auxiliary Methods
- # -----------------
- def to_latex_encoding(self,docutils_encoding):
- """Translate docutils encoding name into LaTeX's.
- Default method is remove "-" and "_" chars from docutils_encoding.
- """
- tr = { 'iso-8859-1': 'latin1', # west european
- 'iso-8859-2': 'latin2', # east european
- 'iso-8859-3': 'latin3', # esperanto, maltese
- 'iso-8859-4': 'latin4', # north european, scandinavian, baltic
- 'iso-8859-5': 'iso88595', # cyrillic (ISO)
- 'iso-8859-9': 'latin5', # turkish
- 'iso-8859-15': 'latin9', # latin9, update to latin1.
- 'mac_cyrillic': 'maccyr', # cyrillic (on Mac)
- 'windows-1251': 'cp1251', # cyrillic (on Windows)
- 'koi8-r': 'koi8-r', # cyrillic (Russian)
- 'koi8-u': 'koi8-u', # cyrillic (Ukrainian)
- 'windows-1250': 'cp1250', #
- 'windows-1252': 'cp1252', #
- 'us-ascii': 'ascii', # ASCII (US)
- # unmatched encodings
- #'': 'applemac',
- #'': 'ansinew', # windows 3.1 ansi
- #'': 'ascii', # ASCII encoding for the range 32--127.
- #'': 'cp437', # dos latin us
- #'': 'cp850', # dos latin 1
- #'': 'cp852', # dos latin 2
- #'': 'decmulti',
- #'': 'latin10',
- #'iso-8859-6': '' # arabic
- #'iso-8859-7': '' # greek
- #'iso-8859-8': '' # hebrew
- #'iso-8859-10': '' # latin6, more complete iso-8859-4
- }
- encoding = docutils_encoding.lower()
- if encoding in tr:
- return tr[encoding]
- # convert: latin-1, latin_1, utf-8 and similar things
- encoding = encoding.replace('_', '').replace('-', '')
- # strip the error handler
- return encoding.split(':')[0]
- def language_label(self, docutil_label):
- return self.language.labels[docutil_label]
- def ensure_math(self, text):
- if not hasattr(self, 'ensure_math_re'):
- chars = { # lnot,pm,twosuperior,threesuperior,mu,onesuperior,times,div
- 'latin1' : '\xac\xb1\xb2\xb3\xb5\xb9\xd7\xf7' , # ¬±²³µ¹×÷
- # TODO?: use texcomp instead.
- }
- self.ensure_math_re = re.compile('([%s])' % chars['latin1'])
- text = self.ensure_math_re.sub(r'\\ensuremath{\1}', text)
- return text
- def encode(self, text):
- """Return text with 'problematic' characters escaped.
- Escape the ten special printing characters ``# $ % & ~ _ ^ \ { }``,
- square brackets ``[ ]``, double quotes and (in OT1) ``< | >``.
- Separate ``-`` (and more in literal text) to prevent input ligatures.
- Translate non-supported Unicode characters.
- """
- if self.verbatim:
- return text
- # Separate compound characters, e.g. '--' to '-{}-'.
- separate_chars = '-'
- # In monospace-font, we also separate ',,', '``' and "''" and some
- # other characters which can't occur in non-literal text.
- if self.literal:
- separate_chars += ',`\'"<>'
- # LaTeX encoding maps:
- special_chars = {
- ord('#'): ur'\#',
- ord('$'): ur'\$',
- ord('%'): ur'\%',
- ord('&'): ur'\&',
- ord('~'): ur'\textasciitilde{}',
- ord('_'): ur'\_',
- ord('^'): ur'\textasciicircum{}',
- ord('\\'): ur'\textbackslash{}',
- ord('{'): ur'\{',
- ord('}'): ur'\}',
- # Square brackets are ordinary chars and cannot be escaped with '\',
- # so we put them in a group '{[}'. (Alternative: ensure that all
- # macros with optional arguments are terminated with {} and text
- # inside any optional argument is put in a group ``[{text}]``).
- # Commands with optional args inside an optional arg must be put
- # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
- ord('['): ur'{[}',
- ord(']'): ur'{]}'
- }
- # Unicode chars that are not recognized by LaTeX's utf8 encoding
- unsupported_unicode_chars = {
- 0x00A0: ur'~', # NO-BREAK SPACE
- 0x00AD: ur'\-', # SOFT HYPHEN
- #
- 0x2011: ur'\hbox{-}', # NON-BREAKING HYPHEN
- 0x21d4: ur'$\Leftrightarrow$',
- # Docutils footnote symbols:
- 0x2660: ur'$\spadesuit$',
- 0x2663: ur'$\clubsuit$',
- }
- # Unicode chars that are recognized by LaTeX's utf8 encoding
- unicode_chars = {
- 0x200C: ur'\textcompwordmark', # ZERO WIDTH NON-JOINER
- 0x2013: ur'\textendash{}',
- 0x2014: ur'\textemdash{}',
- 0x2018: ur'\textquoteleft{}',
- 0x2019: ur'\textquoteright{}',
- 0x201A: ur'\quotesinglbase{}', # SINGLE LOW-9 QUOTATION MARK
- 0x201C: ur'\textquotedblleft{}',
- 0x201D: ur'\textquotedblright{}',
- 0x201E: ur'\quotedblbase{}', # DOUBLE LOW-9 QUOTATION MARK
- 0x2030: ur'\textperthousand{}', # PER MILLE SIGN
- 0x2031: ur'\textpertenthousand{}', # PER TEN THOUSAND SIGN
- 0x2039: ur'\guilsinglleft{}',
- 0x203A: ur'\guilsinglright{}',
- 0x2423: ur'\textvisiblespace{}', # OPEN BOX
- 0x2020: ur'\dag{}',
- 0x2021: ur'\ddag{}',
- 0x2026: ur'\dots{}',
- 0x2122: ur'\texttrademark{}',
- }
- # Unicode chars that require a feature/package to render
- pifont_chars = {
- 0x2665: ur'\ding{170}', # black heartsuit
- 0x2666: ur'\ding{169}', # black diamondsuit
- }
- # recognized with 'utf8', if textcomp is loaded
- textcomp_chars = {
- # Latin-1 Supplement
- 0x00a2: ur'\textcent{}', # ¢ CENT SIGN
- 0x00a4: ur'\textcurrency{}', # ¤ CURRENCY SYMBOL
- 0x00a5: ur'\textyen{}', # ¥ YEN SIGN
- 0x00a6: ur'\textbrokenbar{}', # ¦ BROKEN BAR
- 0x00a7: ur'\textsection{}', # § SECTION SIGN
- 0x00a8: ur'\textasciidieresis{}', # ¨ DIAERESIS
- 0x00a9: ur'\textcopyright{}', # © COPYRIGHT SIGN
- 0x00aa: ur'\textordfeminine{}', # ª FEMININE ORDINAL INDICATOR
- 0x00ac: ur'\textlnot{}', # ¬ NOT SIGN
- 0x00ae: ur'\textregistered{}', # ® REGISTERED SIGN
- 0x00af: ur'\textasciimacron{}', # ¯ MACRON
- 0x00b0: ur'\textdegree{}', # ° DEGREE SIGN
- 0x00b1: ur'\textpm{}', # ± PLUS-MINUS SIGN
- 0x00b2: ur'\texttwosuperior{}', # ² SUPERSCRIPT TWO
- 0x00b3: ur'\textthreesuperior{}', # ³ SUPERSCRIPT THREE
- 0x00b4: ur'\textasciiacute{}', # ´ ACUTE ACCENT
- 0x00b5: ur'\textmu{}', # µ MICRO SIGN
- 0x00b6: ur'\textparagraph{}', # ¶ PILCROW SIGN # not equal to \textpilcrow
- 0x00b9: ur'\textonesuperior{}', # ¹ SUPERSCRIPT ONE
- 0x00ba: ur'\textordmasculine{}', # º MASCULINE ORDINAL INDICATOR
- 0x00bc: ur'\textonequarter{}', # 1/4 FRACTION
- 0x00bd: ur'\textonehalf{}', # 1/2 FRACTION
- 0x00be: ur'\textthreequarters{}', # 3/4 FRACTION
- 0x00d7: ur'\texttimes{}', # × MULTIPLICATION SIGN
- 0x00f7: ur'\textdiv{}', # ÷ DIVISION SIGN
- #
- 0x0192: ur'\textflorin{}', # LATIN SMALL LETTER F WITH HOOK
- 0x02b9: ur'\textasciiacute{}', # MODIFIER LETTER PRIME
- 0x02ba: ur'\textacutedbl{}', # MODIFIER LETTER DOUBLE PRIME
- 0x2016: ur'\textbardbl{}', # DOUBLE VERTICAL LINE
- 0x2022: ur'\textbullet{}', # BULLET
- 0x2032: ur'\textasciiacute{}', # PRIME
- 0x2033: ur'\textacutedbl{}', # DOUBLE PRIME
- 0x2035: ur'\textasciigrave{}', # REVERSED PRIME
- 0x2036: ur'\textgravedbl{}', # REVERSED DOUBLE PRIME
- 0x203b: ur'\textreferencemark{}', # REFERENCE MARK
- 0x203d: ur'\textinterrobang{}', # INTERROBANG
- 0x2044: ur'\textfractionsolidus{}', # FRACTION SLASH
- 0x2045: ur'\textlquil…
Large files files are truncated, but you can click here to view the full file