-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxmloutput.py
executable file
·1685 lines (1388 loc) · 63 KB
/
xmloutput.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 python3
#
# XmlOutput.py: Make it easier to write out WF XML.
# Perl original written 2010-12-22 by Steven J. DeRose.
# Port to Python: 2012-01-10 sjd.
#
import sys
import re
import codecs
import string
from typing import IO, Dict, Union, List, Any
from xml.dom.minidom import Node
from xml.dom.minidom import Document
from html.entities import codepoint2name
#from html.parser import HTMLParser
__metadata__ = {
"title" : "XmlOutput",
"description" : "Make it easier to write out WF XML.",
"rightsHolder" : "Steven J. DeRose",
"creator" : "http://viaf.org/viaf/50334488",
"type" : "http://purl.org/dc/dcmitype/Software",
"language" : "Python 3.7",
"created" : "2012-01-10",
"modified" : "2024-06-18",
"publisher" : "http://github.com/sderose",
"license" : "https://creativecommons.org/licenses/by-sa/3.0/"
}
__version__ = __metadata__["modified"]
descr = """
=Notes=
A Python module to help with generating XML output.
This library lets you issue open and close commands (and many others),
generating the corresponding XML output as you go.
It keeps the output element and xml:lang stacks and some other state
information, handles escaping automatically for all syntactic contexts,
and generally tries to
ensure the output is well-formed XML. It can also make an XML-generating
application more readable by encapsulating a lot of mechanical tasks (such as
checking whether certain elements are current open; adjusting DIVs to get
up or down to a desired level; close all open instances of a given element type(s),
and so on.
==Example==
from xmloutput import XmlOutput
x = XmlOutput()
xo.setOption("indent", True)
xo.setOption("breakETAGO", False)
xo.startDocument("html", systemID="html4.dtd")
xo.openElements([ "html", "head", "title" ])
makeText("RFC file: " + f)
xo.closeThroughElement("head")
xo.openElement("body")
xo.openElement("p", 'id="foo"')
xo.makeText("Hello, world.")
xo.endDocument()
Attributes can be passed to openElement() and its kin as a full string,
a Python dict, or even be queued ahead of time to be issued on whatever
element is opened next.
The encoding (see '''setOutput'''()) defaults to `utf-8`.
To just get stack maintenance and error-checking, but not to produce
actual output, set `xo.outputFH` to None.
To output to a string, use Python's built-in `StringIO` package.
==Testing==
Run a self-test by just invoking the file from the command-line.
=Methods=
* ''__init__''(encoding="utf-8")
Create a new instance of the XmlOutput object. The output character
encoding can be set here, or on '''setOutput'''() (see below).
==Option and information set/get methods==
* ''getVersion''()
Return the version date of the module.
* ''getOption(name)''
Return the current value of option '''name''' (see following).
* ''setOption(name, value)''
Set option '''name''' to '''value'''.
The name is checked for being a known option, but no
checking is done on the value (values are Boolean unless otherwise noted).
** ''ASCIIOnly'' -- Use entities for all non-ASCII content characters.
** ''breakSTAGO'' -- Break before start-tags. Default True.
** ''breakAttrs'' -- Break before each attribute. Default False.
** ''breakSTAGC'' -- Break after start-tags. Default False.
** ''breakETAGO'' -- Break before end-tags. Default False.
** ''breakETAGC'' -- Break after end-tags. Default True.
** ''divTag'' -- what element type is used for nested containers,
like (the default) HTML `div`. See method '''adjustToRank''' for a handy
way to ensure that these get handled right even if the source document
only has headings (`Hn` or similar).
There is presently no special support for numbered `div`s such as found
in many other schemas (div1, div2, ...).
** ''escapeHREFs'' -- Apply %xx escaping to all attributes that appear
to be URIs. That is, ones that match r'(https?|mailto|ftp|local)://'.
Default False. See also '''escapeURI'''(s), which this uses, but can also
be called directly.
** ''escapeText'' -- Escape "<", "&", and "]]>" in text. Default True.
No, it is not necessary to escape ">" or "]" in general.
** ''fixNames'' -- Correct any requested element type names to be
valid XML NAMEs. Default False.
** ''HTMLEntities'' -- Use HTML entities for special
characters when possible. This requires that the F<HTMLparser> library
be installed.
** ''htmlFormat'' -- Do not issue XML-style empty elements. Default False.
** ''idAttrName'' -- Specify an attribute name to treat as an XML ID
(mainly for use with '''trackIDs'''. Default `id`. There is, sadly, no support
here for identifying IDs via DTD or XSD declarations.
** ''indent'' -- Pretty-print the XML output. See also '''iString'''.
Default True.
** ''iri'' -- Allow non-ASCII characters in URIs. Default True.
** ''iString'' -- Use this string as the (repeated) indent-string
for pretty-printing. Default ` ` (4 spaces).
** ''normalizeText'' -- Normalize white-space in output text nodes.
See also '''normalizeTag'''().
** ''encoding'' -- Write output in this character encoding.
** ''suppressWSN'' -- Do not output white-space-only text nodes.
** ''sysgenPrefix'' -- Set what string is prefixed to a serial number
with the '''sysgen'''() call.
** ''trackIDs'' -- (unsupported) Warn if an ID attribute value is
re-used (this does not see any DTD, it just goes by attribute name).
See also '''idAttrName'''.
** ''URIchars'' -- What characters are allowed (unescaped) in URIs.
If the '''iri''' option is set, all non-ASCII characters are also allowed.
Default: "-.\\w\\d_!\\'()*+"
* ''setCantRecurse(types)''
Prevent any element type listed (space-separated) in '''types'''
from being opened recursively.
For example, if this is set for `p` and the open elements
are html/body/div/p/footnote/, attempting to open another `p`, will close
elements until there are no `p` elements left open, after which
the new `p` is opened (in this example, 2 elements would thus be closed).
* ''setSpace(types, n)''
Cause '''n''' extra newlines to be issued before the start of each instance
of any element type in '''types''' (which can be either a list of individual names,
or a string containing white-space-separated names).
The newlines will only be generated if an element also has '''breakSTAGO'''
set, and if it has not been set be `inline` (via '''setInline'''().
* ''setInline(types)''
Add each (space-separated) element type in '''types''' to a list of elements
to be treated as inline (thus getting no breaks around it despite
general options for breaking).
If '''types''' is "#HTML", the HTML 4 inline tags are added to the list:
A ABBR ACRONYM B BASEFONT BDO BIG BR CITE CODE DFN
EM FONT I IMG INPUT KBD LABEL Q S SAMP SELECT SMALL
SPAN STRIKE STRONG SUB SUP TEXTAREA TT U VAR.
Some other tags are only sometimes inline
(APPLET BUTTON DEL IFRAME INS MAP OBJECT SCRIPT).
These are not added by #HTML,
but some or all can be added with another call to '''setInline'''().
* ''setEmpty(types)''
Cause any element type listed (space-separated) in '''types''' to always be
written out as an empty element when opened (thus, no '''closeElement'''() call
is needed for them).
* ''setSuppress(types)''
Record that elements of any type listed (space-separated) in '''types'''
(and their entire subtrees) should not be output.
Not to be confused with the '''suppressWSN''' option.
* ''getCurrentElementName''()
Return the element type name of the innermost open element.
* ''getCurrentFQGI''()
Return the sequence of the types of all open elements, from the top down,
separated by slashes. For example, `html/body/div/div/ul/li/p/i`.
* ''getCurrentLanguage''()
Return the present (possibly inherited) value of `xml:lang`. The language
is set by issuing an actual `xml:lang` attribute.
* ''getDepth''()
Return how many elements are presently open.
==XML attribute creation methods==
* ''queueAttribute(name, value)''
Add an attribute, to be issued with the next start-tag.
If an attribute called '''named''' is already queued, replace it.
* ''getQueuedAttributes''()
Return all queued attributes (if any) as an attribute string (see ''dictToAttrs()'').
They are not cleared (methods than output start-tags do clear them after using).
This is typically only called internally.
Pending attributes are kept in XmlOutput.queuedAttribtutes.
* ''clearQueuedAttributes() ''
Discard any queued attributes. This happens automatically when they are
issued, for example via an '''openElement()''' call (but not just makeStartTag()).
* ''dictToAttrs(dct, sortAttrs=False, normValues=False)''
This is used by `openElement` etc., if they are passed attributes
as a Python dict rather than an attribute string. It turns the dict
into a string attribute list. Queued attributes should have been added to the
dict already if they are to be used. The values are:
* escaped as needed (there is no provision for telling it '''not''' to escape them),
* assembled with a single space before each attribute (even the first!), no spaces around "=",
and double quotes around the values.
* if ''breakAttrs' is true, a newline and indentation is added ''after'' each
* if '''sortAttrs''' is True, the attributes are concatenated in alphabetical order.
* if '''normValues''' is True, each value is processed by '''normalizeSpace'''().
==XML element creation methods==
* ''openElement(etype, attrs=None, makeEmpty=False, nobreak=False)''
Open an instance of the specified element type ('''etype''').
If '''attrs''' is specified, it may be a ready-to-use attribute string, or
a Python dict (whose values are escaped automatically).
(method `dictToAttrs`() can be used to turn any appropriate Python dict
into an attribute list).
If there are queued attributes (see '''queueAttribute'''()), they are
also issued and then de-queued.
If '''makeEmpty''' is specified and true, the element is written as an empty
element (and thus does not remain on the open-element stack).
If '''nobreak''' is True, the tag is not followed by a
line-break even if it normally would be.
* ''openElements(theList)''
Call '''openElement'''() on each item of '''theList'''.
Each such item should be a list or tuple of up to 4 items,
which are just passed on as the arguments to '''openElement''',
if the order [ etype, attrs, makeEmtpty, nobreak ].
Or just pass a string containing one or more whitespace-separated names.
* ''openElementUnlessOpen(gi, attrs=None, nobreak=False)''
Works like '''openElement'''(), except that it does nothing if the element
is '''already''' open. it need not be the innermost/current open element;
for that, see `openElementUnlessCurrent`.
* ''openElementUnlessCurrent(gi, attrs=None, nobreak=False)''
Works like '''openElement'''(), except that it does nothing if the element
is already the innermost/current open element (for that case,
see `openElementUnlessOpen`).
* ''closeElement(type, nobreak=False)''
Close the specified element.
If '''type''' is not open at all, a warning is issued and nothing is closed.
If '''type''' is open but is not the innermost/current open element,
a warning is issued and all elements out to and including it are closed.
If '''type''' is omitted, the innermost element is closed regardless of type.
''Note:'' To close an element even if there are other
elements to close first, and avoid the warning, use '''closeThroughElement'''().
* ''closeAllElements''(nobreak=False)
Close all open elements.
* ''closeToElement(type, nobreak=False)''
Close down to, but not including, the specified element.
If no element of the type is open, nothing happens.
If multiple instances are open, closing stops before closing the
innermost one.
* ''closeThroughElement(type)''
Close down to and including, the specified element.
If no element of the type is open, nothing happens.
If multiple instances are open, closing stops with the
innermost one.
* ''howManyAreOpen(typelist)''
Return the number of instances of the listed element types that are open.
'''typelist''' may be a (space-delimited) string or a list.
* ''closeAllOfThese(typelist)''
Close all instances of any element types in
'''typelist''', which may be a space-delimited string or an actual list.
* ''adjustToRank(n)''
This is for structures which do not have a depth number as part of
the element type name, but do nest. For example, the HTML `div` element.
The recursive element type (you only get one) is specified by the '''divTag''' option.
It is intended to make it easy to build such nested/container structures,
even when input only has (non-nested) headings (like much HTML).
It creates items at whatever level is needed at any given moment.
For example, '''adjustToRank(4)''' would open and close whatever divs are
needed, to get things in the right place to issue an h4, with divs directly
corresponding to hn levels.
SPecifically, this method:
** closes elements down to and including the '''n'''th
nested "div" (if any); then
** opens divs (automatically adding a
'''class="level_X"''' attribute to each), until '''n''' are open.
This leaves everything ready for writing a div title (or in HTML, Hn heading).
If already at level '''n''', it closes the div and opens a new one.
If already nested deeper, the deeper stuff is closed first.
If shallower, it opens as many "div"s as needed.
* ''makeEmptyElement(type, attrs)''
Output an XML empty element of the given element '''type''' and '''attributes'''.
Queued attributes (if any) are also applied. The behavior is affected by
the '''htmlFormat''' option. See also the related '''setEmpty()''' method.
* ''makeSmallElement(type, attrs, text)''
Open an XML element of the given element '''type''' and '''attributes''',
issue the given '''text''' content within it, and then close it.
Queued attributes (if any) are also applied.
==Document and global methods==
* ''setOutput(self, pathOrHandle, version="1.0", encoding="utf-8")''
Opens the requested file (or StringIO instance), and sets the values
for the XML Declaration parameters '''version''' and '''encoding'''. Either or both
of the last two can be set to '' or None, to indicate that they should be
entirely omitted from the XML Declaration. This is mainly
to accommodate `lxml`, which apparently has issues with '''encoding'''
(see [https://stackoverflow.com/questions/2686709]).
* ''startDocument''(doctypename, publicID="", systemID="")
Shorthand for '''makeXMLDeclaration'''() and '''makeDoctype'''().
See also '''endDocument'''().
* ''startHTML(version, title="")''
Shorthand for getting from start to having `body` open.
'''version''' should be one of "4strict", "4transitional" (or just "4"), "xhtml",
or "html5". In all but the last, an XML declaration is issued. Then the
DOCTYPE, html, head, the whole title, end head, and body.
* ''endDocument''()
Do a '''closeAllElements()''', and then close the output file.
See also '''startDocument'''() and '''startHTML'''().
* ''makeXMLDeclaration(self)''
Issue an XML declaration. '''version''' and/or '''encoding''' are generated
in accord with the latest setting from `setOutput`(), which can include
setting them to `None` in order to suppress them.
* ''makeDoctype(doctypename, publicID="", systemID="", xmlDecl=True)''
Output a DOCTYPE declaration.
Also calls `makeXMLDeclaration()` if it hasn't been called already,
unless `xmlDecl` is pass as False.
==Various other methods==
* ''makeComment(text)''
Output an XML comment. '''text''' is escaped as needed.
* ''makeText(text)''
Output '''text''' as XML content. XML delimiters are escaped as needed,
unless the '''escapeText''' option is unset.
With the '''ASCIIOnly''' option, all non-ASCII characters
are turned into character references.
* ''makeRaw(text)''
Dumps '''text''' to the output, with no escaping, no stack management, etc.
This is usually a bad idea, but just in case....
* ''makePI(target, text)''
Create a Processing Instruction directed to the specified '''target''',
with the given '''content'''. '''text''' is escaped as needed.
* ''makeCharRef(e, printIt=True)''
Create and return an entity or character reference, from an integer or
name (the name is not required to be one of the HTML 4 or XML predefined
entities, but must consist only of XML Name characters).
Unless `printIt` is set false, also print it.
If '''e''' is numeric, it results in a 4-digit (or more if needed),
hexadecimal or decimal (according to the 'entityBase' setting),
numeric character reference.
Otherwise '''e''' is treated as an entity name. It is '''not''' required to
be a known HTML entity name.
* ''normalizeTag(tag)''
Given a complete start (or empty) tag, normalize it to canonical XML
form. That is, normalize whitespace, and alphabetize the attributes.
* ''doPrint(s)''
Write the text in '''s''' literally to the output
(this is mainly used internally).
No escaping is done. All bets are off as far as producing well-formed XML.
==Character and name handling==
* ''fixName(name)''
Ensure that the argument is a valid XML NAME.
Any other characters become "_".
* ''escapeXmlContent''(s)
Escape XML delimiters as needed in text content.
* ''normalizeSpace''(s)
Do the equivalent of XSLT's normalize-space() function on '''s'''.
That is, remove leading and trailing whitespace, and reduce any internal
runs of whitespace to a single regular space character.
* ''escapeURI''(s)
Escape non-URI characters in `s` using the URI %xx convention.
If the '''iri''' option is set, don't escape chars just because they're
non-ASCII; only escape URI-prohibited ASCII characters.
See also options '''URIchars''' and '''escapeHREFs'''.
* ''escapeXmlAttribute(s)''
Escape the string '''s''' to be acceptable as an attribute value
(removing <, &, and "). If the '''ASCIIOnly''' option is set, escape non-ASCII
characters in '''s''' as well.
* ''escapeNonASCII(s)''
Replace any non-ASCII characters in the text with entity references.
* ''sysgen''()
Returns a unique identifier each time it's called. A prefix is
applied, set via the '''sysgenPrefix''' option.
Other than the prefix, this just generates a counter.
=Known bugs and limitations=
Doesn't know anything about namespaces (should at least track which ones
are declared and in effect, unify prefixes, avoid nested re-declarations, etc).
Doesn't know anything about conforming to a particular schema.
Automation of `xml:lang` attributes is not finished.
Pretty-printing is incomplete. For example,
'''breakAttrs''' does not put breaks between attributes that are
specified via the second argument to '''openElement'''() and its kin. To get
those breaks, use '''queueAttribute'''() instead.
=History=
* Ported from Perl original written 2010-12-22 by Steven J. DeRose.
* 2012-01-10 sjd: Port to Python.
* 2012-01-25 sjd: Clean up. Redo options.
* 2012-12-21 sjd: More work on porting.
* 2015-04-03: Make escaping to ASCII option work for all contexts.
Add HTMLEntities option.
* 2015-06-02: More port. pylint. escaping comments, pis, uris. entities.
* 2018-06-01: Hook up to StringIO.
* 2018-07-16: Add entityBase.
* 2018-07-21: Add startHTML(), openElements(). Separate makeXMLDeclaration().
* 2018-09-12: Add normalizeTag().
* 2018-10-15: Fix encoding/version options to allow None. Better self-test.
Allow either string or real list for rest of name-lists. Fix bug in
dictToAttrs() and use it in getQueuedAttributes().
* 2018-11-15: Set encoding even when output file is already open. Clean msgs.
Fix py 2/3 for htmlentitydefs. Add startDocument(). Check output for
illegal control characters. self.encoding vs. options['oencoding']!
* 2019-12-11: Start adding support to directly create a DOM.
* 2020-09-09: Better i/f and error-checking for openElements().
Add closeElements(). Improve help. Fix bugs in setEmpty(). Catch errors on
reconfigure for encoding, and warn instead of dieing.
Start `makeDOM` class. Add tests for legit XML NAMEs from xmlregexes.py.
* 2021-07-20: Add typehinting, normalize a few names, drop Python 2 accommodations.
* 2024-06-18: Drop remaining Py2. More type hints.
=To do=
* Finish `makeDOM` class and option.
* Do fancier indenting?
* Option to omit inheritable xml:lang and xmlns attributes.
* Finish div interpolation? See cleanMediaWiki.py:DivWrapper.
* MECS or TAG option with extended open/close semantics? See multiXML.
* Add an '''insertFile'''(escape=True) method?
* Make openElements() accept names a *args.
=Rights=
Copyright 2010-12-22, 2012-01-10 by Steven J. DeRose.
This work is licensed under a
Creative Commons Attribution-Share-alike 3.0 unported license.
For further information on this license, see
[https://creativecommons.org/licenses/by-sa/3.0].
For the most recent version, see [https://github.com/sderose].
=Options=
"""
verbose = 0
def warning(msg:str) -> None:
sys.stderr.write(msg+"\n")
###############################################################################
#
class XmlOutput:
def __init__(
self,
HTMLEntities: bool = False,
encoding: str = "utf-8",
createDOM: bool = False,
out: IO = None
):
self.outputFH = None
self.theDOM = None
if (createDOM): self.theDOM = makeDOM()
elif (out): self.outputFH = out
else: self.outputFH = sys.stdout
self.xmlVersion = "1.0"
self.didXMLDcl = False
self.tagStack = []
self.langStack = []
self.syntax = XmlSyntax()
self.queuedAttributes = {}
# Lists of elements to treat specially
self.spaceSpecs = {} # elementType: nNewlines
self.cantRecurse = {} # Cannot contain themselves
self.inlines = {} # Treat as inline (not newlines)
self.empties = {} # Always treat as empty
self.suppressed = {} # Don't write these types at all
self.sysgenCounter = 1 # For generated IDs
self.htmlp = None # For encoding HTML entities
# options
self.options = {
"ASCIIOnly" : False, # Everything else -> entities
"sysgenPrefix" : "gen", # For generated IDs
# Places to break (^): ^<p ^a="b"^>^...^</p^>^
"breakSTAGO" : True, # Newline before start-tag
"breakAttrs" : False, # Newline before each attribute
"breakSTAGC" : False, # Newline after start-tag
"breakETAGO" : False, # Newline before end-tag
"breakETAGC" : True, # Newline after end-tag
"divTag" : "div", # Tag to use for recursive DIV
"checkCharset" : True, # Raise exception on bad chars
"entityBase" : 16, # Hex or decimal for numeric chars?
"escapeHREFs" : False, # Do URI %xx escaping as needed
"escapeText" : True, # Escape < and & in text.
"fixNames" : False, # Correct any non-WF names
"htmlFormat" : False,
"HTMLEntities" : False, # See below
"idAttrName" : "id",
"indent" : True,
"iri" : True, # Allow Unicode in URIs?
"iString" : " ", # String to repeat to make indents
"normalizeText" : False,
"encoding" : encoding,
"suppressWSN" : False,
"trackIDs" : False, # Unused
"URIchars" : "-.\\w\\d_!\\'()*+",
}
if (HTMLEntities):
self.setOption("HTMLEntities", True)
def setOutput(self, pathOrHandle, version="1.0", encoding=None) -> bool:
"""Use this to determine where stuff goes: either to a
file (specified by path or a handle), or to a string by
using Python's StringIO class. Pass encoding=None to
prevent writing any encoding at all in the XML declaration.
"""
if (encoding): self.setOption("encoding", encoding)
self.xmlVersion = version
if (isinstance(pathOrHandle, str)):
#warning("setOutput for path '%s'" % (pathOrHandle))
try:
self.outputFH = codecs.open(
pathOrHandle, "wb", encoding=self.getOption("encoding"))
except IOError as e:
warning("Failed to open '%s': %s (encoding %s): \n%s" %
(pathOrHandle, e, self.getOption("encoding"), e))
return False
else:
# https://stackoverflow.com/questions/4374455/
#warning("setOutput for handle '%s'" % (pathOrHandle))
succeeded = False
try:
self.outputFH = pathOrHandle
pathOrHandle.reconfigure(encoding=self.getOption("encoding"))
succeeded = True
except AttributeError:
pass
try:
self.outputFH = codecs.getwriter(
self.getOption("encoding"))(pathOrHandle)
succeeded = True
except AttributeError:
pass
if (not succeeded):
warning("Could not configure output encoding!")
return True
def getOption(self, oname):
assert (oname in self.options)
return(self.options[oname])
def setOption(self, oname, ovalue) -> None:
assert (oname in self.options)
self.options[oname] = ovalue
def setSpace(self, enames, nNewlines) -> None:
"""Determine how many newlines get inserted before particular
element types for output.
@param enames: Element types, in a list or space-separated string.
@param nNewlines: How many newlines to put before any of these.
"""
if (isinstance(enames, str)):
enames = re.split(r"\s+", enames)
for e in (enames):
if (not self.syntax.isXmlName(e)):
raise ValueError("'%s' is not a legit XML NAME." % (e))
self.spaceSpecs[e] = nNewlines
def setInline(self, enames) -> None:
"""Define the listed names as "inline" tags, which mainly affects
whether we put linebreaks around them in pretty-printing.
@param enames: Element type names, either as a list or in a
white-space-separated string.
"""
if (isinstance(enames, str)):
enames = re.split(r"\s+", enames)
for e in (enames):
if (not self.syntax.isXmlName(e)):
raise ValueError("'%s' is not a legit XML NAME." % (e))
self.inlines[e] = 1
def setEmpty(self, enames) -> None:
if (isinstance(enames, str)):
enames = re.split(r"\s+", enames)
for e in (enames):
if (not self.syntax.isXmlName(e)):
raise ValueError("'%s' is not a legit XML NAME." % (e))
self.empties[e] = 1
def setSuppress(self, enames) -> None:
if (isinstance(enames, str)):
enames = re.split(r"\s+", enames)
for e in (enames):
if (not self.syntax.isXmlName(e)):
raise ValueError("'%s' is not a legit XML NAME." % (e))
self.suppressed[e] = 1
def setCantRecurse(self, enames) -> None:
"""Define the listed names as not being allowed to contain themselves.
"""
if (isinstance(enames, str)):
enames = re.split(r"\s+", enames)
for e in (enames):
if (not self.syntax.isXmlName(e)):
raise ValueError("'%s' is not a legit XML NAME." % (e))
self.cantRecurse[e] = 1
def setHTML(self) -> None:
"""Set the list of known inline and non-recursive tags as for HTML.
"""
self.setInline(
"A ABBR ACRONYM B BASEFONT BDO BIG CENTER CITE CODE DFN DIR " +
"EM FONT I IMG INPUT LABEL LEGEND KBD OPTGROUP OPTION " +
"Q S SAMP SELECT SMALL SPAN STRIKE STRONG SUB SUP TEXTAREA TT U VAR"
# Sometimes inline:
# APPLET BUTTON DEL IFRAME INS MAP OBJECT SCRIPT"
)
self.setCantRecurse("BR HR HEAD BODY H1 H2 H3 H4 H5 H6 IMG INS P PRE DEL")
self.options["divTag"] = "DIV"
def startHTML(self, version="4strict", title="") -> None:
if (version == "4strict"):
ids = [ "HTML", "-//W3C//DTD HTML 4.01//EN",
"http://www.w3.org/TR/html4/strict.dtd" ]
elif (version == "xhtml"):
ids = [ "html", "-//W3C//DTD XHTML 1.1//EN",
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" ]
elif (version == "html5"): # Meh
ids = [ "html", None, None ]
else: # (version == 4 or version == "4transitional"):
ids = [ "HTML", "-//W3C//DTD HTML 4.01 Transitional//EN",
"http://www.w3.org/TR/html4/loose.dtd" ]
self.setHTML()
self.makeDoctype(ids[0], ids[1], ids[2])
if (version == "xhtml"):
self.queueAttribute("xmlns", "http://www.w3.org/1999/xhtml")
self.openElement("html")
self.openElement("head")
self.openElement("meta",
{ "http-equiv":"content-type", "content":"text/html; charset=utf-8"
})
self.makeSmallElement("title", None, title)
self.closeElement("head")
self.openElement("body")
return
###########################################################################
# INQUIRIES
#
def getCurrentElementName(self):
if (self.getDepth()>0):
return(self.tagStack[-1])
return(None)
def getCurrentFQGI(self):
if (self.getDepth()>0):
return("/".join(self.tagStack))
return(None)
def getCurrentLanguage(self):
if (len(self.langStack)>0):
return(self.langStack[-1])
return(None)
def getDepth(self):
"""Return the number of elements that are currently open.
"""
return(len(self.tagStack))
def getIndentString(self, newline: bool=True, offset:int=0):
"""Return a newline and indent for the current nesting depth.
To get just the spaces, pass newline=False.
If 'offset' is used, it may be signed, and is used to shift the
indentation level away from the actual nesting level.
"""
if (not self.options["indent"]): return("")
level = self.getDepth() + offset
if (level <= 0): level = 0
nl = "\n" if (newline) else ""
return(nl + (self.options["iString"] * level))
def howManyAreOpen(self, giList:Union[List, str]=None):
"""Return the number of instances that are open, of any of the
element types listed in "giList" (which may be a Python list or
a string of whitespace-separated names). If omitted or None,
returns the same thing as getDepth().
"""
if (not giList):
return(self.getDepth())
if (isinstance(giList, str)):
giList = re.split(r"\s+", giList)
nOpen = 0
for i in (range(0, self.getDepth())):
if (self.tagStack[i] in giList): nOpen += 1
return(nOpen)
###########################################################################
# ATTRIBUTE QUEUEING
#
def queueAttribute(self, aname:str, avalue:Any) -> None:
"""Add an attribute-value pair, to be issued with the next generated
start-tag (in addition to any that are passed at that time. After
being issued, the queued attributes are cleared.
TODO: What if one is already queued w/ same name?
"""
if (not self.syntax.isXmlName(aname)):
raise ValueError("'%s' is not a legit XML NAME." % (aname))
if (aname in self.queuedAttributes):
warning("queueAttribute: Attribute '" + aname + "' already queued.")
self.queuedAttributes[aname] = ""
if (avalue):
avalue = "%s" % (avalue)
self.queuedAttributes[aname] = self.escapeXmlAttribute(avalue)
def getQueuedAttributes(self):
"""Return an attribute string including all the queued attributes
(if any), plus a leading space. This just gets them, so you could
in principle duplicate one from another source. To iterate through
them, just access the dict self.queuedAttributes.
"""
return self.dictToAttrs(self.queuedAttributes)
def clearQueuedAttributes(self) -> None:
self.queuedAttributes.clear()
###########################################################################
####### OPEN
#
def openElements(self, theList:List) -> None:
"""Call openElement() for each item of theList.
@param theList represents a list of elements to open. It can be
* a string, which is split into a list of tokens.
* A list
In either case, there is then a list, in which the item(s) must be:
* A single string element name
* A list or tuple of [ name, attrs:dict, makeEmpty, nobreak:bool ]
(these are the arguments to openElement(). Later ones can
be left off.
"""
if (isinstance(theList, str)):
theList = re.split(r"\s+", theList)
if (not isinstance(theList, list)):
raise ValueError(
"Pass a string or list, not %s." % (type(theList)))
for i, stuff in enumerate(theList):
if (isinstance(stuff, str)):
self.openElement(stuff)
elif (not isinstance(stuff, (list, tuple))):
raise ValueError("Item %d is not string, list, or tuple, but %s"
% (i, type(stuff)))
if (len(stuff) == 1):
self.openElement(stuff[0])
elif (len(stuff) == 2):
self.openElement(stuff[0], attrs=stuff[1])
elif (len(stuff) == 3):
self.openElement(stuff[0], attrs=stuff[1],
makeEmpty=stuff[2])
elif (len(stuff) == 4):
self.openElement(stuff[0], attrs=stuff[1],
makeEmpty=stuff[2], nobreak=stuff[3])
else:
raise ValueError("Item %d is length %d, not in 0...4."
% (i, len(stuff)))
return
def openElementUnlessOpen(self, gi:str, attrs:Union[str, Dict]="",
nobreak: bool=False) -> None:
if (self.howManyAreOpen(gi) > 0): return
self.openElement(gi, attrs, nobreak)
def openElementUnlessCurrent(self, gi:str, attrs:Union[str, Dict]="",
nobreak: bool=False) -> None:
if (self.getCurrentElementName() == gi): return
self.openElement(gi, attrs, nobreak)
def openElement(self, gi, attrs:Union[str, Dict]=None, makeEmpty: bool=False,
nobreak: bool=False) -> None:
"""Start a new XML element by issuing the start-tag. Add to stack.
"attrs" may be a string or a dict.
With "makeEmpty" or an element that has been declared always empty
(via setEmpty()), make it an empty element.
"nobreak" suppresses any newline after the start-tag.
"""
if (gi in self.cantRecurse):
while(self.howManyAreOpen(gi) > 0):
self.closeElement()
# Figure out desired whitespace
extra = 0
if (gi in self.spaceSpecs):
extra = self.spaceSpecs[gi]
elif (gi in self.inlines):
pass
elif (self.options["breakSTAGO"] or self.options["indent"]):
extra = 1
self.doPrint(("\n " * extra) + self.getIndentString(newline=False))
tag = self.makeStartTag(gi=gi, attrs=attrs, empty=makeEmpty)
self.clearQueuedAttributes()
self.tagStack.append(gi)
if (len(self.langStack)==0): self.langStack = [args.defaultLang]
self.langStack.append(self.langStack[-1])
if (self.options["breakSTAGC"] and gi not in self.inlines and not nobreak):
tag += "\n"
self.doPrint(tag)
def makeStartTag(self, gi:str, attrs:Union[str, Dict]="", empty:bool=False):
# TODO: Doesn't check for queuedAttribute w/ same name as one in attrs,
# or intersort them, if the attrs are passed as a string, not dict.
if (not self.syntax.isXmlName(gi)):
raise ValueError("'%s' is not a legit XML NAME." % (gi))
tag = "<%" + gi
if (attrs):
if (isinstance(attrs, str)):
tag += " " + attrs.strip()
if (self.queuedAttributes): tag += " " + self.queuedAttributes
else:
dcopy = self.queuedAttributes if self.queuedAttributes else {}
for k, v in attrs: dcopy[k] = v
tag += self.dictToAttrs(attrs, sortAttributes=True)
tag += "/>" if empty else ">"
return tag
def dictToAttrs(self, dct, sortAttributes: bool=None,
sortAttrs: bool=None, normValues: bool=False):
"""Turn a dict into a serialized attribute list (possibly sorted
and/or space-normalized). Escape as needed.
"""
# Backward-compatible naming, for the moment:
if (sortAttributes is None): sortAttributes = sortAttrs
if (sortAttributes is None): sortAttributes = False
if (self.options["breakAttrs"]):
sep = self.getIndentString()
else:
sep = " "
anames = dct.keys()
if (sortAttrs): anames.sort()
attrString = ""
for a in (anames):
if (not self.syntax.isXmlName(a)):
raise ValueError("'%s' is not a legit XML NAME." % (a))
v = dct[a]
if (normValues): v = self.normalizeSpace(v)
attrString += "%s%s=\"%s\"" % (sep, a, self.escapeXmlAttribute(v))
# This spaces at end, so close pointy gets its own line.
if (self.options["breakAttrs"]): attrString += self.getIndentString()
return attrString
###########################################################################
####### CLOSE
#
def closeElements(self, theList:Union[str, List]) -> None:
if (isinstance(theList, str)):
theList = re.split(r"\s+", theList)
if (not isinstance(theList, list)):
raise ValueError(
"Pass a string or list, not %s." % (type(theList)))
for i, stuff in enumerate(theList):
if (isinstance(stuff, str)):
self.closeElement(stuff)
else:
raise ValueError("Item %d is not an element type name, but %s."
% (i, type(stuff)))
return