protected function getAppropriateMode() {
		$builder = $this->builder;
		$stack = $builder->stack;
		$last = false;
		$node = $stack->current;
		for ( $idx = $stack->length() - 1; $idx >= 0; $idx-- ) {
			$node = $stack->item( $idx );
			if ( $idx === 0 ) {
				$last = true;
				if ( $builder->isFragment ) {
					$node = $builder->fragmentContext;
				}
			}

			switch ( $node->htmlName ) {
			case 'select':
				if ( $last ) {
					return self::IN_SELECT;
				}
				for ( $ancestorIdx = $idx - 1; $ancestorIdx >= 1; $ancestorIdx-- ) {
					$ancestor = $stack->item( $ancestorIdx );
					if ( $ancestor->htmlName === 'template' ) {
						return self::IN_SELECT;
					} elseif ( $ancestor->htmlName === 'table' ) {
						return self::IN_SELECT_IN_TABLE;
					}
				}
				return self::IN_SELECT;

			case 'td':
			case 'th':
				if ( !$last ) {
					return self::IN_CELL;
				}
				break;

			case 'tr':
				return self::IN_ROW;

			case 'tbody':
			case 'thead':
			case 'tfoot':
				return self::IN_TABLE_BODY;

			case 'caption':
				return self::IN_CAPTION;

			case 'colgroup':
				return self::IN_COLUMN_GROUP;

			case 'table':
				return self::IN_TABLE;

			case 'template':
				return $this->templateModeStack->current;

			case 'head':
				if ( $last ) {
					return self::IN_BODY;
				} else {
					return self::IN_HEAD;
				}

			case 'body':
				return self::IN_BODY;

			case 'frameset':
				return self::IN_FRAMESET;

			case 'html':
				if ( $builder->headElement === null ) {
					return self::BEFORE_HEAD;
				} else {
					return self::AFTER_HEAD;
				}
			}
		}

		return self::IN_BODY;
	}