-
Notifications
You must be signed in to change notification settings - Fork 0
/
rst2latex_mod
executable file
·273 lines (233 loc) · 9.29 KB
/
rst2latex_mod
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/python3
# $Id: rst2latex.py 5905 2009-04-16 12:04:49Z milde $
# Author: David Goodger <[email protected]>
# Copyright: This module has been placed in the public domain.
"""
A minimal front end to the Docutils Publisher, producing LaTeX.
"""
try:
import locale
locale.setlocale(locale.LC_ALL, "")
except:
pass
from docutils.writers.latex2e import *
from docutils.parsers.rst.directives.images import Image, Figure
from docutils.parsers.rst.directives.body import *
from docutils import nodes
from docutils.parsers.rst import directives, roles
from docutils.core import publish_cmdline
from docutils.parsers.rst.roles import set_classes
from docutils.utils.code_analyzer import Lexer, LexerError, NumberLines
description = (
"Generates LaTeX documents from standalone reStructuredText "
"sources. "
"Reads from <source> (default is stdin) and writes to "
"<destination> (default is stdout). See "
"<http://docutils.sourceforge.net/docs/user/latex.html> for "
"the full reference."
)
# Notes
# =====
#
# - For the `hl` role to work, the following lines must be placed in the preamble:
#
# ```
# \usepackage{color} % xcolor also works
# \usepackage{soul}
# \soulregister\color7
# ```
class hl(nodes.Special, nodes.Inline, nodes.PreBibliographic, nodes.FixedTextElement):
pass
def hl_role(role, rawtext, text, lineno, inliner, options={}, content={}):
if "fg" not in options and "bg" not in options:
msg = inliner.reporter.error(
f"No foreground or background color specified for {role} role.\n"
'The "hl" role cannot be used directly.\n'
'Instead, use the "role" directive to create a new role with '
"associated foreground and/or background colors.",
line=lineno,
)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
roles.set_classes(options)
node = hl(rawtext, utils.unescape(text, True), **options)
node.source, node.line = inliner.reporter.get_source_and_line(lineno)
return [node], []
class mint(nodes.Special, nodes.Inline, nodes.PreBibliographic, nodes.FixedTextElement):
pass
hl_role.options = {
"fg": directives.unchanged,
"bg": directives.unchanged,
"prefix": directives.unchanged,
}
roles.register_canonical_role("hl", hl_role)
def mint_role(role, rawtext, text, lineno, inliner, options={}, content={}):
if "language" not in options:
msg = inliner.reporter.error(
f"No language specified for {role} role.\n"
'The "mint" role cannot be used directly.\n'
'Instead, use the "role" directive to create a new role with '
"associated language for syntax highlighting.",
line=lineno,
)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
roles.set_classes(options)
node = mint(rawtext, utils.unescape(text, True), **options)
node.source, node.line = inliner.reporter.get_source_and_line(lineno)
return [node], []
mint_role.options = {"language": directives.unchanged}
roles.register_canonical_role("mint", mint_role)
# inherit from Figure and extend its run method
class FigureLabel(Figure):
option_spec = Figure.option_spec.copy()
has_content = True
def run(self):
node = super().run()
if isinstance(node[0], nodes.system_message):
return node
figure_node = node[0]
# elevate the image node's 'ids' attribute to the figure node
figure_node["ids"] = figure_node.children[0]["ids"]
figure_node.children[0]["ids"] = []
# raise Exception
return [figure_node] + node[1:]
directives.register_directive("fig", FigureLabel)
class LaTeXTranslator_Mod(LaTeXTranslator):
# output label in depart_figure, instead of visit_figure. this way the label comes after
# the caption, which is required for refs to work.
def visit_figure(self, node):
self.requirements["float_settings"] = PreambleCmds.float_settings
alignment = node.attributes.get("align", "center")
if alignment != "center":
self.out.append('\n\\begin{figure} %% align = "%s"\n' % alignment)
else:
self.out.append("\n\\begin{figure}\n")
def depart_figure(self, node):
if node.get("ids"):
self.out += self.ids_to_labels(node) + ["\n"]
super().depart_figure(node)
def visit_hl(self, node):
fg = node.get("fg", "")
bg = node.get("bg", "")
prefix = node.get("prefix", "")
self.out += "{"
if bg:
self.out += "\\sethlcolor{" + bg + "}\\hl{"
if fg:
self.out += "\\color{" + fg + "}"
if prefix:
self.out += f"{prefix} "
def depart_hl(self, node):
bg = node.get("bg", "")
if bg:
self.out += "}"
self.out += "}"
def visit_mint(self, node):
language = node.get("language", "")
self.out += "\\mintinline[fontsize=\\normalsize]{" + language + "}{"
self.verbatim = True
def depart_mint(self, node):
self.verbatim = False
self.out += "}"
def visit_literal_block(self, node):
"""Render a literal block.
Corresponding rST elements: literal block, parsed-literal, code.
"""
packages = {
"lstlisting": r"\usepackage{listings}"
"\n"
r"\lstset{xleftmargin=\leftmargin}",
"listing": r"\usepackage{moreverb}",
"minted": r"\usepackage{minted}",
"Verbatim": r"\usepackage{fancyvrb}",
"verbatimtab": r"\usepackage{moreverb}",
}
environment = self.literal_block_env
_in_table = self.active_table.is_open()
# TODO: fails if normal text precedes the literal block.
# Check parent node instead?
_autowidth_table = _in_table and self.active_table.colwidths_auto
_plaintext = self.is_plaintext(node)
_listings = (environment == "lstlisting") and _plaintext
_minted = (environment == "minted") and _plaintext
# Labels and classes:
if node.get("ids"):
self.out += ["\n"] + self.ids_to_labels(node)
self.duclass_open(node)
if (
not _plaintext
and "code" in node["classes"]
and self.settings.syntax_highlight != "none"
):
self.requirements["color"] = PreambleCmds.color
self.fallbacks["code"] = PreambleCmds.highlight_rules
# Wrapper?
if _in_table and _plaintext and not _autowidth_table:
# minipage prevents extra vertical space with alltt
# and verbatim-like environments
self.fallbacks["ttem"] = "\n".join(
[
"",
r"% character width in monospaced font",
r"\newlength{\ttemwidth}",
r"\settowidth{\ttemwidth}{\ttfamily M}",
]
)
self.out.append(
"\\begin{minipage}{%d\\ttemwidth}\n"
% (max(len(line) for line in node.astext().split("\n")))
)
self.context.append("\n\\end{minipage}\n")
elif not _in_table and not _listings and not _minted:
# wrap in quote to set off vertically and indent
self.out.append("\\begin{quote}\n")
self.context.append("\n\\end{quote}\n")
else:
self.context.append("\n")
# Use verbatim-like environment, if defined and possible
if (
environment
and _plaintext
and (not _autowidth_table or _listings or _minted)
):
try:
self.requirements["literal_block"] = packages[environment]
except KeyError:
pass
self.verbatim = True
if _in_table and _listings:
self.out.append("\lstset{xleftmargin=0pt}\n")
if _minted:
language = node.get("classes")[1]
self.out.append(
"\\begin{%s}{%s}%s\n"
% (environment, language, self.literal_block_options)
)
else:
self.out.append(
"\\begin{%s}%s\n" % (environment, self.literal_block_options)
)
self.context.append("\n\\end{%s}" % environment)
elif _plaintext and not _autowidth_table:
self.alltt = True
self.requirements["alltt"] = r"\usepackage{alltt}"
self.out.append("\\begin{alltt}\n")
self.context.append("\n\\end{alltt}")
else:
self.literal = True
self.insert_newline = True
self.insert_non_breaking_blanks = True
# \raggedright ensures leading blanks are respected but
# leads to additional leading vspace if the first line
# of the block is overfull :-(
self.out.append("\\ttfamily\\raggedright\n")
self.context.append("")
def depart_literal_block(self, node):
super().depart_literal_block(node)
end_paragraph = node.attributes.get("endpar", "false")
if end_paragraph == "false":
self.out.append("%")
writer = Writer()
writer.translator_class = LaTeXTranslator_Mod
publish_cmdline(writer=writer, description=description)