Source

webstring / webstring / markup.py

Full commit
  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
# -*- coding: utf-8 -*-
'''XML templates.'''

import md5 as _md5
import random as _random
from sys import maxint as _maxint
from random import randint as _randint
from xml.etree.ElementTree import Element as ETElement

from stuf.six import items, u
from lxml.html import HTMLParser, tostring as htostring, xhtml_to_html
from lxml.etree import (
    Element, ElementTree, HTML, XSLT, XML, parse, tostring as xtostring)

from webstring.base import (
    _checkname, _Template, _Group, _Field, _exceptions, _Stemplate,
)

# HTML 5 doctype
_html5 = u('<!DOCTYPE html>')
# XHTML 1.0 strict doctype
_xhtml10 = u(
    '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
    '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
)
# XHTML 1.1 strict doctype
_xhtml11 = u(
    '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" '
    '"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'
)


def _copytree(tree):
    # copies an element.
    element = tree.makeelement(tree.tag, tree.attrib)
    element.tail, element.text = tree.tail, tree.text
    eappend = element.append
    copytree = _copytree
    for child in tree:
        eappend(copytree(child))
    return element


def _copyetree(tree, builder):
    # copies an element to a different ElementTree implementation.
    element = builder(tree.tag, dict(items(tree.attrib)))
    element.tail, element.text = tree.tail, tree.text
    eappend = element.append
    copyetree = _copyetree
    for child in tree:
        eappend(copyetree(child, builder))
    return element


_random.seed()


class _XMLMany(object):

    '''Base class for XML template with sub-templates.'''

    # XML attribute indicating fields and groups
    _mark = 'id'
    _groupmark = 'class'

    def __delattr__(self, attr):
        '''
        Delete an attribute.
        '''
        try:
            # try removing field
            try:
                # delete from internal field dictionary
                obj = self._fielddict.pop(attr)
                # remove from internal field list
                self._fields.remove(obj)
                # remove internal element from parent
                obj._parent.remove(obj._tree)
            except KeyError:
                pass
        # always delete object attribute
        finally:
            if hasattr(self, attr):
                object.__delattr__(self, attr)

    def _addfield(self, child, parent):
        # if element has variable delimiter, make field
        name = _checkname(child.attrib[self._mark])
        # check if processed already
        if name not in self._filter:
            # add to filter list if unprocessed
            self._filter.add(name)
            # add child as field
            self._setfield(
                name, self._field(child, parent, self._auto, self._max)
            )

    def _delgmark(self):
        # removes group delimiter attribute.
        for field in self._fields:
            if hasattr(field, 'groupmark'):
                del field.groupmark

    def _delmark(self):
        # removes variable delimiter attribute.
        for field in self._fields:
            delattr(field, 'mark')

    def templates(self, tempdict):
        '''
        Sets inline text and attribute templates for child fields.

        :argument dict tempdict: Dictionary of templates
        '''
        if isinstance(tempdict, dict):
            # make sure there are no more templates than there are fields
            if len(tempdict) <= len(self):
                self._templates = tempdict
                fielddict = self._fielddict
                XGroup = _XMLGroup
                for key, value in items(tempdict):
                    item = fielddict[key]
                    # handle groups
                    if isinstance(item, XGroup):
                        item.templates(value)
                    # handle fields
                    elif not hasattr(item, 'groupmark'):
                        # check if text template is in dict
                        try:
                            item.template = value['text']
                        except KeyError:
                            pass
                        # check if attribute template is in dict
                        try:
                            item.atemplates(value['attrib'])
                        except KeyError:
                            pass
            # raise exception if more templates than fields
            else:
                raise TypeError('template count exceeds field count')
        else:
            raise TypeError('invalid source for templates')


