Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Parsedown extension to wrap single-image lines in <figure>, not <p>. Public domain. See https://github.com/erusev/parsedown/issues/180#issuecomment-451486639
<?php
class FigureExtParsedown extends Parsedown {
// Matches Markdown image definition
private $MarkdownImageRegex = "~^!\[.*?\]\(.*?\)$~";
public function __construct () {
// Add blockFigure to non-exclusive handlers for text starting with !
$this->BlockTypes['!'][] = 'Figure';
}
protected function blockFigure($Line) {
// If line does not match image def, don't handle it
if (1 !== preg_match($this->MarkdownImageRegex, $Line['text'])) {
return;
}
$InlineImage = $this->inlineImage($Line);
if (!isset($InlineImage)) {
return;
}
$FigureBlock = array(
'element' => array(
'name' => 'figure',
'handler' => 'elements',
'text' => array(
$InlineImage['element']
)
),
);
// Add figcaption if title set
if (!empty($InlineImage['element']['attributes']['title'])) {
$InlineFigcaption = array(
'element' => array(
'name' => 'figcaption',
'text' => $InlineImage['element']['attributes']['title']
),
);
$FigureBlock['element']['text'][] = $InlineFigcaption['element'];
}
return $FigureBlock;
}
}
@anasram

This comment has been minimized.

Copy link

anasram commented Aug 4, 2019

Thank you Krzysztof! I've been looking for such a solution for a while.

  1. However, I'm wondering now how can I add it to pasrsedown. Actually, I want to add it to @picocms, can help me in this please? If there's a generic way to add it to pasrsedown regardless of a specific CMS, it could be nice to add a brief documentation for this.
  2. Also, what do you think of adding height and width HTML properties and values automatically to <img> elements?
  3. What about the license? MIT?
@kantoniak

This comment has been minimized.

Copy link
Owner Author

kantoniak commented Aug 4, 2019

Thanks for reaching out Anas! Afaik Parsedown does not support plugins or modules, so the only way is to subclass Parsedown. I don't have time to work on this, but you may want to search for other extensions - I think I saw somewhere an extension which added attribute support for tags.
The code is public domain, I added a note in the description.

@anasram

This comment has been minimized.

Copy link

anasram commented Aug 31, 2019

Hi Krzysztof!

Please notice that figcaption should come from title attribute, not alt.

@kantoniak

This comment has been minimized.

Copy link
Owner Author

kantoniak commented Aug 31, 2019

That's correct, thank you for pointing that out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.