/
docutils_renderer.py
1104 lines (952 loc) · 42.5 KB
/
docutils_renderer.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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from contextlib import contextmanager
import copy
from itertools import chain
from os.path import splitext
from pathlib import Path
import re
import sys
from typing import List, Optional
from urllib.parse import urlparse, unquote
from docutils import nodes
from docutils.frontend import OptionParser
from docutils.languages import get_language
from docutils.parsers.rst import directives, Directive, DirectiveError, roles
from docutils.parsers.rst import Parser as RSTParser
from docutils.parsers.rst.directives.misc import Include
from docutils.parsers.rst.states import RSTStateMachine, Body, Inliner
from docutils.statemachine import StringList
from docutils.utils import new_document, Reporter
import yaml
from mistletoe import block_token, span_token
from mistletoe.base_renderer import BaseRenderer
from myst_parser import span_tokens as myst_span_tokens
from myst_parser import block_tokens as myst_block_tokens
from myst_parser.parse_directives import parse_directive_text, DirectiveParsingError
from myst_parser.utils import escape_url
class DocutilsRenderer(BaseRenderer):
"""A mistletoe renderer to populate (in-place) a `docutils.document` AST.
Note this renderer has no dependencies on Sphinx.
"""
def __init__(
self,
document: Optional[nodes.document] = None,
current_node: Optional[nodes.Element] = None,
config: Optional[dict] = None,
):
"""Initialise the renderer.
:param document: The document to populate (or create a new one if None)
:param current_node: The root node from which to begin populating
(default is document, or should be an ancestor of document)
:param config: contains configuration specific to the rendering process
"""
self.config = config or {}
self.document = document or self.new_document() # type: nodes.document
self.reporter = self.document.reporter # type: Reporter
self.current_node = current_node or self.document # type: nodes.Element
self.language_module = self.document.settings.language_code # type: str
get_language(self.language_module)
self._level_to_elem = {0: self.document}
_span_tokens = self._tokens_from_module(myst_span_tokens)
_block_tokens = self._tokens_from_module(myst_block_tokens)
super().__init__(*chain(_block_tokens, _span_tokens))
span_token._token_types.value = _span_tokens
block_token._token_types.value = _block_tokens
def new_document(self, source_path="notset") -> nodes.document:
settings = OptionParser(components=(RSTParser,)).get_default_values()
return new_document(source_path, settings=settings)
def add_line_and_source_path(self, node, token):
try:
node.line = token.range[0] + 1
except AttributeError:
pass
node.source = self.document["source"]
def nested_render_text(self, text: str, lineno: int):
"""Render unparsed text."""
token = myst_block_tokens.Document(
text, start_line=lineno, inc_front_matter=False
)
self.render(token)
def render_children(self, token):
for child in token.children:
self.render(child)
@contextmanager
def current_node_context(self, node, append: bool = False):
"""Context manager for temporarily setting the current node."""
if append:
self.current_node.append(node)
current_node = self.current_node
self.current_node = node
yield
self.current_node = current_node
def render_document(self, token):
# TODO deal with footnotes
self.footnotes.update(token.footnotes)
self.render_children(token)
return self.document
def render_front_matter(self, token):
"""Pass document front matter data
For RST, all field lists are captured by
``docutils.docutils.parsers.rst.states.Body.field_marker``,
then, if one occurs at the document, it is transformed by
`docutils.docutils.transforms.frontmatter.DocInfo`, and finally
this is intercepted by sphinx and added to the env in
`sphinx.environment.collectors.metadata.MetadataCollector.process_doc`
So technically the values should be parsed to AST, but this is redundant,
since `process_doc` just converts them back to text.
"""
try:
data = yaml.safe_load(token.content) or {}
except (yaml.parser.ParserError, yaml.scanner.ScannerError) as error:
msg_node = self.reporter.error(
"Front matter block:\n" + str(error), line=token.range[0]
)
msg_node += nodes.literal_block(token.content, token.content)
self.current_node += [msg_node]
return
docinfo = dict_to_docinfo(data)
self.current_node.append(docinfo)
def render_paragraph(self, token):
if len(token.children) == 1 and isinstance(
token.children[0], myst_span_tokens.Target
):
# promote the target to block level
return self.render_target(token.children[0])
para = nodes.paragraph("")
self.add_line_and_source_path(para, token)
with self.current_node_context(para, append=True):
self.render_children(token)
def render_line_comment(self, token):
self.current_node.append(nodes.comment(token.content, token.content))
def render_target(self, token):
text = token.children[0].content
name = nodes.fully_normalize_name(text)
target = nodes.target(text)
target["names"].append(name)
self.document.note_explicit_target(target, self.current_node)
self.current_node.append(target)
def render_raw_text(self, token):
text = token.content
self.current_node.append(nodes.Text(text, text))
def render_escape_sequence(self, token):
text = token.children[0].content
self.current_node.append(nodes.Text(text, text))
def render_line_break(self, token):
if token.soft:
self.current_node.append(nodes.Text("\n"))
else:
self.current_node.append(nodes.raw("", "<br />\n", format="html"))
def render_strong(self, token):
node = nodes.strong()
with self.current_node_context(node, append=True):
self.render_children(token)
def render_emphasis(self, token):
node = nodes.emphasis()
with self.current_node_context(node, append=True):
self.render_children(token)
def render_quote(self, token):
quote = nodes.block_quote()
self.add_line_and_source_path(quote, token)
with self.current_node_context(quote, append=True):
self.render_children(token)
def render_strikethrough(self, token):
# TODO there is no existing node/role for this
raise NotImplementedError
def render_thematic_break(self, token):
node = nodes.transition()
self.add_line_and_source_path(node, token)
self.current_node.append(node)
def render_block_break(self, token):
block_break = nodes.comment(token.content, token.content)
block_break["classes"] += ["block_break"]
self.current_node.append(block_break)
def render_math(self, token):
if token.content.startswith("$$"):
content = token.content[2:-2]
node = nodes.math_block(content, content, nowrap=False, number=None)
else:
content = token.content[1:-1]
node = nodes.math(content, content)
self.current_node.append(node)
def render_block_code(self, token):
# this should never have a language, since it is just indented text, however,
# creating a literal_block with no language will raise a warning in sphinx
text = token.children[0].content
language = token.language or "none"
node = nodes.literal_block(text, text, language=language)
self.add_line_and_source_path(node, token)
self.current_node.append(node)
def render_code_fence(self, token):
if token.language.startswith("{") and token.language.endswith("}"):
return self.render_directive(token)
text = token.children[0].content
language = token.language
if not language:
try:
sphinx_env = self.document.settings.env
language = sphinx_env.temp_data.get(
"highlight_language", sphinx_env.config.highlight_language
)
except AttributeError:
pass
if not language:
language = self.config.get("highlight_language", "")
node = nodes.literal_block(text, text, language=language)
self.add_line_and_source_path(node, token)
self.current_node.append(node)
def render_inline_code(self, token):
text = token.children[0].content
node = nodes.literal(text, text)
self.current_node.append(node)
def _is_section_level(self, level, section):
return self._level_to_elem.get(level, None) == section
def _add_section(self, section, level):
parent_level = max(
section_level
for section_level in self._level_to_elem
if level > section_level
)
parent = self._level_to_elem[parent_level]
parent.append(section)
self._level_to_elem[level] = section
# Prune level to limit
self._level_to_elem = dict(
(section_level, section)
for section_level, section in self._level_to_elem.items()
if section_level <= level
)
def render_heading(self, token):
# Test if we're replacing a section level first
if isinstance(self.current_node, nodes.section):
if self._is_section_level(token.level, self.current_node):
self.current_node = self.current_node.parent
title_node = nodes.title()
self.add_line_and_source_path(title_node, token)
new_section = nodes.section()
self.add_line_and_source_path(new_section, token)
new_section.append(title_node)
self._add_section(new_section, token.level)
self.current_node = title_node
self.render_children(token)
assert isinstance(self.current_node, nodes.title)
text = self.current_node.astext()
# if self.translate_section_name:
# text = self.translate_section_name(text)
name = nodes.fully_normalize_name(text)
section = self.current_node.parent
section["names"].append(name)
self.document.note_implicit_target(section, section)
self.current_node = section
def handle_cross_reference(self, token, destination):
# TODO use the docutils error reporting mechanisms, rather than raising
if not self.config.get("ignore_missing_refs", False):
raise NotImplementedError(
"reference not found in current document: {}\n{}".format(
destination, token
)
)
def render_link(self, token):
ref_node = nodes.reference()
# Check destination is supported for cross-linking and remove extension
# TODO escape urls?
destination = token.target
_, ext = splitext(destination)
# TODO check for other supported extensions, such as those specified in
# the Sphinx conf.py file but how to access this information?
# TODO this should probably only remove the extension for local paths,
# i.e. not uri's starting with http or other external prefix.
# if ext.replace('.', '') in self.supported:
# destination = destination.replace(ext, '')
ref_node["refuri"] = destination
# TODO get line of Link token (requires upstream mistletoe improvements)
# ref_node.line = self._get_line(token)
if token.title:
ref_node["title"] = token.title
next_node = ref_node
url_check = urlparse(destination)
# If there's not a url scheme (e.g. 'https' for 'https:...' links),
# or there is a scheme but it's not in the list of known_url_schemes,
# then assume it's a cross-reference
known_url_schemes = self.config.get("known_url_schemes", None)
if known_url_schemes:
scheme_known = url_check.scheme in known_url_schemes
else:
scheme_known = bool(url_check.scheme)
if not url_check.fragment and not scheme_known:
self.handle_cross_reference(token, destination)
else:
self.current_node.append(next_node)
with self.current_node_context(ref_node):
self.render_children(token)
def render_image(self, token):
img_node = nodes.image()
img_node["uri"] = token.src
img_node["alt"] = ""
if token.children and isinstance(token.children[0], myst_span_tokens.RawText):
img_node["alt"] = token.children[0].content
token.children[0].content = ""
self.current_node.append(img_node)
# TODO how should non-raw alternative text be handled?
# with self.set_current_node(img_node):
# self.render_children(token)
def render_list(self, token):
list_node = None
if token.start is not None:
list_node = nodes.enumerated_list()
# TODO deal with token.start?
# TODO support numerals/letters for lists
# (see https://stackoverflow.com/a/48372856/5033292)
# See docutils/docutils/parsers/rst/states.py:Body.enumerator
# list_node['enumtype'] = 'arabic', 'loweralpha', 'upperroman', etc.
# list_node['start']
# list_node['prefix']
# list_node['suffix']
else:
list_node = nodes.bullet_list()
# TODO deal with token.loose?
# TODO list range
# list_node.line = token.range[0]
self.current_node.append(list_node)
with self.current_node_context(list_node):
self.render_children(token)
def render_list_item(self, token: myst_block_tokens.ListItem):
item_node = nodes.list_item()
# TODO list item range
# node.line = token.range[0]
self.current_node.append(item_node)
with self.current_node_context(item_node):
self.render_children(token)
def render_table(self, token):
table = nodes.table()
table["classes"] += ["colwidths-auto"]
# TODO column alignment
maxcols = max(len(c.children) for c in token.children)
# TODO are colwidths actually required
colwidths = [100 / maxcols] * maxcols
tgroup = nodes.tgroup(cols=len(colwidths))
table += tgroup
for colwidth in colwidths:
colspec = nodes.colspec(colwidth=colwidth)
tgroup += colspec
if hasattr(token, "header"):
thead = nodes.thead()
tgroup += thead
with self.current_node_context(thead):
self.render_table_row(token.header)
tbody = nodes.tbody()
tgroup += tbody
with self.current_node_context(tbody):
self.render_children(token)
self.current_node.append(table)
def render_table_row(self, token):
row = nodes.row()
with self.current_node_context(row, append=True):
self.render_children(token)
def render_table_cell(self, token):
entry = nodes.entry()
with self.current_node_context(entry, append=True):
self.render_children(token)
def render_auto_link(self, token):
if token.mailto:
refuri = "mailto:{}".format(token.target)
else:
refuri = escape_url(token.target)
ref_node = nodes.reference(token.target, token.target, refuri=refuri)
self.current_node.append(ref_node)
def render_html_span(self, token):
self.current_node.append(nodes.raw("", token.content, format="html"))
def render_html_block(self, token):
self.current_node.append(nodes.raw("", token.content, format="html"))
def render_role(self, token):
content = token.children[0].content
name = token.name
# TODO role name white/black lists
lineno = 0 # TODO get line number
inliner = MockInliner(self, lineno)
role_func, messages = roles.role(
name, self.language_module, lineno, self.reporter
)
rawsource = ":{}:`{}`".format(name, content)
# # backslash escapes converted to nulls (``\x00``)
text = span_token.EscapeSequence.strip(content)
if role_func:
nodes, messages2 = role_func(name, rawsource, text, lineno, inliner)
# return nodes, messages + messages2
self.current_node += nodes
else:
message = self.reporter.error(
'Unknown interpreted text role "{}".'.format(name), line=lineno
)
# return ([self.problematic(content, content, msg)], messages + [msg])
problematic = inliner.problematic(text, rawsource, message)
self.current_node += problematic
def render_directive(self, token):
"""Render special fenced code blocks as directives."""
name = token.language[1:-1]
# TODO directive name white/black lists
content = token.children[0].content
self.document.current_line = token.range[0]
# get directive class
directive_class, messages = directives.directive(
name, self.language_module, self.document
) # type: (Directive, list)
if not directive_class:
error = self.reporter.error(
"Unknown directive type '{}'\n".format(name),
# nodes.literal_block(content, content),
line=token.range[0],
)
self.current_node += [error] + messages
return
try:
arguments, options, body_lines = parse_directive_text(
directive_class, token.arguments, content
)
except DirectiveParsingError as error:
error = self.reporter.error(
"Directive '{}':\n{}".format(name, error),
nodes.literal_block(content, content),
line=token.range[0],
)
self.current_node += [error]
return
# initialise directive
if issubclass(directive_class, Include):
directive_instance = MockIncludeDirective(
self,
name=name,
klass=directive_class,
arguments=arguments,
options=options,
body=body_lines,
lineno=token.range[0],
)
else:
state_machine = MockStateMachine(self, token.range[0])
state = MockState(self, state_machine, token.range[0])
directive_instance = directive_class(
name=name,
# the list of positional arguments
arguments=arguments,
# a dictionary mapping option names to values
options=options,
# the directive content line by line
content=StringList(body_lines, self.document["source"]),
# the absolute line number of the first line of the directive
lineno=token.range[0],
# the line offset of the first line of the content
content_offset=0, # TODO get content offset from `parse_directive_text`
# a string containing the entire directive
block_text="\n".join(body_lines),
state=state,
state_machine=state_machine,
)
# run directive
try:
result = directive_instance.run()
except DirectiveError as error:
msg_node = self.reporter.system_message(
error.level, error.msg, line=token.range[0]
)
msg_node += nodes.literal_block(content, content)
result = [msg_node]
except MockingError as exc:
error = self.reporter.error(
"Directive '{}' cannot be mocked:\n{}: {}".format(
name, exc.__class__.__name__, exc
),
nodes.literal_block(content, content),
line=token.range[0],
)
self.current_node += [error]
return
assert isinstance(
result, list
), 'Directive "{}" must return a list of nodes.'.format(name)
for i in range(len(result)):
assert isinstance(
result[i], nodes.Node
), 'Directive "{}" returned non-Node object (index {}): {}'.format(
name, i, result[i]
)
self.current_node += result
class SphinxRenderer(DocutilsRenderer):
"""A mistletoe renderer to populate (in-place) a `docutils.document` AST.
This is sub-class of `DocutilsRenderer` that handles sphinx cross-referencing.
"""
def __init__(self, *args, **kwargs):
"""Intitalise SphinxRenderer
:param load_sphinx_env: load a basic sphinx environment,
when using the renderer as a context manager outside if `sphinx-build`
:param sphinx_conf: a dictionary representation of the sphinx `conf.py`
:param sphinx_srcdir: a path to a source directory
(for example, can be used for `include` statements)
To use this renderer in a 'standalone' fashion::
from myst_parser.block_tokens import Document
with SphinxRenderer(load_sphinx_env=True, sphinx_conf={}) as renderer:
renderer.render(Document("source text"))
"""
self.load_sphinx_env = kwargs.pop("load_sphinx_env", False)
self.sphinx_conf = kwargs.pop("sphinx_conf", None)
self.sphinx_srcdir = kwargs.pop("sphinx_srcdir", None)
super().__init__(*args, **kwargs)
def handle_cross_reference(self, token, destination):
from sphinx import addnodes
wrap_node = addnodes.pending_xref(
reftarget=unquote(destination),
reftype="any",
refdomain=None, # Added to enable cross-linking
refexplicit=len(token.children) > 0,
refwarn=True,
)
# TODO also not correct sourcepos
# wrap_node.line = self._get_line(token)
if token.title:
wrap_node["title"] = token.title
self.current_node.append(wrap_node)
text_node = nodes.TextElement("", "", classes=["xref", "any"])
wrap_node.append(text_node)
with self.current_node_context(text_node):
self.render_children(token)
def mock_sphinx_env(self, configuration=None, sourcedir=None):
"""Load sphinx roles, directives, etc."""
from sphinx.application import builtin_extensions, Sphinx
from sphinx.config import Config
from sphinx.environment import BuildEnvironment
from sphinx.events import EventManager
from sphinx.project import Project
from sphinx.registry import SphinxComponentRegistry
from sphinx.util.tags import Tags
class MockSphinx(Sphinx):
"""Minimal sphinx init to load roles and directives."""
def __init__(self, confoverrides=None, srcdir=None):
self.extensions = {}
self.registry = SphinxComponentRegistry()
self.html_themes = {}
self.events = EventManager(self)
self.tags = Tags(None)
self.config = Config({}, confoverrides or {})
self.config.pre_init_values()
self._init_i18n()
for extension in builtin_extensions:
self.registry.load_extension(self, extension)
# fresh env
self.doctreedir = None
self.srcdir = srcdir
self.confdir = None
self.outdir = None
self.project = Project(srcdir=srcdir, source_suffix=".md")
self.project.docnames = ["mock_docname"]
self.env = BuildEnvironment()
self.env.setup(self)
self.env.temp_data["docname"] = "mock_docname"
self.builder = None
if not confoverrides:
return
# this code is only required for more complex parsing with extensions
for extension in self.config.extensions:
self.setup_extension(extension)
buildername = "dummy"
self.preload_builder(buildername)
self.config.init_values()
self.events.emit("config-inited", self.config)
import tempfile
with tempfile.TemporaryDirectory() as tempdir:
# creating a builder attempts to make the doctreedir
self.doctreedir = tempdir
self.builder = self.create_builder(buildername)
self.doctreedir = None
app = MockSphinx(confoverrides=configuration, srcdir=sourcedir)
self.document.settings.env = app.env
return app
def __enter__(self):
"""If `load_sphinx_env=True`, we set up an environment,
to parse sphinx roles/directives, outside of a `sphinx-build`.
This primarily copies the code in `sphinx.util.docutils.docutils_namespace`
and `sphinx.util.docutils.sphinx_domains`.
"""
if not self.load_sphinx_env:
return super().__enter__()
# store currently loaded roles/directives, so we can revert on exit
self._directives = copy.copy(directives._directives)
self._roles = copy.copy(roles._roles)
# Monkey-patch directive and role dispatch,
# so that sphinx domain-specific markup takes precedence.
self._env = self.mock_sphinx_env(
configuration=self.sphinx_conf, sourcedir=self.sphinx_srcdir
).env
from sphinx.util.docutils import sphinx_domains
self._sphinx_domains = sphinx_domains(self._env)
self._sphinx_domains.enable()
return super().__enter__()
def __exit__(self, exception_type, exception_val, traceback):
if not self.load_sphinx_env:
return super().__exit__(exception_type, exception_val, traceback)
# revert loaded roles/directives
directives._directives = self._directives
roles._roles = self._roles
self._directives = None
self._roles = None
# unregister nodes (see `sphinx.util.docutils.docutils_namespace`)
from sphinx.util.docutils import additional_nodes, unregister_node
for node in list(additional_nodes):
unregister_node(node)
additional_nodes.discard(node)
# revert directive/role function (see `sphinx.util.docutils.sphinx_domains`)
self._sphinx_domains.disable()
self._sphinx_domains = None
self._env = None
return super().__exit__(exception_type, exception_val, traceback)
class MockingError(Exception):
"""An exception to signal an error during mocking of docutils components."""
class MockInliner:
"""A mock version of `docutils.parsers.rst.states.Inliner`.
This is parsed to role functions.
"""
def __init__(self, renderer: DocutilsRenderer, lineno: int):
self._renderer = renderer
self.document = renderer.document
self.reporter = renderer.document.reporter
if not hasattr(self.reporter, "get_source_and_line"):
# TODO this is called by some roles,
# but I can't see how that would work in RST?
self.reporter.get_source_and_line = lambda l: (self.document["source"], l)
self.parent = renderer.current_node
self.language = renderer.language_module
self.rfc_url = "rfc%d.html"
def problematic(self, text: str, rawsource: str, message: nodes.system_message):
msgid = self.document.set_id(message, self.parent)
problematic = nodes.problematic(rawsource, rawsource, refid=msgid)
prbid = self.document.set_id(problematic)
message.add_backref(prbid)
return problematic
# TODO add parse method
def __getattr__(self, name):
"""This method is only be called if the attribute requested has not
been defined. Defined attributes will not be overridden.
"""
# TODO use document.reporter mechanism?
if hasattr(Inliner, name):
msg = "{cls} has not yet implemented attribute '{name}'".format(
cls=type(self).__name__, name=name
)
raise MockingError(msg).with_traceback(sys.exc_info()[2])
msg = "{cls} has no attribute {name}".format(cls=type(self).__name__, name=name)
raise MockingError(msg).with_traceback(sys.exc_info()[2])
class MockState:
"""A mock version of `docutils.parsers.rst.states.RSTState`.
This is parsed to the `Directives.run()` method,
so that they may run nested parses on their content that will be parsed as markdown,
rather than RST.
"""
def __init__(
self, renderer: DocutilsRenderer, state_machine: "MockStateMachine", lineno: int
):
self._renderer = renderer
self._lineno = lineno
self.document = renderer.document
self.state_machine = state_machine
class Struct:
document = self.document
reporter = self.document.reporter
language = self.document.settings.language_code
title_styles = []
section_level = max(renderer._level_to_elem)
section_bubble_up_kludge = False
inliner = MockInliner(renderer, lineno)
self.memo = Struct
def nested_parse(
self,
block: StringList,
input_offset: int,
node: nodes.Element,
match_titles: bool = False,
state_machine_class=None,
state_machine_kwargs=None,
):
current_match_titles = self.state_machine.match_titles
self.state_machine.match_titles = match_titles
with self._renderer.current_node_context(node):
self._renderer.nested_render_text(block, self._lineno + input_offset)
self.state_machine.match_titles = current_match_titles
def inline_text(self, text: str, lineno: int):
# TODO return messages?
messages = []
paragraph = nodes.paragraph("")
renderer = self._renderer.__class__(
document=self.document, current_node=paragraph
)
renderer.render(
myst_block_tokens.Document(
text, start_line=self._lineno, inc_front_matter=False
)
)
textnodes = []
if paragraph.children:
# first child should be paragraph
textnodes = paragraph.children[0].children
return textnodes, messages
# U+2014 is an em-dash:
attribution_pattern = re.compile("^((?:---?(?!-)|\u2014) *)(.+)")
def block_quote(self, lines: List[str], line_offset: int):
"""Parse a block quote, which is a block of text,
followed by an (optional) attribution.
::
No matter where you go, there you are.
-- Buckaroo Banzai
"""
elements = []
# split attribution
last_line_blank = False
blockquote_lines = lines
attribution_lines = []
attribution_line_offset = None
# First line after a blank line must begin with a dash
for i, line in enumerate(lines):
if not line.strip():
last_line_blank = True
continue
if not last_line_blank:
last_line_blank = False
continue
last_line_blank = False
match = self.attribution_pattern.match(line)
if not match:
continue
attribution_line_offset = i
attribution_lines = [match.group(2)]
for at_line in lines[i + 1 :]:
indented_line = at_line[len(match.group(1)) :]
if len(indented_line) != len(at_line.lstrip()):
break
attribution_lines.append(indented_line)
blockquote_lines = lines[:i]
break
# parse block
blockquote = nodes.block_quote()
self.nested_parse(blockquote_lines, line_offset, blockquote)
elements.append(blockquote)
# parse attribution
if attribution_lines:
attribution_text = "\n".join(attribution_lines)
lineno = self._lineno + line_offset + attribution_line_offset
textnodes, messages = self.inline_text(attribution_text, lineno)
attribution = nodes.attribution(attribution_text, "", *textnodes)
(
attribution.source,
attribution.line,
) = self.state_machine.get_source_and_line(lineno)
blockquote += attribution
elements += messages
return elements
def build_table(self, tabledata, tableline, stub_columns=0, widths=None):
return Body.build_table(self, tabledata, tableline, stub_columns, widths)
def build_table_row(self, rowdata, tableline):
return Body.build_table_row(self, rowdata, tableline)
def __getattr__(self, name):
"""This method is only be called if the attribute requested has not
been defined. Defined attributes will not be overridden.
"""
if hasattr(Body, name):
msg = "{cls} has not yet implemented attribute '{name}'".format(
cls=type(self).__name__, name=name
)
raise MockingError(msg).with_traceback(sys.exc_info()[2])
msg = "{cls} has no attribute {name}".format(cls=type(self).__name__, name=name)
raise MockingError(msg).with_traceback(sys.exc_info()[2])
class MockStateMachine:
"""A mock version of `docutils.parsers.rst.states.RSTStateMachine`.
This is parsed to the `Directives.run()` method.
"""
def __init__(self, renderer: DocutilsRenderer, lineno: int):
self._renderer = renderer
self._lineno = lineno
self.document = renderer.document
self.reporter = self.document.reporter
self.node = renderer.current_node
self.match_titles = True
# TODO to allow to access like attributes like input_lines,
# we would need to store the input lines,
# probably via the `Document` token,
# and maybe self._lines = lines[:], then for AstRenderer,
# ignore private attributes
def get_source(self, lineno: Optional[int] = None):
"""Return document source path."""
return self.document["source"]
def get_source_and_line(self, lineno: Optional[int] = None):
"""Return (source path, line) tuple for current or given line number."""
return self.document["source"], lineno or self._lineno
def __getattr__(self, name):
"""This method is only be called if the attribute requested has not
been defined. Defined attributes will not be overridden.
"""
if hasattr(RSTStateMachine, name):
msg = "{cls} has not yet implemented attribute '{name}'".format(
cls=type(self).__name__, name=name
)
raise MockingError(msg).with_traceback(sys.exc_info()[2])
msg = "{cls} has no attribute {name}".format(cls=type(self).__name__, name=name)
raise MockingError(msg).with_traceback(sys.exc_info()[2])
class MockIncludeDirective:
"""This directive uses a lot of statemachine logic that is not yet mocked.
Therefore, we treat it as a special case (at least for now).
See:
https://docutils.sourceforge.io/docs/ref/rst/directives.html#including-an-external-document-fragment
"""
def __init__(
self,
renderer: DocutilsRenderer,
name: str,
klass: Include,
arguments: list,
options: dict,
body: List[str],
lineno: int,
):
self.renderer = renderer
self.document = renderer.document
self.name = name
self.klass = klass
self.arguments = arguments
self.options = options
self.body = body
self.lineno = lineno
def run(self):
from docutils.parsers.rst.directives.body import CodeBlock, NumberLines
if not self.document.settings.file_insertion_enabled:
raise DirectiveError(2, 'Directive "{}" disabled.'.format(self.name))
source_dir = Path(self.document["source"]).absolute().parent
include_arg = "".join([s.strip() for s in self.arguments[0].splitlines()])
if include_arg.startswith("<") and include_arg.endswith(">"):
# # docutils "standard" includes
path = Path(self.klass.standard_include_path).joinpath(include_arg[1:-1])
else:
# if using sphinx interpret absolute paths "correctly",
# i.e. relative to source directory
try:
sphinx_env = self.document.settings.env
_, include_arg = sphinx_env.relfn2path(self.arguments[0])
sphinx_env.note_included(include_arg)
except AttributeError:
pass
path = Path(include_arg)
path = source_dir.joinpath(path)
# read file
encoding = self.options.get("encoding", self.document.settings.input_encoding)
error_handler = self.document.settings.input_encoding_error_handler
# tab_width = self.options.get("tab-width", self.document.settings.tab_width)
try:
file_content = path.read_text(encoding=encoding, errors=error_handler)
except Exception as error:
raise DirectiveError(
4,
'Directive "{}": error reading file: {}\n{error}.'.format(
self.name, path, error
),
)
# get required section of text
startline = self.options.get("start-line", None)
endline = self.options.get("end-line", None)
file_content = "\n".join(file_content.splitlines()[startline:endline])
startline = startline or 0
for split_on_type in ["start-after", "end-before"]:
split_on = self.options.get(split_on_type, None)
if not split_on:
continue
split_index = file_content.find(split_on)