class _NonRoot(object):

    '''
    Base non-root XML template.
    '''

    def __iadd__(self, data):
        '''
        Inserts an element or another template's elements after the internal
        element and this template (self) is returned modified.
        '''
        # process template
        if hasattr(data, 'mark'):
            # get fresh copy of data (needed for lxml compatibility)
            if data._parent is not None:
                data = data.current
            # add to _tempfields
            self._tempfields.append(data)
            # make template's internal tree the data
            data = data._tree
        # process elements
        if hasattr(data, 'tag'):
            # insert element after internal element + self._siblings length
            self._parent.insert(self._index + len(self._siblings), data)
            # insert into sibling tracking list
            self._siblings.append(data)
        else:
            raise TypeError(_exceptions[2])
        return self

    def _getcurrent(self, call, **kw):
        # property that returns the current state of this Field.
        newparent, tfield = _copytree(self._parent), list()
        # sibling elements
        sibs = newparent[self._index:self._index + len(self._siblings)]
        # copy fields based on any new sibling elements
        field = self._field
        group = self._group
        tappend = tfield.append
        auto = self._auto
        max_ = self.max
        for sib in sibs:
            # try making a field
            try:
                tappend(field(sib, newparent, auto, max_))
            except KeyError:
                # try making a group
                try:
                    tappend(group(sib, newparent, auto, max_))
                except KeyError:
                    pass
        # internal elements and siblings for new Field come from copy of parent
        return call(
            newparent[self._index - 1],
            newparent,
            self._auto,
            self.max,
            siblings=sibs,
            tempfield=tfield,
            **kw
        )

    def _getdefault(self, call, **kw):
        # property that returns the default state of self.
        return call(_copytree(self._btree), None, self._auto, self.max, **kw)

    @property
    def _index(self):
        # returns the index under the parent after the internal element.
        try:
            return self._idx
        # store index
        except AttributeError:
            self._idx = self._parent.getchildren().index(self._tree) + 1
            return self._idx

    def append(self, data):
        '''
        Makes an element or another template's elements children of this
        template's internal element.

        :argument data: :class:`template` or element
        '''
        # process elements
        if hasattr(data, 'tag'):
            # make element child of internal element
            self._tree.append(data)
        # process template
        elif hasattr(data, 'mark'):
            # make the other template's children children of internal element
            self._tree.append(data._tree)
            self._tempfields.append(data)
        else:
            raise TypeError(_exceptions[2])

    def render(self, info=None, format='xml', encoding='utf-8'):
        '''
        Returns a :class:`str` version the internal element's parent.

        :keyword info: data to substitute into a document
        :keyword str format: format of document
        :keyword str encoding: encoding for return string
        '''
        tostring = xtostring
        if info is not None:
            self.__imod__(info)
        # build up list of strings from internal element and newer siblings
        output = [tostring(self._tree)]
        output.extend(tostring(f) for f in self._siblings)
        return ''.join(output)

    def reset(self, **kw):
        '''
        Returns a :class:`template` object to its default state.
        '''
        # remove any new siblings
        remove = self._parent.remove
        for item in self._siblings:
            remove(item)
        # save current internal element and its index
        tree, idx = self._tree, self._index
        # re-initialize self
        self.__init__(self._btree, self._parent, self._auto, self.max, **kw)
        # insert the new internal element
        self._parent.insert(idx, self._tree)
        # remove the old internal element
        self._parent.remove(tree)


