+ # 8.2.5.4 The rules for parsing tokens in HTML content
+ # http://www.w3.org/TR/html5/syntax.html#parsing-main-inhtml
+
+ # 8.2.5.4.1 The "initial" insertion mode
+ # http://www.w3.org/TR/html5/syntax.html#the-initial-insertion-mode
+ ins_mode_initial = (t) ->
+ if is_space_tok t
+ return
+ if t.type is TYPE_COMMENT
+ # fixfull this is supposed to be "the last child of the document object"
+ doc.children.push t
+ return
+ if t.type is TYPE_DOCTYPE
+ # fixfull
+ t.name = 'html'
+ doc.children.push t
+ insertion_mode = ins_mode_before_html
+ return
+ # Anything else
+ #fixfull (iframe, quirks)
+ insertion_mode = ins_mode_before_html
+ insertion_mode t # reprocess the token
+ return
+
+ # 8.2.5.4.2 http://www.w3.org/TR/html5/syntax.html#the-before-html-insertion-mode
+ ins_mode_before_html = (t) ->
+ if t.type is TYPE_DOCTYPE
+ parse_error()
+ return
+ if t.type is TYPE_COMMENT
+ doc.children.push t
+ return
+ if is_space_tok t
+ return
+ if t.type is TYPE_START_TAG and t.name is 'html'
+ el = token_to_element t, NS_HTML, doc
+ open_els.unshift(el)
+ # fixfull (big paragraph in spec about manifest, fragment, urls, etc)
+ insertion_mode = ins_mode_before_head
+ return
+ if t.type is TYPE_END_TAG
+ if t.name is 'head' or t.name is 'body' or t.name is 'html' or t.name is 'br'
+ # fall through to "anything else"
+ else
+ parse_error()
+ return
+ # Anything else
+ html_tok = new_open_tag 'html'
+ el = token_to_element html_tok, NS_HTML, doc
+ doc.children.push el
+ open_els.unshift el
+ # ?fixfull browsing context
+ insertion_mode = ins_mode_before_head
+ insertion_mode t
+ return
+
+ # 8.2.5.4.3 http://www.w3.org/TR/html5/syntax.html#the-before-head-insertion-mode
+ ins_mode_before_head = (t) ->
+ if is_space_tok t
+ return
+ if t.type is TYPE_COMMENT
+ insert_comment t
+ return
+ if t.type is TYPE_DOCTYPE
+ parse_error()
+ return
+ if t.type is TYPE_START_TAG and t.name is 'html'
+ ins_mode_in_body t
+ return
+ if t.type is TYPE_START_TAG and t.name is 'head'
+ el = insert_html_element t
+ head_element_pointer = el
+ insertion_mode = ins_mode_in_head
+ if t.type is TYPE_END_TAG
+ if t.name is 'head' or t.name is 'body' or t.name is 'html' or t.name is 'br'
+ # fall through to Anything else below
+ else
+ parse_error()
+ return
+ # Anything else
+ head_tok = new_open_tag 'head'
+ el = insert_html_element head_tok
+ head_element_pointer = el
+ insertion_mode = ins_mode_in_head
+ insertion_mode t # reprocess current token
+