public function format(ElementInterface $element, $format = null)
    {
        if ($element instanceof DoctypeElement) {
            $formats = $this->getOption('formats');
            $doctype = $element->getValue();
            $this->setFormat($doctype);
            if (isset($formats[$doctype])) {
                $element->setValue(null);
            }
        }

        $format = $this->getFormatInstance($format);
        $format->setFormatter($this);

        $formatEvent = new FormatEvent($element, $format);
        $this->trigger($formatEvent);

        $element = $formatEvent->getElement();
        $format = $formatEvent->getFormat();

        $stringifyEvent = new StringifyEvent($formatEvent, $element ? $format($element) : '');
        $this->trigger($stringifyEvent);

        return $stringifyEvent->getOutput();
    }