class _XMLOne(_Field, _NonRoot):

    '''Base XML template field.'''

    # attribute indicating fields
    _mark = 'id'

    def __init__(self, src, parent=None, auto=True, maxlen=25, **kw):
        '''
        :argument src: element source
        :keyword parent: parent element of the source
        :keyword bool auto: turns automagic on and off
        :keyword int maxlen: maximum number of times a field can repeat
        '''
        super(_XMLOne, self).__init__(auto, maxlen, **kw)
        self._group = _XMLGroup
        # parent and inline text template
        self._parent, self._template = parent, kw.get('template')
        # attribute templates
        self._tattrib = kw.get('tattrib', dict())
        if hasattr(src, 'tag'):
            self._setelement(src)

    def __imod__(self, data):
        '''
        Substitutes text data into the internal element's text and attributes
        and this field (self) is returned modified.
        '''
        if isinstance(data, dict):
            # try popping templates
            try:
                txt = data.pop('template')
                # try popping inline text template
                try:
                    self.template = txt.pop('text')
                except KeyError:
                    pass
                # try popping attribute templates
                try:
                    self.atemplates(txt.pop('attrib'))
                except KeyError:
                    pass
            except KeyError:
                pass
            # try popping attribute content
            try:
                self.update(data.pop('attrib'))
            except KeyError:
                pass
        # run superclass method
        return super(_XMLOne, self).__imod__(data)

    def __getitem__(self, key):
        '''Returns the attribute with the given key.'''
        return self._attrib[key]

    def __setitem__(self, key, value):
        '''Sets the XML attribute at the given key.'''
        # set attribute property if automagic on
        if hasattr(self, key):
            setattr(self, key, value)
        else:
            self._setattr(key, value)

    def __delitem__(self, key):
        '''Deletes an XML attribute.'''
        # delete the property if automagic on
        try:
            delattr(self, _checkname(key))
        except AttributeError:
            del self._attrib[key]
        # remove any template for the attribute
        try:
            self._tattrib.pop(key)
        except (AttributeError, KeyError):
            pass

    def __contains__(self, key):
        '''If an XML attribute is in a field.'''
        return key in self._attrib

    def __len__(self):
        '''Number of XML attributes in a field.'''
        return len(self._attrib)

    def __iter__(self):
        '''Iterate over internal XML attribute :class:`dict`.'''
        return iter(self._attrib)

    def _delmark(self):
        # removes variable delimiter attribute from output.
        self.__delitem__(self.mark)
        for field in self._tempfields:
            delattr(field, 'mark')

    def _deltext(self):
        # sets internal element's text attribute to None.
        self._tree.text = None

    def _setattr(self, key, value):
        # sets attribute of the internal element to a new value.
        if isinstance(value, basestring):
            self._tree.set(key, value)
        elif isinstance(value, dict):
            # try string.template substitution
            try:
                self._tree.set(key, self._tattrib[key].substitute(value))
            # try string interpolation
            except AttributeError:
                self._tree.set(key, self._tattrib[key] % value)
        if self._auto:
            name = _checkname(key)
            # make attribute attribute of self's superclass if automagic on
            setattr(self.__class__, name, _Attribute(key, name))

    def _setelement(self, tree):
        # set internal element.
        self.__name__ = _checkname(tree.attrib[self.mark])
        # set internal element and backup tree
        self._tree, self._btree = tree, _copytree(tree)
        # make tree attribute dictionary a field attribute
        self._attrib, tattrib = tree.attrib, dict()
        # if inline text template in tree, assign it to template
        try:
            self.template = tree.text
        except TypeError:
            pass
        checkname_ = _checkname
        auto = self._auto
        mark = self.mark
        setattr_ = setattr
        cls = self.__class__
        for attr, atext in items(self._attrib):
            # if attribute template text in template source, add to _tattrib
            if '$' in atext or '%' in atext:
                tattrib[attr] = atext
            # make XML attrs attributes of self if automagic on & not a mark
            if auto and attr != mark:
                name = checkname_(attr)
                # set new class as attribute of self's superclass
                setattr_(cls, name, _Attribute(attr, name))
        # assign any attribute templates
        if tattrib:
            self.atemplates(tattrib)

    def _settemplate(self, text):
        # sets inline text templates for the internal element.
        if isinstance(text, basestring):
            # make string.template instance if delimiter '$' found.
            if '$' in text:
                self._template = _Stemplate(text)
            # use standard Python format string if delimiter '%' found
            elif '%' in text:
                self._template = text
            # raise exception if no delimiter found
            else:
                raise TypeError(_exceptions[8])
        else:
            raise TypeError(_exceptions[7])

    def _settext(self, text):
        # sets internal element's text attribute.
        if isinstance(text, basestring):
            self._tree.text = text
        elif isinstance(text, dict):
            # try string.template substitution
            try:
                self._tree.text = self._template.substitute(text)
            # try string interpolation
            except AttributeError:
                self._tree.text = self._template % text
        else:
            raise TypeError(_exceptions[7])

    @property
    def current(self):
        '''Returns the current state of self.'''
        return self._getcurrent(
            self._field, template=self._template, tattrib=self._tattrib,
        )

    @property
    def default(self):
        '''Returns the default state of self.'''
        return self._getdefault(
            self._field, template=self._template, tattrib=self._tattrib,
        )

    def atemplates(self, attr):
        '''
        Sets templates for the internal element's attributes.

        :argument attr: attribute template
        '''
        if isinstance(attr, dict):
            tattrib = dict()
            # set template for each item in attrib dict
            Stemplate = _Stemplate
            for key, value in items(attr):
                # make string.template instance if delimiter '$' is found
                if '$' in value:
                    tattrib[key] = Stemplate(value)
                # use standard Python format string if delimiter '%' found
                elif '%' in value:
                    tattrib[key] = value
                # raise exception if no delimiter found
                else:
                    raise TypeError(_exceptions[8])
            # assign object attribute for attribute template dictionary
            self._tattrib.update(tattrib)
        else:
            raise TypeError(_exceptions[7])

    def purge(self, *attrs):
        '''
        Removes XML attributes from a field.

        :param tuple attrs: attributes to remove
        '''
        delitem = self.__delitem__
        for item in attrs:
            delitem(item)

    def reset(self, **kw):
        '''Return :class:`template` object to its default state.'''
        super(_XMLOne, self).reset(
            template=self._template, tattrib=self._tattrib,
        )

    def update(self, attr):
        '''
        Set internal element attributes with :class:`dict`.

        :argument dict attr: element attributes
        '''
        if isinstance(attr, dict):
            _setattr = self._setattr
            for key, value in items(attr):
                _setattr(key, value)
        else:
            raise TypeError('invalid attribute source')

    # template variable delimiter attribute name
    mark = property(lambda self: self._mark, _Field._setmark, _delmark)
    # internal element text
    text = property(lambda self: self._tree.text, _settext, _deltext)
    # internal element text template
    template = property(lambda self: self._template, _settemplate)


