Private/ConvertTo-MarkdownHtmlBlock.ps1

function ConvertTo-MarkdownHtmlBlock {
    <#
    .SYNOPSIS
        Rewrites HTML so that a Markdown card of Ghost shows it as it is.

    .DESCRIPTION
        Markdown may contain HTML, but it only leaves HTML alone while it reads it as an HTML block. Such a
        block starts at a line that begins with a tag such as <p> or <div>, and it ends at the first empty line.
        What follows an empty line is read as Markdown again. In the HTML that Ghost renders for a post, that is
        often the rest of a code block. Its comments become headings, its lists become lists, and the code is
        lost.

        This function returns the same HTML without an empty line in it, so that all of it is one block:

        - Between elements an empty line means nothing. It is removed.
        - Inside <pre> and <textarea> an empty line is text. The line break before it is written as the
          character reference &#10;, which a browser reads as that line break. The text stays the same.
        - Inside <script> and <style> a character reference is not read. An empty line is removed there. That
          only changes a script that holds a text of several lines with an empty line in it.

        The block also has to start. HTML that begins with a code block, a comment, a script or plain text is
        not read as one block to the end. A line break is put after such a beginning, and before the first tag
        that starts a block, so that Markdown reads everything from there as HTML. A line break between
        elements changes nothing in what a browser shows.

    .EXAMPLE
        ConvertTo-MarkdownHtmlBlock -Html "<p>Run it:</p><pre><code>first`n`nsecond</code></pre>"

        Returns the HTML with first&#10; on one line and second on the next, without the empty line.

    .EXAMPLE
        ConvertTo-MarkdownHtmlBlock -Html '<pre><code>code</code></pre><p>Text</p>'

        Returns the code block on a line of its own, followed by a line with the paragraph.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        # The HTML, as Ghost renders it for a post or a page.
        [Parameter(Mandatory)]
        [AllowEmptyString()]
        [string] $Html
    )

    $text = ($Html -replace '\r\n?', "`n").Trim()
    if (-not $text) {
        return ''
    }

    # The elements whose content is not ordinary HTML, each from its opening tag to its closing tag.
    $verbatim = '(?is)<(?<tag>pre|textarea|script|style)(?=[\s>])[^>]*>.*?</\k<tag>\s*>'
    # A line with nothing on it, or with spaces and tabs only, together with the line break before it.
    $emptyLine = '\n[ \t]*(?=\n)'

    $builder = [System.Text.StringBuilder]::new()
    $position = 0
    foreach ($match in [regex]::Matches($text, $verbatim)) {
        $between = $text.Substring($position, $match.Index - $position)
        [void] $builder.Append(($between -replace $emptyLine, ''))

        if (@('pre', 'textarea') -contains $match.Groups['tag'].Value.ToLowerInvariant()) {
            # The line break that is followed by an empty line becomes a character reference.
            [void] $builder.Append(($match.Value -replace '\n(?=[ \t]*\n)', '&#10;'))
        }
        else {
            [void] $builder.Append(($match.Value -replace $emptyLine, ''))
        }
        $position = $match.Index + $match.Length
    }
    [void] $builder.Append(($text.Substring($position) -replace $emptyLine, ''))
    $text = $builder.ToString()

    # The tags that start an HTML block which runs to the next empty line. Markdown knows more of them. These
    # are the ones that the content of a post begins with.
    $names = 'address|article|aside|blockquote|details|div|dl|fieldset|figure|footer|form|h[1-6]|header|hr'
    $names = "$names|iframe|main|nav|ol|p|section|table|ul"
    $block = "</?(?:$names)(?=[\s>]|/>|\z)"
    # The tags and the comment that start a block which ends at their own closing tag.
    $closed = '<(?<name>pre|script|style|textarea)(?=[\s>]|\z)'

    $result = [System.Text.StringBuilder]::new()
    $rest = $text
    while ($rest) {
        if ($rest -match "(?i)\A$block") {
            # Everything from here is one block.
            break
        }

        $end = -1
        if ($rest.StartsWith('<!--', [System.StringComparison]::Ordinal)) {
            $close = $rest.IndexOf('-->', 4, [System.StringComparison]::Ordinal)
            if ($close -ge 0) {
                $end = $close + 3
            }
        }
        elseif ($rest -match "(?i)\A$closed") {
            $closing = [regex]::Match($rest, ('(?i)</{0}\s*>' -f $Matches['name']))
            if ($closing.Success) {
                $end = $closing.Index + $closing.Length
            }
        }
        else {
            # Text or an element inside a line. Markdown reads it as a paragraph, up to a line that starts a
            # block.
            $next = [regex]::Match($rest, "(?i)(?:$block|$closed|<!--)")
            if ($next.Success -and $next.Index -gt 0) {
                $end = $next.Index
            }
        }
        if ($end -lt 0) {
            break
        }

        [void] $result.Append($rest.Substring(0, $end).TrimEnd()).Append("`n")
        $rest = $rest.Substring($end).TrimStart()
    }
    [void] $result.Append($rest)

    $result.ToString().TrimEnd()
}