Private/Get-MarkdownImage.ps1
|
function Get-MarkdownImage { <# .SYNOPSIS Finds the images in Markdown and returns where each one points to. .DESCRIPTION Returns the destination of every image in the text, with its position, so that the destination can be replaced. Three forms are found: the Markdown image, , the HTML image, <img src="destination">, and the image that takes its destination from a reference definition: ![alt][name], ![name][] or ![name], with a line [name]: destination elsewhere in the text. For the last form, the destination that is returned is the one in the definition, once, however many images use it. A name is compared without regard to case, and the first definition of a name counts. A definition that no image uses, such as that of a link, is left out. An image inside code, a fenced block or a code span, is text about an image and is left out, and so is a definition there. Markdown does not read a block of HTML: lines that start with a tag such as <p>, <div> or <figure>, up to the first empty line, a <pre>, <script>, <style> or <textarea> element up to the line that closes it, and a comment. In such a block only the HTML image is found. A backtick there is no code, and the Markdown image and the definition are text. Export-GhostPost writes a post that was made in the editor as one such block. The text is expected to have line feeds as line endings, as Read-GhostPostFile returns it. .EXAMPLE Get-MarkdownImage -Markdown '' Returns one object with the destination images/diagram.png, its index 13 and its length 18. .EXAMPLE Get-MarkdownImage -Markdown "![A diagram][diagram]`n`n[diagram]: images/diagram.png" Returns one object with the destination images/diagram.png, at its place in the definition. #> [CmdletBinding()] [OutputType([pscustomobject])] param( # The Markdown to search. [Parameter(Mandatory)] [AllowEmptyString()] [string] $Markdown ) # A block of HTML and code come first, so that each is taken as a whole. The blocks are the ones Markdown # knows: an element that keeps its text as it is, a comment, and the lines from a block tag to an empty # line. An image with its destination has the group path. An image that names a definition has the group # alt, and a definition has the groups name and target. $pattern = @' (?<html> ^[ ]{0,3}<(?:pre|script|style|textarea)(?=[\s>]|\z)(?s:.*?)(?:</(?:pre|script|style|textarea)>[^\n]*|\z) | ^[ ]{0,3}<!--(?s:.*?)(?:-->[^\n]*|\z) | ^[ ]{0,3}</?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details |dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html |iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section |summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?=[\s>]|/>|\z) (?s:.*?)(?=\n[ \t]*(?:\n|\z)|\z) ) | (?<code> ^[ ]{0,3}(?<fence>`{3,}|~{3,})[^\n]*\n(?s:.*?)(?:^[ ]{0,3}\k<fence>[`~]*[ \t]*$|\z) | (?<!`)(?<ticks>`+)(?!`)(?s:.+?)(?<!`)\k<ticks>(?!`) ) | !\[(?:[^\[\]\\]|\\.|\[[^\[\]]*\])*\] \([ \t]*\n?[ \t]* (?:<(?<path>[^<>\n]*)>|(?<path>(?:[^\s()<>]|\([^\s()<>]*\))+)) (?:\s+(?:"[^"]*"|'[^']*'|\([^()]*\)))? \s*\) | !\[(?<alt>(?:[^\[\]\\]|\\.|\[[^\[\]]*\])*)\](?:\[(?<label>[^\[\]]*)\])? | ^[ ]{0,3}\[(?<name>(?:[^\[\]\\\n]|\\.)+)\]:[ \t]*(?:<(?<target>[^<>\n]*)>|(?<target>[^\s<>]+)) | <img\b[^>]*?(?<![\w-])src\s*=\s*(?:"(?<path>[^"]*)"|'(?<path>[^']*)') '@ $options = [System.Text.RegularExpressions.RegexOptions] 'IgnorePatternWhitespace, Multiline, IgnoreCase' # The HTML image by itself, for a block of HTML. $tag = '<img\b[^>]*?(?<![\w-])src\s*=\s*(?:"(?<path>[^"]*)"|''(?<path>[^'']*)'')' $tagOptions = [System.Text.RegularExpressions.RegexOptions]::IgnoreCase # The names that images use and the definitions, by the name as Markdown compares it. $used = @{} $definitions = @{} $images = @( foreach ($match in [regex]::Matches($Markdown, $pattern, $options)) { $path = $match.Groups['path'] if ($match.Groups['html'].Success) { foreach ($inner in [regex]::Matches($match.Value, $tag, $tagOptions)) { [pscustomobject]@{ Destination = $inner.Groups['path'].Value Index = $match.Index + $inner.Groups['path'].Index Length = $inner.Groups['path'].Length } } } elseif ($path.Success) { [pscustomobject]@{ Destination = $path.Value Index = $path.Index Length = $path.Length } } elseif ($match.Groups['name'].Success) { $name = ($match.Groups['name'].Value -replace '\s+', ' ').Trim().ToLowerInvariant() if ($name -and -not $definitions.ContainsKey($name)) { $definitions[$name] = $match.Groups['target'] } } elseif ($match.Groups['alt'].Success) { # ![alt][name] names the definition; ![name][] and ![name] use the description as the name. $name = $match.Groups['label'].Value if ([string]::IsNullOrWhiteSpace($name)) { $name = $match.Groups['alt'].Value } $name = ($name -replace '\s+', ' ').Trim().ToLowerInvariant() if ($name) { $used[$name] = $true } } } foreach ($name in $definitions.Keys) { if ($used.ContainsKey($name)) { [pscustomobject]@{ Destination = $definitions[$name].Value Index = $definitions[$name].Index Length = $definitions[$name].Length } } } ) $images | Sort-Object -Property Index } |