class _Attribute(object):

    '''Class for manipulating the XML attributes of an internal element.'''

    __slots__ = '_key', '_name'

    def __init__(self, key, name):
        self._key, self._name = key, name

    def __repr__(self):
        return ''.join(('attribute: ', self._key))

    def __get__(self, inst1, inst2):
        return inst1._attrib[self._key]

    def __set__(self, inst, value):
        inst._setattr(self._key, value)

    def __delete__(self, inst):
        # delete the XML attribute from internal element
        del inst._attrib[self._key]
        # delete self as attribute of object's superclass
        delattr(inst.__class__, self._name)


class _XMLField(object):

    '''Dispatcher for XML template fields.'''

    _group, _klass = None, _XMLOne

    def __new__(cls, *arg, **kw):
        c = cls._klass
        c._group, c._field = cls._group, cls
        # make new class if automagic on to avoid attribute property overlap
        if arg[2]:
            c = type(
                _md5.new(str(_randint(0, _maxint))).digest(),
                (c,),
                dict(c.__dict__)
            )
        return c(*arg, **kw)


class _XMLGroup(_XMLMany, _Group, _NonRoot):

    '''XML group template.'''

    _field = _XMLField

    def __init__(self, src=None, parent=None, auto=True, maxlen=25, **kw):
        '''
        :keyword src: element source
        :keyword parent: parent element of the source
        :keyword bool auto: turns automagic on and off
        :keyword int maxlen: maximum number of times a field can repeat
        '''
        super(_XMLGroup, self).__init__(auto, maxlen, **kw)
        self._parent = parent
        if hasattr(src, 'tag'):
            self._setelement(src)
        self._templates = kw.get('templates')
        if self._templates is not None:
            self.templates(self._templates)
        self._group = self.__class__

    def _delgmark(self):
        # removes group mark attribute from output.
        del self._tree.attrib[self._groupmark]
        super(_XMLGroup, self)._delgmark()
        # remove groupmark on any concatentated groups
        for field in self._tempfields:
            if hasattr(field, 'groupmark'):
                del field.groupmark

    def _delmark(self):
        # removes variable mark attribute from output.
        super(_XMLGroup, self)._delmark()
        for field in self._tempfields:
            delattr(field, 'mark')

    def _setelement(self, tree):
        # sets the internal element.
        self.__name__ = _checkname(tree.attrib[self.groupmark])
        # set internal element and backup tree attributes
        self._tree, self._btree = tree, _copytree(tree)
        addfield = self._addfield
        # find fields in group
        for parent in tree.getiterator():
            # get child, parent pairs
            for child in parent:
                try:
                    addfield(child, parent)
                except KeyError:
                    pass

    # template variable attribute name
    mark = property(lambda self: self._mark, _Field._setmark, _delmark)
    # group delimiter attribute name
    groupmark = property(
        lambda self: self._groupmark, _Group._setgmark, _delgmark
    )

    @property
    def current(self):
        '''Current state of this group.'''
        return self._getcurrent(_XMLGroup, templates=self._templates)

    @property
    def default(self):
        '''Default state of this group.'''
        return self._getdefault(_XMLGroup, templates=self._templates)

    def reset(self, **kw):
        '''Resets group back to its default state. '''
        super(_XMLGroup, self).reset(templates=self._templates)


