Debian Codegraph @

docutils/writers/xetex/__init__.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # :Author: Günter Milde <[email protected]>
3 # :Revision: $Revision: 10196 $
4 # :Date: $Date: 2025-08-07 08:35:37 +0200 (Do, 07. Aug 2025) $
5 # :Copyright: © 2010 Günter Milde.
6 # :License: Released under the terms of the `2-Clause BSD license`_, in short:
7 #
8 # Copying and distribution of this file, with or without modification,
9 # are permitted in any medium without royalty provided the copyright
10 # notice and this notice are preserved.
11 # This file is offered as-is, without any warranty.
12 #
13 # .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
14
15 """
16 XeLaTeX document tree Writer.
17
18 A variant of Docutils' standard 'latex2e' writer producing LaTeX output
19 suited for processing with the Unicode-aware TeX engines
20 LuaTeX and XeTeX.
21 """
22
23 from __future__ import annotations
24
25 __docformat__ = 'reStructuredText'
26
27 from docutils import frontend
28 from docutils.writers import latex2e
29 from docutils.writers.latex2e import PreambleCmds
30
31
32 class Writer(latex2e.Writer):
33 """A writer for Unicode-aware LaTeX variants (XeTeX, LuaTeX)"""
34
35 supported = ('latex', 'tex', 'xetex', 'xelatex', 'luatex', 'lualatex')
36 """Formats this writer supports."""
37
38 default_template = 'xelatex.tex'
39 default_preamble = """\
40 % Linux Libertine (free, wide coverage, not only for Linux)
41 \\setmainfont{Linux Libertine O}
42 \\setsansfont{Linux Biolinum O}
43 \\setmonofont[HyphenChar=None,Scale=MatchLowercase]{DejaVu Sans Mono}"""
44
45 config_section = 'xetex writer'
46 config_section_dependencies = ('writers', 'latex writers')
47
48 # use a copy of the parent spec with some modifications:
49 settings_spec = frontend.filter_settings_spec(
50 latex2e.Writer.settings_spec,
51 # removed settings
52 'font_encoding',
53 # changed settings:
54 template=('Template file. Default: "%s".' % default_template,
55 ['--template'],
56 {'default': default_template, 'metavar': '<file>'}),
57 latex_preamble=('Customization by LaTeX code in the preamble. '
58 'Default: select "Linux Libertine" fonts.',
59 ['--latex-preamble'],
60 {'metavar': '<preamble>',
61 'default': default_preamble}),
62 )
63
64 def __init__(self) -> None:
65 latex2e.Writer.__init__(self)
66 self.settings_defaults.update({'fontencoding': ''}) # use default (TU)
67 self.translator_class = XeLaTeXTranslator
68
69
70 class Babel(latex2e.Babel):
71 """Language specifics for XeTeX.
72
73 Use `polyglossia` instead of `babel` and adapt settings.
74 """
75 language_codes = latex2e.Babel.language_codes.copy()
76 # Additionally supported or differently named languages:
77 language_codes.update({
78 # code Polyglossia-name comment
79 'cop': 'coptic',
80 'de': 'german', # new spelling (de_1996)
81 'de-1901': 'ogerman', # old spelling
82 'dv': 'divehi', # Maldivian
83 'dsb': 'lsorbian',
84 'el-polyton': 'polygreek',
85 'fa': 'farsi',
86 'grc': 'ancientgreek',
87 'ko': 'korean',
88 'hsb': 'usorbian',
89 'sh-Cyrl': 'serbian', # Serbo-Croatian, Cyrillic script
90 'sh-Latn': 'croatian', # Serbo-Croatian, Latin script
91 'sq': 'albanian',
92 'sr': 'serbian', # Cyrillic script (sr-Cyrl)
93 'th': 'thai',
94 'vi': 'vietnamese',
95 # zh-Latn: ??? # Chinese Pinyin
96 })
97 # normalize (downcase) keys
98 language_codes = {k.lower(): v for k, v in language_codes.items()}
99
100 # Languages without Polyglossia support:
101 for key in ('af', # 'afrikaans',
102 'de-AT', # 'naustrian',
103 'de-AT-1901', # 'austrian',
104 # TODO: use variant=... for English variants
105 'en-CA', # 'canadian',
106 'en-GB', # 'british',
107 'en-NZ', # 'newzealand',
108 'en-US', # 'american',
109 'fr-CA', # 'canadien',
110 'grc-ibycus', # 'ibycus', (Greek Ibycus encoding)
111 'sr-Latn', # 'serbian script=latin'
112 ):
113 del language_codes[key.lower()]
114
115 warn_msg = 'Language "%s" not supported by LaTeX (polyglossia)'
116
117 def __init__(self, language_code, reporter) -> None:
118 self.language_code = language_code
119 self.reporter = reporter
120 self.language = self.language_name(language_code)
121 self.otherlanguages = {}
122 self.warn_msg = 'Language "%s" not supported by Polyglossia.'
123 self.quote_index = 0
124 self.quotes = ('"', '"')
125 # language dependent configuration:
126 # double quotes are "active" in some languages (e.g. German).
127 self.literal_double_quote = '"' # TODO: use \textquotedbl ?
128
129 def __call__(self):
130 setup = [r'\usepackage{polyglossia}',
131 r'\setdefaultlanguage{%s}' % self.language]
132 if self.otherlanguages:
133 setup.append(r'\setotherlanguages{%s}' %
134 ','.join(sorted(self.otherlanguages.keys())))
135 return '\n'.join(setup)
136
137
138 class XeLaTeXTranslator(latex2e.LaTeXTranslator):
139 """
140 Generate code for LaTeX using Unicode fonts (XeLaTex or LuaLaTeX).
141
142 See the docstring of docutils.writers._html_base.HTMLTranslator for
143 notes on and examples of safe subclassing.
144 """
145
146 def __init__(self, document) -> None:
147 self.is_xetex = True # typeset with XeTeX or LuaTeX engine
148 latex2e.LaTeXTranslator.__init__(self, document, Babel)
149 if self.latex_encoding == 'utf8':
150 self.requirements.pop('_inputenc', None)
151 else:
152 self.requirements['_inputenc'] = (r'\XeTeXinputencoding %s '
153 % self.latex_encoding)
154
155 def to_latex_length(self, length_str: str, node=None) -> str:
156 """Convert "measure" `length_str` to LaTeX length specification.
157
158 XeTeX does not know the length unit px.
159 Use ``\\pdfpxdimen``, the macro holding the value of 1 px in pdfTeX.
160 This way, configuring works the same for pdftex and xetex.
161 """
162 length_str = super().to_latex_length(length_str, node)
163 if length_str.endswith('px'):
164 if not self.fallback_stylesheet:
165 self.fallbacks['_providelength'] = PreambleCmds.providelength
166 self.fallbacks['px'] = '\n\\DUprovidelength{\\pdfpxdimen}{1bp}'
167 return length_str.replace('px', '\\pdfpxdimen')
168 return length_str