-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtranslator.py
1794 lines (1495 loc) · 59.7 KB
/
translator.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
"""
Translator for RST to MYST Conversion
TODO:
1. Given the way SphinxTranslator works we should remove all unecessary methods
https://github.com/sphinx-doc/sphinx/blob/275d93b5068a4b6af4c912d5bebb2df928416060/sphinx/util/docutils.py#L438
"""
from __future__ import unicode_literals
import re
from docutils import nodes
from sphinx.util import logging
from sphinx.util.docutils import SphinxTranslator
from .myst import MystSyntax
from .accumulators import List
from .accumulators import TableBuilder
logger = logging.getLogger(__name__)
class MystTranslator(SphinxTranslator):
"""Myst Translator
docutils:
1. https://docutils.sourceforge.io/docs/ref/doctree.html
2. https://docutils.sourceforge.io/docs/ref/doctree.html#element-reference
sphinx:
1. https://www.sphinx-doc.org/en/master/extdev/nodes.html
2. https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html
.. todo::
1. review NotImplementedError to see if visit methods in base classes
are suitable
"""
indentation = " " * 2
# Boolean(State Tracking)
admonition = False
attribution = False
attention = False
caption = False
caution = False
citation = False
danger = False
download_reference = False
error = False
hint = False
important = False
literal = False
literal_block = False
math = False
note = False
inpage_reference = False
reference = False
tip = False
toctree = False
topic = False
warning = False
# Dict(State Tracking)
# Block Quote
block_quote = dict()
block_quote["in"] = False
block_quote["type"] = None
block_quote["collect"] = []
# Figure
figure = dict()
figure["in"] = False
figure["figure-options"] = None
# Footnotes
footnote = {}
footnote["in"] = False
footnote_reference = dict()
footnote_reference["in"] = False
footnote_reference["autoid"] = []
# Bullet List
bullet_list = dict()
bullet_list["in"] = True
bullet_list["marker"] = "*"
bullet_list["level"] = -1
# Image
image = dict()
image["in"] = False
image["skip-reference"] = False
# Index
index = dict()
index["in"] = False
index["type"] = None
# Math
math_block = dict()
math_block["in"] = False
math_block["options"] = []
# Accumulators
List = None
Table = None
# sphinx.ext.todo
todo = False
def __init__(self, document, builder):
"""
A Myst(Markdown) Translator
"""
super().__init__(document, builder)
# Config
self.target_mystnb = self.builder.config["tomyst_target_mystnb"]
self.default_ext = ".myst"
self.default_language = self.builder.config["tomyst_default_language"]
self.language_synonyms = self.builder.config["tomyst_language_synonyms"]
self.language_synonyms.append(self.default_language)
self.debug = self.builder.config["tomyst_debug"]
# Document Settings
self.syntax = MystSyntax()
self.images = []
self.section_level = 0
# Support for sphinxcontrib-bibtex data
if "sphinxcontrib.bibtex" in self.builder.config.extensions:
self.bibtex_cache = self.builder.env.bibtex_cache
# ----------#
# -Document-#
# ----------#
def visit_document(self, node):
self.output = []
if self.target_mystnb:
self.output.append(self.builder.config["tomyst_jupytext_header"].lstrip())
self.add_newline()
def depart_document(self, node):
self.body = "".join(self.output)
def unknown_visit(self, node):
raise NotImplementedError("Unknown node: " + node.__class__.__name__)
def unknown_departure(self, node):
pass
# -------#
# -Nodes-#
# -------#
# -- Text -- #
def visit_Text(self, node):
text = node.astext()
if self.caption:
raise nodes.SkipNode
if self.math_block["in"]:
text = text.strip()
if self.index["in"] and self.index["type"] == "role":
presyntax, postsyntax = self.index["role_syntax"]
text = presyntax + text + postsyntax
# Switch off index and role
self.index["in"] = False
self.index["type"] = None
self.text = text
def depart_Text(self, node):
# Accumulators
if self.List:
self.List.addto_list_item(self.text)
return
if self.Table:
self.Table.add_item(self.text)
return
if self.block_quote["in"] and self.block_quote["type"] == "block_quote":
self.block_quote["collect"].append(self.text)
return
# Adjust Spacing
if self.math_block["in"]:
self.text = self.text
if self.literal_block:
self.text = self.text + "\n"
if self.caption and self.toctree: # TODO: Check this condition
self.text = "# {}".format(self.text)
self.output.append(self.text)
# -- Elements --- #
# docutils.elements.abbreviation
# https://docutils.sourceforge.io/docs/ref/doctree.html#abbreviation
# docutils.elements.acroynm
# https://docutils.sourceforge.io/docs/ref/doctree.html#acronym
# docutils.elements.address
# https://docutils.sourceforge.io/docs/ref/doctree.html#address
# docutils.elements.admonition
# types: attention, caution, danger, error, hint, important, note, tip, warning
# https://docutils.sourceforge.io/docs/ref/rst/directives.html#admonitions
def visit_admonition(self, node):
self.admonition = True
title = self.infer_admonition_attrs(node)
if title is None:
raise SyntaxWarning("title attribute cannot be None")
syntax = self.syntax.visit_admonition(title)
self.output.append(syntax)
self.add_newline()
def infer_admonition_attrs(self, node):
title = None
for child in node.children:
if type(child) is nodes.title:
title = child.astext()
return title
def depart_admonition(self, node):
self.remove_newline()
self.output.append(self.syntax.depart_admonition())
self.add_newparagraph()
self.admonition = False
# docutils.elements.attention
# https://docutils.sourceforge.io/docs/ref/doctree.html#attention
def visit_attention(self, node):
self.attention = True
self.output.append(self.syntax.visit_directive("attention"))
self.add_newline()
def depart_attention(self, node):
self.remove_newline()
self.output.append(self.syntax.depart_directive())
self.add_newparagraph()
self.attention = False
# docutils.elements.attribution
# https://docutils.sourceforge.io/docs/ref/doctree.html#attribution
def visit_attribution(self, node):
self.attribution = True
self.add_newline()
self.output.append(self.syntax.visit_attribution())
def depart_attribution(self, node):
self.attribution = False
self.add_newline()
# docutils.elements.author
# https://docutils.sourceforge.io/docs/ref/doctree.html#author
# https://docutils.sourceforge.io/docs/ref/doctree.html#authors
# sphinxcontrib-bibtex
# https://sphinxcontrib-bibtex.readthedocs.io/en/latest/index.html
def visit_bibliography(self, node):
"""
TODO: add support for directive options :cited:, :notcited:, :all:
and :filter:
https://sphinxcontrib-bibtex.readthedocs.io/en/latest/usage.html#filtering
"""
docname = self.builder.current_docname
bib_id = node.attributes["ids"][0]
bib_cache = self.bibtex_cache.get_bibliography_cache(docname, bib_id)
srcdir = self.builder.srcdir
# Extract Directive Info
files = [x.replace(srcdir + "/", "") for x in bib_cache.bibfiles]
options = {}
if bib_cache.style != "alpha":
options["style"] = bib_cache.style
if bib_cache.encoding != "utf-8-sig":
options["encoding"] = bib_cache.encoding
if bib_cache.enumtype != "arabic":
options["enumtype"] = bib_cache.enumtype
if bib_cache.start != 1:
options["start"] = bib_cache.start
if bib_cache.labelprefix != "":
options["labelprefix"] = bib_cache.labelprefix
if bib_cache.keyprefix != "":
options["keyprefix"] = bib_cache.keyprefix
options = self.myst_options(options)
directive = self.syntax.visit_directive(
"bibliography", argument=" ".join(files), options=options
)
self.output.append(directive)
self.add_newline()
def depart_bibliography(self, node):
self.output.append(self.syntax.depart_directive())
self.add_newparagraph()
# docutils.element.block_quote
# class types: epigraph
# https://docutils.sourceforge.io/docs/ref/doctree.html#block-quote
def visit_block_quote(self, node):
self.block_quote["in"] = True
# Determine class type
if "epigraph" in node.attributes["classes"]:
self.block_quote["type"] = "epigraph"
self.output.append(self.syntax.visit_directive("epigraph"))
self.add_newline()
elif "highlights" in node.attributes["classes"]:
self.block_quote["type"] = "highlights"
self.output.append(self.syntax.visit_directive("highlights"))
self.add_newline()
elif "pull-quote" in node.attributes["classes"]:
self.block_quote["type"] = "pull-quote"
self.output.append(self.syntax.visit_directive("pull-quote"))
self.add_newline()
else:
self.block_quote["type"] = "block_quote"
self.block_quote["collect"] = ["> "]
def depart_block_quote(self, node):
if self.block_quote["type"] != "block_quote":
self.output.append(self.syntax.depart_directive())
self.add_newparagraph()
else:
# Add block_quote lines to output
linemarker = self.syntax.visit_block_quote()
if (
self.block_quote["collect"]
and self.block_quote["collect"][-1] == "\n\n"
):
self.block_quote["collect"].pop()
block = "".join(self.block_quote["collect"])
block = block.replace("\n", "\n{}".format(linemarker))
self.output.append(block)
self.add_newparagraph()
self.block_quote["collect"] = []
self.block_quote["in"] = False
# docutils.elements.bullet_list
# https://docutils.sourceforge.io/docs/ref/doctree.html#bullet-list
def visit_bullet_list(self, node):
marker = None
if node.hasattr("bullet"):
marker = node.attributes["bullet"]
if not self.List:
self.List = List(marker=marker)
else:
# Finalise any open List Item
if self.List.list_item:
self.List.add_list_item()
self.List = List(marker=marker, parent=self.List)
def depart_bullet_list(self, node):
if self.List.parent == "base":
self.output.append(self.List.to_markdown())
self.add_newparagraph()
self.List = None
else:
self.List = self.List.add_to_parent()
# docutils.elements.caption
# https://docutils.sourceforge.io/docs/ref/doctree.html#caption
def visit_caption(self, node):
self.caption = True
if self.literal_block:
raise nodes.SkipNode
def depart_caption(self, node):
self.caption = False
if self.toctree:
self.output.append("\n")
# docutils.elements.caution
# https://docutils.sourceforge.io/docs/ref/doctree.html#caution
def visit_caution(self, node):
self.caution = True
self.output.append(self.syntax.visit_directive("caution"))
self.add_newline()
def depart_caution(self, node):
self.remove_newline()
self.output.append(self.syntax.depart_directive())
self.add_newparagraph()
self.caution = False
# docutils.citations
# https://docutils.sourceforge.io/docs/ref/rst/directives.html#citations
def visit_citation(self, node):
self.citation = True
if "ids" in node.attributes:
id_text = ""
for id_ in node.attributes["ids"]:
id_text += "{} ".format(id_)
else:
id_text = id_text[:-1]
self.output.append(self.syntax.visit_citation(id_text))
def depart_citation(self, node):
self.citation = False
# docutils.elements.citation_reference
# https://docutils.sourceforge.io/docs/ref/doctree.html#citation-reference
def visit_citation_reference(self, node):
citation = node.astext()
self.output.append(self.syntax.visit_role("cite", citation))
raise nodes.SkipChildren
def depart_citation_reference(self, node):
self.output.append(self.syntax.depart_role())
# docutils.elements.classifier
# https://docutils.sourceforge.io/docs/ref/doctree.html#classifier
# docutils.elements.colspec
# uses: table
# https://docutils.sourceforge.io/docs/ref/doctree.html#colspec
def visit_colspec(self, node):
self.Table.add_column_width(node["colwidth"])
# docutils.elements.comment
# https://docutils.sourceforge.io/docs/ref/doctree.html#comment
def visit_comment(self, node):
raise nodes.SkipNode
# sphinx.nodes.compact_paragraph
# https://www.sphinx-doc.org/en/master/extdev/nodes.html?highlight=compact_paragraph#sphinx.addnodes.compact_paragraph
def visit_compact_paragraph(self, node):
pass # TODO: review
def depart_compact_paragraph(self, node):
pass
# docutils.elements.compound
# https://docutils.sourceforge.io/docs/ref/doctree.html#compound
def visit_compound(self, node):
pass
# if "toctree-wrapper" in node['classes']:
# self.toctree = True
def depart_compound(self, node):
pass
# if "toctree-wrapper" in node['classes']:
# self.toctree = False
# docutils.elements.contact
# https://docutils.sourceforge.io/docs/ref/doctree.html#contact
# docutils.elements.container
# https://docutils.sourceforge.io/docs/ref/doctree.html#container
def visit_container(self, node):
pass
def depart_container(self, node):
pass
# docutils.elements.copyright
# https://docutils.sourceforge.io/docs/ref/doctree.html#copyright
# docutils.elements.danger
# https://docutils.sourceforge.io/docs/ref/doctree.html#danger
def visit_danger(self, node):
self.danger = True
self.output.append(self.syntax.visit_directive("danger"))
self.add_newline()
def depart_danger(self, node):
self.remove_newline()
self.output.append(self.syntax.depart_directive())
self.add_newparagraph()
self.danger = False
# docutils.elements.date
# https://docutils.sourceforge.io/docs/ref/doctree.html#date
# docutils.elements.decoration
# https://docutils.sourceforge.io/docs/ref/doctree.html#decoration
# docutils.elements.definition
# https://docutils.sourceforge.io/docs/ref/doctree.html#definition
def visit_definition(self, node):
pass
# Current Syntax consists of HTML markers
# self.output.append(self.syntax.visit_definition()) #html markers!
# self.add_newline()
def depart_definition(self, node):
pass
# Current Syntax consists of HTML markers
# self.output.append(self.syntax.depart_definition())
# self.add_newline()
# docutils.elements.definition_list
# https://docutils.sourceforge.io/docs/ref/doctree.html#definition-list
def visit_definition_list(self, node):
msg = """
SKIP [definition_list] objects are not supported in commonmark
""".strip()
logger.warning(msg)
raise nodes.SkipNode
# Current Syntax consists of HTML markers
# self.add_newline()
# self.output.append(self.syntax.visit_definition_list())
# self.add_newline()
def depart_definition_list(self, node):
pass
# Current Syntax consists of HTML markers
# self.add_newline()
# self.output.append(self.syntax.depart_definition_list())
# self.add_newparagraph()
# docutils.elements.definition_list_item
# https://docutils.sourceforge.io/docs/ref/doctree.html#definition-list-item
def visit_definition_list_item(self, node):
pass
def depart_definition_list_item(self, node):
pass
# docutils.elements.description
# https://docutils.sourceforge.io/docs/ref/doctree.html#description
# docutils.elements.docinfo
# https://docutils.sourceforge.io/docs/ref/doctree.html#docinfo
# docutils.elements.doctest-block
# https://docutils.sourceforge.io/docs/ref/doctree.html#doctest-block
# docutils.elements.document
# https://docutils.sourceforge.io/docs/ref/doctree.html#document
# sphinx.nodes.download_reference
# https://www.sphinx-doc.org/en/master/extdev/nodes.html#new-inline-nodes
def visit_download_reference(self, node):
self.download_reference = True
html = "<a href={} download>".format(node["reftarget"])
self.output.append(html)
def depart_download_reference(self, node):
self.download_reference = False
self.output.append("</a>")
# docutils.elements.emphasis
# uses: Text
# https://docutils.sourceforge.io/docs/ref/doctree.html#emphasis
def visit_emphasis(self, node):
syntax = self.syntax.visit_italic()
if self.List:
self.List.addto_list_item(syntax)
elif self.Table:
self.Table.add_item(syntax)
elif self.block_quote["in"] and self.block_quote["type"] == "block_quote":
self.block_quote["collect"].append(syntax)
else:
self.output.append(syntax)
def depart_emphasis(self, node):
syntax = self.syntax.depart_italic()
if self.List:
self.List.addto_list_item(syntax)
elif self.Table:
self.Table.add_item(syntax)
elif self.block_quote["in"] and self.block_quote["type"] == "block_quote":
self.block_quote["collect"].append(syntax)
else:
self.output.append(syntax)
# docutils.elements.entry
# uses: table?
# https://docutils.sourceforge.io/docs/ref/doctree.html#entry
def visit_entry(self, node):
pass
def depart_entry(self, node):
pass
# docutils.elements.enumerated_list
# https://docutils.sourceforge.io/docs/ref/doctree.html#enumerated-list
def visit_enumerated_list(self, node):
"""
.. TODO: should use item_count to make a more readable
list in markdown output
.. TODO: add support for different styles of enumerated
lists. This currently is nested numbered lists
"""
marker = "1."
if not self.List:
self.List = List(marker=marker)
else:
# Finalise any open List Item
if self.List.list_item:
self.List.add_list_item()
self.List = List(marker=marker, parent=self.List)
def depart_enumerated_list(self, node):
if self.List.parent == "base":
self.output.append(self.List.to_markdown())
self.add_newparagraph()
self.List = None
else:
self.List = self.List.add_to_parent()
# docutils.elements.error
# https://docutils.sourceforge.io/docs/ref/doctree.html#error
def visit_error(self, node):
self.error = True
self.output.append(self.syntax.visit_directive("error"))
self.add_newline()
def depart_error(self, node):
self.remove_newline()
self.output.append(self.syntax.depart_directive())
self.add_newparagraph()
self.error = False
# docutils.elements.field
# https://docutils.sourceforge.io/docs/ref/doctree.html#field
def visit_field(self, node):
# for child in node.children:
# if type(child) is nodes.field_name:
# field_name = child.astext()
# elif type(child) is nodes.field_body:
# field_body = child.astext()
raise NotImplementedError
# docutils.elements.field_body
# https://docutils.sourceforge.io/docs/ref/doctree.html#field-body
def visit_field_body(self, node):
self.visit_definition(node) # TODO: review if wrapper of definition
def depart_field_body(self, node):
self.depart_definition(node)
# docutils.elements.field_list
# https://docutils.sourceforge.io/docs/ref/doctree.html#field-list
def visit_field_list(self, node):
self.visit_definition_list(node)
def depart_field_list(self, node):
self.depart_definition_list(node)
# docutils.element.field_name
# https://docutils.sourceforge.io/docs/ref/doctree.html#field-name
def visit_field_name(self, node):
self.visit_term(node)
def depart_field_name(self, node):
self.depart_term(node)
# docutils.figure
# https://docutils.sourceforge.io/docs/ref/rst/directives.html#figure
def visit_figure(self, node):
"""
Note: additional options need parsing in image node
"""
self.figure["in"] = True
self.figure["figure-options"] = self.infer_figure_attrs(node)
def infer_figure_attrs(self, node):
"""
:align: -> align
:figwidth: -> width
:figclass: -> classes
"""
options = {}
if node.hasattr("align"):
align = node.attributes["align"]
if align not in ["default"]: # if not set may have default value = default
options["align"] = align
if node.hasattr("width"):
options["figwidth"] = node.attributes["width"]
if len(node.attributes["classes"]) > 0:
classes = str(node.attributes["classes"]).strip("[]").strip("'")
options["figclass"] = classes
return options
def depart_figure(self, node):
self.figure["in"] = False
self.figure["figure-options"] = None
# docutils.elements.footer
# https://docutils.sourceforge.io/docs/ref/doctree.html#footer
# docutils.elements.footnote
# https://docutils.sourceforge.io/docs/ref/doctree.html#footnote
def visit_footnote(self, node):
self.footnote["in"] = True
try:
refname = node.attributes["names"][0]
except IndexError:
refname = self.footnote_reference["autoid"].pop(0)
self.output.append(self.syntax.visit_footnote(refname))
def depart_footnote(self, node):
self.footnote["in"] = False
# docutils.elements.footnote_reference
# https://docutils.sourceforge.io/docs/ref/doctree.html#footnote-reference
def visit_footnote_reference(self, node):
self.footnote_reference["in"] = True
if node.hasattr("refname"):
refname = node.attributes["refname"]
else:
count = len(self.footnote_reference["autoid"])
autoid = "autoid_{}".format(count)
self.footnote_reference["autoid"].append(autoid)
refname = autoid
syntax = self.syntax.visit_footnote_reference(refname)
if self.List:
self.List.addto_list_item(syntax)
elif self.Table:
self.Table.add_item(syntax)
else:
self.output.append(syntax)
def depart_footnote_reference(self, node):
self.footnote_reference["in"] = False
# docutils.elements.generated
# https://docutils.sourceforge.io/docs/ref/doctree.html#generated
# docutils.elements.header
# https://docutils.sourceforge.io/docs/ref/doctree.html#header
# sphinx.elements.highlightlang
# https://www.sphinx-doc.org/en/master/extdev/nodes.html#sphinx.addnodes.highlightlang
def visit_highlightlang(self, node):
if self.debug:
msg = "[highlightang] typically handeled by transform/post-transform"
logger.info(msg)
def depart_highlightlang(self, node):
pass
# docutils.elements.hint
# https://docutils.sourceforge.io/docs/ref/doctree.html#hint
def visit_hint(self, node):
self.hint = True
self.output.append(self.syntax.visit_directive("hint"))
self.add_newline()
def depart_hint(self, node):
self.remove_newline()
self.output.append(self.syntax.depart_directive())
self.add_newparagraph()
self.hint = False
# docutils.elements.image
# https://docutils.sourceforge.io/docs/ref/rst/directives.html#images
def visit_image(self, node):
"""
1. the scale, height and width properties are not combined in this
as in http://docutils.sourceforge.net/docs/ref/rst/directives.html#image
"""
self.image["in"] = True
# Image wrapped within a reference
if self.reference:
if self.output[-1] == self.syntax.visit_reference():
self.output.pop()
self.image["skip-reference"] = True
options = self.infer_image_attrs(node)
if self.figure["in"]:
figure_options = self.figure["figure-options"]
options = {**options, **figure_options} # Figure options take precedence
options = self.myst_options(options)
uri = node.attributes["uri"]
self.images.append(uri)
if self.figure["in"]:
syntax = self.syntax.visit_figure(uri, options)
else:
syntax = self.syntax.visit_image(uri, options)
self.output.append(syntax)
def infer_image_attrs(self, node):
"""
https://docutils.sourceforge.io/docs/ref/rst/directives.html#image-options
:alt: -> alt
:height: -> height
:width: -> width
:scale: -> scale
:align: -> align
:target: -> node.parent = docutils.nodes.reference
"""
options = {}
for option in ["alt", "height", "width", "scale", "align"]:
if node.hasattr(option):
options[option] = node.attributes[option]
if type(node.parent) is nodes.reference:
if node.parent.hasattr("refuri"):
options["target"] = node.parent.attributes["refuri"]
return options
def depart_image(self, node):
self.add_newline()
self.output.append(self.syntax.depart_figure())
self.add_newparagraph()
self.image["in"] = False
# docutils.elements.important
# https://docutils.sourceforge.io/docs/ref/doctree.html#important
def visit_important(self, node):
self.important = True
self.output.append(self.syntax.visit_directive("important"))
self.add_newline()
def depart_important(self, node):
self.remove_newline()
self.output.append(self.syntax.depart_directive())
self.add_newparagraph()
self.important = False
# sphinx.nodes.index
# https://www.sphinx-doc.org/en/master/extdev/nodes.html#new-inline-nodes
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#index-generating-markup
def visit_index(self, node):
self.index["in"] = True
inline = True # default value
if node.hasattr("inline"):
inline = node.attributes["inline"]
if inline:
self.parse_index_as_role(node) # Syntax is parsed at Text Node
else:
syntax = self.parse_index_as_directive(node)
self.output.append(syntax)
self.add_newparagraph()
def parse_index_as_role(self, node):
self.index["type"] = "role"
if len(node.attributes["entries"]) != 1:
# Issue Warning
docname = self.builder.current_docname
line = node.line
msg = """
[{}:{}] contains an inline :index: role that cannot be converted.
""".format(
docname, line
).strip()
logger.warning(msg)
raise nodes.SkipNode
else:
entry = node.attributes["entries"][0]
entrytype, entryname, target, ignored, key = entry
presyntax = "{" + "index" + "}`"
postsyntax = " <{}: {}>`".format(entrytype, entryname)
# Save info for parsing at first Text node
self.index["role_syntax"] = (presyntax, postsyntax)
def parse_index_as_directive(self, node):
self.index["type"] = "directive"
entries = []
options = []
for entry in node.attributes["entries"]:
entrytype, entryname, target, ignored, key = entry
entries.append("{}: {}".format(entrytype, entryname))
# Sphinx > 3.0
if not re.match("index-", target) and target != "":
option = ":name: {}".format(target)
if option not in options:
options.append(option)
# -Construct Syntax
syntax = []
if len(entries) == 1:
syntax.append(self.syntax.visit_directive("index", argument=entries[0]))
else:
syntax.append(self.syntax.visit_directive("index"))
syntax += entries
syntax += options
syntax.append(self.syntax.depart_directive())
return "\n".join(syntax)
def depart_index(self, node):
if self.index["type"] == "role":
# Delay state change until parsed by visit_Text
pass
else:
self.index["in"] = False
self.index["type"] = None
# docutils.elements.inline
# uses: container?
# https://docutils.sourceforge.io/docs/ref/doctree.html#inline
def visit_inline(self, node):
pass
def depart_inline(self, node):
pass
# docutils.container.label
# https://docutils.sourceforge.io/docs/ref/doctree.html#label
def visit_label(self, node):
if self.citation:
self.output.append(self.syntax.visit_label())
def depart_label(self, node):
if self.citation:
self.output.append(self.syntax.depart_label())
self.add_space()
# docutils.elements.legend
# https://docutils.sourceforge.io/docs/ref/doctree.html#legend
# docutils.elements.line
# https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#line-blocks
def visit_line(self, node):
pass # TODO: remove? use SphinxTranslator version
def depart_line(self, node):
pass
# docutils.elements.line_block
# https://docutils.sourceforge.io/docs/ref/doctree.html#line-block
def visit_line_block(self, node):
pass # TODO: remove? use SphinxTranslator version
def depart_line_block(self, node):
pass
# docutils.elements.list_item
# https://docutils.sourceforge.io/docs/ref/doctree.html#list-item
def visit_list_item(self, node):
self.List.start_list_item()
def depart_list_item(self, node):
if self.List.list_item:
self.List.add_list_item()
# docutils.element.literal
# https://docutils.sourceforge.io/docs/ref/doctree.html#literal
def visit_literal(self, node):
self.literal = True
if self.download_reference:
return # TODO: can we just raise SkipNode?
syntax = self.syntax.visit_literal()
if self.List:
self.List.addto_list_item(syntax)
elif self.Table:
self.Table.add_item(syntax)
elif self.block_quote["in"] and self.block_quote["type"] == "block_quote":
self.block_quote["collect"].append(syntax)
else:
self.output.append(syntax)
def depart_literal(self, node):
if self.download_reference:
return
syntax = self.syntax.depart_literal()
if self.List:
self.List.addto_list_item(syntax)
elif self.Table:
self.Table.add_item(syntax)
elif self.block_quote["in"] and self.block_quote["type"] == "block_quote":
self.block_quote["collect"].append(syntax)
else:
self.output.append(syntax)
self.literal = False
# docutils.element.literal_block
# https://docutils.sourceforge.io/docs/ref/doctree.html#literal-block
def visit_literal_block(self, node):
self.literal_block = True
options = self.infer_literal_block_attrs(node)
if node.hasattr("language"):
self.nodelang = node.attributes["language"].strip()
if self.nodelang == "default":
self.nodelang = self.default_language
# A code-block that isn't the same as the kernel