This repository has been archived by the owner on Jan 13, 2024. It is now read-only.
/
sphinx_mathdef_extension.py
471 lines (404 loc) · 15.7 KB
/
sphinx_mathdef_extension.py
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# -*- coding: utf-8 -*-
"""
@file
@brief Defines a sphinx extension to give a title to a math,
inspired from `math.py <https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/math.py>`_.
.. versionadded:: 1.4
"""
import sys
import os
from docutils import nodes
from docutils.parsers.rst import directives
import sphinx
from sphinx.locale import _
from sphinx.environment import NoUri
from docutils.parsers.rst import Directive
from docutils.parsers.rst.directives.admonitions import BaseAdmonition
from docutils.statemachine import StringList
from sphinx.util.nodes import set_source_info, process_index_entry
from sphinx import addnodes
from ..texthelper.texts_language import TITLES
class mathdef_node(nodes.admonition):
"""
defines ``mathdef`` ndoe
"""
pass
class mathdeflist(nodes.General, nodes.Element):
"""
defines ``mathdeflist`` node
"""
pass
class MathDef(BaseAdmonition):
"""
A ``mathdef`` entry, displayed in the form of an admonition.
It takes the following options:
* *title*: a title for the math
* *tag*: a tag to have several categories of math
* *lid* or *label*: a label to refer to
* *index*: to add an entry to the index (comma separated)
Example::
.. mathdef::
:title: title
:tag: definition or theorem or ...
:lid: id (used for further reference)
Description of the math
"""
node_class = mathdef_node
has_content = True
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
option_spec = {
'class': directives.class_option,
'title': directives.unchanged,
'tag': directives.unchanged,
'lid': directives.unchanged,
'label': directives.unchanged,
'index': directives.unchanged,
}
def run(self):
"""
builds the mathdef text
"""
# sett = self.state.document.settings
# language_code = sett.language_code
lineno = self.lineno
env = self.state.document.settings.env if hasattr(
self.state.document.settings, "env") else None
docname = None if env is None else env.docname
if docname is not None:
docname = docname.replace("\\", "/").split("/")[-1]
legend = "{0}:{1}".format(docname, lineno)
else:
legend = ''
if hasattr(env, "settings") and hasattr(env.settings, "mathdef_link_number"):
number_format = env.settings.mathdef_link_number
elif hasattr(self.state.document.settings, "mathdef_link_number"):
number_format = self.state.document.settings.mathdef_link_number
else:
raise ValueError(
"mathdef_link_number is not defined in the configuration")
if not self.options.get('class'):
self.options['class'] = ['admonition-mathdef']
# body
(mathdef,) = super(MathDef, self).run()
if isinstance(mathdef, nodes.system_message):
return [mathdef]
# add a label
lid = self.options.get('lid', self.options.get('label', None))
if lid:
container = nodes.container()
tnl = [".. _{0}:".format(lid), ""]
content = StringList(tnl)
self.state.nested_parse(content, self.content_offset, container)
else:
container = None
# mid
mathtag = self.options.get('tag', '').strip()
if len(mathtag) == 0:
raise ValueError("tag is empty")
if env is not None:
mid = int(env.new_serialno('indexmathe-u-%s' % mathtag)) + 1
else:
mid = -1
# id of the section
first_letter = docname[0] if docname else ""
number = mid
label_number = number_format.format(
number=number, first_letter=first_letter)
# title
title = self.options.get('title', "").strip()
if len(title) > 0:
title = "{0} {1} : {2}".format(mathtag, label_number, title)
else:
raise ValueError("title is empty")
# main node
ttitle = title
title = nodes.title(text=_(title))
if container is not None:
mathdef.insert(0, title)
mathdef.insert(0, container)
else:
mathdef.insert(0, title)
mathdef['mathtag'] = mathtag
mathdef['mathmid'] = mid
mathdef['mathtitle'] = ttitle
set_source_info(self, mathdef)
if env is not None:
targetid = 'indexmathe-%s%s' % (mathtag,
env.new_serialno('indexmathe%s' % mathtag))
ids = [targetid]
targetnode = nodes.target(legend, '', ids=ids[0])
try:
self.state.add_target(targetid, '', targetnode, lineno)
except Exception as e:
raise Exception("Issue in\n File '{0}', line {1}\ntid={2}\ntnode={3}".format(
None if env is None else env.docname, lineno, targetid, targetnode)) from e
# index node
index = self.options.get('index', None)
imposed = ",".join(a for a in [mathtag, ttitle] if a)
if index is None or len(index.strip()) == 0:
index = imposed
else:
index += "," + imposed
if index is not None:
indexnode = addnodes.index()
indexnode['entries'] = ne = []
indexnode['inline'] = False
set_source_info(self, indexnode)
for entry in index.split(","):
ne.extend(process_index_entry(entry, targetid))
else:
indexnode = None
else:
targetnode = None
indexnode = None
return [a for a in [indexnode, targetnode, mathdef] if a is not None]
def process_mathdefs(app, doctree):
"""
collect all mathdefs in the environment
this is not done in the directive itself because it some transformations
must have already been run, e.g. substitutions
"""
env = app.builder.env
if not hasattr(env, 'mathdef_all_mathsext'):
env.mathdef_all_mathsext = []
for node in doctree.traverse(mathdef_node):
try:
targetnode = node.parent[node.parent.index(node) - 1]
if not isinstance(targetnode, nodes.target):
raise IndexError
except IndexError:
targetnode = None
newnode = node.deepcopy()
mathtag = newnode['mathtag']
mathtitle = newnode['mathtitle']
mathmid = newnode['mathmid']
del newnode['ids']
del newnode['mathtag']
env.mathdef_all_mathsext.append({
'docname': env.docname,
'source': node.source or env.doc2path(env.docname),
'lineno': node.line,
'mathdef': newnode,
'target': targetnode,
'mathtag': mathtag,
'mathtitle': mathtitle,
'mathmid': mathmid,
})
class MathDefList(Directive):
"""
A list of all mathdef entries, for a specific tag.
* tag: a tag to have several categories of mathdef
* contents: add a bullet list with links to added blocs
Example::
.. mathdeflist::
:tag: issue
:contents:
"""
has_content = False
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
option_spec = {
'tag': directives.unchanged,
'contents': directives.unchanged,
}
def run(self):
"""
Simply insert an empty mathdeflist node which will be replaced later
when process_mathdef_nodes is called
"""
env = self.state.document.settings.env if hasattr(
self.state.document.settings, "env") else None
tag = self.options.get('tag', '').strip()
contents = self.options.get(
'contents', False) in (True, "True", "true", 1, "1", "", None, "None")
if env is not None:
targetid = 'indexmathelist-%s' % env.new_serialno('indexmathelist')
targetnode = nodes.target('', '', ids=[targetid])
n = mathdeflist('')
n["mathtag"] = tag
n["mathcontents"] = contents
n['docname'] = env.docname if env else "none"
return [targetnode, n]
else:
n = mathdeflist('')
n["mathtag"] = tag
n["mathcontents"] = contents
n['docname'] = env.docname if env else "none"
return [n]
def process_mathdef_nodes(app, doctree, fromdocname):
"""
process_mathdef_nodes
"""
if not app.config['mathdef_include_mathsext']:
for node in doctree.traverse(mathdef_node):
node.parent.remove(node)
# Replace all mathdeflist nodes with a list of the collected mathsext.
# Augment each mathdef with a backlink to the original location.
env = app.builder.env
if hasattr(env, "settings") and hasattr(env.settings, "language_code"):
lang = env.settings.language_code
else:
lang = "en"
orig_entry = TITLES[lang]["original entry"]
mathmes = TITLES[lang]["mathmes"]
if not hasattr(env, 'mathdef_all_mathsext'):
env.mathdef_all_mathsext = []
for ilist, node in enumerate(doctree.traverse(mathdeflist)):
if 'ids' in node:
node['ids'] = []
if not app.config['mathdef_include_mathsext']:
node.replace_self([])
continue
nbmath = 0
content = []
mathtag = node["mathtag"]
add_contents = node["mathcontents"]
mathdocname = node["docname"]
if add_contents:
bullets = nodes.enumerated_list()
content.append(bullets)
double_list = [(info.get('mathtitle', ''), info)
for info in env.mathdef_all_mathsext]
double_list.sort(key=lambda x: x[:1])
for n, mathdef_info_ in enumerate(double_list):
mathdef_info = mathdef_info_[1]
if mathdef_info["mathtag"] != mathtag:
continue
nbmath += 1
para = nodes.paragraph(classes=['mathdef-source'])
if app.config['mathdef_link_only']:
description = _('<<%s>>' % orig_entry)
else:
description = (
_(mathmes) %
(orig_entry, os.path.split(mathdef_info['source'])[-1],
mathdef_info['lineno'])
)
desc1 = description[:description.find('<<')]
desc2 = description[description.find('>>') + 2:]
para += nodes.Text(desc1, desc1)
# Create a reference
newnode = nodes.reference('', '', internal=True)
innernode = nodes.emphasis(
_(orig_entry), _(orig_entry))
try:
newnode['refuri'] = app.builder.get_relative_uri(
fromdocname, mathdef_info['docname'])
try:
newnode['refuri'] += '#' + mathdef_info['target']['refid']
except Exception as e:
raise KeyError("refid in not present in '{0}'".format(
mathdef_info['target'])) from e
except NoUri:
# ignore if no URI can be determined, e.g. for LaTeX output
pass
newnode.append(innernode)
para += newnode
para += nodes.Text(desc2, desc2)
# (Recursively) resolve references in the mathdef content
mathdef_entry = mathdef_info['mathdef']
idss = ["index-mathdef-%d-%d" % (ilist, n)]
# Insert into the mathreflist
if add_contents:
title = mathdef_info['mathtitle']
item = nodes.list_item()
p = nodes.paragraph()
item += p
newnode = nodes.reference('', '', internal=True)
innernode = nodes.paragraph(text=title)
try:
newnode['refuri'] = app.builder.get_relative_uri(
fromdocname, mathdocname)
newnode['refuri'] += '#' + idss[0]
except NoUri:
# ignore if no URI can be determined, e.g. for LaTeX output
pass
newnode.append(innernode)
p += newnode
bullets += item
mathdef_entry["ids"] = idss
env.resolve_references(mathdef_entry, mathdef_info['docname'],
app.builder)
# Insert into the mathdeflist
content.append(mathdef_entry)
content.append(para)
node.replace_self(content)
def purge_mathsext(app, env, docname):
"""
purge_mathsext
"""
if not hasattr(env, 'mathdef_all_mathsext'):
return
env.mathdef_all_mathsext = [mathdef for mathdef in env.mathdef_all_mathsext
if mathdef['docname'] != docname]
def merge_mathdef(app, env, docnames, other):
"""
merge_mathdef
"""
if not hasattr(other, 'mathdef_all_mathsext'):
return
if not hasattr(env, 'mathdef_all_mathsext'):
env.mathdef_all_mathsext = []
env.mathdef_all_mathsext.extend(other.mathdef_all_mathsext)
def visit_mathdef_node(self, node):
"""
visit_mathdef_node
"""
self.visit_admonition(node)
def depart_mathdef_node(self, node):
"""
depart_mathdef_node,
see https://github.com/sphinx-doc/sphinx/blob/master/sphinx/writers/html.py
"""
self.depart_admonition(node)
def visit_mathdeflist_node(self, node):
"""
visit_mathdeflist_node
see https://github.com/sphinx-doc/sphinx/blob/master/sphinx/writers/html.py
"""
self.visit_admonition(node)
def depart_mathdeflist_node(self, node):
"""
depart_mathdef_node
"""
self.depart_admonition(node)
def setup(app):
"""
setup for ``mathdef`` (sphinx)
"""
if hasattr(app, "add_mapping"):
app.add_mapping('mathdef', mathdef_node)
app.add_mapping('mathdeflist', mathdeflist)
app.add_config_value('mathdef_include_mathsext', True, 'html')
app.add_config_value('mathdef_link_only', True, 'html')
app.add_config_value('mathdef_link_number',
"{first_letter}.{number}", 'html')
app.add_node(mathdeflist,
html=(visit_mathdeflist_node, depart_mathdeflist_node),
latex=(visit_mathdeflist_node, depart_mathdeflist_node),
text=(visit_mathdeflist_node, depart_mathdeflist_node),
man=(visit_mathdeflist_node, depart_mathdeflist_node),
texinfo=(visit_mathdeflist_node, depart_mathdeflist_node))
app.add_node(mathdef_node,
html=(visit_mathdef_node, depart_mathdef_node),
latex=(visit_mathdef_node, depart_mathdef_node),
text=(visit_mathdef_node, depart_mathdef_node),
man=(visit_mathdef_node, depart_mathdef_node),
texinfo=(visit_mathdef_node, depart_mathdef_node))
app.add_directive('mathdef', MathDef)
app.add_directive('mathdeflist', MathDefList)
if sys.version_info[0] == 2:
# Sphinx does not accept unicode here
app.connect('doctree-read'.encode("ascii"), process_mathdefs)
app.connect('doctree-resolved'.encode("ascii"), process_mathdef_nodes)
app.connect('env-purge-doc'.encode("ascii"), purge_mathsext)
app.connect('env-merge-info'.encode("ascii"), merge_mathdef)
else:
app.connect('doctree-read', process_mathdefs)
app.connect('doctree-resolved', process_mathdef_nodes)
app.connect('env-purge-doc', purge_mathsext)
app.connect('env-merge-info', merge_mathdef)
return {'version': sphinx.__display_version__, 'parallel_read_safe': True}