and blocks to Markdown - that should stay as HTML
// except if the current node is a code tag, which needs to be converted by the CodeConverter.
if ($element->isDescendantOf(['pre', 'code']) && $element->getTagName() !== 'code') {
- return;
+ return '';
}
// Give converter a chance to inspect/modify the DOM before children are converted
@@ -190,18 +199,31 @@ class HtmlConverter implements HtmlConverterInterface
// If the node has children, convert those to Markdown first
if ($element->hasChildren()) {
+ $childFollowsInlineContent = false;
foreach ($element->getChildren() as $child) {
- $this->convertChildren($child);
+ $childMarkdown = $this->convertChildren($child, $childFollowsInlineContent);
+ if ($child->getTagName() === '#comment' || \trim($childMarkdown, ' ') === '') {
+ continue;
+ }
+
+ $childFollowsInlineContent = ! $child->isBlock() && \substr(\rtrim($childMarkdown, ' '), -1) !== "\n";
}
}
// Now that child nodes have been converted, convert the original node
$markdown = $this->convertToMarkdown($element);
+ // These blocks only add newlines after themselves, so one that follows inline content, like an image, needs them before it too
+ if ($followsInlineContent && \in_array($element->getTagName(), self::SEPARATED_BLOCK_TAGS, true) && \trim($markdown) !== '') {
+ $markdown = "\n\n" . $markdown;
+ }
+
// Create a DOM text node containing the Markdown equivalent of the original node
// Replace the old $node e.g. 'Title
' with the new $markdown_node e.g. '### Title'
$element->setFinalMarkdown($markdown);
+
+ return $markdown;
}
/**
diff --git a/tests/HtmlConverterTest.php b/tests/HtmlConverterTest.php
index e62247e..816a491 100644
--- a/tests/HtmlConverterTest.php
+++ b/tests/HtmlConverterTest.php
@@ -134,6 +134,10 @@ class HtmlConverterTest extends TestCase
public function testImage(): void
{
$this->assertHtmlGivesMarkdown('
', '');
+ $this->assertHtmlGivesMarkdown("
\nA new header
", "\n\n### A new header");
+ $this->assertHtmlGivesMarkdown('
Paragraph
', "\n\nParagraph");
+ $this->assertHtmlGivesMarkdown('
A new header
', "[](b.html)\n\n### A new header");
+ $this->assertHtmlGivesMarkdown('
Paragraph
', "> \n> \n> Paragraph");
}
public function testAnchor(): void