class Template(_XMLMany, _Template):

    '''Root template.'''

    __name__ = 'root'
    _field = _XMLField
    _group = _XMLGroup
    _parent = None

    def __init__(self, src=None, auto=True, maxlen=25, **kw):
        '''
        :keyword src: path, string, or element source
        :keyword bool auto: turns automagic on or off
        :keyword int maxlen: maximum number of times a template can repeat
        '''
        super(Template, self).__init__(auto, maxlen, **kw)
        # process element if source is an element
        if hasattr(src, 'tag'):
            self._setelement(src)
        # check if source exists
        elif src is not None:
            # try reading source from a file
            try:
                open(src)
                self.fromfile(src)
            except IOError:
                # try reading from a string
                try:
                    self.fromstring(src)
                except SyntaxError:
                    raise IOError(_exceptions[1])
        # assign any templates
        self._templates = kw.get('templates')
        if self._templates is not None:
            self.templates(self._templates)

    def __iadd__(self, data):
        '''
        Inserts an element or another template's internal elements after
        the internal element and returns the modified template (self).

        :argument data: template or element
        '''
        # process element
        if hasattr(data, 'tag'):
            self._tree.append(data)
        # process template
        elif hasattr(data, 'mark'):
            # make internal element of other template child of this internal
            # element
            self._tree.append(_copytree(data._tree))
            # extend template's internal fields with group template's fields
            if hasattr(data, 'groupmark'):
                self._fields.extend(data._fields)
            # append standalone fields to template's field's
            else:
                self._fields.append(data)
        else:
            raise TypeError(_exceptions[2])
        return self

    def __getstate__(self):
        # convert internal and backup elements to pure Python element trees
        return dict(
            tree=_copyetree(self._tree, ETElement),
            _mark=self.mark,
            btree=_copyetree(self._btree, ETElement),
            _templates=self._templates,
            _groupmark=self.groupmark,
            _auto=self._auto,
            _max=self._max,
        )

    def __setstate__(self, s):
        # recreate internal trackers
        self._fielddict, self._fields, self._filter = dict(), list(), set()
        # convert old tree and backup tree to cElementTrees
        tree = _copyetree(s.pop('tree'), Element)
        btree = _copyetree(s.pop('btree'), Element)
        # update internal dictionary
        self.__dict__.update(s)
        # recreate tree
        self._setelement(tree)
        # reassign backuptree
        self._btree = btree
        # reprocess templates
        if self._templates is not None:
            self.templates(self._templates)

    def _addgroup(self, child, parent):
        # verify element is a group element
        realname = child.attrib[self._groupmark]
        name = _checkname(realname)
        # check if group already processed
        if name not in self._filter:
            # mark as processed
            self._filter.add(name)
            # extract any groups under the group's element
            addgroup = self._addgroup
            for element in child:
                try:
                    addgroup(element, child)
                except KeyError:
                    pass
            # make new group template w/o passing group's element to __init__
            node = self._group(None, parent, self._auto, self._max)
            # add self's filter to avoid duplicate children
            node._filter = self._filter
            # process group's element
            node._setelement(child)
            # only attach groups with children to root template
            if len(node):
                self._setfield(name, node)

    def _setelement(self, tree):
        # set internal element and backup element
        self._tree, self._btree = tree, _copytree(tree)
        # find fields and groups
        addfield = self._addfield
        addgroup = self._addgroup
        for parent in tree.getiterator():
            for child in parent:
                # try making child a field
                try:
                    addfield(child, parent)
                except KeyError:
                    # try making child a group
                    try:
                        addgroup(child, parent)
                    except KeyError:
                        pass

    def _setgmark(self, mark):
        # sets the groupmark for a group or root.
        super(Template, self)._setgmark(mark)
        # set mark on all child Groups
        for field in self._fields:
            if hasattr(field, 'groupmark'):
                field.groupmark = mark

    def _setxslt(self, stylesheet):
        '''Sets XSLT stylesheet for template.'''
        self._xslt = XSLT(XML(stylesheet))

    def transform(self, stylesheet=None, **kw):
        '''
        Transforms template based on XSLT stylesheet.

        :keyword str stylesheet: XSLT document
        :param kw: keyword arguments
        '''
        if stylesheet is not None:
            self._setxslt(stylesheet)
        return u(self._xslt(self._tree, **kw))

    def xinclude(self):
        '''Processes xinclude statements in template.'''
        ElementTree(self._tree).xinclude()

    def fromfile(self, path):
        '''
        Creates element from file source.

        :argument str path: path to template source
        '''
        self._setelement(parse(path).getroot())

    def fromstring(self, instring):
        '''
        Creates element from :class:`str` source.

        :argument str instring: :class:`str` source for internal element
        '''
        self._setelement(XML(instring))

    def render(self, info=None, format='xml'):
        '''
        :class:`str` version of element.

        :keyword info: data to substitute into an XML document
        :keyword str format: format of document
        '''
        if info is not None:
            self.__imod__(info)
        return xtostring(self._tree)

    def reset(self):
        '''Return template to its default state.'''
        self.__init__(
            self._btree, self._auto, self._max, templates=self._templates
        )

    # create property that returns the current template state
    current = property(lambda self: Template(_copytree(self._tree),
        self._auto, self._max, templates=self._templates))
    # create property that returns the default template state
    default = property(lambda self: Template(_copytree(self._btree),
        self._auto, self._max, templates=self._templates))
    # XSLT property
    xslt = property(lambda self: self._xslt, _setxslt)

    # template variable attribute name
    mark = property(
        lambda self: self._mark, _Field._setmark, _XMLMany._delmark
    )
    # group delimiter attribute name
    groupmark = property(
        lambda self: self._groupmark, _Template._setgmark, _XMLMany._delgmark
    )


