-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswish.py
1647 lines (1429 loc) · 66.8 KB
/
swish.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
# Copyright (C) 2020
# Author: Kacper Sokol <[email protected]>
# License: new BSD
"""
Implements the `swish` directive for Jupyter Book and Sphinx.
"""
import glob
import os
import re
import sphinx.util.osutil
import sys
from docutils import nodes
from docutils.parsers.rst import Directive, directives
import sphinx_prolog
STATIC_CSS_FILES = ['jquery-ui.min.css', 'lpn.css', 'sphinx-prolog.css']
STATIC_JS_FILES = ['jquery.js', 'jquery-ui.min.js', 'lpn.js']
STATIC_FILES = (STATIC_CSS_FILES + STATIC_JS_FILES
+ ['lpn/lpn-run.png', 'lpn/lpn-close.png'])
if sys.version_info >= (3, 0):
unicode = str
_EXAMPLES_RGX = '\s*^/\*\*\s*<examples>\s*$.*?(?!^\*/\s*$).*?^\*/\s*$\s*'
EXAMPLES_PATTERN = re.compile(_EXAMPLES_RGX, flags=(re.M | re.I | re.S))
_LABEL_RGX = '<(swishq:\S+)>'
LABEL_PATTERN = re.compile(_LABEL_RGX, flags=(re.M | re.I | re.S))
_LABEL_STRING_RGX = '(?:^.+<)(\S+)(?:>\s*$)'
LABEL_STRING_PATTERN = re.compile(_LABEL_STRING_RGX, flags=(re.M | re.I | re.S))
_HIDE_EXAMPLES_RGX = ('$\s*^\s*<span class="cm">\s*/\*\*\s*<examples>\s*'
'</span>.*?<span class="cm">\s*\*/\s*</span>')
HIDE_EXAMPLES_PATTERN = re.compile(
_HIDE_EXAMPLES_RGX, flags=(re.M | re.I | re.S))
PROLOG_TEMP_DIR = 'src/code/temp'
PROLOG_OUT_DIR = '_sources/prolog_build_files'
PROLOG_SUFFIX = '-merged.pl'
#### SWISH directive ##########################################################
class swish_box(nodes.General, nodes.Element):
"""A `docutils` node holding Simply Logical swish boxes."""
def visit_swish_box_node(self, node):
"""Builds an opening HTML tag for Simply Logical swish boxes."""
inline = node.attributes.get('inline', False)
inline_tag = 'span' if inline else 'div'
lang = node.attributes.get('language')
if lang is None:
cls = 'extract swish'
else:
# ensure Prolog syntax highlighting
assert lang == 'Prolog', 'SWISH query blocks must be Prolog syntax'
# support Prolog code syntax highlighting -> the `highlight` class
cls = 'extract swish highlight highlight-{} notranslate'.format(lang)
self.body.append(self.starttag(node, inline_tag, CLASS=cls))
def depart_swish_box_node(self, node):
"""Builds a closing HTML tag for Simply Logical swish boxes."""
inline = node.attributes.get('inline', False)
# lack of `\n` after the `span` tag ensures correct spacing of the text
inline_tag = '</span>' if inline else '</div>\n'
self.body.append(inline_tag)
def visit_swish_box_node_(self, node):
"""
Builds a prefix for embedding Simply Logical swish boxes in LaTeX and raw
text.
"""
raise NotImplemented
def depart_swish_box_node_(self, node):
"""
Builds a postfix for embedding Simply Logical swish boxes in LaTeX and raw
text.
"""
raise NotImplemented
class swish_code(nodes.literal_block, nodes.Element):
"""
A `docutils` node holding the **code** embedded in the Simply Logical swish
boxes.
"""
def visit_swish_code_node(self, node):
"""Builds an opening HTML tag for Simply Logical swish **code** boxes."""
env = self.document.settings.env
attributes = {}
class_list = ['literal-block', 'source', 'swish']
# get node id
node_ids = node.get('ids', [])
assert len(node_ids) == 1
assert node_ids[0].startswith('swish')
assert node_ids[0].endswith('-code')
#
swish_label = node.get('label', None)
assert swish_label is not None
assert node_ids[0] == '{}-code'.format(nodes.make_id(swish_label))
lang = node.attributes.get('language')
# ensure Prolog syntax highlighting
assert lang == 'Prolog', 'SWISH query blocks must be Prolog syntax'
# get user-provided SWISH queries if present (`query-text` HTML attribute)
query_text = node.attributes.get('query_text', None)
if query_text is not None:
attributes['query-text'] = query_text
# get user-provided SWISH query id if present (`query-id` HTML attribute)
query_id = node.attributes.get('query_id', None)
if query_id is not None:
# ensure that all of the referenced queries are also in this
# document as otherwise the inheritance JavaScript will not work
if not hasattr(env, 'sl_swish_query'):
raise RuntimeError('A swish query box with *{}* id has not '
'been found.'.format(query_id))
iid = []
for i_ in query_id.strip().split(' '):
i = i_.strip()
if not i:
continue
if env.sl_swish_query[i] not in self.docnames:
raise RuntimeError(
('The code block *{}* placed in *{}* document uses query '
'*{}*, which is in a different document (*{}*). '
'Query referencing only works in a scope of a single '
'document.'.format(swish_label, self.docnames, i,
env.sl_swish_query[i]))
)
iid.append('{}-query'.format(nodes.make_id(i)))
attributes['query-id'] = ' '.join(iid)
# composes the `inherit-id` HTML attribute if present
inherit_id = node.attributes.get('inherit_id', None)
if inherit_id is not None:
iid = []
for i_ in inherit_id.strip().split(' '):
i = i_.strip()
if not i:
continue
iid.append('{}-code'.format(nodes.make_id(i)))
# ensure that all of the inherited code blocks are also in this
# document as otherwise the inheritance JavaScript will not work
assert hasattr(env, 'sl_swish_code')
if env.sl_swish_code[i]['main_doc'] not in self.docnames:
raise RuntimeError(
('The code block *{}* placed in *{}* document inherits '
'*{}*, which is in a different document (*{}*). '
'Inheritance only works in a scope of a single '
'document.'.format(swish_label, self.docnames, i,
env.sl_swish_code[i]['main_doc']))
)
attributes['inherit-id'] = ' '.join(iid)
# if the code block inherits from another, it needs a special class
class_list.append('inherit')
# composes the `source-text-start` HTML attribute if present
source_text_start = node.attributes.get('source_text_start', None)
if source_text_start is not None:
attributes['source-text-start'] = source_text_start
# composes the `source-text-end` HTML attribute if present
source_text_end = node.attributes.get('source_text_end', None)
if source_text_end is not None:
attributes['source-text-end'] = source_text_end
# compose the `prolog_file` HTML attribute if present
prolog_file = node.attributes.get('prolog_file', None)
if prolog_file is not None:
attributes['prolog-file'] = prolog_file
# if the block is being inherited from, it needs a special class
if (hasattr(env, 'sl_swish_inherited')
and swish_label in env.sl_swish_inherited):
class_list.append('temp')
# If either of the `source-text-start` or `source-text-end` attributes are
# present, call a modified version of the `starttag` method/function that
# does not prune whitespaces (such as newline characters) from the content
# of the attributes.
# This is achieved by modifying the call to `attval` (towards the end of
# the implementation) with a substitute function (not removing
# whitespace characters) that is also ported to this file.
if 'source-text-start' in attributes or 'source-text-end' in attributes:
# escape html such as <, >, ", etc. but **preserve new lines**
tag = starttag(self, node, 'pre', # suffix='',
CLASS=' '.join(class_list),
**attributes)
else:
tag = self.starttag(node, 'pre', # suffix='',
CLASS=' '.join(class_list),
**attributes)
#self.body.append(tag)
#self.visit_literal_block(node)
highlighted = self.highlighter.highlight_block(
node.rawsource, lang, location=node)
# strip the external `<div class="highlight"><pre>` and `</pre></div>` tags
# (the existing swish extract syntax has been adapted)
assert highlighted.startswith('<div class="highlight"><pre>')
highlighted = highlighted[28:]
assert highlighted.endswith('</pre></div>\n')
highlighted = highlighted[:-13]
# hide the examples block
hide_examples_global = env.config.sp_swish_hide_examples
assert isinstance(hide_examples_global, bool)
assert 'hide_examples' in node.attributes
hide_examples_local = node.attributes['hide_examples']
assert isinstance(hide_examples_local, bool) or hide_examples_local is None
if hide_examples_global and hide_examples_local in (None, True):
hide_examples = True
elif hide_examples_global and hide_examples_local is False:
hide_examples = False
elif not hide_examples_global and hide_examples_local:
hide_examples = True
elif not hide_examples_global and hide_examples_local in (None, False):
hide_examples = False
else:
assert False
# hide each occurrence of the examples block
if hide_examples:
highlighted = HIDE_EXAMPLES_PATTERN.sub(
lambda x: '<div class="hide-examples">{}</div>'.format(x.group(0)),
highlighted)
self.body.append(tag + highlighted)
self.body.append('</pre>')
# otherwise the raw content is inserted and
# the `depart_swish_query_node` method is executed
# (see the depart_swish_code_node method for more details)
raise nodes.SkipNode
def starttag(self, node, tagname, suffix='\n', empty=False, **attributes):
"""
Construct and return a start tag given a node (id & class attributes
are extracted), tag name, and optional attributes.
Ported from https://docutils.sourceforge.io/docutils/writers/_html_base.py
with a tweaked `attval` call towards the end.
"""
tagname = tagname.lower()
prefix = []
atts = {}
ids = []
for (name, value) in attributes.items():
atts[name.lower()] = value
classes = []
languages = []
# unify class arguments and move language specification
for cls in node.get('classes', []) + atts.pop('class', '').split():
if cls.startswith('language-'):
languages.append(cls[9:])
elif cls.strip() and cls not in classes:
classes.append(cls)
if languages:
# attribute name is 'lang' in XHTML 1.0 but 'xml:lang' in 1.1
atts[self.lang_attribute] = languages[0]
if classes:
atts['class'] = ' '.join(classes)
assert 'id' not in atts
ids.extend(node.get('ids', []))
if 'ids' in atts:
ids.extend(atts['ids'])
del atts['ids']
if ids:
atts['id'] = ids[0]
for id in ids[1:]:
# Add empty "span" elements for additional IDs. Note
# that we cannot use empty "a" elements because there
# may be targets inside of references, but nested "a"
# elements aren't allowed in XHTML (even if they do
# not all have a "href" attribute).
if empty or isinstance(node,
(nodes.bullet_list, nodes.docinfo,
nodes.definition_list, nodes.enumerated_list,
nodes.field_list, nodes.option_list,
nodes.table)):
# Insert target right in front of element.
prefix.append('<span id="%s"></span>' % id)
else:
# Non-empty tag. Place the auxiliary <span> tag
# *inside* the element, as the first child.
suffix += '<span id="%s"></span>' % id
attlist = sorted(atts.items())
parts = [tagname]
for name, value in attlist:
# value=None was used for boolean attributes without
# value, but this isn't supported by XHTML.
assert value is not None
if isinstance(value, list):
values = [unicode(v) for v in value]
# the modified call to the `attval` function/method
parts.append('%s="%s"' % (name.lower(),
attval(self, ' '.join(values))))
else:
# the modified call to the `attval` function/method
parts.append('%s="%s"' % (name.lower(),
attval(self, unicode(value))))
if empty:
infix = ' /'
else:
infix = ''
return ''.join(prefix) + '<%s%s>' % (' '.join(parts), infix) + suffix
def attval(self, text):
"""
Cleanse, HTML encode, and return attribute value text.
Ported from https://docutils.sourceforge.io/docutils/writers/_html_base.py
and tweaked to preserve *whitespaces* -- such as *newline* characters --
in the content of HTML attributes.
(Needed for `source-text-start` and `source-text-end' attributes of the
swish code boxes, which contain raw Prolog code.)
"""
encoded = self.encode(text)
if self.in_mailto and self.settings.cloak_email_addresses:
# Cloak at-signs ("%40") and periods with HTML entities.
encoded = encoded.replace('%40', '%40')
encoded = encoded.replace('.', '.')
return encoded
def depart_swish_code_node(self, node):
"""Builds a closing HTML tag for Simply Logical swish **code** boxes."""
self.depart_literal_block(node)
def visit_swish_code_node_(self, node):
"""
Builds a prefix for embedding Simply Logical swish **code** boxes in LaTeX
and raw text.
"""
raise NotImplemented
def depart_swish_code_node_(self, node):
"""
Builds a postfix for embedding Simply Logical swish **code** boxes in LaTeX
and raw text.
"""
raise NotImplemented
def strip_examples_block(text):
"""
Strips the *examples* block of text from the input text::
file content
file content
...
/** <examples>
content that will be stripped
content that will be stripped
...
content that will be stripped
*/
resulting in::
file content
file content
...
"""
no_examples = EXAMPLES_PATTERN.sub('\n', text).strip()
return no_examples
class SWISH(Directive):
"""
Defines the `swish` directive for building Simply Logical swish boxes with
code.
The `swish` directive is of the form::
.. swish:: swish:1.2.3 (required)
:query-text: ?-linked(a,b,X). ?-linked(X,a,Y). (optional)
:inherit-id: swish:4.1.1 [swish:4.1.2 swish:4.1.3] (optional)
:source-text-start: 4.1.1-start (optional)
:source-text-end: 4.1.1-end (optional)
:hide-examples: false
:build-file: false
All of the ids need to be Prolog code files **with** the `swish:` prefix
and **without the** `.pl` **extension**, located in a single directory.
The directory is provided to Sphinx via the `sp_code_directory` config
setting and is **required**.
Optionally, the `sp_swish_url` config setting can be provided, which
specifies the URL of the execution swish server. If one is not given,
the default URL hardcoded in the swish JavaScript library will be used
(i.e., `https://swish.swi-prolog.org/`).
Optionally, `sp_swish_hide_examples` can globally toggle the visibility of
the *example* blocks in SWISH code blocks.
If any of the code blocks uses `build-file` set to `true`,
the `sp_swish_book_url` config setting must be provided.
This directive operates on three Sphinx environmental variables:
sl_swish_code
A dictionary encoding the association between code files and documents.
See the description of the `memorise_code` method for more details.
sl_has_swish
A set of names of documents that include swish boxes.
sl_swish_inherited
A dictionary of code ids that are being inherited by swish boxes.
The value for each code id is a set of documents that included the
inheritance.
This Sphinx extension monitors the code files for changes and
regenerates the content pages that use them if a change is detected.
"""
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = False
has_content = True
option_spec = {'query-text': directives.unchanged,
'query-id': directives.unchanged,
'inherit-id': directives.unchanged,
'source-text-start': directives.unchanged,
'source-text-end': directives.unchanged,
'hide-examples': directives.unchanged,
'build-file': directives.unchanged}
def run(self):
"""Builds a swish box."""
# NOTE: using `env.note_dependency()` may simplify monitoring for code
# file changes.
env = self.state.document.settings.env
options = self.options
# memorise that this document (a content source file) uses at least
# one swish box
if not hasattr(env, 'sl_has_swish'):
env.sl_has_swish = set()
if env.docname not in env.sl_has_swish:
env.sl_has_swish.add(env.docname)
# retrieve the path to the directory holding the code files
sp_code_directory = env.config.sp_code_directory
assert isinstance(sp_code_directory, str) or sp_code_directory is None
# get the code file name for this particular swish box
assert len(self.arguments) == 1, (
'Just one argument -- code block id (possibly encoding the code '
'file name -- expected')
code_filename_id = self.arguments[0]
assert code_filename_id.startswith('swish:'), (
'The code box label ({}) must start with the "swish:" '
'prefix.'.format(code_filename_id))
assert not code_filename_id.endswith('.pl'), (
'The code box label ({}) must not end with the ".pl" '
'extension prefix.'.format(code_filename_id))
# add the .pl extension as it is missing
code_filename = '{}.pl'.format(code_filename_id[6:])
# process the options -- they are used as HTML attributes
attributes = {}
# memorise implicit SWISH queries
query_text = options.get('query-text', None)
if query_text is not None:
query_text = query_text.strip()
attributes['query_text'] = query_text
# memorise SWISH query box id
query_id = options.get('query-id', None)
if query_id is not None:
id_collector = []
for iid in query_id.strip().split(' '):
iid = iid.strip()
if not iid:
continue
if not iid.startswith('swishq:'):
raise RuntimeError(
'The *query-id* parameter of a swish box '
'should start with the "swishq:" prefix.')
if iid.endswith('.pl'):
raise RuntimeError(
'The *query-id* parameter of a swish box '
'should not use the ".pl" extension.')
##### existence of the query id is checked in the #####
##### `check_inheritance_correctness` function #####
if iid in id_collector:
raise RuntimeError('The *{}* query block id provided via '
'the *query-id* parameter of the *{}* '
'code block is duplicated.'.format(
iid, code_filename_id))
else:
id_collector.append(iid)
attributes['query_id'] = query_id
# extract `inherit-id` (which may contain multiple ids) and memorise it
inherit_id = options.get('inherit-id', None)
inherit_id_collector = []
if inherit_id is not None:
for iid in inherit_id.strip().split(' '):
iid = iid.strip()
if not iid:
continue
if not iid.startswith('swish:'):
raise RuntimeError('The *inherit-id* parameter of a swish '
'box should start with the "swish:" '
'prefix.')
if iid.endswith('.pl'):
raise RuntimeError('The *inherit-id* parameter of a swish '
'box should not use the ".pl" '
'extension.')
##### existence of the inherited ids is checked in the #####
##### `check_inheritance_correctness` function #####
if iid in inherit_id_collector:
raise RuntimeError('The *{}* code block id provided via '
'the *inherit-id* parameter of the *{}* '
'code block is duplicated.'.format(
iid, code_filename_id))
else:
inherit_id_collector.append(iid)
# memorise that this code id will be inherited
if not hasattr(env, 'sl_swish_inherited'):
env.sl_swish_inherited = dict()
if iid in env.sl_swish_inherited:
env.sl_swish_inherited[iid].add(env.docname)
else:
env.sl_swish_inherited[iid] = {env.docname}
attributes['inherit_id'] = inherit_id
# extract `source-text-start` and memorise it
source_start = options.get('source-text-start', None)
if source_start is not None:
localised_directory = localise_code_directory(
sp_code_directory, '*source text start*')
if not source_start.endswith('.pl'):
source_start += '.pl'
source_start_path = os.path.join(localised_directory, source_start)
sphinx_prolog.file_exists(source_start_path)
# memorise the association between the document and code box
self.memorise_code(source_start, source_start_path)
with open(source_start_path, 'r') as f:
contents = f.read()
# clean out the examples section
raw_content = strip_examples_block(contents)
attributes['source_text_start'] = '{}\n\n'.format(raw_content)
# extract `source-text-end` and memorise it
source_end = options.get('source-text-end', None)
if source_end is not None:
localised_directory = localise_code_directory(
sp_code_directory, '*source text end*')
if not source_end.endswith('.pl'):
source_end += '.pl'
source_end_path = os.path.join(localised_directory, source_end)
sphinx_prolog.file_exists(source_end_path)
# memorise the association between the document and code box
self.memorise_code(source_end, source_end_path)
with open(source_end_path, 'r') as f:
contents = f.read()
# clean out the examples section
raw_content = strip_examples_block(contents)
attributes['source_text_end'] = '\n{}'.format(raw_content)
# hide examples locally
hide_examples = options.get('hide-examples', None)
if isinstance(hide_examples, str):
if hide_examples == '':
hide_examples = True
elif hide_examples.lower() == 'false':
hide_examples = False
else:
raise RuntimeError('The *hide-examples* parameter placed in '
'the *{}* SWISH box must either be *true* '
'or *false.*'.format(code_filename_id))
assert isinstance(hide_examples, bool) or hide_examples is None
attributes['hide_examples'] = hide_examples
# build a Prolog code file
build_file = options.get('build-file', False)
if build_file == '':
build_file = True
assert isinstance(build_file, bool)
# if the content is given explicitly, use it instead of loading a file
if self.content:
contents = '\n'.join(self.content)
# memorise the association between the document (a content source
# file) and the code box
self.memorise_code(code_filename_id, None, is_main_codeblock=True)
else:
localised_directory = localise_code_directory(
sp_code_directory, 'SWISH box content')
# compose the full path to the code file and ensure it exists
path_localised = os.path.join(localised_directory, code_filename)
# path_original = os.path.join(sp_code_directory, code_filename)
sphinx_prolog.file_exists(path_localised)
# memorise the association between the document (a content source
# file) and the code box -- this is used for watching for code file
# updates
self.memorise_code(code_filename_id, path_localised,
is_main_codeblock=True)
# read in the code file and create a swish **code** node
with open(path_localised, 'r') as f:
contents = f.read()
# compose a single Prolog file from inherit-id, source-text-start and
# source-text-end parameters to be uploaded and sourced by SWISH
if build_file:
code_collector = {}
# load the inherited files
if inherit_id_collector:
assert 'inherit_id' in attributes
code_collector['inherit'] = inherit_id_collector
del attributes['inherit_id']
assert 'inherit_id' not in attributes
# load the source-text-start contents
if 'source_text_start' in attributes:
code_collector['start'] = [
'/*Begin ~source text start~*/',
attributes['source_text_start'].strip(),
'/*End ~source text start~*/\n'
]
del attributes['source_text_start']
assert 'source_text_start' not in attributes
# load the code block contents
code_collector['contents'] = contents
# load the source-text-end contents
if 'source_text_end' in attributes:
code_collector['end'] = [
'\n/*Begin ~source text end~*/',
attributes['source_text_end'].strip(),
'/*End ~source text end~*/\n'
]
del attributes['source_text_end']
assert 'source_text_end' not in attributes
# get a name for this Prolog file
build_file_name = '{}{}'.format(
code_filename_id[6:], PROLOG_SUFFIX)
code_collector['filename'] = build_file_name
# get a request URL for this Prolog file
sp_swish_book_url = env.config.sp_swish_book_url
if sp_swish_book_url is None:
raise RuntimeError('The sp_swish_book_url sphinx config value '
'must be provided since the *{}* code '
'block was set to use an external Prolog '
'file via the *build-file* '
'parameter.'.format(code_filename_id))
prolog_temp_store = os.path.join(sp_swish_book_url, PROLOG_OUT_DIR)
attributes['prolog_file'] = os.path.join(
prolog_temp_store, build_file_name)
# This file is built in the resolve_prolog_files function -- see
# its documentation for the explanation
attributes['pending_file'] = code_collector
# strip the content of the block from examples if requested
hide_examples_global = env.config.sp_swish_hide_examples
assert isinstance(hide_examples_global, bool)
if hide_examples_global and hide_examples in (None, True):
_hide_examples = True
elif hide_examples_global and hide_examples is False:
_hide_examples = False
elif not hide_examples_global and hide_examples:
_hide_examples = True
elif not hide_examples_global and hide_examples in (None, False):
_hide_examples = False
else:
assert False
# hide each occurrence of the examples block
if _hide_examples:
contents = strip_examples_block(contents)
# since we have already hidden examples here, we set the
# hide_examples attribute to False to avoid repeating the step
# in the visit_swish_code_node function
attributes['hide_examples'] = False
lang = 'Prolog'
pre = swish_code(contents.strip(), contents,
ids=['{}-code'.format(
nodes.make_id(code_filename_id))],
label=code_filename_id,
language=lang,
**attributes)
# create the outer swish node
box = swish_box(language=lang) # needed for syntax colouring
# assign label and id (`ids=[nodes.make_id(code_filename_id)]`)
self.options['name'] = code_filename_id
self.add_name(box)
# insert the swish code node into the outer node
box += pre
return [box]
def memorise_code(self, code_filename_id, path_localised,
is_main_codeblock=False):
"""
Memorises the association between the current document (a content
source file containing the instantiation of the `swish` directive
encoded by this object) and the code box.
This procedure is also applied to *linked sources* (`source-text-start`
and `source-text-end`) in addition to the code box itself.
All of this information is stored in the `sl_swish_code` Sphinx
environmental variable, which has the following structure::
{'code_id': {'docs': set(docnames),
'main_doc': the_main_document_using_this_code_block,
'path': file_path_to_code_id,
'signature': creation_time_of_file_path_to_code_id},
...
}
Memorising this information allows to watch for changes in the code
files and force Sphinx to rebuild pages that include swish boxes that
depend upon them.
`path` and `signature` are both `None` if the content of the SWISH box
was given explicitly as the directive content.
"""
env = self.state.document.settings.env
if not hasattr(env, 'sl_swish_code'):
env.sl_swish_code = {}
# if code id has already been seen, verify that the code file has not
# changed and add the document name to the watchlist for this code file
if code_filename_id in env.sl_swish_code:
# verify signature
if path_localised is None:
assert env.sl_swish_code[code_filename_id]['path'] is None
assert env.sl_swish_code[code_filename_id]['signature'] is None
else:
if (os.path.getmtime(path_localised)
!= env.sl_swish_code[code_filename_id]['signature']):
raise RuntimeError('A code file signature has changed '
'during the runtime.')
# add the document name to the set of dependent files
env.sl_swish_code[code_filename_id]['docs'].add(env.docname)
# check if this docname is the main one using this codeblock
if is_main_codeblock:
if env.sl_swish_code[code_filename_id]['main_doc'] is None:
env.sl_swish_code[code_filename_id]['main_doc'] = (
env.docname)
else:
raise RuntimeError(
('Only one code block can be created from each source '
'file. The code id {} is used by {} and cannot be '
'used by {}.').format(
code_filename_id,
env.sl_swish_code[code_filename_id]['main_doc'],
env.docname)
)
# if code id has not been seen, create a new item storing its details
else:
if path_localised is None:
timestamp = None
else:
timestamp = os.path.getmtime(path_localised)
env.sl_swish_code[code_filename_id] = {
'docs': {env.docname},
'main_doc': env.docname if is_main_codeblock else None,
'path': path_localised,
'signature': timestamp
}
def localise_code_directory(sp_code_directory, request_type=None):
"""Localise the code directory path."""
if request_type is None:
request_type = 'SWISH box content'
if sp_code_directory is None:
raise RuntimeError('The sp_code_directory sphinx config value '
'must be set when loading {} from a file.'.format(
request_type))
# localise the directory if given as an absolute path
if sp_code_directory.startswith('/'):
localised_directory = '.' + sp_code_directory
else:
localised_directory = sp_code_directory
# check whether the directory exists
if not os.path.exists(localised_directory):
raise RuntimeError('The sp_code_directory ({}) does not '
'exist.'.format(localised_directory))
return localised_directory
def purge_swish_detect(app, env, docname):
"""
Cleans the information stored in the Sphinx environment about documents
with swish blocks (`sl_has_swish`), inherited ids (`sl_swish_inherited`)
and the links between documents and swish code sources (`sl_swish_code`).
If a document gets regenerated, the information whether this document
has a swish directive is removed before the document is processed again.
Similarly, links from code files to this document are purged.
This function is hooked up to the `env-purge-doc` Sphinx event.
"""
if hasattr(env, 'sl_has_swish'):
# if the document was recorded to have a swish block and is now being
# rebuilt, remove it from the store
if docname in env.sl_has_swish:
env.sl_has_swish.remove(docname)
if hasattr(env, 'sl_swish_inherited'):
nodes_to_remove = set()
for inherit_id, docname_set in env.sl_swish_inherited.items():
if docname in docname_set:
docs_no = len(docname_set)
if docs_no > 1:
docname_set.remove(docname)
elif docs_no == 1:
docname_set.remove(docname)
nodes_to_remove.add(inherit_id)
else:
assert inherit_id in nodes_to_remove
for i in nodes_to_remove:
del env.sl_swish_inherited[i]
if hasattr(env, 'sl_swish_code'):
nodes_to_remove = set()
for code_id, code_node in env.sl_swish_code.items():
# if the document was linked to any source code file and is now
# being rebuilt, remove it from the appropriate stores
if docname in code_node['docs']:
docs_no = len(code_node['docs'])
if docs_no > 1:
code_node['docs'].remove(docname)
elif docs_no == 1:
code_node['docs'].remove(docname)
nodes_to_remove.add(code_id)
else:
assert code_id in nodes_to_remove
if docname == code_node['main_doc']:
code_node['main_doc'] = None
for i in nodes_to_remove:
del env.sl_swish_code[i]
def merge_swish_detect(app, env, docnames, other):
"""
In case documents are processed in parallel, the data stored in
`sl_has_swish`, `sl_swish_inherited` and `sl_swish_code` Sphinx
environment variables from different threads need to be merged.
This function is hooked up to the `env-merge-info` Sphinx event.
"""
if not hasattr(env, 'sl_has_swish'):
env.sl_has_swish = set()
if hasattr(other, 'sl_has_swish'):
# join two sets by taking their union
env.sl_has_swish |= other.sl_has_swish
if not hasattr(env, 'sl_swish_inherited'):
env.sl_swish_inherited = dict()
if hasattr(other, 'sl_swish_inherited'):
# join two sets by taking their union
for key, val in other.sl_swish_inherited.items():
if key in env.sl_swish_inherited:
env.sl_swish_inherited[key] |= val
else:
env.sl_swish_inherited[key] = val
if not hasattr(env, 'sl_swish_code'):
env.sl_swish_code = {}
if hasattr(other, 'sl_swish_code'):
for key, val in other.sl_swish_code.items():
# if this code file has already been referred to in another
# document
if key in env.sl_swish_code:
# verify timestamp and path
if ((env.sl_swish_code[key]['signature'] != val['signature'])
or (env.sl_swish_code[key]['path'] != val['path'])):
raise RuntimeError('A code file signature has changed '
'during the runtime.')
# join two sets by taking their union
env.sl_swish_code[key]['docs'] |= val['docs']
# choose the main document name
if val['main_doc'] is not None:
if env.sl_swish_code[key]['main_doc'] is None:
env.sl_swish_code[key]['main_doc'] = val['main_doc']
else:
raise RuntimeError(
('Two documents ({} and {}) are using the same '
'code file as a main source ().'
'file. The code id {} is used by {} and cannot be '
'used by {}.').format(
val['main_doc'],
env.sl_swish_code[key]['main_doc'],
key)
)
# if this code file has not yet been referred to
else:
# transfer the whole content
env.sl_swish_code[key] = val
def inject_swish_detect(app, doctree, docname):
"""
Injects call to the swish JavaScript library in documents that have swish
code blocks.
This function is hooked up to the `doctree-resolved` Sphinx event.
"""
env = app.builder.env
# if no swish code blocks were detected, skip this step
if not hasattr(env, 'sl_has_swish'):
return
# if this document does not have any swish code blocks, skip this step
if docname not in env.sl_has_swish:
return
# check for a user-specified SWISH server URL in the config
sp_swish_url = env.config.sp_swish_url
if sp_swish_url:
call = 'swish:"{:s}"'.format(sp_swish_url)
else:
call = ''
swish_function = ('\n\n <script>$(function() {{ $(".swish").LPN('
'{{{}}}); }});</script>\n'.format(call))
# `format='html'` is crucial to avoid escaping html characters
script_node = nodes.raw(swish_function, swish_function, format='html')
# add the call node to the document
doctree.append(script_node)
def analyse_swish_code(app, env, added, changed, removed):
"""
Ensures that when a code file is edited all the linked documents are
updated.
This function is hooked up to the `env-get-outdated` Sphinx event.
"""
# skip this step if no swish code blocks were found
if not hasattr(env, 'sl_swish_code'):
return set()
# check whether any code file has changed
changed_code_files = set()
for code_dict in env.sl_swish_code.values():
# if the file still exists, check whether it has been updated
if code_dict['path'] is not None:
if os.path.exists(code_dict['path']):
file_signature = os.path.getmtime(code_dict['path'])
if file_signature != code_dict['signature']:
# check which files use this code file and refresh them
changed_code_files = changed_code_files.union(
code_dict['docs'])
# if the file has been removed, refresh the affected docs
else:
changed_code_files = changed_code_files.union(
code_dict['docs'])
else:
assert code_dict['signature'] is None
# disregard documents that are already marked to be updated or were
# discarded
changed_code_files -= removed | changed | added
return changed_code_files
def check_inheritance_correctness(app, doctree, docname):
"""
Checks whether SWISH ids provided via the `inherit-id` (code boxes) and
`query-id` (query boxes) parameters exist.
"""
# go through every swish code
for node in doctree.traverse(swish_code):
# get the inherit-id and query-id strings
inherit_id = node.attributes.get('inherit_id', '')
query_id = node.attributes.get('query_id', '')
# we are only interested in the nodes that inherit something
if inherit_id:
# analyse each inherited id
for iid_ in inherit_id.strip().split(' '):
iid = iid_.strip()