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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
|
"""
sphinx.writers.text
~~~~~~~~~~~~~~~~~~~
Custom docutils writer for plain text.
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import math
import os
import re
import textwrap
import warnings
from itertools import groupby, chain
from typing import Iterable, cast
from docutils import nodes, writers
from docutils.utils import column_width
from sphinx import addnodes
from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.locale import admonitionlabels, _
from sphinx.util.docutils import SphinxTranslator
if False:
# For type annotation
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union # NOQA
from sphinx.builders.text import TextBuilder # NOQA
class Cell:
"""Represents a cell in a table.
It can span on multiple columns or on multiple lines.
"""
def __init__(self, text="", rowspan=1, colspan=1):
self.text = text
self.wrapped = [] # type: List[str]
self.rowspan = rowspan
self.colspan = colspan
self.col = None
self.row = None
def __repr__(self):
return "<Cell {!r} {}v{}/{}>{}>".format(
self.text, self.row, self.rowspan, self.col, self.colspan
)
def __hash__(self):
return hash((self.col, self.row))
def wrap(self, width):
self.wrapped = my_wrap(self.text, width)
class Table:
"""Represents a table, handling cells that can span on multiple lines
or rows, like::
+-----------+-----+
| AAA | BBB |
+-----+-----+ |
| | XXX | |
| +-----+-----+
| DDD | CCC |
+-----+-----------+
This class can be used in two ways:
- Either with absolute positions: call ``table[line, col] = Cell(...)``,
this overwrite an existing cell if any.
- Either with relative positions: call the ``add_row()`` and
``add_cell(Cell(...))`` as needed.
Cell spanning on multiple rows or multiple columns (having a
colspan or rowspan greater than one) are automatically referenced
by all the table cells they covers. This is a usefull
representation as we can simply check ``if self[x, y] is self[x,
y+1]`` to recognize a rowspan.
Colwidth is not automatically computed, it has to be given, either
at construction time, either during the table construction.
Example usage::
table = Table([6, 6])
table.add_cell(Cell("foo"))
table.add_cell(Cell("bar"))
table.set_separator()
table.add_row()
table.add_cell(Cell("FOO"))
table.add_cell(Cell("BAR"))
print(table)
+--------+--------+
| foo | bar |
|========|========|
| FOO | BAR |
+--------+--------+
"""
def __init__(self, colwidth=None):
self.lines = [] # type: List[List[Cell]]
self.separator = 0
self.colwidth = (colwidth if colwidth is not None
else []) # type: List[int]
self.current_line = 0
self.current_col = 0
def add_row(self):
"""Add a row to the table, to use with ``add_cell()``. It is not needed
to call ``add_row()`` before the first ``add_cell()``.
"""
self.current_line += 1
self.current_col = 0
def set_separator(self):
"""Sets the separator below the current line.
"""
self.separator = len(self.lines)
def add_cell(self, cell):
"""Add a cell to the current line, to use with ``add_row()``. To add
a cell spanning on multiple lines or rows, simply set the
``cell.colspan`` or ``cell.rowspan`` BEFORE inserting it to
the table.
"""
while self[self.current_line, self.current_col]:
self.current_col += 1
self[self.current_line, self.current_col] = cell
self.current_col += cell.colspan
def __getitem__(self, pos):
line, col = pos
self._ensure_has_line(line + 1)
self._ensure_has_column(col + 1)
return self.lines[line][col]
def __setitem__(self, pos, cell):
line, col = pos
self._ensure_has_line(line + cell.rowspan)
self._ensure_has_column(col + cell.colspan)
for dline in range(cell.rowspan):
for dcol in range(cell.colspan):
self.lines[line + dline][col + dcol] = cell
cell.row = line
cell.col = col
def _ensure_has_line(self, line):
while len(self.lines) < line:
self.lines.append([])
def _ensure_has_column(self, col):
for line in self.lines:
while len(line) < col:
line.append(None)
def __repr__(self):
return "\n".join(repr(line) for line in self.lines)
def cell_width(self, cell, source):
"""Give the cell width, according to the given source (either
``self.colwidth`` or ``self.measured_widths``).
This take into account cells spanning on multiple columns.
"""
width = 0
for i in range(self[cell.row, cell.col].colspan):
width += source[cell.col + i]
return width + (cell.colspan - 1) * 3
@property
def cells(self):
seen = set() # type: Set[Cell]
for lineno, line in enumerate(self.lines):
for colno, cell in enumerate(line):
if cell and cell not in seen:
yield cell
seen.add(cell)
def rewrap(self):
"""Call ``cell.wrap()`` on all cells, and measure each column width
after wrapping (result written in ``self.measured_widths``).
"""
self.measured_widths = self.colwidth[:]
for cell in self.cells:
cell.wrap(width=self.cell_width(cell, self.colwidth))
if not cell.wrapped:
continue
width = math.ceil(max(column_width(x) for x in cell.wrapped) / cell.colspan)
for col in range(cell.col, cell.col + cell.colspan):
self.measured_widths[col] = max(self.measured_widths[col], width)
def physical_lines_for_line(self, line):
"""From a given line, compute the number of physical lines it spans
due to text wrapping.
"""
physical_lines = 1
for cell in line:
physical_lines = max(physical_lines, len(cell.wrapped))
return physical_lines
def __str__(self):
out = []
self.rewrap()
def writesep(char="-", lineno=None):
# type: (str, Optional[int]) -> str
"""Called on the line *before* lineno.
Called with no *lineno* for the last sep.
"""
out = [] # type: List[str]
for colno, width in enumerate(self.measured_widths):
if (
lineno is not None and
lineno > 0 and
self[lineno, colno] is self[lineno - 1, colno]
):
out.append(" " * (width + 2))
else:
out.append(char * (width + 2))
head = "+" if out[0][0] == "-" else "|"
tail = "+" if out[-1][0] == "-" else "|"
glue = [
"+" if left[0] == "-" or right[0] == "-" else "|"
for left, right in zip(out, out[1:])
]
glue.append(tail)
return head + "".join(chain(*zip(out, glue)))
for lineno, line in enumerate(self.lines):
if self.separator and lineno == self.separator:
out.append(writesep("=", lineno))
else:
out.append(writesep("-", lineno))
for physical_line in range(self.physical_lines_for_line(line)):
linestr = ["|"]
for colno, cell in enumerate(line):
if cell.col != colno:
continue
if lineno != cell.row:
physical_text = ""
elif physical_line >= len(cell.wrapped):
physical_text = ""
else:
physical_text = cell.wrapped[physical_line]
adjust_len = len(physical_text) - column_width(physical_text)
linestr.append(
" " +
physical_text.ljust(
self.cell_width(cell, self.measured_widths) + 1 + adjust_len
) + "|"
)
out.append("".join(linestr))
out.append(writesep("-"))
return "\n".join(out)
class TextWrapper(textwrap.TextWrapper):
"""Custom subclass that uses a different word separator regex."""
wordsep_re = re.compile(
r'(\s+|' # any whitespace
r'(?<=\s)(?::[a-z-]+:)?`\S+|' # interpreted text start
r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|' # hyphenated words
r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash
def _wrap_chunks(self, chunks):
# type: (List[str]) -> List[str]
"""_wrap_chunks(chunks : [string]) -> [string]
The original _wrap_chunks uses len() to calculate width.
This method respects wide/fullwidth characters for width adjustment.
"""
lines = [] # type: List[str]
if self.width <= 0:
raise ValueError("invalid width %r (must be > 0)" % self.width)
chunks.reverse()
while chunks:
cur_line = []
cur_len = 0
if lines:
indent = self.subsequent_indent
else:
indent = self.initial_indent
width = self.width - column_width(indent)
if self.drop_whitespace and chunks[-1].strip() == '' and lines:
del chunks[-1]
while chunks:
l = column_width(chunks[-1])
if cur_len + l <= width:
cur_line.append(chunks.pop())
cur_len += l
else:
break
if chunks and column_width(chunks[-1]) > width:
self._handle_long_word(chunks, cur_line, cur_len, width)
if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
del cur_line[-1]
if cur_line:
lines.append(indent + ''.join(cur_line))
return lines
def _break_word(self, word, space_left):
# type: (str, int) -> Tuple[str, str]
"""_break_word(word : string, space_left : int) -> (string, string)
Break line by unicode width instead of len(word).
"""
total = 0
for i, c in enumerate(word):
total += column_width(c)
if total > space_left:
return word[:i - 1], word[i - 1:]
return word, ''
def _split(self, text):
# type: (str) -> List[str]
"""_split(text : string) -> [string]
Override original method that only split by 'wordsep_re'.
This '_split' split wide-characters into chunk by one character.
"""
def split(t):
# type: (str) -> List[str]
return super(TextWrapper, self)._split(t)
chunks = [] # type: List[str]
for chunk in split(text):
for w, g in groupby(chunk, column_width):
if w == 1:
chunks.extend(split(''.join(g)))
else:
chunks.extend(list(g))
return chunks
def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
# type: (List[str], List[str], int, int) -> None
"""_handle_long_word(chunks : [string],
cur_line : [string],
cur_len : int, width : int)
Override original method for using self._break_word() instead of slice.
"""
space_left = max(width - cur_len, 1)
if self.break_long_words:
l, r = self._break_word(reversed_chunks[-1], space_left)
cur_line.append(l)
reversed_chunks[-1] = r
elif not cur_line:
cur_line.append(reversed_chunks.pop())
MAXWIDTH = 70
STDINDENT = 3
def my_wrap(text, width=MAXWIDTH, **kwargs):
# type: (str, int, Any) -> List[str]
w = TextWrapper(width=width, **kwargs)
return w.wrap(text)
class TextWriter(writers.Writer):
supported = ('text',)
settings_spec = ('No options here.', '', ())
settings_defaults = {} # type: Dict
output = None
def __init__(self, builder):
# type: (TextBuilder) -> None
super().__init__()
self.builder = builder
def translate(self):
# type: () -> None
visitor = self.builder.create_translator(self.document, self.builder)
self.document.walkabout(visitor)
self.output = cast(TextTranslator, visitor).body
class TextTranslator(SphinxTranslator):
builder = None # type: TextBuilder
def __init__(self, document, builder):
# type: (nodes.document, TextBuilder) -> None
super().__init__(document, builder)
newlines = self.config.text_newlines
if newlines == 'windows':
self.nl = '\r\n'
elif newlines == 'native':
self.nl = os.linesep
else:
self.nl = '\n'
self.sectionchars = self.config.text_sectionchars
self.add_secnumbers = self.config.text_add_secnumbers
self.secnumber_suffix = self.config.text_secnumber_suffix
self.states = [[]] # type: List[List[Tuple[int, Union[str, List[str]]]]]
self.stateindent = [0]
self.list_counter = [] # type: List[int]
self.sectionlevel = 0
self.lineblocklevel = 0
self.table = None # type: Table
def add_text(self, text):
# type: (str) -> None
self.states[-1].append((-1, text))
def new_state(self, indent=STDINDENT):
# type: (int) -> None
self.states.append([])
self.stateindent.append(indent)
def end_state(self, wrap=True, end=[''], first=None):
# type: (bool, List[str], str) -> None
content = self.states.pop()
maxindent = sum(self.stateindent)
indent = self.stateindent.pop()
result = [] # type: List[Tuple[int, List[str]]]
toformat = [] # type: List[str]
def do_format():
# type: () -> None
if not toformat:
return
if wrap:
res = my_wrap(''.join(toformat), width=MAXWIDTH - maxindent)
else:
res = ''.join(toformat).splitlines()
if end:
res += end
result.append((indent, res))
for itemindent, item in content:
if itemindent == -1:
toformat.append(item) # type: ignore
else:
do_format()
result.append((indent + itemindent, item)) # type: ignore
toformat = []
do_format()
if first is not None and result:
itemindent, item = result[0]
result_rest, result = result[1:], []
if item:
toformat = [first + ' '.join(item)]
do_format() # re-create `result` from `toformat`
_dummy, new_item = result[0]
result.insert(0, (itemindent - indent, [new_item[0]]))
result[1] = (itemindent, new_item[1:])
result.extend(result_rest)
self.states[-1].extend(result)
def visit_document(self, node):
# type: (nodes.Element) -> None
self.new_state(0)
def depart_document(self, node):
# type: (nodes.Element) -> None
self.end_state()
self.body = self.nl.join(line and (' ' * indent + line)
for indent, lines in self.states[0]
for line in lines)
# XXX header/footer?
def visit_section(self, node):
# type: (nodes.Element) -> None
self._title_char = self.sectionchars[self.sectionlevel]
self.sectionlevel += 1
def depart_section(self, node):
# type: (nodes.Element) -> None
self.sectionlevel -= 1
def visit_topic(self, node):
# type: (nodes.Element) -> None
self.new_state(0)
def depart_topic(self, node):
# type: (nodes.Element) -> None
self.end_state()
visit_sidebar = visit_topic
depart_sidebar = depart_topic
def visit_rubric(self, node):
# type: (nodes.Element) -> None
self.new_state(0)
self.add_text('-[ ')
def depart_rubric(self, node):
# type: (nodes.Element) -> None
self.add_text(' ]-')
self.end_state()
def visit_compound(self, node):
# type: (nodes.Element) -> None
pass
def depart_compound(self, node):
# type: (nodes.Element) -> None
pass
def visit_glossary(self, node):
# type: (nodes.Element) -> None
pass
def depart_glossary(self, node):
# type: (nodes.Element) -> None
pass
def visit_title(self, node):
# type: (nodes.Element) -> None
if isinstance(node.parent, nodes.Admonition):
self.add_text(node.astext() + ': ')
raise nodes.SkipNode
self.new_state(0)
def get_section_number_string(self, node):
# type: (nodes.Element) -> str
if isinstance(node.parent, nodes.section):
anchorname = '#' + node.parent['ids'][0]
numbers = self.builder.secnumbers.get(anchorname)
if numbers is None:
numbers = self.builder.secnumbers.get('')
if numbers is not None:
return '.'.join(map(str, numbers)) + self.secnumber_suffix
return ''
def depart_title(self, node):
# type: (nodes.Element) -> None
if isinstance(node.parent, nodes.section):
char = self._title_char
else:
char = '^'
text = ''
text = ''.join(x[1] for x in self.states.pop() if x[0] == -1) # type: ignore
if self.add_secnumbers:
text = self.get_section_number_string(node) + text
self.stateindent.pop()
title = ['', text, '%s' % (char * column_width(text)), '']
if len(self.states) == 2 and len(self.states[-1]) == 0:
# remove an empty line before title if it is first section title in the document
title.pop(0)
self.states[-1].append((0, title))
def visit_subtitle(self, node):
# type: (nodes.Element) -> None
pass
def depart_subtitle(self, node):
# type: (nodes.Element) -> None
pass
def visit_attribution(self, node):
# type: (nodes.Element) -> None
self.add_text('-- ')
def depart_attribution(self, node):
# type: (nodes.Element) -> None
pass
def visit_desc(self, node):
# type: (nodes.Element) -> None
pass
def depart_desc(self, node):
# type: (nodes.Element) -> None
pass
def visit_desc_signature(self, node):
# type: (nodes.Element) -> None
self.new_state(0)
def depart_desc_signature(self, node):
# type: (nodes.Element) -> None
# XXX: wrap signatures in a way that makes sense
self.end_state(wrap=False, end=None)
def visit_desc_signature_line(self, node):
# type: (nodes.Element) -> None
pass
def depart_desc_signature_line(self, node):
# type: (nodes.Element) -> None
self.add_text('\n')
def visit_desc_name(self, node):
# type: (nodes.Element) -> None
pass
def depart_desc_name(self, node):
# type: (nodes.Element) -> None
pass
def visit_desc_addname(self, node):
# type: (nodes.Element) -> None
pass
def depart_desc_addname(self, node):
# type: (nodes.Element) -> None
pass
def visit_desc_type(self, node):
# type: (nodes.Element) -> None
pass
def depart_desc_type(self, node):
# type: (nodes.Element) -> None
pass
def visit_desc_returns(self, node):
# type: (nodes.Element) -> None
self.add_text(' -> ')
def depart_desc_returns(self, node):
# type: (nodes.Element) -> None
pass
def visit_desc_parameterlist(self, node):
# type: (nodes.Element) -> None
self.add_text('(')
self.first_param = 1
def depart_desc_parameterlist(self, node):
# type: (nodes.Element) -> None
self.add_text(')')
def visit_desc_parameter(self, node):
# type: (nodes.Element) -> None
if not self.first_param:
self.add_text(', ')
else:
self.first_param = 0
self.add_text(node.astext())
raise nodes.SkipNode
def visit_desc_optional(self, node):
# type: (nodes.Element) -> None
self.add_text('[')
def depart_desc_optional(self, node):
# type: (nodes.Element) -> None
self.add_text(']')
def visit_desc_annotation(self, node):
# type: (nodes.Element) -> None
pass
def depart_desc_annotation(self, node):
# type: (nodes.Element) -> None
pass
def visit_desc_content(self, node):
# type: (nodes.Element) -> None
self.new_state()
self.add_text(self.nl)
def depart_desc_content(self, node):
# type: (nodes.Element) -> None
self.end_state()
def visit_figure(self, node):
# type: (nodes.Element) -> None
self.new_state()
def depart_figure(self, node):
# type: (nodes.Element) -> None
self.end_state()
def visit_caption(self, node):
# type: (nodes.Element) -> None
pass
def depart_caption(self, node):
# type: (nodes.Element) -> None
pass
def visit_productionlist(self, node):
# type: (nodes.Element) -> None
self.new_state()
names = []
productionlist = cast(Iterable[addnodes.production], node)
for production in productionlist:
names.append(production['tokenname'])
maxlen = max(len(name) for name in names)
lastname = None
for production in productionlist:
if production['tokenname']:
self.add_text(production['tokenname'].ljust(maxlen) + ' ::=')
lastname = production['tokenname']
elif lastname is not None:
self.add_text('%s ' % (' ' * len(lastname)))
self.add_text(production.astext() + self.nl)
self.end_state(wrap=False)
raise nodes.SkipNode
def visit_footnote(self, node):
# type: (nodes.Element) -> None
label = cast(nodes.label, node[0])
self._footnote = label.astext().strip()
self.new_state(len(self._footnote) + 3)
def depart_footnote(self, node):
# type: (nodes.Element) -> None
self.end_state(first='[%s] ' % self._footnote)
def visit_citation(self, node):
# type: (nodes.Element) -> None
if len(node) and isinstance(node[0], nodes.label):
self._citlabel = node[0].astext()
else:
self._citlabel = ''
self.new_state(len(self._citlabel) + 3)
def depart_citation(self, node):
# type: (nodes.Element) -> None
self.end_state(first='[%s] ' % self._citlabel)
def visit_label(self, node):
# type: (nodes.Element) -> None
raise nodes.SkipNode
def visit_legend(self, node):
# type: (nodes.Element) -> None
pass
def depart_legend(self, node):
# type: (nodes.Element) -> None
pass
# XXX: option list could use some better styling
def visit_option_list(self, node):
# type: (nodes.Element) -> None
pass
def depart_option_list(self, node):
# type: (nodes.Element) -> None
pass
def visit_option_list_item(self, node):
# type: (nodes.Element) -> None
self.new_state(0)
def depart_option_list_item(self, node):
# type: (nodes.Element) -> None
self.end_state()
def visit_option_group(self, node):
# type: (nodes.Element) -> None
self._firstoption = True
def depart_option_group(self, node):
# type: (nodes.Element) -> None
self.add_text(' ')
def visit_option(self, node):
# type: (nodes.Element) -> None
if self._firstoption:
self._firstoption = False
else:
self.add_text(', ')
def depart_option(self, node):
# type: (nodes.Element) -> None
pass
def visit_option_string(self, node):
# type: (nodes.Element) -> None
pass
def depart_option_string(self, node):
# type: (nodes.Element) -> None
pass
def visit_option_argument(self, node):
# type: (nodes.Element) -> None
self.add_text(node['delimiter'])
def depart_option_argument(self, node):
# type: (nodes.Element) -> None
pass
def visit_description(self, node):
# type: (nodes.Element) -> None
pass
def depart_description(self, node):
# type: (nodes.Element) -> None
pass
def visit_tabular_col_spec(self, node):
# type: (nodes.Element) -> None
raise nodes.SkipNode
def visit_colspec(self, node):
# type: (nodes.Element) -> None
self.table.colwidth.append(node["colwidth"])
raise nodes.SkipNode
def visit_tgroup(self, node):
# type: (nodes.Element) -> None
pass
def depart_tgroup(self, node):
# type: (nodes.Element) -> None
pass
def visit_thead(self, node):
# type: (nodes.Element) -> None
pass
def depart_thead(self, node):
# type: (nodes.Element) -> None
pass
def visit_tbody(self, node):
# type: (nodes.Element) -> None
self.table.set_separator()
def depart_tbody(self, node):
# type: (nodes.Element) -> None
pass
def visit_row(self, node):
# type: (nodes.Element) -> None
if self.table.lines:
self.table.add_row()
def depart_row(self, node):
# type: (nodes.Element) -> None
pass
def visit_entry(self, node):
# type: (nodes.Element) -> None
self.entry = Cell(
rowspan=node.get("morerows", 0) + 1, colspan=node.get("morecols", 0) + 1
)
self.new_state(0)
def depart_entry(self, node):
# type: (nodes.Element) -> None
text = self.nl.join(self.nl.join(x[1]) for x in self.states.pop())
self.stateindent.pop()
self.entry.text = text
self.table.add_cell(self.entry)
self.entry = None
def visit_table(self, node):
# type: (nodes.Element) -> None
if self.table:
raise NotImplementedError('Nested tables are not supported.')
self.new_state(0)
self.table = Table()
def depart_table(self, node):
# type: (nodes.Element) -> None
self.add_text(str(self.table))
self.table = None
self.end_state(wrap=False)
def visit_acks(self, node):
# type: (nodes.Element) -> None
bullet_list = cast(nodes.bullet_list, node[0])
list_items = cast(Iterable[nodes.list_item], bullet_list)
self.new_state(0)
self.add_text(', '.join(n.astext() for n in list_items) + '.')
self.end_state()
raise nodes.SkipNode
def visit_image(self, node):
# type: (nodes.Element) -> None
if 'alt' in node.attributes:
self.add_text(_('[image: %s]') % node['alt'])
self.add_text(_('[image]'))
raise nodes.SkipNode
def visit_transition(self, node):
# type: (nodes.Element) -> None
indent = sum(self.stateindent)
self.new_state(0)
self.add_text('=' * (MAXWIDTH - indent))
self.end_state()
raise nodes.SkipNode
def visit_bullet_list(self, node):
# type: (nodes.Element) -> None
self.list_counter.append(-1)
def depart_bullet_list(self, node):
# type: (nodes.Element) -> None
self.list_counter.pop()
def visit_enumerated_list(self, node):
# type: (nodes.Element) -> None
self.list_counter.append(node.get('start', 1) - 1)
def depart_enumerated_list(self, node):
# type: (nodes.Element) -> None
self.list_counter.pop()
def visit_definition_list(self, node):
# type: (nodes.Element) -> None
self.list_counter.append(-2)
def depart_definition_list(self, node):
# type: (nodes.Element) -> None
self.list_counter.pop()
def visit_list_item(self, node):
# type: (nodes.Element) -> None
if self.list_counter[-1] == -1:
# bullet list
self.new_state(2)
elif self.list_counter[-1] == -2:
# definition list
pass
else:
# enumerated list
self.list_counter[-1] += 1
self.new_state(len(str(self.list_counter[-1])) + 2)
def depart_list_item(self, node):
# type: (nodes.Element) -> None
if self.list_counter[-1] == -1:
self.end_state(first='* ')
elif self.list_counter[-1] == -2:
pass
else:
self.end_state(first='%s. ' % self.list_counter[-1])
def visit_definition_list_item(self, node):
# type: (nodes.Element) -> None
self._classifier_count_in_li = len(node.traverse(nodes.classifier))
def depart_definition_list_item(self, node):
# type: (nodes.Element) -> None
pass
def visit_term(self, node):
# type: (nodes.Element) -> None
self.new_state(0)
def depart_term(self, node):
# type: (nodes.Element) -> None
if not self._classifier_count_in_li:
self.end_state(end=None)
def visit_classifier(self, node):
# type: (nodes.Element) -> None
self.add_text(' : ')
def depart_classifier(self, node):
# type: (nodes.Element) -> None
self._classifier_count_in_li -= 1
if not self._classifier_count_in_li:
self.end_state(end=None)
def visit_definition(self, node):
# type: (nodes.Element) -> None
self.new_state()
def depart_definition(self, node):
# type: (nodes.Element) -> None
self.end_state()
def visit_field_list(self, node):
# type: (nodes.Element) -> None
pass
def depart_field_list(self, node):
# type: (nodes.Element) -> None
pass
def visit_field(self, node):
# type: (nodes.Element) -> None
pass
def depart_field(self, node):
# type: (nodes.Element) -> None
pass
def visit_field_name(self, node):
# type: (nodes.Element) -> None
self.new_state(0)
def depart_field_name(self, node):
# type: (nodes.Element) -> None
self.add_text(':')
self.end_state(end=None)
def visit_field_body(self, node):
# type: (nodes.Element) -> None
self.new_state()
def depart_field_body(self, node):
# type: (nodes.Element) -> None
self.end_state()
def visit_centered(self, node):
# type: (nodes.Element) -> None
pass
def depart_centered(self, node):
# type: (nodes.Element) -> None
pass
def visit_hlist(self, node):
# type: (nodes.Element) -> None
pass
def depart_hlist(self, node):
# type: (nodes.Element) -> None
pass
def visit_hlistcol(self, node):
# type: (nodes.Element) -> None
pass
def depart_hlistcol(self, node):
# type: (nodes.Element) -> None
pass
def visit_admonition(self, node):
# type: (nodes.Element) -> None
self.new_state(0)
def depart_admonition(self, node):
# type: (nodes.Element) -> None
self.end_state()
def _visit_admonition(self, node):
# type: (nodes.Element) -> None
self.new_state(2)
if isinstance(node.children[0], nodes.Sequential):
self.add_text(self.nl)
def _depart_admonition(self, node):
# type: (nodes.Element) -> None
label = admonitionlabels[node.tagname]
self.end_state(first=label + ': ')
visit_attention = _visit_admonition
depart_attention = _depart_admonition
visit_caution = _visit_admonition
depart_caution = _depart_admonition
visit_danger = _visit_admonition
depart_danger = _depart_admonition
visit_error = _visit_admonition
depart_error = _depart_admonition
visit_hint = _visit_admonition
depart_hint = _depart_admonition
visit_important = _visit_admonition
depart_important = _depart_admonition
visit_note = _visit_admonition
depart_note = _depart_admonition
visit_tip = _visit_admonition
depart_tip = _depart_admonition
visit_warning = _visit_admonition
depart_warning = _depart_admonition
visit_seealso = _visit_admonition
depart_seealso = _depart_admonition
def visit_versionmodified(self, node):
# type: (nodes.Element) -> None
self.new_state(0)
def depart_versionmodified(self, node):
# type: (nodes.Element) -> None
self.end_state()
def visit_literal_block(self, node):
# type: (nodes.Element) -> None
self.new_state()
def depart_literal_block(self, node):
# type: (nodes.Element) -> None
self.end_state(wrap=False)
def visit_doctest_block(self, node):
# type: (nodes.Element) -> None
self.new_state(0)
def depart_doctest_block(self, node):
# type: (nodes.Element) -> None
self.end_state(wrap=False)
def visit_line_block(self, node):
# type: (nodes.Element) -> None
self.new_state()
self.lineblocklevel += 1
def depart_line_block(self, node):
# type: (nodes.Element) -> None
self.lineblocklevel -= 1
self.end_state(wrap=False, end=None)
if not self.lineblocklevel:
self.add_text('\n')
def visit_line(self, node):
# type: (nodes.Element) -> None
pass
def depart_line(self, node):
# type: (nodes.Element) -> None
self.add_text('\n')
def visit_block_quote(self, node):
# type: (nodes.Element) -> None
self.new_state()
def depart_block_quote(self, node):
# type: (nodes.Element) -> None
self.end_state()
def visit_compact_paragraph(self, node):
# type: (nodes.Element) -> None
pass
def depart_compact_paragraph(self, node):
# type: (nodes.Element) -> None
pass
def visit_paragraph(self, node):
# type: (nodes.Element) -> None
if not isinstance(node.parent, nodes.Admonition) or \
isinstance(node.parent, addnodes.seealso):
self.new_state(0)
def depart_paragraph(self, node):
# type: (nodes.Element) -> None
if not isinstance(node.parent, nodes.Admonition) or \
isinstance(node.parent, addnodes.seealso):
self.end_state()
def visit_target(self, node):
# type: (nodes.Element) -> None
raise nodes.SkipNode
def visit_index(self, node):
# type: (nodes.Element) -> None
raise nodes.SkipNode
def visit_toctree(self, node):
# type: (nodes.Element) -> None
raise nodes.SkipNode
def visit_pending_xref(self, node):
# type: (nodes.Element) -> None
pass
def depart_pending_xref(self, node):
# type: (nodes.Element) -> None
pass
def visit_reference(self, node):
# type: (nodes.Element) -> None
if self.add_secnumbers:
numbers = node.get("secnumber")
if numbers is not None:
self.add_text('.'.join(map(str, numbers)) + self.secnumber_suffix)
def depart_reference(self, node):
# type: (nodes.Element) -> None
pass
def visit_number_reference(self, node):
# type: (nodes.Element) -> None
text = nodes.Text(node.get('title', '#'))
self.visit_Text(text)
raise nodes.SkipNode
def visit_download_reference(self, node):
# type: (nodes.Element) -> None
pass
def depart_download_reference(self, node):
# type: (nodes.Element) -> None
pass
def visit_emphasis(self, node):
# type: (nodes.Element) -> None
self.add_text('*')
def depart_emphasis(self, node):
# type: (nodes.Element) -> None
self.add_text('*')
def visit_literal_emphasis(self, node):
# type: (nodes.Element) -> None
self.add_text('*')
def depart_literal_emphasis(self, node):
# type: (nodes.Element) -> None
self.add_text('*')
def visit_strong(self, node):
# type: (nodes.Element) -> None
self.add_text('**')
def depart_strong(self, node):
# type: (nodes.Element) -> None
self.add_text('**')
def visit_literal_strong(self, node):
# type: (nodes.Element) -> None
self.add_text('**')
def depart_literal_strong(self, node):
# type: (nodes.Element) -> None
self.add_text('**')
def visit_abbreviation(self, node):
# type: (nodes.Element) -> None
self.add_text('')
def depart_abbreviation(self, node):
# type: (nodes.Element) -> None
if node.hasattr('explanation'):
self.add_text(' (%s)' % node['explanation'])
def visit_manpage(self, node):
# type: (nodes.Element) -> None
return self.visit_literal_emphasis(node)
def depart_manpage(self, node):
# type: (nodes.Element) -> None
return self.depart_literal_emphasis(node)
def visit_title_reference(self, node):
# type: (nodes.Element) -> None
self.add_text('*')
def depart_title_reference(self, node):
# type: (nodes.Element) -> None
self.add_text('*')
def visit_literal(self, node):
# type: (nodes.Element) -> None
self.add_text('"')
def depart_literal(self, node):
# type: (nodes.Element) -> None
self.add_text('"')
def visit_subscript(self, node):
# type: (nodes.Element) -> None
self.add_text('_')
def depart_subscript(self, node):
# type: (nodes.Element) -> None
pass
def visit_superscript(self, node):
# type: (nodes.Element) -> None
self.add_text('^')
def depart_superscript(self, node):
# type: (nodes.Element) -> None
pass
def visit_footnote_reference(self, node):
# type: (nodes.Element) -> None
self.add_text('[%s]' % node.astext())
raise nodes.SkipNode
def visit_citation_reference(self, node):
# type: (nodes.Element) -> None
self.add_text('[%s]' % node.astext())
raise nodes.SkipNode
def visit_Text(self, node):
# type: (nodes.Text) -> None
self.add_text(node.astext())
def depart_Text(self, node):
# type: (nodes.Text) -> None
pass
def visit_generated(self, node):
# type: (nodes.Element) -> None
pass
def depart_generated(self, node):
# type: (nodes.Element) -> None
pass
def visit_inline(self, node):
# type: (nodes.Element) -> None
if 'xref' in node['classes'] or 'term' in node['classes']:
self.add_text('*')
def depart_inline(self, node):
# type: (nodes.Element) -> None
if 'xref' in node['classes'] or 'term' in node['classes']:
self.add_text('*')
def visit_container(self, node):
# type: (nodes.Element) -> None
pass
def depart_container(self, node):
# type: (nodes.Element) -> None
pass
def visit_problematic(self, node):
# type: (nodes.Element) -> None
self.add_text('>>')
def depart_problematic(self, node):
# type: (nodes.Element) -> None
self.add_text('<<')
def visit_system_message(self, node):
# type: (nodes.Element) -> None
self.new_state(0)
self.add_text('<SYSTEM MESSAGE: %s>' % node.astext())
self.end_state()
raise nodes.SkipNode
def visit_comment(self, node):
# type: (nodes.Element) -> None
raise nodes.SkipNode
def visit_meta(self, node):
# type: (nodes.Element) -> None
# only valid for HTML
raise nodes.SkipNode
def visit_raw(self, node):
# type: (nodes.Element) -> None
if 'text' in node.get('format', '').split():
self.new_state(0)
self.add_text(node.astext())
self.end_state(wrap = False)
raise nodes.SkipNode
def visit_math(self, node):
# type: (nodes.Element) -> None
pass
def depart_math(self, node):
# type: (nodes.Element) -> None
pass
def visit_math_block(self, node):
# type: (nodes.Element) -> None
self.new_state()
def depart_math_block(self, node):
# type: (nodes.Element) -> None
self.end_state()
def unknown_visit(self, node):
# type: (nodes.Node) -> None
raise NotImplementedError('Unknown node: ' + node.__class__.__name__)
def _make_depart_admonition(name): # type: ignore
# type: (str) -> Callable[[TextTranslator, nodes.Element], None]
warnings.warn('TextTranslator._make_depart_admonition() is deprecated.',
RemovedInSphinx30Warning)
def depart_admonition(self, node):
# type: (TextTranslator, nodes.Element) -> None
self.end_state(first=admonitionlabels[name] + ': ')
return depart_admonition
|