class HTMLTemplate(Template):

    '''HTML template.'''

    def fromfile(self, path):
        '''
        Load template from file source.

        :param str path: path to template
        '''
        # try ordinary XML parsing
        try:
            super(HTMLTemplate, self).fromfile(path)
        # feed through the HTML parser to handle broken HTML
        except:
            self._setelement(parse(path), HTMLParser())

    def fromstring(self, instring):
        '''
        Load template from string.

        :argument str path: source for internal template
        '''
        # try parsing the string as straight XML
        try:
            super(HTMLTemplate, self).fromstring(instring)
        # feed through the HTML parser to handle broken HTML
        except:
            self._setelement(HTML(instring))

    def pipe(self, info=None, format='html', encoding='unicode'):
        '''
        A string version of the internal element's parent and resets this
        :class:`HTMLTemplate`.

        :keyword info: data to substitute into a document
        :keyword str format: format of document
        :keyword str encoding: encoding type for returned string
        '''
        return super(HTMLTemplate, self).pipe(info, format)

    def render(self, info=None, format='html', encoding='unicode'):
        '''
        Render string from template.

        :keyword info: data to substitute into a document
        :keyword str format: HTML doctype to use for string
        :param str encoding: encoding type for return string
        '''
        # substitute any info into the document
        if info is not None:
            self.__imod__(info)
        tree = _copytree(self._tree)
        # use XHTML 1.0 doctype
        if format == 'html':
            # strip namespace prefix from HTML
            xhtml_to_html(tree)
            doc = htostring(tree, encoding=encoding, doctype=_html5)
        # use XHTML 1.1 doctype
        elif format == 'xhtml10':
            doc = htostring(
                tree, method='xml', encoding=encoding, doctype=_xhtml10,
            )
        # use HTML 5 doctype
        elif format == 'xhtml11':
            doc = htostring(
                tree, method='xml', encoding=encoding, doctype=_xhtml11,
            )
        return doc

    def write(self, path, info=None, format='html', encoding='unicode'):
        '''
        Write rendered template to file.

        :argument str path: path of destination file
        :keyword info: data to substitute into a document
        :keyword str format: HTML format of document
        :keyword str encoding: encoding type for return string
        '''
        super(HTMLTemplate, self).write(path, info, format)