forked from nltk/nltk_book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rst.py
executable file
·2750 lines (2356 loc) · 105 KB
/
rst.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
#!/usr/bin/env python
#
# Natural Language Toolkit: Documentation generation script
#
# Copyright (C) 2001-2012 NLTK Project
# Author: Edward Loper <[email protected]>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
r"""
This is a customized driver for converting docutils reStructuredText
documents into HTML and LaTeX. It customizes the standard writers in
the following ways:
- Source code highlighting is added to all doctest blocks. In
the HTML output, highlighting is performed using css classes:
'pysrc-prompt', 'pysrc-keyword', 'pysrc-string', 'pysrc-comment',
and 'pysrc-output'. In the LaTeX output, highlighting uses five
new latex commands: '\pysrcprompt', '\pysrckeyword',
'\pysrcstring', '\pysrccomment', and '\pyrcoutput'.
- A new "example" directive is defined.
- A new "doctest-ignore" directive is defined.
- A new "tree" directive is defined.
- New directives "def", "ifdef", and "ifndef", which can be used
to conditionally control the inclusion of sections. This is
used, e.g., to make sure that the definitions in 'definitions.rst'
are only performed once, even if 'definitions.rst' is included
multiple times.
"""
# compat hack:
import operator, numbers, collections
operator.isNumberType = lambda x:isinstance(x, numbers.Number)
operator.isSequenceType = lambda x:isinstance(x, collections.Sequence)
import re, os.path, textwrap, sys, pickle
from optparse import OptionParser
from tree2image import tree_to_image
import docutils.core, docutils.nodes, docutils.io
from docutils.writers import Writer
from docutils.writers.html4css1 import HTMLTranslator, Writer as HTMLWriter
from docutils.writers.latex2e import LaTeXTranslator, Writer as LaTeXWriter
from docutils.parsers.rst import directives, roles
from docutils.readers.standalone import Reader as StandaloneReader
from docutils.transforms import Transform
import docutils.writers.html4css1
from doctest import DocTestParser
import docutils.statemachine
try: import PIL.Image
except: pass
LATEX_VALIGN_IS_BROKEN = True
"""Set to true to compensate for a bug in the latex writer. I've
submitted a patch to docutils, so hopefully this wil be fixed
soon."""
LATEX_DPI = 144
"""The scaling factor that should be used to display bitmapped images
in latex/pdf output (specified in dots per inch). E.g., if a
bitmapped image is 100 pixels wide, it will be scaled to
100/LATEX_DPI inches wide for the latex/pdf output. (Larger
values produce smaller images in the generated pdf.)"""
OUTPUT_FORMAT = None
"""A global variable, set by main(), indicating the output format for
the current file. Can be 'latex' or 'html' or 'ref'."""
OUTPUT_BASENAME = None
"""A global variable, set by main(), indicating the base filename
of the current file (i.e., the filename with its extension
stripped). This is used to generate filenames for images."""
TREE_IMAGE_DIR = 'tree_images/'
"""The directory that tree images should be written to."""
EXTERN_REFERENCE_FILES = []
"""A list of .ref files, for crossrefering to external documents (used
when building one chapter at a time)."""
BIBTEX_FILE = '../refs.bib'
"""The name of the bibtex file used to generate bibliographic entries."""
BIBLIOGRAPHY_HTML = "bibliography.html"
"""The name of the HTML file containing the bibliography (for
hyperrefs from citations)."""
# needs to include "../doc" so it works in /doc_contrib
LATEX_STYLESHEET_PATH = '../../doc/definitions.sty'
"""The name of the LaTeX style file used for generating PDF output."""
LOCAL_BIBLIOGRAPHY = False
"""If true, assume that this document contains the bibliography, and
link to it locally; if false, assume that bibliographic links
should point to L{BIBLIOGRAPHY_HTML}."""
PYLISTING_DIR = 'pylisting/'
"""The directory where pylisting files should be written."""
PYLISTING_EXTENSION = ".py"
"""Extension for pylisting files."""
INCLUDE_DOCTESTS_IN_PYLISTING_FILES = False
"""If true, include code from doctests in the generated pylisting
files. """
CALLOUT_IMG = '<img src="callouts/callout%s.gif" alt="[%s]" class="callout" />'
"""HTML code for callout images in pylisting blocks."""
REF_EXTENSION = '.ref'
"""File extension for reference files."""
# needs to include "../doc" so it works in /doc_contrib
CSS_STYLESHEET = '../nltkdoc.css'
######################################################################
#{ Reference files
######################################################################
def read_ref_file(basename=None):
if basename is None: basename = OUTPUT_BASENAME
if not os.path.exists(basename + REF_EXTENSION):
warning('File %r does not exist!' %
(basename + REF_EXTENSION))
return dict(targets=(),terms={},reference_labes={})
f = open(basename + REF_EXTENSION, 'rb')
ref_info = pickle.load(f)
f.close()
return ref_info
def write_ref_file(ref_info):
f = open(OUTPUT_BASENAME + REF_EXTENSION, 'wb')
pickle.dump(ref_info, f)
f.close()
def add_to_ref_file(**ref_info):
if os.path.exists(OUTPUT_BASENAME + REF_EXTENSION):
info = read_ref_file()
info.update(ref_info)
write_ref_file(info)
else:
write_ref_file(ref_info)
######################################################################
#{ Directives
######################################################################
class example(docutils.nodes.paragraph): pass
def example_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
"""
Basic use::
.. example:: John went to the store.
To refer to examples, use::
.. _store:
.. example:: John went to the store.
In store_, John performed an action.
"""
text = '\n'.join(content)
node = example(text)
state.nested_parse(content, content_offset, node)
return [node]
example_directive.content = True
directives.register_directive('example', example_directive)
directives.register_directive('ex', example_directive)
def doctest_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
"""
Used to explicitly mark as doctest blocks things that otherwise
wouldn't look like doctest blocks.
"""
text = '\n'.join(content)
if re.match(r'.*\n\s*\n', block_text):
warning('doctest-ignore on line %d will not be ignored, '
'because there is\na blank line between ".. doctest-ignore::"'
' and the doctest example.' % lineno)
return [docutils.nodes.doctest_block(text, text, codeblock=True)]
doctest_directive.content = True
directives.register_directive('doctest-ignore', doctest_directive)
_treenum = 0
def tree_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
global _treenum
text = '\n'.join(arguments) + '\n'.join(content)
_treenum += 1
# Note: the two filenames generated by these two cases should be
# different, to prevent conflicts.
if OUTPUT_FORMAT == 'latex':
density, scale = 300, 150
scale = scale * options.get('scale', 100) / 100
filename = '%s-tree-%s.pdf' % (OUTPUT_BASENAME, _treenum)
align = LATEX_VALIGN_IS_BROKEN and 'bottom' or 'top'
elif OUTPUT_FORMAT == 'html':
density, scale = 100, 100
density = density * options.get('scale', 100) / 100
filename = '%s-tree-%s.png' % (OUTPUT_BASENAME, _treenum)
align = 'top'
elif OUTPUT_FORMAT == 'ref':
return []
elif OUTPUT_FORMAT == 'docbook':
# warning('TREE DIRECTIVE -- CHECK THIS')
scale = options.get('scale', 60)
density = 300 * scale / 100
filename = '%s-tree-%s.png' % (OUTPUT_BASENAME, _treenum)
align = 'top'
else:
assert 0, 'bad output format %r' % OUTPUT_FORMAT
if not os.path.exists(TREE_IMAGE_DIR):
os.mkdir(TREE_IMAGE_DIR)
try:
filename = os.path.join(TREE_IMAGE_DIR, filename)
tree_to_image(text, filename, density)
except Exception as e:
raise
warning('Error parsing tree: %s\n%s\n%s' % (e, text, filename))
return [example(text, text)]
imagenode = docutils.nodes.image(uri=filename, scale=scale, align=align)
return [imagenode]
tree_directive.arguments = (1,0,1)
tree_directive.content = True
tree_directive.options = {'scale': directives.nonnegative_int}
directives.register_directive('tree', tree_directive)
def avm_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
text = '\n'.join(content)
try:
if OUTPUT_FORMAT == 'latex':
latex_avm = parse_avm(textwrap.dedent(text)).as_latex()
return [docutils.nodes.paragraph('','',
docutils.nodes.raw('', latex_avm, format='latex'))]
elif OUTPUT_FORMAT == 'html':
return [parse_avm(textwrap.dedent(text)).as_table()]
elif OUTPUT_FORMAT == 'ref':
return [docutils.nodes.paragraph()]
# pass through for now
elif OUTPUT_FORMAT == 'docbook':
return [docutils.nodes.literal_block('', textwrap.dedent(text))]
except ValueError as e:
if isinstance(e.args[0], int):
warning('Error parsing avm on line %s' % (lineno+e.args[0]))
else:
raise
warning('Error parsing avm on line %s: %s' % (lineno, e))
node = example(text, text)
state.nested_parse(content, content_offset, node)
return [node]
avm_directive.content = True
directives.register_directive('avm', avm_directive)
def def_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
state_machine.document.setdefault('__defs__', {})[arguments[0]] = 1
return []
def_directive.arguments = (1, 0, 0)
directives.register_directive('def', def_directive)
def ifdef_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
if arguments[0] in state_machine.document.get('__defs__', ()):
node = docutils.nodes.compound('')
state.nested_parse(content, content_offset, node)
return [node]
else:
return []
ifdef_directive.arguments = (1, 0, 0)
ifdef_directive.content = True
directives.register_directive('ifdef', ifdef_directive)
def ifndef_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
if arguments[0] not in state_machine.document.get('__defs__', ()):
node = docutils.nodes.compound('')
state.nested_parse(content, content_offset, node)
return [node]
else:
return []
ifndef_directive.arguments = (1, 0, 0)
ifndef_directive.content = True
directives.register_directive('ifndef', ifndef_directive)
######################################################################
#{ Table Directive
######################################################################
_table_ids = set()
def table_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
# The identifier for this table.
if arguments:
table_id = arguments[0]
if table_id in _table_ids:
warning("Duplicate table id %r" % table_id)
_table_ids.add(table_id)
# Create a target element for the table
target = docutils.nodes.target(names=[table_id])
state_machine.document.note_explicit_target(target)
# Parse the contents.
node = docutils.nodes.compound('')
state.nested_parse(content, content_offset, node)
if len(node) == 0 or not isinstance(node[0], docutils.nodes.table):
return [state_machine.reporter.error(
'Error in "%s" directive: expected table as first child' %
name)]
# Move the caption into the table.
table = node[0]
caption = docutils.nodes.caption('','', *node[1:])
table.append(caption)
# Return the target and the table.
if arguments:
return [target, table]
else:
return [table]
table_directive.arguments = (0,1,0) # 1 optional arg, no whitespace
table_directive.content = True
table_directive.options = {'caption': directives.unchanged}
directives.register_directive('table', table_directive)
######################################################################
#{ Program Listings
######################################################################
# We define a new attribute for doctest blocks: 'is_codeblock'. If
# this attribute is true, then the block contains python code only
# (i.e., don't expect to find prompts.)
class pylisting(docutils.nodes.General, docutils.nodes.Element):
"""
Python source code listing.
Children: doctest_block+ caption?
"""
class callout_marker(docutils.nodes.Inline, docutils.nodes.Element):
"""
A callout marker for doctest block. This element contains no
children; and defines the attribute 'number'.
"""
DOCTEST_BLOCK_RE = re.compile('((?:^>>>.*\n?(?:.*[^ ].*\n?)+\s*)+)',
re.MULTILINE)
CALLOUT_RE = re.compile(r'#[ ]+\[_([\w-]+)\][ ]*', re.MULTILINE)
from docutils.nodes import fully_normalize_name as normalize_name
_listing_ids = set()
def pylisting_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
# The identifier for this listing.
listing_id = arguments[0]
if listing_id in _listing_ids:
warning("Duplicate listing id %r" % listing_id)
_listing_ids.add(listing_id)
# Create the pylisting element itself.
listing = pylisting('\n'.join(content), name=listing_id, callouts={})
# Create a target element for the pylisting.
target = docutils.nodes.target(names=[listing_id])
state_machine.document.note_explicit_target(target)
# Divide the text into doctest blocks.
for i, v in enumerate(DOCTEST_BLOCK_RE.split('\n'.join(content))):
pysrc = re.sub(r'\A( *\n)+', '', v.rstrip())
if pysrc.strip():
listing.append(docutils.nodes.doctest_block(pysrc, pysrc,
is_codeblock=(i%2==0)))
# Add an optional caption.
if options.get('caption'):
cap = options['caption'].split('\n')
caption = docutils.nodes.compound()
state.nested_parse(docutils.statemachine.StringList(cap),
content_offset, caption)
if (len(caption) == 1 and isinstance(caption[0],
docutils.nodes.paragraph)):
listing.append(docutils.nodes.caption('', '', *caption[0]))
else:
warning("Caption should be a single paragraph")
listing.append(docutils.nodes.caption('', '', *caption))
return [target, listing]
pylisting_directive.arguments = (1,0,0) # 1 required arg, no whitespace
pylisting_directive.content = True
pylisting_directive.options = {'caption': directives.unchanged}
directives.register_directive('pylisting', pylisting_directive)
def callout_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
if arguments:
prefix = '%s-' % arguments[0]
else:
prefix = ''
node = docutils.nodes.compound('')
state.nested_parse(content, content_offset, node)
if not (len(node.children) == 1 and
isinstance(node[0], docutils.nodes.field_list)):
return [state_machine.reporter.error(
'Error in "%s" directive: may contain a single definition '
'list only.' % (name), line=lineno)]
node[0]['classes'] = ['callouts']
for field in node[0]:
if len(field[0]) != 1:
return [state_machine.reporter.error(
'Error in "%s" directive: bad field id' % (name), line=lineno)]
field_name = prefix+('%s' % field[0][0])
field[0].clear()
field[0].append(docutils.nodes.reference(field_name, field_name,
refid=field_name))
field[0]['classes'] = ['callout']
return [node[0]]
callout_directive.arguments = (0,1,0) # 1 optional arg, no whitespace
callout_directive.content = True
directives.register_directive('callouts', callout_directive)
_OPTION_DIRECTIVE_RE = re.compile(
r'(\n[ ]*\.\.\.[ ]*)?#\s*doctest:\s*([^\n\'"]*)$', re.MULTILINE)
def strip_doctest_directives(text):
return _OPTION_DIRECTIVE_RE.sub('', text)
######################################################################
#{ RST In/Out table
######################################################################
def rst_example_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
raw = docutils.nodes.literal_block('', '\n'.join(content))
out = docutils.nodes.compound('')
state.nested_parse(content, content_offset, out)
if OUTPUT_FORMAT == 'latex':
return [
docutils.nodes.definition_list('',
docutils.nodes.definition_list_item('',
docutils.nodes.term('','Input'),
docutils.nodes.definition('', raw)),
docutils.nodes.definition_list_item('',
docutils.nodes.term('','Rendered'),
docutils.nodes.definition('', out)))]
else:
return [
docutils.nodes.table('',
docutils.nodes.tgroup('',
docutils.nodes.colspec(colwidth=5,classes=['rst-raw']),
docutils.nodes.colspec(colwidth=5),
docutils.nodes.thead('',
docutils.nodes.row('',
docutils.nodes.entry('',
docutils.nodes.paragraph('','Input')),
docutils.nodes.entry('',
docutils.nodes.paragraph('','Rendered')))),
docutils.nodes.tbody('',
docutils.nodes.row('',
docutils.nodes.entry('',raw),
docutils.nodes.entry('',out)))),
classes=["rst-example"])]
rst_example_directive.arguments = (0, 0, 0)
rst_example_directive.content = True
directives.register_directive('rst_example', rst_example_directive)
######################################################################
#{ Glosses
######################################################################
"""
.. gloss::
This | is | used | to | make | aligned | glosses.
NN | BE | VB | TO | VB | JJ | NN
*Foog blogg blarg.*
"""
class gloss(docutils.nodes.Element): "glossrow+"
class glossrow(docutils.nodes.Element): "paragraph+"
def gloss_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
# Transform into a table.
lines = list(content)
maxlen = max(len(line) for line in lines)
format = '%%-%ds' % maxlen
lines = [format % line for line in lines]
tablestr = ''
prevline = ''
for line in (lines+['']):
div = ['-']*(maxlen+2)
for m in re.finditer(r'\|', prevline):
div[m.start()] = '+'
for m in re.finditer(r'\|', line):
div[m.start()] = '+'
tablestr += ''.join(div) + '\n' + line + '\n'
prevline = line
table_lines = tablestr.strip().split('\n')
new_content = docutils.statemachine.StringList(table_lines)
# [XX] DEBUG GLOSSES:
# print 'converted to:'
# print tablestr
# Parse the table.
node = docutils.nodes.compound('')
state.nested_parse(new_content, content_offset, node)
if not (len(node.children) == 1 and
isinstance(node[0], docutils.nodes.table)):
error = state_machine.reporter.error(
'Error in "%s" directive: may contain a single table '
'only.' % (name), line=lineno)
return [error]
table = node[0]
table['classes'] = ['gloss', 'nolines']
colspecs = table[0]
for colspec in colspecs:
colspec['colwidth'] = colspec.get('colwidth',4)/2
return [example('', '', table)]
gloss_directive.arguments = (0, 0, 0)
gloss_directive.content = True
directives.register_directive('gloss', gloss_directive)
######################################################################
#{ Bibliography
######################################################################
class Citations(Transform):
default_priority = 500 # before footnotes.
def apply(self):
if not os.path.exists(BIBTEX_FILE):
warning('Warning bibtex file %r not found. '
'Not linking citations.' % BIBTEX_FILE)
return
bibliography = self.read_bibinfo(BIBTEX_FILE)
for k, citation_refs in self.document.citation_refs.items():
for citation_ref in citation_refs[:]:
cite = bibliography.get(citation_ref['refname'].lower())
if cite:
new_cite = self.citeref(cite, citation_ref['refname'])
citation_ref.replace_self(new_cite)
self.document.citation_refs[k].remove(citation_ref)
def citeref(self, cite, key):
if LOCAL_BIBLIOGRAPHY:
return docutils.nodes.raw('', '\cite{%s}' % key, format='latex')
else:
return docutils.nodes.reference('', '', docutils.nodes.Text(cite),
refuri='%s#%s' % (BIBLIOGRAPHY_HTML, key))
BIB_ENTRY = re.compile(r'@\w+{.*')
def read_bibinfo(self, filename):
bibliography = {} # key -> authors, year
key = None
for line in open(filename):
line = line.strip()
# @InProceedings{<key>,
m = re.match(r'@\w+{([^,]+),$', line)
if m:
key = m.group(1).strip().lower()
bibliography[key] = [None, None]
# author = <authors>,
m = re.match(r'(?i)author\s*=\s*(.*)$', line)
if m and key:
bibliography[key][0] = self.bib_authors(m.group(1))
else:
m = re.match(r'(?i)editor\s*=\s*(.*)$', line)
if m and key:
bibliography[key][0] = self.bib_authors(m.group(1))
# year = <year>,
m = re.match(r'(?i)year\s*=\s*(.*)$', line)
if m and key:
bibliography[key][1] = self.bib_year(m.group(1))
for key in bibliography:
if bibliography[key][0] is None: warning('no author found:', key)
if bibliography[key][1] is None: warning('no year found:', key)
bibliography[key] = '(%s, %s)' % tuple(bibliography[key])
#debug('%20s %s' % (key, `bibliography[key]`))
return bibliography
def bib_year(self, year):
return re.sub(r'["\'{},]', "", year)
def bib_authors(self, authors):
# Strip trailing comma:
if authors[-1:] == ',': authors=authors[:-1]
# Strip quotes or braces:
authors = re.sub(r'"(.*)"$', r'\1', authors)
authors = re.sub(r'{(.*)}$', r'\1', authors)
authors = re.sub(r"'(.*)'$", r'\1', authors)
# Split on 'and':
authors = re.split(r'\s+and\s+', authors)
# Keep last name only:
authors = [a.split()[-1] for a in authors]
# Combine:
if len(authors) == 1:
return authors[0]
elif len(authors) == 2:
return '%s & %s' % tuple(authors)
elif len(authors) == 3:
return '%s, %s, & %s' % tuple(authors)
else:
return '%s et al' % authors[0]
return authors
######################################################################
#{ Indexing
######################################################################
#class termdef(docutils.nodes.Inline, docutils.nodes.TextElement): pass
class idxterm(docutils.nodes.Inline, docutils.nodes.TextElement): pass
class index(docutils.nodes.Element): pass
def idxterm_role(name, rawtext, text, lineno, inliner,
options={}, content=[]):
if name == 'dt': options['classes'] = ['termdef']
elif name == 'topic': options['classes'] = ['topic']
else: options['classes'] = ['term']
# Recursively parse the contents of the index term, in case it
# contains a substitiution (like |alpha|).
nodes, msgs = inliner.parse(text, lineno, memo=inliner,
parent=inliner.parent)
return [idxterm(rawtext, '', *nodes, **options)], []
roles.register_canonical_role('dt', idxterm_role)
roles.register_canonical_role('idx', idxterm_role)
roles.register_canonical_role('topic', idxterm_role)
def index_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
pending = docutils.nodes.pending(ConstructIndex)
pending.details.update(options)
state_machine.document.note_pending(pending)
return [index('', pending)]
index_directive.arguments = (0, 0, 0)
index_directive.content = False
index_directive.options = {'extern': directives.flag}
directives.register_directive('index', index_directive)
class SaveIndexTerms(Transform):
default_priority = 810 # before NumberReferences transform
def apply(self):
v = FindTermVisitor(self.document)
self.document.walkabout(v)
if OUTPUT_FORMAT == 'ref':
add_to_ref_file(terms=v.terms)
class ConstructIndex(Transform):
default_priority = 820 # after NumberNodes, before NumberReferences.
def apply(self):
# Find any indexed terms in this document.
v = FindTermVisitor(self.document)
self.document.walkabout(v)
terms = v.terms
# Check the extern reference files for additional terms.
if 'extern' in self.startnode.details:
for filename in EXTERN_REFERENCE_FILES:
basename = os.path.splitext(filename)[0]
terms.update(read_ref_file(basename)['terms'])
# Build the index & insert it into the document.
index_node = self.build_index(terms)
self.startnode.replace_self(index_node)
def build_index(self, terms):
if not terms: return []
top = docutils.nodes.bullet_list('', classes=['index'])
start_letter = None
section = None
for key in sorted(terms.keys()):
if key[:1] != start_letter:
top.append(docutils.nodes.list_item(
'', docutils.nodes.paragraph('', key[:1].upper()+'\n',
classes=['index-heading']),
docutils.nodes.bullet_list('', classes=['index-section']),
classes=['index']))
section = top[-1][-1]
section.append(self.entry(terms[key]))
start_letter = key[:1]
return top
def entry(self, term_info):
entrytext, name, sectnum = term_info
if sectnum is not None:
entrytext.append(docutils.nodes.emphasis('', ' (%s)' % sectnum))
ref = docutils.nodes.reference('', '', refid=name,
#resolved=True,
*entrytext)
para = docutils.nodes.paragraph('', '', ref)
return docutils.nodes.list_item('', para, classes=['index'])
class FindTermVisitor(docutils.nodes.SparseNodeVisitor):
def __init__(self, document):
self.terms = {}
docutils.nodes.NodeVisitor.__init__(self, document)
def unknown_visit(self, node): pass
def unknown_departure(self, node): pass
def visit_idxterm(self, node):
node['name'] = node['id'] = self.idxterm_key(node)
node['names'] = node['ids'] = [node['id']]
container = self.container_section(node)
entrytext = node.deepcopy()
if container: sectnum = container.get('sectnum')
else: sectnum = '0'
name = node['name']
self.terms[node['name']] = (entrytext, name, sectnum)
def idxterm_key(self, node):
key = re.sub('\W', '_', node.astext().lower())+'_index_term'
if key not in self.terms: return key
n = 2
while '%s_%d' % (key, n) in self.terms: n += 1
return '%s_%d' % (key, n)
def container_section(self, node):
while not isinstance(node, docutils.nodes.section):
if node.parent is None: return None
else: node = node.parent
return node
######################################################################
#{ Crossreferences
######################################################################
class ResolveExternalCrossrefs(Transform):
"""
Using the information from EXTERN_REFERENCE_FILES, look for any
links to external targets, and set their `refuid` appropriately.
Also, if they are a figure, section, table, or example, then
replace the link of the text with the appropriate counter.
"""
default_priority = 849 # right before dangling refs
def apply(self):
ref_dict = self.build_ref_dict()
v = ExternalCrossrefVisitor(self.document, ref_dict)
self.document.walkabout(v)
def build_ref_dict(self):
"""{target -> (uri, label)}"""
ref_dict = {}
for filename in EXTERN_REFERENCE_FILES:
basename = os.path.splitext(filename)[0]
if OUTPUT_FORMAT == 'html':
uri = os.path.split(basename)[-1]+'.html'
else:
uri = os.path.split(basename)[-1]+'.pdf'
if basename == OUTPUT_BASENAME:
pass # don't read our own ref file.
elif not os.path.exists(basename+REF_EXTENSION):
warning('%s does not exist' % (basename+REF_EXTENSION))
else:
ref_info = read_ref_file(basename)
#print basename
#print ref_info.keys()
for ref in ref_info['targets']:
label = ref_info['reference_labels'].get(ref)
ref_dict[ref] = (uri, label)
return ref_dict
class ExternalCrossrefVisitor(docutils.nodes.NodeVisitor):
def __init__(self, document, ref_dict):
docutils.nodes.NodeVisitor.__init__(self, document)
self.ref_dict = ref_dict
def unknown_visit(self, node): pass
def unknown_departure(self, node): pass
# Don't mess with the table of contents.
def visit_topic(self, node):
if 'contents' in node.get('classes', ()):
raise docutils.nodes.SkipNode
def visit_reference(self, node):
if node.resolved: return
node_id = node.get('refid') or node.get('refname')
if node_id in self.ref_dict:
uri, label = self.ref_dict[node_id]
#debug('xref: %20s -> %-30s (label=%s)' % (
# node_id, uri+'#'+node_id, label))
node['refuri'] = '%s#%s' % (uri, node_id)
node.resolved = True
if label is not None:
if node.get('expanded_ref'):
warning('Label %s is defined both locally (%s) and '
'externally (%s)' % (node_id, node[0], label))
# hmm...
else:
node.clear()
node.append(docutils.nodes.Text(label))
process_reference_text(node, node_id)
######################################################################
#{ Figure & Example Numbering
######################################################################
# [xx] number examples, figures, etc, relative to chapter? e.g.,
# figure 3.2? maybe number examples within-chapter, but then restart
# the counter?
class section_context(docutils.nodes.Invisible, docutils.nodes.Element):
def __init__(self, context):
docutils.nodes.Element.__init__(self, '', context=context)
assert self['context'] in ('body', 'preface', 'appendix')
def section_context_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
return [section_context(name)]
section_context_directive.arguments = (0,0,0)
directives.register_directive('preface', section_context_directive)
directives.register_directive('body', section_context_directive)
directives.register_directive('appendix', section_context_directive)
class NumberNodes(Transform):
"""
This transform adds numbers to figures, tables, and examples; and
converts references to the figures, tables, and examples to use
these numbers. For example, given the rst source::
.. _my_example:
.. ex:: John likes Mary.
See example my_example_.
This transform will assign a number to the example, '(1)', and
will replace the following text with 'see example (1)', with an
appropriate link.
"""
# dangling = 850; contents = 720.
default_priority = 800
def apply(self):
v = NumberingVisitor(self.document)
self.document.walkabout(v)
self.document.reference_labels = v.reference_labels
self.document.callout_labels = v.callout_labels
class NumberReferences(Transform):
default_priority = 830
def apply(self):
v = ReferenceVisitor(self.document, self.document.reference_labels,
self.document.callout_labels)
self.document.walkabout(v)
# Save reference info to a pickle file.
if OUTPUT_FORMAT == 'ref':
add_to_ref_file(reference_labels=self.document.reference_labels,
targets=v.targets)
class NumberingVisitor(docutils.nodes.NodeVisitor):
"""
A transforming visitor that adds figure numbers to all figures,
and converts any references to figures to use the text 'Figure #';
and adds example numbers to all examples, and converts any
references to examples to use the text 'Example #'.
"""
LETTERS = 'abcdefghijklmnopqrstuvwxyz'
ROMAN = 'i ii iii iv v vi vii viii ix x'.split()
ROMAN += ['x%s' % r for r in ROMAN]
def __init__(self, document):
docutils.nodes.NodeVisitor.__init__(self, document)
self.reference_labels = {}
self.figure_num = 0
self.table_num = 0
self.example_num = [0]
self.section_num = [0]
self.listing_num = 0
self.callout_labels = {} # name -> number
self.set_section_context = None
self.section_context = 'body' # preface, appendix, body
#////////////////////////////////////////////////////////////
# Figures
#////////////////////////////////////////////////////////////
def visit_figure(self, node):
self.figure_num += 1
num = '%s.%s' % (self.format_section_num(1), self.figure_num)
for node_id in self.get_ids(node):
self.reference_labels[node_id] = '%s' % num
self.label_node(node, 'Figure %s' % num)
#////////////////////////////////////////////////////////////
# Tables
#////////////////////////////////////////////////////////////
def visit_table(self, node):
if 'avm' in node['classes']: return
if 'gloss' in node['classes']: return
if 'rst-example' in node['classes']: return
if 'doctest-list' in node['classes']: return
self.table_num += 1
num = '%s.%s' % (self.format_section_num(1), self.table_num)
for node_id in self.get_ids(node):
self.reference_labels[node_id] = '%s' % num
self.label_node(node, 'Table %s' % num)
#////////////////////////////////////////////////////////////
# Listings
#////////////////////////////////////////////////////////////
def visit_pylisting(self, node):
self.visit_figure(node)
pyfile = re.sub('\W', '_', node['name']) + PYLISTING_EXTENSION
num = '%s.%s' % (self.format_section_num(1), self.figure_num)
self.label_node(node, 'Example %s (%s)' % (num, pyfile),
PYLISTING_DIR + pyfile)
self.callout_labels.update(node['callouts'])
# self.listing_num += 1
# num = '%s.%s' % (self.format_section_num(1), self.listing_num)
# for node_id in self.get_ids(node):
# self.reference_labels[node_id] = '%s' % num
# pyfile = re.sub('\W', '_', node['name']) + PYLISTING_EXTENSION
# self.label_node(node, 'Listing %s (%s)' % (num, pyfile),
# PYLISTING_DIR + pyfile)
# self.callout_labels.update(node['callouts'])
def visit_doctest_block(self, node):
if isinstance(node.parent, pylisting):
callouts = node['callouts'] = node.parent['callouts']
else:
callouts = node['callouts'] = {}
pysrc = ''.join(('%s' % c) for c in node)
for callout_id in CALLOUT_RE.findall(pysrc):
callouts[callout_id] = len(callouts)+1
self.callout_labels.update(callouts)
#////////////////////////////////////////////////////////////
# Sections
#////////////////////////////////////////////////////////////
max_section_depth = 2
no_section_numbers_in_preface = True
TOP_SECTION = 'chapter'
# [xx] I don't think this currently does anything..
def visit_document(self, node):
if (len(node)>0 and isinstance(node[0], docutils.nodes.title) and
isinstance(node[0].children[0], docutils.nodes.Text) and
re.match(r'(\d+(.\d+)*)\.?\s+', node[0].children[0])):
node['sectnum'] = node[0].children[0].split()[0]
for node_id in node.get('ids', []):
self.reference_labels[node_id] = '%s' % node['sectnum']
def visit_section(self, node):
title = node[0]
# Check if we're entering a new context.
if len(self.section_num) == 1 and self.set_section_context:
self.start_new_context(node)
# Record the section's context in its title.
title['section_context'] = self.section_context
# Increment the section counter.
self.section_num[-1] += 1
# If a section number is given explicitly as part of the
# title, then it overrides our counter.
if isinstance(title.children[0], docutils.nodes.Text):
m = re.match(r'(\d+(.\d+)*)\.?\s+', title.children[0])
if m:
pieces = [int(n) for n in m.group(1).split('.')]
if len(pieces) == len(self.section_num):
self.section_num = pieces
title.children[0] = docutils.nodes.Text(title.children[0][m.end():])
else: