Skip to content
Snippets Groups Projects
html5parser.py 79.7 KiB
Newer Older
  • Learn to ignore specific revisions
  • 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
    # Differences from the current specification are as follows:
    # * Phases and insertion modes are one concept in parser.py.
    # * EOF handling is slightly different to make sure <html>, <head> and <body>
    #   always exist.
    
    
    try:
        frozenset
    except NameError:
        # Import from the sets module for python 2.3
        from sets import Set as set
        from sets import ImmutableSet as frozenset
    import gettext
    _ = gettext.gettext
    import sys
    
    import tokenizer
    
    import treebuilders
    from treebuilders._base import Marker
    from treebuilders import simpletree
    
    import utils
    from constants import contentModelFlags, spaceCharacters, asciiUpper2Lower
    from constants import scopingElements, formattingElements, specialElements
    from constants import headingElements, tableInsertModeElements
    from constants import cdataElements, rcdataElements, voidElements
    
    class HTMLParser(object):
        """HTML parser. Generates a tree structure from a stream of (possibly
            malformed) HTML"""
    
        def __init__(self, strict = False, tree=simpletree.TreeBuilder,
                     tokenizer=tokenizer.HTMLTokenizer):
            """
            strict - raise an exception when a parse error is encountered
    
            tree - a treebuilder class controlling the type of tree that will be
            returned. Built in treebuilders can be accessed through
            html5lib.treebuilders.getTreeBuilder(treeType)
            """
    
            # Raise an exception on the first error encountered
            self.strict = strict
    
            self.tree = tree()
            self.tokenizer_class = tokenizer
            self.errors = []
    
            # "quirks" / "almost-standards" / "standards"
            self.quirksMode = "standards"
    
            self.phases = {
                "initial": InitialPhase(self, self.tree),
                "rootElement": RootElementPhase(self, self.tree),
                "beforeHead": BeforeHeadPhase(self, self.tree),
                "inHead": InHeadPhase(self, self.tree),
                # XXX "inHeadNoscript": InHeadNoScriptPhase(self, self.tree),
                "afterHead": AfterHeadPhase(self, self.tree),
                "inBody": InBodyPhase(self, self.tree),
                "inTable": InTablePhase(self, self.tree),
                "inCaption": InCaptionPhase(self, self.tree),
                "inColumnGroup": InColumnGroupPhase(self, self.tree),
                "inTableBody": InTableBodyPhase(self, self.tree),
                "inRow": InRowPhase(self, self.tree),
                "inCell": InCellPhase(self, self.tree),
                "inSelect": InSelectPhase(self, self.tree),
                "afterBody": AfterBodyPhase(self, self.tree),
                "inFrameset": InFramesetPhase(self, self.tree),
                "afterFrameset": AfterFramesetPhase(self, self.tree),
                "trailingEnd": TrailingEndPhase(self, self.tree)
            }
    
        def _parse(self, stream, innerHTML=False, container="div",
                   encoding=None, **kwargs):
            
            self.tree.reset()
            self.firstStartTag = False
            self.errors = []
    
            self.tokenizer = self.tokenizer_class(stream, encoding=encoding,
                                                  parseMeta=not innerHTML, **kwargs)
    
            if innerHTML:
                self.innerHTML = container.lower()
    
                if self.innerHTML in cdataElements:
                    self.tokenizer.contentModelFlag = tokenizer.contentModelFlags["RCDATA"]
                elif self.innerHTML in rcdataElements:
                    self.tokenizer.contentModelFlag = tokenizer.contentModelFlags["CDATA"]
                elif self.innerHTML == 'plaintext':
                    self.tokenizer.contentModelFlag = tokenizer.contentModelFlags["PLAINTEXT"]
                else:
                    # contentModelFlag already is PCDATA
                    #self.tokenizer.contentModelFlag = tokenizer.contentModelFlags["PCDATA"]
                    pass
                self.phase = self.phases["rootElement"]
                self.phase.insertHtmlElement()
                self.resetInsertionMode()
            else:
                self.innerHTML = False
                self.phase = self.phases["initial"]
    
            # We only seem to have InBodyPhase testcases where the following is
            # relevant ... need others too
            self.lastPhase = None
    
            # XXX This is temporary for the moment so there isn't any other
            # changes needed for the parser to work with the iterable tokenizer
            for token in self.tokenizer:
                token = self.normalizeToken(token)
                type = token["type"]
                method = getattr(self.phase, "process%s" % type, None)
                if type in ("Characters", "SpaceCharacters", "Comment"):
                    method(token["data"])
                elif type == "StartTag":
                    method(token["name"], token["data"])
                elif type == "EndTag":
                    method(token["name"])
                elif type == "Doctype":
                    method(token["name"], token["publicId"], token["systemId"], token["correct"])
                else:
                    self.parseError(token["data"])
    
            # When the loop finishes it's EOF
            self.phase.processEOF()
    
        def parse(self, stream, encoding=None):
            """Parse a HTML document into a well-formed tree
    
            stream - a filelike object or string containing the HTML to be parsed
    
            The optional encoding parameter must be a string that indicates
            the encoding.  If specified, that encoding will be used,
            regardless of any BOM or later declaration (such as in a meta
            element)
            """
            self._parse(stream, innerHTML=False, encoding=encoding)
            return self.tree.getDocument()
        
        def parseFragment(self, stream, container="div", encoding=None):
            """Parse a HTML fragment into a well-formed tree fragment
            
            container - name of the element we're setting the innerHTML property
            if set to None, default to 'div'
    
            stream - a filelike object or string containing the HTML to be parsed
    
            The optional encoding parameter must be a string that indicates
            the encoding.  If specified, that encoding will be used,
            regardless of any BOM or later declaration (such as in a meta
            element)
            """
            self._parse(stream, True, container=container, encoding=encoding)
            return self.tree.getFragment()
    
        def parseError(self, data="XXX ERROR MESSAGE NEEDED"):
            # XXX The idea is to make data mandatory.
            self.errors.append((self.tokenizer.stream.position(), data))
            if self.strict:
                raise ParseError
    
        def normalizeToken(self, token):
            """ HTML5 specific normalizations to the token stream """
    
            if token["type"] == "EmptyTag":
                # When a solidus (/) is encountered within a tag name what happens
                # depends on whether the current tag name matches that of a void
                # element.  If it matches a void element atheists did the wrong
                # thing and if it doesn't it's wrong for everyone.
    
                if token["name"] not in voidElements:
                    self.parseError(_(u"Solidus (/) incorrectly placed in tag."))
    
                token["type"] = "StartTag"
    
            if token["type"] == "StartTag":
                token["data"] = dict(token["data"][::-1])
    
            return token
    
    
        def resetInsertionMode(self):
            # The name of this method is mostly historical. (It's also used in the
            # specification.)
            last = False
            newModes = {
                "select":"inSelect",
                "td":"inCell",
                "th":"inCell",
                "tr":"inRow",
                "tbody":"inTableBody",
                "thead":"inTableBody",
                "tfoot":"inTableBody",
                "caption":"inCaption",
                "colgroup":"inColumnGroup",
                "table":"inTable",
                "head":"inBody",
                "body":"inBody",
                "frameset":"inFrameset"
            }
            for node in self.tree.openElements[::-1]:
                nodeName = node.name
                if node == self.tree.openElements[0]:
                    last = True
                    if nodeName not in ['td', 'th']:
                        # XXX
                        assert self.innerHTML
                        nodeName = self.innerHTML
                # Check for conditions that should only happen in the innerHTML
                # case
                if nodeName in ("select", "colgroup", "head", "frameset"):
                    # XXX
                    assert self.innerHTML
                if nodeName in newModes:
                    self.phase = self.phases[newModes[nodeName]]
                    break
                elif nodeName == "html":
                    if self.tree.headPointer is None:
                        self.phase = self.phases["beforeHead"]
                    else:
                       self.phase = self.phases["afterHead"]
                    break
                elif last:
                    self.phase = self.phases["inBody"]
                    break
    
    class Phase(object):
        """Base class for helper object that implements each phase of processing
        """
        # Order should be (they can be omitted):
        # * EOF
        # * Comment
        # * Doctype
        # * SpaceCharacters
        # * Characters
        # * StartTag
        #   - startTag* methods
        # * EndTag
        #   - endTag* methods
    
        def __init__(self, parser, tree):
            self.parser = parser
            self.tree = tree
    
        def processEOF(self):
            self.tree.generateImpliedEndTags()
            if len(self.tree.openElements) > 2:
                self.parser.parseError(_(u"Unexpected end of file. "
                  u"Missing closing tags."))
            elif len(self.tree.openElements) == 2 and\
              self.tree.openElements[1].name != "body":
                # This happens for framesets or something?
                self.parser.parseError(_(u"Unexpected end of file. Expected end "
                  u"tag (%s) first.") % (self.tree.openElements[1].name,))
            elif self.parser.innerHTML and len(self.tree.openElements) > 1 :
                # XXX This is not what the specification says. Not sure what to do
                # here.
                self.parser.parseError(_(u"XXX innerHTML EOF"))
            # Betting ends.
    
        def processComment(self, data):
            # For most phases the following is correct. Where it's not it will be
            # overridden.
            self.tree.insertComment(data, self.tree.openElements[-1])
    
        def processDoctype(self, name, publicId, systemId, correct):
            self.parser.parseError(_(u"Unexpected DOCTYPE. Ignored."))
    
        def processSpaceCharacters(self, data):
            self.tree.insertText(data)
    
        def processStartTag(self, name, attributes):
            self.startTagHandler[name](name, attributes)
    
        def startTagHtml(self, name, attributes):
            if self.parser.firstStartTag == False and name == "html":
               self.parser.parseError(_(u"html needs to be the first start tag."))
            # XXX Need a check here to see if the first start tag token emitted is
            # this token... If it's not, invoke self.parser.parseError().
            for attr, value in attributes.iteritems():
                if attr not in self.tree.openElements[0].attributes:
                    self.tree.openElements[0].attributes[attr] = value
            self.parser.firstStartTag = False
    
        def processEndTag(self, name):
            self.endTagHandler[name](name)
    
    
    class InitialPhase(Phase):
        # This phase deals with error handling as well which is currently not
        # covered in the specification. The error handling is typically known as
        # "quirks mode". It is expected that a future version of HTML5 will defin
        # this.
        def processEOF(self):
            self.parser.parseError(_(u"Unexpected End of file. Expected DOCTYPE."))
            self.parser.phase = self.parser.phases["rootElement"]
            self.parser.phase.processEOF()
    
        def processComment(self, data):
            self.tree.insertComment(data, self.tree.document)
    
        def processDoctype(self, name, publicId, systemId, correct):
            nameLower = name.translate(asciiUpper2Lower)
            if nameLower != "html" or publicId != None or\
              systemId != None:
                self.parser.parseError(_(u"Erroneous DOCTYPE."))
            # XXX need to update DOCTYPE tokens
            self.tree.insertDoctype(name, publicId, systemId)
            
            if publicId == None:
              publicId = ""
            if publicId != "":
              publicId = publicId.translate(asciiUpper2Lower)
    
            if nameLower != "html":
                # XXX quirks mode
                pass
            else:
                if publicId in\
                  ("+//silmaril//dtd html pro v0r11 19970101//en",
                   "-//advasoft ltd//dtd html 3.0 aswedit + extensions//en",
                   "-//as//dtd html 3.0 aswedit + extensions//en",
                   "-//ietf//dtd html 2.0 level 1//en",
                   "-//ietf//dtd html 2.0 level 2//en",
                   "-//ietf//dtd html 2.0 strict level 1//en",
                   "-//ietf//dtd html 2.0 strict level 2//en",
                   "-//ietf//dtd html 2.0 strict//en",
                   "-//ietf//dtd html 2.0//en",
                   "-//ietf//dtd html 2.1e//en",
                   "-//ietf//dtd html 3.0//en",
                   "-//ietf//dtd html 3.0//en//",
                   "-//ietf//dtd html 3.2 final//en",
                   "-//ietf//dtd html 3.2//en",
                   "-//ietf//dtd html 3//en",
                   "-//ietf//dtd html level 0//en",
                   "-//ietf//dtd html level 0//en//2.0",
                   "-//ietf//dtd html level 1//en",
                   "-//ietf//dtd html level 1//en//2.0",
                   "-//ietf//dtd html level 2//en",
                   "-//ietf//dtd html level 2//en//2.0",
                   "-//ietf//dtd html level 3//en",
                   "-//ietf//dtd html level 3//en//3.0",
                   "-//ietf//dtd html strict level 0//en",
                   "-//ietf//dtd html strict level 0//en//2.0",
                   "-//ietf//dtd html strict level 1//en",
                   "-//ietf//dtd html strict level 1//en//2.0",
                   "-//ietf//dtd html strict level 2//en",
                   "-//ietf//dtd html strict level 2//en//2.0",
                   "-//ietf//dtd html strict level 3//en",
                   "-//ietf//dtd html strict level 3//en//3.0",
                   "-//ietf//dtd html strict//en",
                   "-//ietf//dtd html strict//en//2.0",
                   "-//ietf//dtd html strict//en//3.0",
                   "-//ietf//dtd html//en",
                   "-//ietf//dtd html//en//2.0",
                   "-//ietf//dtd html//en//3.0",
                   "-//metrius//dtd metrius presentational//en",
                   "-//microsoft//dtd internet explorer 2.0 html strict//en",
                   "-//microsoft//dtd internet explorer 2.0 html//en",
                   "-//microsoft//dtd internet explorer 2.0 tables//en",
                   "-//microsoft//dtd internet explorer 3.0 html strict//en",
                   "-//microsoft//dtd internet explorer 3.0 html//en",
                   "-//microsoft//dtd internet explorer 3.0 tables//en",
                   "-//netscape comm. corp.//dtd html//en",
                   "-//netscape comm. corp.//dtd strict html//en",
                   "-//o'reilly and associates//dtd html 2.0//en",
                   "-//o'reilly and associates//dtd html extended 1.0//en",
                   "-//spyglass//dtd html 2.0 extended//en",
                   "-//sq//dtd html 2.0 hotmetal + extensions//en",
                   "-//sun microsystems corp.//dtd hotjava html//en",
                   "-//sun microsystems corp.//dtd hotjava strict html//en",
                   "-//w3c//dtd html 3 1995-03-24//en",
                   "-//w3c//dtd html 3.2 draft//en",
                   "-//w3c//dtd html 3.2 final//en",
                   "-//w3c//dtd html 3.2//en",
                   "-//w3c//dtd html 3.2s draft//en",
                   "-//w3c//dtd html 4.0 frameset//en",
                   "-//w3c//dtd html 4.0 transitional//en",
                   "-//w3c//dtd html experimental 19960712//en",
                   "-//w3c//dtd html experimental 970421//en",
                   "-//w3c//dtd w3 html//en",
                   "-//w3o//dtd w3 html 3.0//en",
                   "-//w3o//dtd w3 html 3.0//en//",
                   "-//w3o//dtd w3 html strict 3.0//en//",
                   "-//webtechs//dtd mozilla html 2.0//en",
                   "-//webtechs//dtd mozilla html//en",
                   "-/w3c/dtd html 4.0 transitional/en",
                   "html")\
                  or (publicId in\
                  ("-//w3c//dtd html 4.01 frameset//EN",
                   "-//w3c//dtd html 4.01 transitional//EN") and systemId == None)\
                  or (systemId != None and\
                    systemId == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"):
                    #XXX quirks mode
                    pass
    
            self.parser.phase = self.parser.phases["rootElement"]
    
        def processSpaceCharacters(self, data):
            pass
    
        def processCharacters(self, data):
            self.parser.parseError(_(u"Unexpected non-space characters. "
              u"Expected DOCTYPE."))
            self.parser.phase = self.parser.phases["rootElement"]
            self.parser.phase.processCharacters(data)
    
        def processStartTag(self, name, attributes):
            self.parser.parseError(_(u"Unexpected start tag (%s). Expected DOCTYPE.") % (name,))
            self.parser.phase = self.parser.phases["rootElement"]
            self.parser.phase.processStartTag(name, attributes)
    
        def processEndTag(self, name):
            self.parser.parseError(_(u"Unexpected end tag (%s). Expected DOCTYPE.") % (name,))
            self.parser.phase = self.parser.phases["rootElement"]
            self.parser.phase.processEndTag(name)
    
    
    class RootElementPhase(Phase):
        # helper methods
        def insertHtmlElement(self):
            element = self.tree.createElement("html", {})
            self.tree.openElements.append(element)
            self.tree.document.appendChild(element)
            self.parser.phase = self.parser.phases["beforeHead"]
    
        # other
        def processEOF(self):
            self.insertHtmlElement()
            self.parser.phase.processEOF()
    
        def processComment(self, data):
            self.tree.insertComment(data, self.tree.document)
    
        def processSpaceCharacters(self, data):
            pass
    
        def processCharacters(self, data):
            self.insertHtmlElement()
            self.parser.phase.processCharacters(data)
    
        def processStartTag(self, name, attributes):
            if name == "html":
                self.parser.firstStartTag = True
            self.insertHtmlElement()
            self.parser.phase.processStartTag(name, attributes)
    
        def processEndTag(self, name):
            self.insertHtmlElement()
            self.parser.phase.processEndTag(name)
    
    
    class BeforeHeadPhase(Phase):
        def __init__(self, parser, tree):
            Phase.__init__(self, parser, tree)
    
            self.startTagHandler = utils.MethodDispatcher([
                ("html", self.startTagHtml),
                ("head", self.startTagHead)
            ])
            self.startTagHandler.default = self.startTagOther
    
            self.endTagHandler = utils.MethodDispatcher([
                (("html", "head", "body", "br", "p"), self.endTagImplyHead)
            ])
            self.endTagHandler.default = self.endTagOther
    
        def processEOF(self):
            self.startTagHead("head", {})
            self.parser.phase.processEOF()
    
        def processCharacters(self, data):
            self.startTagHead("head", {})
            self.parser.phase.processCharacters(data)
    
        def startTagHead(self, name, attributes):
            self.tree.insertElement(name, attributes)
            self.tree.headPointer = self.tree.openElements[-1]
            self.parser.phase = self.parser.phases["inHead"]
    
        def startTagOther(self, name, attributes):
            self.startTagHead("head", {})
            self.parser.phase.processStartTag(name, attributes)
    
        def endTagImplyHead(self, name):
            self.startTagHead("head", {})
            self.parser.phase.processEndTag(name)
    
        def endTagOther(self, name):
            self.parser.parseError(_(u"Unexpected end tag (%s) after the (implied) root element.") % (name,))
    
    class InHeadPhase(Phase):
        def __init__(self, parser, tree):
            Phase.__init__(self, parser, tree)
    
            self.startTagHandler =  utils.MethodDispatcher([
                ("html", self.startTagHtml),
                ("title", self.startTagTitle),
                ("style", self.startTagStyle),
                ("noscript", self.startTagNoScript),
                ("script", self.startTagScript),
                (("base", "link", "meta"), self.startTagBaseLinkMeta),
                ("head", self.startTagHead)
            ])
            self.startTagHandler.default = self.startTagOther
    
            self. endTagHandler = utils.MethodDispatcher([
                ("head", self.endTagHead),
                (("html", "body", "br", "p"), self.endTagImplyAfterHead),
                (("title", "style", "script", "noscript"),
                  self.endTagTitleStyleScriptNoScript)
            ])
            self.endTagHandler.default = self.endTagOther
    
        # helper
        def appendToHead(self, element):
            if self.tree.headPointer is not None:
                self.tree.headPointer.appendChild(element)
            else:
                assert self.parser.innerHTML
                self.tree.openElements[-1].appendChild(element)
    
        # the real thing
        def processEOF(self):
            if self.tree.openElements[-1].name in ("title", "style", "script"):
                self.parser.parseError(_(u"Unexpected end of file. "
                  u"Expected end tag (%s).") % (self.tree.openElements[-1].name,))
                self.tree.openElements.pop()
            self.anythingElse()
            self.parser.phase.processEOF()
    
        def processCharacters(self, data):
            if self.tree.openElements[-1].name in\
              ("title", "style", "script", "noscript"):
                self.tree.insertText(data)
            else:
                self.anythingElse()
                self.parser.phase.processCharacters(data)
    
        def startTagHead(self, name, attributes):
            self.parser.parseError(_(u"Unexpected start tag head in existing head. Ignored"))
    
        def startTagTitle(self, name, attributes):
            element = self.tree.createElement(name, attributes)
            self.appendToHead(element)
            self.tree.openElements.append(element)
            self.parser.tokenizer.contentModelFlag = contentModelFlags["RCDATA"]
    
        def startTagStyle(self, name, attributes):
            element = self.tree.createElement(name, attributes)
            if self.tree.headPointer is not None and\
              self.parser.phase == self.parser.phases["inHead"]:
                self.appendToHead(element)
            else:
                self.tree.openElements[-1].appendChild(element)
            self.tree.openElements.append(element)
            self.parser.tokenizer.contentModelFlag = contentModelFlags["CDATA"]
    
        def startTagNoScript(self, name, attributes):
            # XXX Need to decide whether to implement the scripting disabled case.
            element = self.tree.createElement(name, attributes)
            if self.tree.headPointer is not None and\
              self.parser.phase == self.parser.phases["inHead"]:
                self.appendToHead(element)
            else:
                self.tree.openElements[-1].appendChild(element)
            self.tree.openElements.append(element)
            self.parser.tokenizer.contentModelFlag = contentModelFlags["CDATA"]
        
        def startTagScript(self, name, attributes):
            #XXX Inner HTML case may be wrong
            element = self.tree.createElement(name, attributes)
            element._flags.append("parser-inserted")
            if (self.tree.headPointer is not None and
                self.parser.phase == self.parser.phases["inHead"]):
                self.appendToHead(element)
            else:
                self.tree.openElements[-1].appendChild(element)
            self.tree.openElements.append(element)
            self.parser.tokenizer.contentModelFlag = contentModelFlags["CDATA"]
    
        def startTagBaseLinkMeta(self, name, attributes):
            element = self.tree.createElement(name, attributes)
            if (self.tree.headPointer is not None and
                self.parser.phase == self.parser.phases["inHead"]):
                self.appendToHead(element)
            else:
                self.tree.openElements[-1].appendChild(element)
    
        def startTagOther(self, name, attributes):
            self.anythingElse()
            self.parser.phase.processStartTag(name, attributes)
    
        def endTagHead(self, name):
            if self.tree.openElements[-1].name == "head":
                self.tree.openElements.pop()
            else:
                self.parser.parseError(_(u"Unexpected end tag (%s). Ignored.") % u'head')
            self.parser.phase = self.parser.phases["afterHead"]
    
        def endTagImplyAfterHead(self, name):
            self.anythingElse()
            self.parser.phase.processEndTag(name)
    
        def endTagTitleStyleScriptNoScript(self, name):
            if self.tree.openElements[-1].name == name:
                self.tree.openElements.pop()
            else:
                self.parser.parseError(_(u"Unexpected end tag (%s). Ignored.") % (name,))
    
        def endTagOther(self, name):
            self.parser.parseError(_(u"Unexpected end tag (%s). Ignored.") % (name,))
    
        def anythingElse(self):
            if self.tree.openElements[-1].name == "head":
                self.endTagHead("head")
            else:
                self.parser.phase = self.parser.phases["afterHead"]
    
    # XXX If we implement a parser for which scripting is disabled we need to
    # implement this phase.
    #
    # class InHeadNoScriptPhase(Phase):
    
    class AfterHeadPhase(Phase):
        def __init__(self, parser, tree):
            Phase.__init__(self, parser, tree)
    
            self.startTagHandler = utils.MethodDispatcher([
                ("html", self.startTagHtml),
                ("body", self.startTagBody),
                ("frameset", self.startTagFrameset),
                (("base", "link", "meta", "script", "style", "title"),
                  self.startTagFromHead)
            ])
            self.startTagHandler.default = self.startTagOther
    
        def processEOF(self):
            self.anythingElse()
            self.parser.phase.processEOF()
    
        def processCharacters(self, data):
            self.anythingElse()
            self.parser.phase.processCharacters(data)
    
        def startTagBody(self, name, attributes):
            self.tree.insertElement(name, attributes)
            self.parser.phase = self.parser.phases["inBody"]
    
        def startTagFrameset(self, name, attributes):
            self.tree.insertElement(name, attributes)
            self.parser.phase = self.parser.phases["inFrameset"]
    
        def startTagFromHead(self, name, attributes):
            self.parser.parseError(_(u"Unexpected start tag (%s) that can be in head. Moved.") % (name,))
            self.parser.phase = self.parser.phases["inHead"]
            self.parser.phase.processStartTag(name, attributes)
    
        def startTagOther(self, name, attributes):
            self.anythingElse()
            self.parser.phase.processStartTag(name, attributes)
    
        def processEndTag(self, name):
            self.anythingElse()
            self.parser.phase.processEndTag(name)
    
        def anythingElse(self):
            self.tree.insertElement("body", {})
            self.parser.phase = self.parser.phases["inBody"]
    
    
    class InBodyPhase(Phase):
        # http://www.whatwg.org/specs/web-apps/current-work/#in-body
        # the crazy mode
        def __init__(self, parser, tree):
            Phase.__init__(self, parser, tree)
    
            #Keep a ref to this for special handling of whitespace in <pre>
            self.processSpaceCharactersNonPre = self.processSpaceCharacters
    
            self.startTagHandler = utils.MethodDispatcher([
                ("html", self.startTagHtml),
                (("base", "link", "meta", "script", "style"),
                  self.startTagProcessInHead),
                ("title", self.startTagTitle),
                ("body", self.startTagBody),
                (("address", "blockquote", "center", "dir", "div", "dl",
                  "fieldset", "listing", "menu", "ol", "p", "pre", "ul"),
                  self.startTagCloseP),
                ("form", self.startTagForm),
                (("li", "dd", "dt"), self.startTagListItem),
                ("plaintext",self.startTagPlaintext),
                (headingElements, self.startTagHeading),
                ("a", self.startTagA),
                (("b", "big", "em", "font", "i", "s", "small", "strike", "strong",
                  "tt", "u"),self.startTagFormatting),
                ("nobr", self.startTagNobr),
                ("button", self.startTagButton),
                (("marquee", "object"), self.startTagMarqueeObject),
                ("xmp", self.startTagXmp),
                ("table", self.startTagTable),
                (("area", "basefont", "bgsound", "br", "embed", "img", "param",
                  "spacer", "wbr"), self.startTagVoidFormatting),
                ("hr", self.startTagHr),
                ("image", self.startTagImage),
                ("input", self.startTagInput),
                ("isindex", self.startTagIsIndex),
                ("textarea", self.startTagTextarea),
                (("iframe", "noembed", "noframes", "noscript"), self.startTagCdata),
                ("select", self.startTagSelect),
                (("caption", "col", "colgroup", "frame", "frameset", "head",
                  "option", "optgroup", "tbody", "td", "tfoot", "th", "thead",
                  "tr"), self.startTagMisplaced),
                (("event-source", "section", "nav", "article", "aside", "header",
                  "footer", "datagrid", "command"), self.startTagNew)
            ])
            self.startTagHandler.default = self.startTagOther
    
            self.endTagHandler = utils.MethodDispatcher([
                ("p",self.endTagP),
                ("body",self.endTagBody),
                ("html",self.endTagHtml),
                (("address", "blockquote", "center", "div", "dl", "fieldset",
                  "listing", "menu", "ol", "pre", "ul"), self.endTagBlock),
                ("form", self.endTagForm),
                (("dd", "dt", "li"), self.endTagListItem),
                (headingElements, self.endTagHeading),
                (("a", "b", "big", "em", "font", "i", "nobr", "s", "small",
                  "strike", "strong", "tt", "u"), self.endTagFormatting),
                (("marquee", "object", "button"), self.endTagButtonMarqueeObject),
                (("head", "frameset", "select", "optgroup", "option", "table",
                  "caption", "colgroup", "col", "thead", "tfoot", "tbody", "tr",
                  "td", "th"), self.endTagMisplaced),
                ("br", self.endTagBr),
                (("area", "basefont", "bgsound", "embed", "hr", "image",
                  "img", "input", "isindex", "param", "spacer", "wbr", "frame"),
                  self.endTagNone),
                (("noframes", "noscript", "noembed", "textarea", "xmp", "iframe"),
                  self.endTagCdataTextAreaXmp),
                (("event-source", "section", "nav", "article", "aside", "header",
                  "footer", "datagrid", "command"), self.endTagNew)
                ])
            self.endTagHandler.default = self.endTagOther
    
        # helper
        def addFormattingElement(self, name, attributes):
            self.tree.insertElement(name, attributes)
            self.tree.activeFormattingElements.append(
                self.tree.openElements[-1])
    
        # the real deal
        def processSpaceCharactersDropNewline(self, data):
            # Sometimes (start of <pre> and <textarea> blocks) we want to drop
            # leading newlines
            self.processSpaceCharacters = self.processSpaceCharactersNonPre
            if (data.startswith("\n") and
                self.tree.openElements[-1].name in ("pre", "textarea") and
                not self.tree.openElements[-1].hasContent()):
                data = data[1:]
            if data:
                self.tree.reconstructActiveFormattingElements()
                self.tree.insertText(data)
    
        def processCharacters(self, data):
            # XXX The specification says to do this for every character at the
            # moment, but apparently that doesn't match the real world so we don't
            # do it for space characters.
            self.tree.reconstructActiveFormattingElements()
            self.tree.insertText(data)
    
        #This matches the current spec but may not match the real world
        def processSpaceCharacters(self, data):
            self.tree.reconstructActiveFormattingElements()
            self.tree.insertText(data)
    
        def startTagProcessInHead(self, name, attributes):
            self.parser.phases["inHead"].processStartTag(name, attributes)
    
        def startTagTitle(self, name, attributes):
            self.parser.parseError(_(u"Unexpected start tag (%s) that belongs in the head. Moved.") % (name,))
            self.parser.phases["inHead"].processStartTag(name, attributes)
    
        def startTagBody(self, name, attributes):
            self.parser.parseError(_(u"Unexpected start tag (body)."))
            if (len(self.tree.openElements) == 1
                or self.tree.openElements[1].name != "body"):
                assert self.parser.innerHTML
            else:
                for attr, value in attributes.iteritems():
                    if attr not in self.tree.openElements[1].attributes:
                        self.tree.openElements[1].attributes[attr] = value
    
        def startTagCloseP(self, name, attributes):
            if self.tree.elementInScope("p"):
                self.endTagP("p")
            self.tree.insertElement(name, attributes)
            if name == "pre":
                self.processSpaceCharacters = self.processSpaceCharactersDropNewline
    
        def startTagForm(self, name, attributes):
            if self.tree.formPointer:
                self.parser.parseError("Unexpected start tag (form). Ignored.")
            else:
                if self.tree.elementInScope("p"):
                    self.endTagP("p")
                self.tree.insertElement(name, attributes)
                self.tree.formPointer = self.tree.openElements[-1]
    
        def startTagListItem(self, name, attributes):
            if self.tree.elementInScope("p"):
                self.endTagP("p")
            stopNames = {"li":("li"), "dd":("dd", "dt"), "dt":("dd", "dt")}
            stopName = stopNames[name]
            # AT Use reversed in Python 2.4...
            for i, node in enumerate(self.tree.openElements[::-1]):
                if node.name in stopName:
                    poppedNodes = []
                    for j in range(i+1):
                        poppedNodes.append(self.tree.openElements.pop())
                    if i >= 1:
                        self.parser.parseError(
                            (i == 1 and _(u"Missing end tag (%s)") or _(u"Missing end tags (%s)"))
                                % u", ".join([item.name for item in poppedNodes[:-1]]))
                    break
            
    
                # Phrasing elements are all non special, non scoping, non
                # formatting elements
                if (node.name in (specialElements | scopingElements)
                  and node.name not in ("address", "div")):
                    break
            # Always insert an <li> element.
            self.tree.insertElement(name, attributes)
    
        def startTagPlaintext(self, name, attributes):
            if self.tree.elementInScope("p"):
                self.endTagP("p")
            self.tree.insertElement(name, attributes)
            self.parser.tokenizer.contentModelFlag = contentModelFlags["PLAINTEXT"]
    
        def startTagHeading(self, name, attributes):
            if self.tree.elementInScope("p"):
                self.endTagP("p")
            # Uncomment the following for IE7 behavior:
            #
            #for item in headingElements:
            #    if self.tree.elementInScope(item):
            #        self.parser.parseError(_(u"Unexpected start tag (" + name +\
            #          ")."))
            #        item = self.tree.openElements.pop()
            #        while item.name not in headingElements:
            #            item = self.tree.openElements.pop()
            #        break
            self.tree.insertElement(name, attributes)
    
        def startTagA(self, name, attributes):
            afeAElement = self.tree.elementInActiveFormattingElements("a")
            if afeAElement:
                self.parser.parseError(_(u"Unexpected start tag (%s) implies "
                  u"end tag (%s).") % (u'a', u'a'))
                self.endTagFormatting("a")
                if afeAElement in self.tree.openElements:
                    self.tree.openElements.remove(afeAElement)
                if afeAElement in self.tree.activeFormattingElements:
                    self.tree.activeFormattingElements.remove(afeAElement)
            self.tree.reconstructActiveFormattingElements()
            self.addFormattingElement(name, attributes)
    
        def startTagFormatting(self, name, attributes):
            self.tree.reconstructActiveFormattingElements()
            self.addFormattingElement(name, attributes)
    
        def startTagNobr(self, name, attributes):
            self.tree.reconstructActiveFormattingElements()
            if self.tree.elementInScope("nobr"):
                self.parser.parseError(_(u"Unexpected start tag (%s) implies "
                  u"end tag (%s).") % (u'nobr', u'nobr'))
                self.processEndTag("nobr")
                # XXX Need tests that trigger the following
                self.tree.reconstructActiveFormattingElements()
            self.addFormattingElement(name, attributes)
    
        def startTagButton(self, name, attributes):
            if self.tree.elementInScope("button"):
                self.parser.parseError(_(u"Unexpected start tag (%s) implied "
                  u"end tag (%s).") % (u'button', u'button'))
                self.processEndTag("button")
                self.parser.phase.processStartTag(name, attributes)
            else:
                self.tree.reconstructActiveFormattingElements()
                self.tree.insertElement(name, attributes)
                self.tree.activeFormattingElements.append(Marker)
    
        def startTagMarqueeObject(self, name, attributes):
            self.tree.reconstructActiveFormattingElements()
            self.tree.insertElement(name, attributes)
            self.tree.activeFormattingElements.append(Marker)
    
        def startTagXmp(self, name, attributes):
            self.tree.reconstructActiveFormattingElements()
            self.tree.insertElement(name, attributes)
            self.parser.tokenizer.contentModelFlag = contentModelFlags["CDATA"]
    
        def startTagTable(self, name, attributes):
            if self.tree.elementInScope("p"):
                self.processEndTag("p")
            self.tree.insertElement(name, attributes)
            self.parser.phase = self.parser.phases["inTable"]
    
        def startTagVoidFormatting(self, name, attributes):
            self.tree.reconstructActiveFormattingElements()
            self.tree.insertElement(name, attributes)
            self.tree.openElements.pop()
    
        def startTagHr(self, name, attributes):
            if self.tree.elementInScope("p"):
                self.endTagP("p")
            self.tree.insertElement(name, attributes)
            self.tree.openElements.pop()
    
        def startTagImage(self, name, attributes):
            # No really...
            self.parser.parseError(_(u"Unexpected start tag (image). Treated "
              u"as img."))
            self.processStartTag("img", attributes)
    
        def startTagInput(self, name, attributes):
            self.tree.reconstructActiveFormattingElements()
            self.tree.insertElement(name, attributes)
            if self.tree.formPointer:
                # XXX Not exactly sure what to do here
                self.tree.openElements[-1].form = self.tree.formPointer
            self.tree.openElements.pop()
    
        def startTagIsIndex(self, name, attributes):
            self.parser.parseError("Unexpected start tag isindex. Don't use it!")
            if self.tree.formPointer:
                return
            self.processStartTag("form", {})
            self.processStartTag("hr", {})
            self.processStartTag("p", {})
            self.processStartTag("label", {})
            # XXX Localization ...
            self.processCharacters(
                "This is a searchable index. Insert your search keywords here: ")
            attributes["name"] = "isindex"
            attrs = [[key,value] for key,value in attributes.iteritems()]
            self.processStartTag("input", dict(attrs))
            self.processEndTag("label")
            self.processEndTag("p")
            self.processStartTag("hr", {})
            self.processEndTag("form")
    
        def startTagTextarea(self, name, attributes):
            # XXX Form element pointer checking here as well...
            self.tree.insertElement(name, attributes)
            self.parser.tokenizer.contentModelFlag = contentModelFlags["RCDATA"]
            self.processSpaceCharacters = self.processSpaceCharactersDropNewline
    
        def startTagCdata(self, name, attributes):
            """iframe, noembed noframes, noscript(if scripting enabled)"""
            self.tree.insertElement(name, attributes)
            self.parser.tokenizer.contentModelFlag = contentModelFlags["CDATA"]
    
        def startTagSelect(self, name, attributes):
            self.tree.reconstructActiveFormattingElements()
            self.tree.insertElement(name, attributes)
            self.parser.phase = self.parser.phases["inSelect"]
    
        def startTagMisplaced(self, name, attributes):
            """ Elements that should be children of other elements that have a
            different insertion mode; here they are ignored
            "caption", "col", "colgroup", "frame", "frameset", "head",
            "option", "optgroup", "tbody", "td", "tfoot", "th", "thead",
            "tr", "noscript"
            """
            self.parser.parseError(_(u"Unexpected start tag (%s). Ignored.") % (name,))
    
        def startTagNew(self, name, attributes):
            """New HTML5 elements, "event-source", "section", "nav",
            "article", "aside", "header", "footer", "datagrid", "command"
            """
            sys.stderr.write("Warning: Undefined behaviour for start tag %s"%name)
            self.startTagOther(name, attributes)
            #raise NotImplementedError
    
        def startTagOther(self, name, attributes):
            self.tree.reconstructActiveFormattingElements()
            self.tree.insertElement(name, attributes)
    
        def endTagP(self, name):
            if self.tree.elementInScope("p"):
                self.tree.generateImpliedEndTags("p")
            if self.tree.openElements[-1].name != "p":
                self.parser.parseError(_(u"Unexpected end tag (%s).") % (u'p',))
            if self.tree.elementInScope("p"):
                while self.tree.elementInScope("p"):
                    self.tree.openElements.pop()
            else: