Merge pull request #4244 from MrPetovan/develop

Composer: php-markdown updated to 1.8.0
This commit is contained in:
Michael Vogel 2018-01-15 14:58:38 +01:00 committed by GitHub
commit cc3b6a265c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 409 additions and 368 deletions

19
composer.lock generated
View file

@ -161,30 +161,25 @@
}, },
{ {
"name": "michelf/php-markdown", "name": "michelf/php-markdown",
"version": "1.7.0", "version": "1.8.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/michelf/php-markdown.git", "url": "https://github.com/michelf/php-markdown.git",
"reference": "1f51cc520948f66cd2af8cbc45a5ee175e774220" "reference": "01ab082b355bf188d907b9929cd99b2923053495"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/michelf/php-markdown/zipball/1f51cc520948f66cd2af8cbc45a5ee175e774220", "url": "https://api.github.com/repos/michelf/php-markdown/zipball/01ab082b355bf188d907b9929cd99b2923053495",
"reference": "1f51cc520948f66cd2af8cbc45a5ee175e774220", "reference": "01ab082b355bf188d907b9929cd99b2923053495",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": ">=5.3.0" "php": ">=5.3.0"
}, },
"type": "library", "type": "library",
"extra": {
"branch-alias": {
"dev-lib": "1.4.x-dev"
}
},
"autoload": { "autoload": {
"psr-0": { "psr-4": {
"Michelf": "" "Michelf\\": "Michelf/"
} }
}, },
"notification-url": "https://packagist.org/downloads/", "notification-url": "https://packagist.org/downloads/",
@ -208,7 +203,7 @@
"keywords": [ "keywords": [
"markdown" "markdown"
], ],
"time": "2016-10-29T18:58:20+00:00" "time": "2018-01-15T00:49:33+00:00"
}, },
{ {
"name": "mobiledetect/mobiledetectlib", "name": "mobiledetect/mobiledetectlib",

View file

@ -17,6 +17,7 @@ return array(
'Friendica\\Content\\ForumManager' => $baseDir . '/src/Content/ForumManager.php', 'Friendica\\Content\\ForumManager' => $baseDir . '/src/Content/ForumManager.php',
'Friendica\\Content\\OEmbed' => $baseDir . '/src/Content/OEmbed.php', 'Friendica\\Content\\OEmbed' => $baseDir . '/src/Content/OEmbed.php',
'Friendica\\Content\\Smilies' => $baseDir . '/src/Content/Smilies.php', 'Friendica\\Content\\Smilies' => $baseDir . '/src/Content/Smilies.php',
'Friendica\\Content\\Text\\Markdown' => $baseDir . '/src/Content/Text/Markdown.php',
'Friendica\\Core\\Cache' => $baseDir . '/src/Core/Cache.php', 'Friendica\\Core\\Cache' => $baseDir . '/src/Core/Cache.php',
'Friendica\\Core\\Config' => $baseDir . '/src/Core/Config.php', 'Friendica\\Core\\Config' => $baseDir . '/src/Core/Config.php',
'Friendica\\Core\\NotificationsManager' => $baseDir . '/src/Core/NotificationsManager.php', 'Friendica\\Core\\NotificationsManager' => $baseDir . '/src/Core/NotificationsManager.php',

View file

@ -7,7 +7,6 @@ $baseDir = dirname($vendorDir);
return array( return array(
'Text' => array($vendorDir . '/pear/text_languagedetect'), 'Text' => array($vendorDir . '/pear/text_languagedetect'),
'Michelf' => array($vendorDir . '/michelf/php-markdown'),
'HTMLPurifier' => array($vendorDir . '/ezyang/htmlpurifier/library'), 'HTMLPurifier' => array($vendorDir . '/ezyang/htmlpurifier/library'),
'Detection' => array($vendorDir . '/mobiledetect/mobiledetectlib/namespaced'), 'Detection' => array($vendorDir . '/mobiledetect/mobiledetectlib/namespaced'),
); );

View file

@ -6,6 +6,7 @@ $vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir); $baseDir = dirname($vendorDir);
return array( return array(
'Michelf\\' => array($vendorDir . '/michelf/php-markdown/Michelf'),
'League\\HTMLToMarkdown\\' => array($vendorDir . '/league/html-to-markdown/src'), 'League\\HTMLToMarkdown\\' => array($vendorDir . '/league/html-to-markdown/src'),
'Friendica\\' => array($baseDir . '/src'), 'Friendica\\' => array($baseDir . '/src'),
); );

View file

@ -14,6 +14,10 @@ class ComposerStaticInitFriendica
); );
public static $prefixLengthsPsr4 = array ( public static $prefixLengthsPsr4 = array (
'M' =>
array (
'Michelf\\' => 8,
),
'L' => 'L' =>
array ( array (
'League\\HTMLToMarkdown\\' => 22, 'League\\HTMLToMarkdown\\' => 22,
@ -25,6 +29,10 @@ class ComposerStaticInitFriendica
); );
public static $prefixDirsPsr4 = array ( public static $prefixDirsPsr4 = array (
'Michelf\\' =>
array (
0 => __DIR__ . '/..' . '/michelf/php-markdown/Michelf',
),
'League\\HTMLToMarkdown\\' => 'League\\HTMLToMarkdown\\' =>
array ( array (
0 => __DIR__ . '/..' . '/league/html-to-markdown/src', 0 => __DIR__ . '/..' . '/league/html-to-markdown/src',
@ -43,13 +51,6 @@ class ComposerStaticInitFriendica
0 => __DIR__ . '/..' . '/pear/text_languagedetect', 0 => __DIR__ . '/..' . '/pear/text_languagedetect',
), ),
), ),
'M' =>
array (
'Michelf' =>
array (
0 => __DIR__ . '/..' . '/michelf/php-markdown',
),
),
'H' => 'H' =>
array ( array (
'HTMLPurifier' => 'HTMLPurifier' =>
@ -78,6 +79,7 @@ class ComposerStaticInitFriendica
'Friendica\\Content\\ForumManager' => __DIR__ . '/../..' . '/src/Content/ForumManager.php', 'Friendica\\Content\\ForumManager' => __DIR__ . '/../..' . '/src/Content/ForumManager.php',
'Friendica\\Content\\OEmbed' => __DIR__ . '/../..' . '/src/Content/OEmbed.php', 'Friendica\\Content\\OEmbed' => __DIR__ . '/../..' . '/src/Content/OEmbed.php',
'Friendica\\Content\\Smilies' => __DIR__ . '/../..' . '/src/Content/Smilies.php', 'Friendica\\Content\\Smilies' => __DIR__ . '/../..' . '/src/Content/Smilies.php',
'Friendica\\Content\\Text\\Markdown' => __DIR__ . '/../..' . '/src/Content/Text/Markdown.php',
'Friendica\\Core\\Cache' => __DIR__ . '/../..' . '/src/Core/Cache.php', 'Friendica\\Core\\Cache' => __DIR__ . '/../..' . '/src/Core/Cache.php',
'Friendica\\Core\\Config' => __DIR__ . '/../..' . '/src/Core/Config.php', 'Friendica\\Core\\Config' => __DIR__ . '/../..' . '/src/Core/Config.php',
'Friendica\\Core\\NotificationsManager' => __DIR__ . '/../..' . '/src/Core/NotificationsManager.php', 'Friendica\\Core\\NotificationsManager' => __DIR__ . '/../..' . '/src/Core/NotificationsManager.php',

View file

@ -160,33 +160,28 @@
}, },
{ {
"name": "michelf/php-markdown", "name": "michelf/php-markdown",
"version": "1.7.0", "version": "1.8.0",
"version_normalized": "1.7.0.0", "version_normalized": "1.8.0.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/michelf/php-markdown.git", "url": "https://github.com/michelf/php-markdown.git",
"reference": "1f51cc520948f66cd2af8cbc45a5ee175e774220" "reference": "01ab082b355bf188d907b9929cd99b2923053495"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/michelf/php-markdown/zipball/1f51cc520948f66cd2af8cbc45a5ee175e774220", "url": "https://api.github.com/repos/michelf/php-markdown/zipball/01ab082b355bf188d907b9929cd99b2923053495",
"reference": "1f51cc520948f66cd2af8cbc45a5ee175e774220", "reference": "01ab082b355bf188d907b9929cd99b2923053495",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": ">=5.3.0" "php": ">=5.3.0"
}, },
"time": "2016-10-29T18:58:20+00:00", "time": "2018-01-15T00:49:33+00:00",
"type": "library", "type": "library",
"extra": {
"branch-alias": {
"dev-lib": "1.4.x-dev"
}
},
"installation-source": "dist", "installation-source": "dist",
"autoload": { "autoload": {
"psr-0": { "psr-4": {
"Michelf": "" "Michelf\\": "Michelf/"
} }
}, },
"notification-url": "https://packagist.org/downloads/", "notification-url": "https://packagist.org/downloads/",

View file

@ -0,0 +1,3 @@
*~
/composer.lock
/vendor/

View file

@ -1,11 +1,11 @@
PHP Markdown Lib PHP Markdown Lib
Copyright (c) 2004-2016 Michel Fortin Copyright (c) 2004-2018 Michel Fortin
<https://michelf.ca/> <https://michelf.ca/>
All rights reserved. All rights reserved.
Based on Markdown Based on Markdown
Copyright (c) 2003-2006 John Gruber Copyright (c) 2003-2006 John Gruber
<https://daringfireball.net/> <https://daringfireball.net/>
All rights reserved. All rights reserved.
Redistribution and use in source and binary forms, with or without Redistribution and use in source and binary forms, with or without

View file

@ -4,7 +4,7 @@
* *
* @package php-markdown * @package php-markdown
* @author Michel Fortin <michel.fortin@michelf.com> * @author Michel Fortin <michel.fortin@michelf.com>
* @copyright 2004-2016 Michel Fortin <https://michelf.com/projects/php-markdown/> * @copyright 2004-2018 Michel Fortin <https://michelf.com/projects/php-markdown/>
* @copyright (Original Markdown) 2004-2006 John Gruber <https://daringfireball.net/projects/markdown/> * @copyright (Original Markdown) 2004-2006 John Gruber <https://daringfireball.net/projects/markdown/>
*/ */
@ -18,7 +18,7 @@ class Markdown implements MarkdownInterface {
* Define the package version * Define the package version
* @var string * @var string
*/ */
const MARKDOWNLIB_VERSION = "1.7.0"; const MARKDOWNLIB_VERSION = "1.8.0";
/** /**
* Simple function interface - Initialize the parser and return the result * Simple function interface - Initialize the parser and return the result
@ -61,14 +61,14 @@ class Markdown implements MarkdownInterface {
* @var int * @var int
*/ */
public $tab_width = 4; public $tab_width = 4;
/** /**
* Change to `true` to disallow markup or entities. * Change to `true` to disallow markup or entities.
* @var boolean * @var boolean
*/ */
public $no_markup = false; public $no_markup = false;
public $no_entities = false; public $no_entities = false;
/** /**
* Change to `true` to enable line breaks on \n without two trailling spaces * Change to `true` to enable line breaks on \n without two trailling spaces
@ -94,7 +94,7 @@ class Markdown implements MarkdownInterface {
* @var callable * @var callable
*/ */
public $header_id_func = null; public $header_id_func = null;
/** /**
* Optional function for converting code block content to HTML * Optional function for converting code block content to HTML
* @var callable * @var callable
@ -111,7 +111,7 @@ class Markdown implements MarkdownInterface {
* Class attribute to toggle "enhanced ordered list" behaviour * Class attribute to toggle "enhanced ordered list" behaviour
* setting this to true will allow ordered lists to start from the index * setting this to true will allow ordered lists to start from the index
* number that is defined first. * number that is defined first.
* *
* For example: * For example:
* 2. List item two * 2. List item two
* 3. List item three * 3. List item three
@ -155,17 +155,17 @@ class Markdown implements MarkdownInterface {
public function __construct() { public function __construct() {
$this->_initDetab(); $this->_initDetab();
$this->prepareItalicsAndBold(); $this->prepareItalicsAndBold();
$this->nested_brackets_re = $this->nested_brackets_re =
str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth). str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
str_repeat('\])*', $this->nested_brackets_depth); str_repeat('\])*', $this->nested_brackets_depth);
$this->nested_url_parenthesis_re = $this->nested_url_parenthesis_re =
str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth). str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth); str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
$this->escape_chars_re = '['.preg_quote($this->escape_chars).']'; $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
// Sort document, block, and span gamut in ascendent priority order. // Sort document, block, and span gamut in ascendent priority order.
asort($this->document_gamut); asort($this->document_gamut);
asort($this->block_gamut); asort($this->block_gamut);
@ -180,13 +180,19 @@ class Markdown implements MarkdownInterface {
protected $urls = array(); protected $urls = array();
protected $titles = array(); protected $titles = array();
protected $html_hashes = array(); protected $html_hashes = array();
/** /**
* Status flag to avoid invalid nesting. * Status flag to avoid invalid nesting.
* @var boolean * @var boolean
*/ */
protected $in_anchor = false; protected $in_anchor = false;
/**
* Status flag to avoid invalid nesting.
* @var boolean
*/
protected $in_emphasis_processing = false;
/** /**
* Called before the transformation process starts to setup parser states. * Called before the transformation process starts to setup parser states.
* @return void * @return void
@ -197,8 +203,9 @@ class Markdown implements MarkdownInterface {
$this->titles = $this->predef_titles; $this->titles = $this->predef_titles;
$this->html_hashes = array(); $this->html_hashes = array();
$this->in_anchor = false; $this->in_anchor = false;
$this->in_emphasis_processing = false;
} }
/** /**
* Called after the transformation process to clear any variable which may * Called after the transformation process to clear any variable which may
* be taking up memory unnecessarly. * be taking up memory unnecessarly.
@ -221,7 +228,7 @@ class Markdown implements MarkdownInterface {
*/ */
public function transform($text) { public function transform($text) {
$this->setup(); $this->setup();
# Remove UTF-8 BOM and marker character in input, if present. # Remove UTF-8 BOM and marker character in input, if present.
$text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text); $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
@ -248,7 +255,7 @@ class Markdown implements MarkdownInterface {
foreach ($this->document_gamut as $method => $priority) { foreach ($this->document_gamut as $method => $priority) {
$text = $this->$method($text); $text = $this->$method($text);
} }
$this->teardown(); $this->teardown();
return $text . "\n"; return $text . "\n";
@ -271,7 +278,7 @@ class Markdown implements MarkdownInterface {
* @return string * @return string
*/ */
protected function stripLinkDefinitions($text) { protected function stripLinkDefinitions($text) {
$less_than_tab = $this->tab_width - 1; $less_than_tab = $this->tab_width - 1;
// Link defs are in the form: ^[id]: url "optional title" // Link defs are in the form: ^[id]: url "optional title"
@ -338,8 +345,8 @@ class Markdown implements MarkdownInterface {
* for is hard-coded: * for is hard-coded:
* *
* * List "a" is made of tags which can be both inline or block-level. * * List "a" is made of tags which can be both inline or block-level.
* These will be treated block-level when the start tag is alone on * These will be treated block-level when the start tag is alone on
* its line, otherwise they're not matched here and will be taken as * its line, otherwise they're not matched here and will be taken as
* inline later. * inline later.
* * List "b" is made of tags which are always block-level; * * List "b" is made of tags which are always block-level;
*/ */
@ -363,7 +370,7 @@ class Markdown implements MarkdownInterface {
| |
\'[^\']*\' # text inside single quotes (tolerate ">") \'[^\']*\' # text inside single quotes (tolerate ">")
)* )*
)? )?
'; ';
$content = $content =
str_repeat(' str_repeat('
@ -380,7 +387,7 @@ class Markdown implements MarkdownInterface {
str_repeat(' str_repeat('
</\2\s*> # closing nested tag </\2\s*> # closing nested tag
) )
| |
<(?!/\2\s*> # other tags with a different name <(?!/\2\s*> # other tags with a different name
) )
)*', )*',
@ -409,9 +416,9 @@ class Markdown implements MarkdownInterface {
) )
( # save in $1 ( # save in $1
# Match from `\n<tag>` to `</tag>\n`, handling nested tags # Match from `\n<tag>` to `</tag>\n`, handling nested tags
# in between. # in between.
[ ]{0,'.$less_than_tab.'} [ ]{0,'.$less_than_tab.'}
<('.$block_tags_b_re.')# start tag = $2 <('.$block_tags_b_re.')# start tag = $2
'.$attr.'> # attributes followed by > and \n '.$attr.'> # attributes followed by > and \n
@ -429,28 +436,28 @@ class Markdown implements MarkdownInterface {
</\3> # the matching end tag </\3> # the matching end tag
[ ]* # trailing spaces/tabs [ ]* # trailing spaces/tabs
(?=\n+|\Z) # followed by a newline or end of document (?=\n+|\Z) # followed by a newline or end of document
| # Special case just for <hr />. It was easier to make a special | # Special case just for <hr />. It was easier to make a special
# case than to make the other regex more complicated. # case than to make the other regex more complicated.
[ ]{0,'.$less_than_tab.'} [ ]{0,'.$less_than_tab.'}
<(hr) # start tag = $2 <(hr) # start tag = $2
'.$attr.' # attributes '.$attr.' # attributes
/?> # the matching end tag /?> # the matching end tag
[ ]* [ ]*
(?=\n{2,}|\Z) # followed by a blank line or end of document (?=\n{2,}|\Z) # followed by a blank line or end of document
| # Special case for standalone HTML comments: | # Special case for standalone HTML comments:
[ ]{0,'.$less_than_tab.'} [ ]{0,'.$less_than_tab.'}
(?s: (?s:
<!-- .*? --> <!-- .*? -->
) )
[ ]* [ ]*
(?=\n{2,}|\Z) # followed by a blank line or end of document (?=\n{2,}|\Z) # followed by a blank line or end of document
| # PHP and ASP-style processor instructions (<? and <%) | # PHP and ASP-style processor instructions (<? and <%)
[ ]{0,'.$less_than_tab.'} [ ]{0,'.$less_than_tab.'}
(?s: (?s:
<([?%]) # $2 <([?%]) # $2
@ -459,7 +466,7 @@ class Markdown implements MarkdownInterface {
) )
[ ]* [ ]*
(?=\n{2,}|\Z) # followed by a blank line or end of document (?=\n{2,}|\Z) # followed by a blank line or end of document
) )
)}Sxmi', )}Sxmi',
array($this, '_hashHTMLBlocks_callback'), array($this, '_hashHTMLBlocks_callback'),
@ -479,9 +486,9 @@ class Markdown implements MarkdownInterface {
$key = $this->hashBlock($text); $key = $this->hashBlock($text);
return "\n\n$key\n\n"; return "\n\n$key\n\n";
} }
/** /**
* Called whenever a tag must be hashed when a function insert an atomic * Called whenever a tag must be hashed when a function insert an atomic
* element in the text stream. Passing $text to through this function gives * element in the text stream. Passing $text to through this function gives
* a unique text-token which will be reverted back when calling unhash. * a unique text-token which will be reverted back when calling unhash.
* *
@ -498,7 +505,7 @@ class Markdown implements MarkdownInterface {
// Swap back any tag hash found in $text so we do not have to `unhash` // Swap back any tag hash found in $text so we do not have to `unhash`
// multiple times at the end. // multiple times at the end.
$text = $this->unhash($text); $text = $this->unhash($text);
// Then hash the block. // Then hash the block.
static $i = 0; static $i = 0;
$key = "$boundary\x1A" . ++$i . $boundary; $key = "$boundary\x1A" . ++$i . $boundary;
@ -531,10 +538,10 @@ class Markdown implements MarkdownInterface {
/** /**
* Run block gamut tranformations. * Run block gamut tranformations.
* *
* We need to escape raw HTML in Markdown source before doing anything * We need to escape raw HTML in Markdown source before doing anything
* else. This need to be done for each block, and not only at the * else. This need to be done for each block, and not only at the
* begining in the Markdown function since hashed blocks can be part of * begining in the Markdown function since hashed blocks can be part of
* list items and could have been indented. Indented blocks would have * list items and could have been indented. Indented blocks would have
* been seen as a code block in a previous pass of hashHTMLBlocks. * been seen as a code block in a previous pass of hashHTMLBlocks.
* *
* @param string $text * @param string $text
@ -546,7 +553,7 @@ class Markdown implements MarkdownInterface {
} }
/** /**
* Run block gamut tranformations, without hashing HTML blocks. This is * Run block gamut tranformations, without hashing HTML blocks. This is
* useful when HTML blocks are known to be already hashed, like in the first * useful when HTML blocks are known to be already hashed, like in the first
* whole-document pass. * whole-document pass.
* *
@ -554,11 +561,11 @@ class Markdown implements MarkdownInterface {
* @return string * @return string
*/ */
protected function runBasicBlockGamut($text) { protected function runBasicBlockGamut($text) {
foreach ($this->block_gamut as $method => $priority) { foreach ($this->block_gamut as $method => $priority) {
$text = $this->$method($text); $text = $this->$method($text);
} }
// Finally form paragraph and restore hashed blocks. // Finally form paragraph and restore hashed blocks.
$text = $this->formParagraphs($text); $text = $this->formParagraphs($text);
@ -582,7 +589,7 @@ class Markdown implements MarkdownInterface {
[ ]* # Tailing spaces [ ]* # Tailing spaces
$ # End of line. $ # End of line.
}mx', }mx',
"\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n", "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
$text $text
); );
} }
@ -629,10 +636,10 @@ class Markdown implements MarkdownInterface {
*/ */
protected function doHardBreaks($text) { protected function doHardBreaks($text) {
if ($this->hard_wrap) { if ($this->hard_wrap) {
return preg_replace_callback('/ *\n/', return preg_replace_callback('/ *\n/',
array($this, '_doHardBreaks_callback'), $text); array($this, '_doHardBreaks_callback'), $text);
} else { } else {
return preg_replace_callback('/ {2,}\n/', return preg_replace_callback('/ {2,}\n/',
array($this, '_doHardBreaks_callback'), $text); array($this, '_doHardBreaks_callback'), $text);
} }
} }
@ -656,7 +663,7 @@ class Markdown implements MarkdownInterface {
return $text; return $text;
} }
$this->in_anchor = true; $this->in_anchor = true;
// First, handle reference-style links: [link text] [id] // First, handle reference-style links: [link text] [id]
$text = preg_replace_callback('{ $text = preg_replace_callback('{
( # wrap whole match in $1 ( # wrap whole match in $1
@ -729,7 +736,7 @@ class Markdown implements MarkdownInterface {
// for shortcut links like [this][] or [this]. // for shortcut links like [this][] or [this].
$link_id = $link_text; $link_id = $link_text;
} }
// lower-case and turn embedded newlines into spaces // lower-case and turn embedded newlines into spaces
$link_id = strtolower($link_id); $link_id = strtolower($link_id);
$link_id = preg_replace('{[ ]?\n}', ' ', $link_id); $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
@ -737,14 +744,14 @@ class Markdown implements MarkdownInterface {
if (isset($this->urls[$link_id])) { if (isset($this->urls[$link_id])) {
$url = $this->urls[$link_id]; $url = $this->urls[$link_id];
$url = $this->encodeURLAttribute($url); $url = $this->encodeURLAttribute($url);
$result = "<a href=\"$url\""; $result = "<a href=\"$url\"";
if ( isset( $this->titles[$link_id] ) ) { if ( isset( $this->titles[$link_id] ) ) {
$title = $this->titles[$link_id]; $title = $this->titles[$link_id];
$title = $this->encodeAttribute($title); $title = $this->encodeAttribute($title);
$result .= " title=\"$title\""; $result .= " title=\"$title\"";
} }
$link_text = $this->runSpanGamut($link_text); $link_text = $this->runSpanGamut($link_text);
$result .= ">$link_text</a>"; $result .= ">$link_text</a>";
$result = $this->hashPart($result); $result = $this->hashPart($result);
@ -779,7 +786,7 @@ class Markdown implements MarkdownInterface {
$title = $this->encodeAttribute($title); $title = $this->encodeAttribute($title);
$result .= " title=\"$title\""; $result .= " title=\"$title\"";
} }
$link_text = $this->runSpanGamut($link_text); $link_text = $this->runSpanGamut($link_text);
$result .= ">$link_text</a>"; $result .= ">$link_text</a>";
@ -807,7 +814,7 @@ class Markdown implements MarkdownInterface {
\] \]
) )
}xs', }xs',
array($this, '_doImages_reference_callback'), $text); array($this, '_doImages_reference_callback'), $text);
// Next, handle inline images: ![alt text](url "optional title") // Next, handle inline images: ![alt text](url "optional title")
@ -906,7 +913,7 @@ class Markdown implements MarkdownInterface {
* Setext-style headers: * Setext-style headers:
* Header 1 * Header 1
* ======== * ========
* *
* Header 2 * Header 2
* -------- * --------
*/ */
@ -944,7 +951,7 @@ class Markdown implements MarkdownInterface {
if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1])) { if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1])) {
return $matches[0]; return $matches[0];
} }
$level = $matches[2]{0} == '=' ? 1 : 2; $level = $matches[2]{0} == '=' ? 1 : 2;
// ID attribute generation // ID attribute generation
@ -977,7 +984,7 @@ class Markdown implements MarkdownInterface {
* @param string $headerValue * @param string $headerValue
* @return string * @return string
*/ */
protected function _generateIdFromHeaderValue($headerValue) { protected function _generateIdFromHeaderValue($headerValue) {
if (!is_callable($this->header_id_func)) { if (!is_callable($this->header_id_func)) {
return ""; return "";
} }
@ -1035,10 +1042,10 @@ class Markdown implements MarkdownInterface {
) )
) )
'; // mx '; // mx
// We use a different prefix before nested lists than top-level lists. // We use a different prefix before nested lists than top-level lists.
//See extended comment in _ProcessListItems(). //See extended comment in _ProcessListItems().
if ($this->list_level) { if ($this->list_level) {
$text = preg_replace_callback('{ $text = preg_replace_callback('{
^ ^
@ -1132,7 +1139,7 @@ class Markdown implements MarkdownInterface {
* without resorting to mind-reading. Perhaps the solution is to * without resorting to mind-reading. Perhaps the solution is to
* change the syntax rules such that sub-lists must start with a * change the syntax rules such that sub-lists must start with a
* starting cardinal number; e.g. "1." or "a.". * starting cardinal number; e.g. "1." or "a.".
*/ */
$this->list_level++; $this->list_level++;
// Trim trailing blank lines: // Trim trailing blank lines:
@ -1166,7 +1173,7 @@ class Markdown implements MarkdownInterface {
$marker_space = $matches[3]; $marker_space = $matches[3];
$tailing_blank_line =& $matches[5]; $tailing_blank_line =& $matches[5];
if ($leading_line || $tailing_blank_line || if ($leading_line || $tailing_blank_line ||
preg_match('/\n{2,}/', $item)) preg_match('/\n{2,}/', $item))
{ {
// Replace marker with the appropriate whitespace indentation // Replace marker with the appropriate whitespace indentation
@ -1273,7 +1280,7 @@ class Markdown implements MarkdownInterface {
* @var array * @var array
*/ */
protected $em_strong_prepared_relist; protected $em_strong_prepared_relist;
/** /**
* Prepare regular expressions for searching emphasis tokens in any * Prepare regular expressions for searching emphasis tokens in any
* context. * context.
@ -1289,7 +1296,7 @@ class Markdown implements MarkdownInterface {
} }
$token_relist[] = $em_re; $token_relist[] = $em_re;
$token_relist[] = $strong_re; $token_relist[] = $strong_re;
// Construct master expression from list. // Construct master expression from list.
$token_re = '{(' . implode('|', $token_relist) . ')}'; $token_re = '{(' . implode('|', $token_relist) . ')}';
$this->em_strong_prepared_relist["$em$strong"] = $token_re; $this->em_strong_prepared_relist["$em$strong"] = $token_re;
@ -1303,24 +1310,29 @@ class Markdown implements MarkdownInterface {
* @return string * @return string
*/ */
protected function doItalicsAndBold($text) { protected function doItalicsAndBold($text) {
if ($this->in_emphasis_processing) {
return $text; // avoid reentrency
}
$this->in_emphasis_processing = true;
$token_stack = array(''); $token_stack = array('');
$text_stack = array(''); $text_stack = array('');
$em = ''; $em = '';
$strong = ''; $strong = '';
$tree_char_em = false; $tree_char_em = false;
while (1) { while (1) {
// Get prepared regular expression for seraching emphasis tokens // Get prepared regular expression for seraching emphasis tokens
// in current context. // in current context.
$token_re = $this->em_strong_prepared_relist["$em$strong"]; $token_re = $this->em_strong_prepared_relist["$em$strong"];
// Each loop iteration search for the next emphasis token. // Each loop iteration search for the next emphasis token.
// Each token is then passed to handleSpanToken. // Each token is then passed to handleSpanToken.
$parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
$text_stack[0] .= $parts[0]; $text_stack[0] .= $parts[0];
$token =& $parts[1]; $token =& $parts[1];
$text =& $parts[2]; $text =& $parts[2];
if (empty($token)) { if (empty($token)) {
// Reached end of text span: empty stack without emitting. // Reached end of text span: empty stack without emitting.
// any more emphasis. // any more emphasis.
@ -1330,7 +1342,7 @@ class Markdown implements MarkdownInterface {
} }
break; break;
} }
$token_len = strlen($token); $token_len = strlen($token);
if ($tree_char_em) { if ($tree_char_em) {
// Reached closing marker while inside a three-char emphasis. // Reached closing marker while inside a three-char emphasis.
@ -1369,7 +1381,7 @@ class Markdown implements MarkdownInterface {
$$tag = ''; // $$tag stands for $em or $strong $$tag = ''; // $$tag stands for $em or $strong
} }
} else { } else {
// Reached opening three-char emphasis marker. Push on token // Reached opening three-char emphasis marker. Push on token
// stack; will be handled by the special condition above. // stack; will be handled by the special condition above.
$em = $token{0}; $em = $token{0};
$strong = "$em$em"; $strong = "$em$em";
@ -1383,6 +1395,7 @@ class Markdown implements MarkdownInterface {
if (strlen($token_stack[0]) == 1) { if (strlen($token_stack[0]) == 1) {
$text_stack[1] .= array_shift($token_stack); $text_stack[1] .= array_shift($token_stack);
$text_stack[0] .= array_shift($text_stack); $text_stack[0] .= array_shift($text_stack);
$em = '';
} }
// Closing strong marker: // Closing strong marker:
array_shift($token_stack); array_shift($token_stack);
@ -1417,6 +1430,7 @@ class Markdown implements MarkdownInterface {
} }
} }
} }
$this->in_emphasis_processing = false;
return $text_stack[0]; return $text_stack[0];
} }
@ -1453,9 +1467,9 @@ class Markdown implements MarkdownInterface {
$bq = $this->runBlockGamut($bq); // recurse $bq = $this->runBlockGamut($bq); // recurse
$bq = preg_replace('/^/m', " ", $bq); $bq = preg_replace('/^/m', " ", $bq);
// These leading spaces cause problem with <pre> content, // These leading spaces cause problem with <pre> content,
// so we need to fix that: // so we need to fix that:
$bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx', $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
array($this, '_doBlockQuotes_callback2'), $bq); array($this, '_doBlockQuotes_callback2'), $bq);
return "\n" . $this->hashBlock("<blockquote>\n$bq\n</blockquote>") . "\n\n"; return "\n" . $this->hashBlock("<blockquote>\n$bq\n</blockquote>") . "\n\n";
@ -1525,7 +1539,7 @@ class Markdown implements MarkdownInterface {
// // We can't call Markdown(), because that resets the hash; // // We can't call Markdown(), because that resets the hash;
// // that initialization code should be pulled into its own sub, though. // // that initialization code should be pulled into its own sub, though.
// $div_content = $this->hashHTMLBlocks($div_content); // $div_content = $this->hashHTMLBlocks($div_content);
// //
// // Run document gamut methods on the content. // // Run document gamut methods on the content.
// foreach ($this->document_gamut as $method => $priority) { // foreach ($this->document_gamut as $method => $priority) {
// $div_content = $this->$method($div_content); // $div_content = $this->$method($div_content);
@ -1582,9 +1596,9 @@ class Markdown implements MarkdownInterface {
return $url; return $url;
} }
/** /**
* Smart processing for ampersands and angle brackets that need to * Smart processing for ampersands and angle brackets that need to
* be encoded. Valid character entities are left alone unless the * be encoded. Valid character entities are left alone unless the
* no-entities mode is set. * no-entities mode is set.
* @param string $text * @param string $text
@ -1596,7 +1610,7 @@ class Markdown implements MarkdownInterface {
} else { } else {
// Ampersand-encoding based entirely on Nat Irons's Amputator // Ampersand-encoding based entirely on Nat Irons's Amputator
// MT plugin: <http://bumppo.net/projects/amputator/> // MT plugin: <http://bumppo.net/projects/amputator/>
$text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/', $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
'&amp;', $text); '&amp;', $text);
} }
// Encode remaining <'s // Encode remaining <'s
@ -1724,7 +1738,7 @@ class Markdown implements MarkdownInterface {
*/ */
protected function parseSpan($str) { protected function parseSpan($str) {
$output = ''; $output = '';
$span_re = '{ $span_re = '{
( (
\\\\'.$this->escape_chars_re.' \\\\'.$this->escape_chars_re.'
@ -1752,16 +1766,16 @@ class Markdown implements MarkdownInterface {
}xs'; }xs';
while (1) { while (1) {
// Each loop iteration seach for either the next tag, the next // Each loop iteration seach for either the next tag, the next
// openning code span marker, or the next escaped character. // openning code span marker, or the next escaped character.
// Each token is then passed to handleSpanToken. // Each token is then passed to handleSpanToken.
$parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE); $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
// Create token from text preceding tag. // Create token from text preceding tag.
if ($parts[0] != "") { if ($parts[0] != "") {
$output .= $parts[0]; $output .= $parts[0];
} }
// Check if we reach the end. // Check if we reach the end.
if (isset($parts[1])) { if (isset($parts[1])) {
$output .= $this->handleSpanToken($parts[1], $parts[2]); $output .= $this->handleSpanToken($parts[1], $parts[2]);
@ -1770,7 +1784,7 @@ class Markdown implements MarkdownInterface {
break; break;
} }
} }
return $output; return $output;
} }
@ -1787,7 +1801,7 @@ class Markdown implements MarkdownInterface {
return $this->hashPart("&#". ord($token{1}). ";"); return $this->hashPart("&#". ord($token{1}). ";");
case "`": case "`":
// Search for end marker in remaining text. // Search for end marker in remaining text.
if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm', if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
$str, $matches)) $str, $matches))
{ {
$str = $matches[2]; $str = $matches[2];
@ -1823,11 +1837,11 @@ class Markdown implements MarkdownInterface {
* For each line we separate the line in blocks delemited by tab characters. * For each line we separate the line in blocks delemited by tab characters.
* Then we reconstruct every line by adding the appropriate number of space * Then we reconstruct every line by adding the appropriate number of space
* between each blocks. * between each blocks.
* *
* @param string $text * @param string $text
* @return string * @return string
*/ */
protected function detab($text) { protected function detab($text) {
$text = preg_replace_callback('/^.*\t.*$/m', $text = preg_replace_callback('/^.*\t.*$/m',
array($this, '_detab_callback'), $text); array($this, '_detab_callback'), $text);
@ -1842,7 +1856,7 @@ class Markdown implements MarkdownInterface {
protected function _detab_callback($matches) { protected function _detab_callback($matches) {
$line = $matches[0]; $line = $matches[0];
$strlen = $this->utf8_strlen; // strlen function for UTF-8. $strlen = $this->utf8_strlen; // strlen function for UTF-8.
// Split in blocks. // Split in blocks.
$blocks = explode("\t", $line); $blocks = explode("\t", $line);
// Add each blocks to the line. // Add each blocks to the line.
@ -1850,7 +1864,7 @@ class Markdown implements MarkdownInterface {
unset($blocks[0]); // Do not add first block twice. unset($blocks[0]); // Do not add first block twice.
foreach ($blocks as $block) { foreach ($blocks as $block) {
// Calculate amount of space, insert spaces, insert block. // Calculate amount of space, insert spaces, insert block.
$amount = $this->tab_width - $amount = $this->tab_width -
$strlen($line, 'UTF-8') % $this->tab_width; $strlen($line, 'UTF-8') % $this->tab_width;
$line .= str_repeat(" ", $amount) . $block; $line .= str_repeat(" ", $amount) . $block;
} }
@ -1859,20 +1873,20 @@ class Markdown implements MarkdownInterface {
/** /**
* Check for the availability of the function in the `utf8_strlen` property * Check for the availability of the function in the `utf8_strlen` property
* (initially `mb_strlen`). If the function is not available, create a * (initially `mb_strlen`). If the function is not available, create a
* function that will loosely count the number of UTF-8 characters with a * function that will loosely count the number of UTF-8 characters with a
* regular expression. * regular expression.
* @return void * @return void
*/ */
protected function _initDetab() { protected function _initDetab() {
if (function_exists($this->utf8_strlen)) { if (function_exists($this->utf8_strlen)) {
return; return;
} }
$this->utf8_strlen = create_function('$text', 'return preg_match_all( $this->utf8_strlen = function($text) {
"/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/", return preg_match_all('/[\x00-\xBF]|[\xC0-\xFF][\x80-\xBF]*/', $text, $m);
$text, $m);'); };
} }
/** /**
@ -1881,7 +1895,7 @@ class Markdown implements MarkdownInterface {
* @return string * @return string
*/ */
protected function unhash($text) { protected function unhash($text) {
return preg_replace_callback('/(.)\x1A[0-9]+\1/', return preg_replace_callback('/(.)\x1A[0-9]+\1/',
array($this, '_unhash_callback'), $text); array($this, '_unhash_callback'), $text);
} }

View file

@ -4,7 +4,7 @@
* *
* @package php-markdown * @package php-markdown
* @author Michel Fortin <michel.fortin@michelf.com> * @author Michel Fortin <michel.fortin@michelf.com>
* @copyright 2004-2016 Michel Fortin <https://michelf.com/projects/php-markdown/> * @copyright 2004-2018 Michel Fortin <https://michelf.com/projects/php-markdown/>
* @copyright (Original Markdown) 2004-2006 John Gruber <https://daringfireball.net/projects/markdown/> * @copyright (Original Markdown) 2004-2006 John Gruber <https://daringfireball.net/projects/markdown/>
*/ */
@ -23,14 +23,14 @@ class MarkdownExtra extends \Michelf\Markdown {
* @var string * @var string
*/ */
public $fn_id_prefix = ""; public $fn_id_prefix = "";
/** /**
* Optional title attribute for footnote links and backlinks. * Optional title attribute for footnote links and backlinks.
* @var string * @var string
*/ */
public $fn_link_title = ""; public $fn_link_title = "";
public $fn_backlink_title = ""; public $fn_backlink_title = "";
/** /**
* Optional class attribute for footnote links and backlinks. * Optional class attribute for footnote links and backlinks.
* @var string * @var string
@ -73,20 +73,26 @@ class MarkdownExtra extends \Michelf\Markdown {
*/ */
public $predef_abbr = array(); public $predef_abbr = array();
/**
* Only convert atx-style headers if there's a space between the header and #
* @var boolean
*/
public $hashtag_protection = false;
/** /**
* Parser implementation * Parser implementation
*/ */
/** /**
* Constructor function. Initialize the parser object. * Constructor function. Initialize the parser object.
* @return void * @return void
*/ */
public function __construct() { public function __construct() {
// Add extra escapable characters before parent constructor // Add extra escapable characters before parent constructor
// initialize the table. // initialize the table.
$this->escape_chars .= ':|'; $this->escape_chars .= ':|';
// Insert extra document, block, and span transformations. // Insert extra document, block, and span transformations.
// Parent constructor will do the sorting. // Parent constructor will do the sorting.
$this->document_gamut += array( $this->document_gamut += array(
"doFencedCodeBlocks" => 5, "doFencedCodeBlocks" => 5,
@ -103,12 +109,12 @@ class MarkdownExtra extends \Michelf\Markdown {
"doFootnotes" => 5, "doFootnotes" => 5,
"doAbbreviations" => 70, "doAbbreviations" => 70,
); );
$this->enhanced_ordered_list = true; $this->enhanced_ordered_list = true;
parent::__construct(); parent::__construct();
} }
/** /**
* Extra variables used during extra transformations. * Extra variables used during extra transformations.
* @var array * @var array
@ -118,21 +124,21 @@ class MarkdownExtra extends \Michelf\Markdown {
protected $footnotes_ref_count = array(); protected $footnotes_ref_count = array();
protected $footnotes_numbers = array(); protected $footnotes_numbers = array();
protected $abbr_desciptions = array(); protected $abbr_desciptions = array();
/** @var @string */ /** @var string */
protected $abbr_word_re = ''; protected $abbr_word_re = '';
/** /**
* Give the current footnote number. * Give the current footnote number.
* @var integer * @var integer
*/ */
protected $footnote_counter = 1; protected $footnote_counter = 1;
/** /**
* Setting up Extra-specific variables. * Setting up Extra-specific variables.
*/ */
protected function setup() { protected function setup() {
parent::setup(); parent::setup();
$this->footnotes = array(); $this->footnotes = array();
$this->footnotes_ordered = array(); $this->footnotes_ordered = array();
$this->footnotes_ref_count = array(); $this->footnotes_ref_count = array();
@ -140,7 +146,7 @@ class MarkdownExtra extends \Michelf\Markdown {
$this->abbr_desciptions = array(); $this->abbr_desciptions = array();
$this->abbr_word_re = ''; $this->abbr_word_re = '';
$this->footnote_counter = 1; $this->footnote_counter = 1;
foreach ($this->predef_abbr as $abbr_word => $abbr_desc) { foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
if ($this->abbr_word_re) if ($this->abbr_word_re)
$this->abbr_word_re .= '|'; $this->abbr_word_re .= '|';
@ -159,11 +165,11 @@ class MarkdownExtra extends \Michelf\Markdown {
$this->footnotes_numbers = array(); $this->footnotes_numbers = array();
$this->abbr_desciptions = array(); $this->abbr_desciptions = array();
$this->abbr_word_re = ''; $this->abbr_word_re = '';
parent::teardown(); parent::teardown();
} }
/** /**
* Extra attribute parser * Extra attribute parser
*/ */
@ -197,7 +203,7 @@ class MarkdownExtra extends \Michelf\Markdown {
*/ */
protected function doExtraAttributes($tag_name, $attr, $defaultIdValue = null, $classes = array()) { protected function doExtraAttributes($tag_name, $attr, $defaultIdValue = null, $classes = array()) {
if (empty($attr) && !$defaultIdValue && empty($classes)) return ""; if (empty($attr) && !$defaultIdValue && empty($classes)) return "";
// Split on components // Split on components
preg_match_all('/[#.a-z][-_:a-zA-Z0-9=]+/', $attr, $matches); preg_match_all('/[#.a-z][-_:a-zA-Z0-9=]+/', $attr, $matches);
$elements = $matches[0]; $elements = $matches[0];
@ -288,38 +294,38 @@ class MarkdownExtra extends \Michelf\Markdown {
/** /**
* HTML block parser * HTML block parser
*/ */
/** /**
* Tags that are always treated as block tags * Tags that are always treated as block tags
* @var string * @var string
*/ */
protected $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend|article|section|nav|aside|hgroup|header|footer|figcaption|figure'; protected $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend|article|section|nav|aside|hgroup|header|footer|figcaption|figure';
/** /**
* Tags treated as block tags only if the opening tag is alone on its line * Tags treated as block tags only if the opening tag is alone on its line
* @var string * @var string
*/ */
protected $context_block_tags_re = 'script|noscript|style|ins|del|iframe|object|source|track|param|math|svg|canvas|audio|video'; protected $context_block_tags_re = 'script|noscript|style|ins|del|iframe|object|source|track|param|math|svg|canvas|audio|video';
/** /**
* Tags where markdown="1" default to span mode: * Tags where markdown="1" default to span mode:
* @var string * @var string
*/ */
protected $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address'; protected $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
/** /**
* Tags which must not have their contents modified, no matter where * Tags which must not have their contents modified, no matter where
* they appear * they appear
* @var string * @var string
*/ */
protected $clean_tags_re = 'script|style|math|svg'; protected $clean_tags_re = 'script|style|math|svg';
/** /**
* Tags that do not need to be closed. * Tags that do not need to be closed.
* @var string * @var string
*/ */
protected $auto_close_tags_re = 'hr|img|param|source|track'; protected $auto_close_tags_re = 'hr|img|param|source|track';
/** /**
* Hashify HTML Blocks and "clean tags". * Hashify HTML Blocks and "clean tags".
* *
@ -330,7 +336,7 @@ class MarkdownExtra extends \Michelf\Markdown {
* hard-coded. * hard-coded.
* *
* This works by calling _HashHTMLBlocks_InMarkdown, which then calls * This works by calling _HashHTMLBlocks_InMarkdown, which then calls
* _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1" * _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
* attribute is found within a tag, _HashHTMLBlocks_InHTML calls back * attribute is found within a tag, _HashHTMLBlocks_InHTML calls back
* _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag. * _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
* These two functions are calling each other. It's recursive! * These two functions are calling each other. It's recursive!
@ -344,15 +350,15 @@ class MarkdownExtra extends \Michelf\Markdown {
// Call the HTML-in-Markdown hasher. // Call the HTML-in-Markdown hasher.
list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text); list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
return $text; return $text;
} }
/** /**
* Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags. * Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
* *
* * $indent is the number of space to be ignored when checking for code * * $indent is the number of space to be ignored when checking for code
* blocks. This is important because if we don't take the indent into * blocks. This is important because if we don't take the indent into
* account, something like this (which looks right) won't work as expected: * account, something like this (which looks right) won't work as expected:
* *
* <div> * <div>
@ -364,11 +370,11 @@ class MarkdownExtra extends \Michelf\Markdown {
* If you don't like this, just don't indent the tag on which * If you don't like this, just don't indent the tag on which
* you apply the markdown="1" attribute. * you apply the markdown="1" attribute.
* *
* * If $enclosing_tag_re is not empty, stops at the first unmatched closing * * If $enclosing_tag_re is not empty, stops at the first unmatched closing
* tag with that name. Nested tags supported. * tag with that name. Nested tags supported.
* *
* * If $span is true, text inside must treated as span. So any double * * If $span is true, text inside must treated as span. So any double
* newline will be replaced by a single newline so that it does not create * newline will be replaced by a single newline so that it does not create
* paragraphs. * paragraphs.
* *
* Returns an array of that form: ( processed text , remaining text ) * Returns an array of that form: ( processed text , remaining text )
@ -382,18 +388,18 @@ class MarkdownExtra extends \Michelf\Markdown {
protected function _hashHTMLBlocks_inMarkdown($text, $indent = 0, protected function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
$enclosing_tag_re = '', $span = false) $enclosing_tag_re = '', $span = false)
{ {
if ($text === '') return array('', ''); if ($text === '') return array('', '');
// Regex to check for the presense of newlines around a block tag. // Regex to check for the presense of newlines around a block tag.
$newline_before_re = '/(?:^\n?|\n\n)*$/'; $newline_before_re = '/(?:^\n?|\n\n)*$/';
$newline_after_re = $newline_after_re =
'{ '{
^ # Start of text following the tag. ^ # Start of text following the tag.
(?>[ ]*<!--.*?-->)? # Optional comment. (?>[ ]*<!--.*?-->)? # Optional comment.
[ ]*\n # Must be followed by newline. [ ]*\n # Must be followed by newline.
}xs'; }xs';
// Regex to match any tag. // Regex to match any tag.
$block_tag_re = $block_tag_re =
'{ '{
@ -448,7 +454,7 @@ class MarkdownExtra extends \Michelf\Markdown {
) )
}xs'; }xs';
$depth = 0; // Current depth inside the tag tree. $depth = 0; // Current depth inside the tag tree.
$parsed = ""; // Parsed text that will be returned. $parsed = ""; // Parsed text that will be returned.
@ -457,31 +463,31 @@ class MarkdownExtra extends \Michelf\Markdown {
do { do {
// Split the text using the first $tag_match pattern found. // Split the text using the first $tag_match pattern found.
// Text before pattern will be first in the array, text after // Text before pattern will be first in the array, text after
// pattern will be at the end, and between will be any catches made // pattern will be at the end, and between will be any catches made
// by the pattern. // by the pattern.
$parts = preg_split($block_tag_re, $text, 2, $parts = preg_split($block_tag_re, $text, 2,
PREG_SPLIT_DELIM_CAPTURE); PREG_SPLIT_DELIM_CAPTURE);
// If in Markdown span mode, add a empty-string span-level hash // If in Markdown span mode, add a empty-string span-level hash
// after each newline to prevent triggering any block element. // after each newline to prevent triggering any block element.
if ($span) { if ($span) {
$void = $this->hashPart("", ':'); $void = $this->hashPart("", ':');
$newline = "\n$void"; $newline = "\n$void";
$parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void; $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
} }
$parsed .= $parts[0]; // Text before current tag. $parsed .= $parts[0]; // Text before current tag.
// If end of $text has been reached. Stop loop. // If end of $text has been reached. Stop loop.
if (count($parts) < 3) { if (count($parts) < 3) {
$text = ""; $text = "";
break; break;
} }
$tag = $parts[1]; // Tag to handle. $tag = $parts[1]; // Tag to handle.
$text = $parts[2]; // Remaining text after current tag. $text = $parts[2]; // Remaining text after current tag.
$tag_re = preg_quote($tag); // For use in a regular expression. $tag_re = preg_quote($tag); // For use in a regular expression.
// Check for: Fenced code block marker. // Check for: Fenced code block marker.
// Note: need to recheck the whole tag to disambiguate backtick // Note: need to recheck the whole tag to disambiguate backtick
// fences from code spans // fences from code spans
@ -490,7 +496,7 @@ class MarkdownExtra extends \Michelf\Markdown {
$fence_indent = strlen($capture[1]); // use captured indent in re $fence_indent = strlen($capture[1]); // use captured indent in re
$fence_re = $capture[2]; // use captured fence in re $fence_re = $capture[2]; // use captured fence in re
if (preg_match('{^(?>.*\n)*?[ ]{' . ($fence_indent) . '}' . $fence_re . '[ ]*(?:\n|$)}', $text, if (preg_match('{^(?>.*\n)*?[ ]{' . ($fence_indent) . '}' . $fence_re . '[ ]*(?:\n|$)}', $text,
$matches)) $matches))
{ {
// End marker found: pass text unchanged until marker. // End marker found: pass text unchanged until marker.
$parsed .= $tag . $matches[0]; $parsed .= $tag . $matches[0];
@ -503,7 +509,7 @@ class MarkdownExtra extends \Michelf\Markdown {
} }
// Check for: Indented code block. // Check for: Indented code block.
else if ($tag{0} == "\n" || $tag{0} == " ") { else if ($tag{0} == "\n" || $tag{0} == " ") {
// Indented code block: pass it unchanged, will be handled // Indented code block: pass it unchanged, will be handled
// later. // later.
$parsed .= $tag; $parsed .= $tag;
} }
@ -525,7 +531,7 @@ class MarkdownExtra extends \Michelf\Markdown {
} }
} }
// Check for: Opening Block level tag or // Check for: Opening Block level tag or
// Opening Context Block tag (like ins and del) // Opening Context Block tag (like ins and del)
// used as a block tag (tag is alone on it's line). // used as a block tag (tag is alone on it's line).
else if (preg_match('{^<(?:' . $this->block_tags_re . ')\b}', $tag) || else if (preg_match('{^<(?:' . $this->block_tags_re . ')\b}', $tag) ||
( preg_match('{^<(?:' . $this->context_block_tags_re . ')\b}', $tag) && ( preg_match('{^<(?:' . $this->context_block_tags_re . ')\b}', $tag) &&
@ -534,9 +540,9 @@ class MarkdownExtra extends \Michelf\Markdown {
) )
{ {
// Need to parse tag and following text using the HTML parser. // Need to parse tag and following text using the HTML parser.
list($block_text, $text) = list($block_text, $text) =
$this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true); $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
// Make sure it stays outside of any paragraph by adding newlines. // Make sure it stays outside of any paragraph by adding newlines.
$parsed .= "\n\n$block_text\n\n"; $parsed .= "\n\n$block_text\n\n";
} }
@ -547,9 +553,9 @@ class MarkdownExtra extends \Michelf\Markdown {
{ {
// Need to parse tag and following text using the HTML parser. // Need to parse tag and following text using the HTML parser.
// (don't check for markdown attribute) // (don't check for markdown attribute)
list($block_text, $text) = list($block_text, $text) =
$this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false); $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
$parsed .= $block_text; $parsed .= $block_text;
} }
// Check for: Tag with same name as enclosing tag. // Check for: Tag with same name as enclosing tag.
@ -567,14 +573,14 @@ class MarkdownExtra extends \Michelf\Markdown {
$text = $tag . $text; $text = $tag . $text;
break; break;
} }
$parsed .= $tag; $parsed .= $tag;
} }
else { else {
$parsed .= $tag; $parsed .= $tag;
} }
} while ($depth >= 0); } while ($depth >= 0);
return array($parsed, $text); return array($parsed, $text);
} }
@ -594,7 +600,7 @@ class MarkdownExtra extends \Michelf\Markdown {
*/ */
protected function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) { protected function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
if ($text === '') return array('', ''); if ($text === '') return array('', '');
// Regex to match `markdown` attribute inside of a tag. // Regex to match `markdown` attribute inside of a tag.
$markdown_attr_re = ' $markdown_attr_re = '
{ {
@ -602,15 +608,15 @@ class MarkdownExtra extends \Michelf\Markdown {
markdown markdown
\s*=\s* \s*=\s*
(?> (?>
(["\']) # $1: quote delimiter (["\']) # $1: quote delimiter
(.*?) # $2: attribute value (.*?) # $2: attribute value
\1 # matching delimiter \1 # matching delimiter
| |
([^\s>]*) # $3: unquoted attribute value ([^\s>]*) # $3: unquoted attribute value
) )
() # $4: make $3 always defined (avoid warnings) () # $4: make $3 always defined (avoid warnings)
}xs'; }xs';
// Regex to match any tag. // Regex to match any tag.
$tag_re = '{ $tag_re = '{
( # $2: Capture whole tag. ( # $2: Capture whole tag.
@ -633,9 +639,9 @@ class MarkdownExtra extends \Michelf\Markdown {
<!\[CDATA\[.*?\]\]> # CData Block <!\[CDATA\[.*?\]\]> # CData Block
) )
}xs'; }xs';
$original_text = $text; // Save original text in case of faliure. $original_text = $text; // Save original text in case of faliure.
$depth = 0; // Current depth inside the tag tree. $depth = 0; // Current depth inside the tag tree.
$block_text = ""; // Temporary text holder for current text. $block_text = ""; // Temporary text holder for current text.
$parsed = ""; // Parsed text that will be returned. $parsed = ""; // Parsed text that will be returned.
@ -649,22 +655,22 @@ class MarkdownExtra extends \Michelf\Markdown {
do { do {
// Split the text using the first $tag_match pattern found. // Split the text using the first $tag_match pattern found.
// Text before pattern will be first in the array, text after // Text before pattern will be first in the array, text after
// pattern will be at the end, and between will be any catches made // pattern will be at the end, and between will be any catches made
// by the pattern. // by the pattern.
$parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
if (count($parts) < 3) { if (count($parts) < 3) {
// End of $text reached with unbalenced tag(s). // End of $text reached with unbalenced tag(s).
// In that case, we return original text unchanged and pass the // In that case, we return original text unchanged and pass the
// first character as filtered to prevent an infinite loop in the // first character as filtered to prevent an infinite loop in the
// parent function. // parent function.
return array($original_text{0}, substr($original_text, 1)); return array($original_text{0}, substr($original_text, 1));
} }
$block_text .= $parts[0]; // Text before current tag. $block_text .= $parts[0]; // Text before current tag.
$tag = $parts[1]; // Tag to handle. $tag = $parts[1]; // Tag to handle.
$text = $parts[2]; // Remaining text after current tag. $text = $parts[2]; // Remaining text after current tag.
// Check for: Auto-close tag (like <hr/>) // Check for: Auto-close tag (like <hr/>)
// Comments and Processing Instructions. // Comments and Processing Instructions.
if (preg_match('{^</?(?:' . $this->auto_close_tags_re . ')\b}', $tag) || if (preg_match('{^</?(?:' . $this->auto_close_tags_re . ')\b}', $tag) ||
@ -680,20 +686,20 @@ class MarkdownExtra extends \Michelf\Markdown {
if ($tag{1} == '/') $depth--; if ($tag{1} == '/') $depth--;
else if ($tag{strlen($tag)-2} != '/') $depth++; else if ($tag{strlen($tag)-2} != '/') $depth++;
} }
// Check for `markdown="1"` attribute and handle it. // Check for `markdown="1"` attribute and handle it.
if ($md_attr && if ($md_attr &&
preg_match($markdown_attr_re, $tag, $attr_m) && preg_match($markdown_attr_re, $tag, $attr_m) &&
preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3])) preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
{ {
// Remove `markdown` attribute from opening tag. // Remove `markdown` attribute from opening tag.
$tag = preg_replace($markdown_attr_re, '', $tag); $tag = preg_replace($markdown_attr_re, '', $tag);
// Check if text inside this tag must be parsed in span mode. // Check if text inside this tag must be parsed in span mode.
$this->mode = $attr_m[2] . $attr_m[3]; $this->mode = $attr_m[2] . $attr_m[3];
$span_mode = $this->mode == 'span' || $this->mode != 'block' && $span_mode = $this->mode == 'span' || $this->mode != 'block' &&
preg_match('{^<(?:' . $this->contain_span_tags_re . ')\b}', $tag); preg_match('{^<(?:' . $this->contain_span_tags_re . ')\b}', $tag);
// Calculate indent before tag. // Calculate indent before tag.
if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) { if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) {
$strlen = $this->utf8_strlen; $strlen = $this->utf8_strlen;
@ -701,48 +707,48 @@ class MarkdownExtra extends \Michelf\Markdown {
} else { } else {
$indent = 0; $indent = 0;
} }
// End preceding block with this tag. // End preceding block with this tag.
$block_text .= $tag; $block_text .= $tag;
$parsed .= $this->$hash_method($block_text); $parsed .= $this->$hash_method($block_text);
// Get enclosing tag name for the ParseMarkdown function. // Get enclosing tag name for the ParseMarkdown function.
// (This pattern makes $tag_name_re safe without quoting.) // (This pattern makes $tag_name_re safe without quoting.)
preg_match('/^<([\w:$]*)\b/', $tag, $matches); preg_match('/^<([\w:$]*)\b/', $tag, $matches);
$tag_name_re = $matches[1]; $tag_name_re = $matches[1];
// Parse the content using the HTML-in-Markdown parser. // Parse the content using the HTML-in-Markdown parser.
list ($block_text, $text) list ($block_text, $text)
= $this->_hashHTMLBlocks_inMarkdown($text, $indent, = $this->_hashHTMLBlocks_inMarkdown($text, $indent,
$tag_name_re, $span_mode); $tag_name_re, $span_mode);
// Outdent markdown text. // Outdent markdown text.
if ($indent > 0) { if ($indent > 0) {
$block_text = preg_replace("/^[ ]{1,$indent}/m", "", $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
$block_text); $block_text);
} }
// Append tag content to parsed text. // Append tag content to parsed text.
if (!$span_mode) $parsed .= "\n\n$block_text\n\n"; if (!$span_mode) $parsed .= "\n\n$block_text\n\n";
else $parsed .= "$block_text"; else $parsed .= "$block_text";
// Start over with a new block. // Start over with a new block.
$block_text = ""; $block_text = "";
} }
else $block_text .= $tag; else $block_text .= $tag;
} }
} while ($depth > 0); } while ($depth > 0);
// Hash last block text that wasn't processed inside the loop. // Hash last block text that wasn't processed inside the loop.
$parsed .= $this->$hash_method($block_text); $parsed .= $this->$hash_method($block_text);
return array($parsed, $text); return array($parsed, $text);
} }
/** /**
* Called whenever a tag must be hashed when a function inserts a "clean" tag * Called whenever a tag must be hashed when a function inserts a "clean" tag
* in $text, it passes through this function and is automaticaly escaped, * in $text, it passes through this function and is automaticaly escaped,
* blocking invalid nested overlap. * blocking invalid nested overlap.
* @param string $text * @param string $text
* @return string * @return string
@ -835,7 +841,7 @@ class MarkdownExtra extends \Michelf\Markdown {
// for shortcut links like [this][] or [this]. // for shortcut links like [this][] or [this].
$link_id = $link_text; $link_id = $link_text;
} }
// lower-case and turn embedded newlines into spaces // lower-case and turn embedded newlines into spaces
$link_id = strtolower($link_id); $link_id = strtolower($link_id);
$link_id = preg_replace('{[ ]?\n}', ' ', $link_id); $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
@ -843,7 +849,7 @@ class MarkdownExtra extends \Michelf\Markdown {
if (isset($this->urls[$link_id])) { if (isset($this->urls[$link_id])) {
$url = $this->urls[$link_id]; $url = $this->urls[$link_id];
$url = $this->encodeURLAttribute($url); $url = $this->encodeURLAttribute($url);
$result = "<a href=\"$url\""; $result = "<a href=\"$url\"";
if ( isset( $this->titles[$link_id] ) ) { if ( isset( $this->titles[$link_id] ) ) {
$title = $this->titles[$link_id]; $title = $this->titles[$link_id];
@ -852,7 +858,7 @@ class MarkdownExtra extends \Michelf\Markdown {
} }
if (isset($this->ref_attr[$link_id])) if (isset($this->ref_attr[$link_id]))
$result .= $this->ref_attr[$link_id]; $result .= $this->ref_attr[$link_id];
$link_text = $this->runSpanGamut($link_text); $link_text = $this->runSpanGamut($link_text);
$result .= ">$link_text</a>"; $result .= ">$link_text</a>";
$result = $this->hashPart($result); $result = $this->hashPart($result);
@ -889,7 +895,7 @@ class MarkdownExtra extends \Michelf\Markdown {
$result .= " title=\"$title\""; $result .= " title=\"$title\"";
} }
$result .= $attr; $result .= $attr;
$link_text = $this->runSpanGamut($link_text); $link_text = $this->runSpanGamut($link_text);
$result .= ">$link_text</a>"; $result .= ">$link_text</a>";
@ -917,7 +923,7 @@ class MarkdownExtra extends \Michelf\Markdown {
\] \]
) )
}xs', }xs',
array($this, '_doImages_reference_callback'), $text); array($this, '_doImages_reference_callback'), $text);
// Next, handle inline images: ![alt text](url "optional title") // Next, handle inline images: ![alt text](url "optional title")
@ -1021,7 +1027,7 @@ class MarkdownExtra extends \Michelf\Markdown {
// Setext-style headers: // Setext-style headers:
// Header 1 {#header1} // Header 1 {#header1}
// ======== // ========
// //
// Header 2 {#header2 .class1 .class2} // Header 2 {#header2 .class1 .class2}
// -------- // --------
// //
@ -1042,7 +1048,7 @@ class MarkdownExtra extends \Michelf\Markdown {
// //
$text = preg_replace_callback('{ $text = preg_replace_callback('{
^(\#{1,6}) # $1 = string of #\'s ^(\#{1,6}) # $1 = string of #\'s
[ ]* [ ]'.($this->hashtag_protection ? '+' : '*').'
(.+?) # $2 = Header text (.+?) # $2 = Header text
[ ]* [ ]*
\#* # optional closing #\'s (not counted) \#* # optional closing #\'s (not counted)
@ -1107,10 +1113,10 @@ class MarkdownExtra extends \Michelf\Markdown {
[ ]{0,' . $less_than_tab . '} # Allowed whitespace. [ ]{0,' . $less_than_tab . '} # Allowed whitespace.
[|] # Optional leading pipe (present) [|] # Optional leading pipe (present)
(.+) \n # $1: Header row (at least one pipe) (.+) \n # $1: Header row (at least one pipe)
[ ]{0,' . $less_than_tab . '} # Allowed whitespace. [ ]{0,' . $less_than_tab . '} # Allowed whitespace.
[|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline
( # $3: Cells ( # $3: Cells
(?> (?>
[ ]* # Allowed whitespace. [ ]* # Allowed whitespace.
@ -1132,10 +1138,10 @@ class MarkdownExtra extends \Michelf\Markdown {
^ # Start of a line ^ # Start of a line
[ ]{0,' . $less_than_tab . '} # Allowed whitespace. [ ]{0,' . $less_than_tab . '} # Allowed whitespace.
(\S.*[|].*) \n # $1: Header row (at least one pipe) (\S.*[|].*) \n # $1: Header row (at least one pipe)
[ ]{0,' . $less_than_tab . '} # Allowed whitespace. [ ]{0,' . $less_than_tab . '} # Allowed whitespace.
([-:]+[ ]*[|][-| :]*) \n # $2: Header underline ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline
( # $3: Cells ( # $3: Cells
(?> (?>
.* [|] .* \n # Row content .* [|] .* \n # Row content
@ -1159,7 +1165,7 @@ class MarkdownExtra extends \Michelf\Markdown {
$content = $matches[3]; $content = $matches[3];
$content = preg_replace('/^ *[|]/m', '', $content); $content = preg_replace('/^ *[|]/m', '', $content);
return $this->_doTable_callback(array($matches[0], $head, $underline, $content)); return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
} }
@ -1192,7 +1198,7 @@ class MarkdownExtra extends \Michelf\Markdown {
$head = preg_replace('/[|] *$/m', '', $head); $head = preg_replace('/[|] *$/m', '', $head);
$underline = preg_replace('/[|] *$/m', '', $underline); $underline = preg_replace('/[|] *$/m', '', $underline);
$content = preg_replace('/[|] *$/m', '', $content); $content = preg_replace('/[|] *$/m', '', $content);
// Reading alignement from header underline. // Reading alignement from header underline.
$separators = preg_split('/ *[|] */', $underline); $separators = preg_split('/ *[|] */', $underline);
foreach ($separators as $n => $s) { foreach ($separators as $n => $s) {
@ -1205,14 +1211,14 @@ class MarkdownExtra extends \Michelf\Markdown {
else else
$attr[$n] = ''; $attr[$n] = '';
} }
// Parsing span elements, including code spans, character escapes, // Parsing span elements, including code spans, character escapes,
// and inline HTML tags, so that pipes inside those gets ignored. // and inline HTML tags, so that pipes inside those gets ignored.
$head = $this->parseSpan($head); $head = $this->parseSpan($head);
$headers = preg_split('/ *[|] */', $head); $headers = preg_split('/ *[|] */', $head);
$col_count = count($headers); $col_count = count($headers);
$attr = array_pad($attr, $col_count, ''); $attr = array_pad($attr, $col_count, '');
// Write column headers. // Write column headers.
$text = "<table>\n"; $text = "<table>\n";
$text .= "<thead>\n"; $text .= "<thead>\n";
@ -1221,20 +1227,20 @@ class MarkdownExtra extends \Michelf\Markdown {
$text .= " <th$attr[$n]>" . $this->runSpanGamut(trim($header)) . "</th>\n"; $text .= " <th$attr[$n]>" . $this->runSpanGamut(trim($header)) . "</th>\n";
$text .= "</tr>\n"; $text .= "</tr>\n";
$text .= "</thead>\n"; $text .= "</thead>\n";
// Split content by row. // Split content by row.
$rows = explode("\n", trim($content, "\n")); $rows = explode("\n", trim($content, "\n"));
$text .= "<tbody>\n"; $text .= "<tbody>\n";
foreach ($rows as $row) { foreach ($rows as $row) {
// Parsing span elements, including code spans, character escapes, // Parsing span elements, including code spans, character escapes,
// and inline HTML tags, so that pipes inside those gets ignored. // and inline HTML tags, so that pipes inside those gets ignored.
$row = $this->parseSpan($row); $row = $this->parseSpan($row);
// Split row by cell. // Split row by cell.
$row_cells = preg_split('/ *[|] */', $row, $col_count); $row_cells = preg_split('/ *[|] */', $row, $col_count);
$row_cells = array_pad($row_cells, $col_count, ''); $row_cells = array_pad($row_cells, $col_count, '');
$text .= "<tr>\n"; $text .= "<tr>\n";
foreach ($row_cells as $n => $cell) foreach ($row_cells as $n => $cell)
$text .= " <td$attr[$n]>" . $this->runSpanGamut(trim($cell)) . "</td>\n"; $text .= " <td$attr[$n]>" . $this->runSpanGamut(trim($cell)) . "</td>\n";
@ -1242,7 +1248,7 @@ class MarkdownExtra extends \Michelf\Markdown {
} }
$text .= "</tbody>\n"; $text .= "</tbody>\n";
$text .= "</table>"; $text .= "</table>";
return $this->hashBlock($text) . "\n"; return $this->hashBlock($text) . "\n";
} }
@ -1299,7 +1305,7 @@ class MarkdownExtra extends \Michelf\Markdown {
protected function _doDefLists_callback($matches) { protected function _doDefLists_callback($matches) {
// Re-usable patterns to match list item bullets and number markers: // Re-usable patterns to match list item bullets and number markers:
$list = $matches[1]; $list = $matches[1];
// Turn double returns into triple returns, so that we can make a // Turn double returns into triple returns, so that we can make a
// paragraph for the last item in a list, if necessary: // paragraph for the last item in a list, if necessary:
$result = trim($this->processDefListItems($list)); $result = trim($this->processDefListItems($list));
@ -1314,9 +1320,9 @@ class MarkdownExtra extends \Michelf\Markdown {
* @return string * @return string
*/ */
protected function processDefListItems($list_str) { protected function processDefListItems($list_str) {
$less_than_tab = $this->tab_width - 1; $less_than_tab = $this->tab_width - 1;
// Trim trailing blank lines: // Trim trailing blank lines:
$list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
@ -1327,9 +1333,9 @@ class MarkdownExtra extends \Michelf\Markdown {
[ ]{0,' . $less_than_tab . '} # leading whitespace [ ]{0,' . $less_than_tab . '} # leading whitespace
(?!\:[ ]|[ ]) # negative lookahead for a definition (?!\:[ ]|[ ]) # negative lookahead for a definition
# mark (colon) or more whitespace. # mark (colon) or more whitespace.
(?> \S.* \n)+? # actual term (not whitespace). (?> \S.* \n)+? # actual term (not whitespace).
) )
(?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed
# with a definition mark. # with a definition mark.
}xm', }xm',
array($this, '_processDefListItems_callback_dt'), $list_str); array($this, '_processDefListItems_callback_dt'), $list_str);
@ -1346,8 +1352,8 @@ class MarkdownExtra extends \Michelf\Markdown {
(?: # next term or end of text (?: # next term or end of text
[ ]{0,' . $less_than_tab . '} \:[ ] | [ ]{0,' . $less_than_tab . '} \:[ ] |
<dt> | \z <dt> | \z
) )
) )
}xm', }xm',
array($this, '_processDefListItems_callback_dd'), $list_str); array($this, '_processDefListItems_callback_dd'), $list_str);
@ -1399,14 +1405,14 @@ class MarkdownExtra extends \Michelf\Markdown {
* ~~~ * ~~~
* Code block * Code block
* ~~~ * ~~~
* *
* @param string $text * @param string $text
* @return string * @return string
*/ */
protected function doFencedCodeBlocks($text) { protected function doFencedCodeBlocks($text) {
$less_than_tab = $this->tab_width; $less_than_tab = $this->tab_width;
$text = preg_replace_callback('{ $text = preg_replace_callback('{
(?:\n|\A) (?:\n|\A)
# 1: Opening marker # 1: Opening marker
@ -1422,7 +1428,7 @@ class MarkdownExtra extends \Michelf\Markdown {
' . $this->id_class_attr_catch_re . ' # 3: Extra attributes ' . $this->id_class_attr_catch_re . ' # 3: Extra attributes
)? )?
[ ]* \n # Whitespace and newline following marker. [ ]* \n # Whitespace and newline following marker.
# 4: Content # 4: Content
( (
(?> (?>
@ -1430,7 +1436,7 @@ class MarkdownExtra extends \Michelf\Markdown {
.*\n+ .*\n+
)+ )+
) )
# Closing marker. # Closing marker.
\1 [ ]* (?= \n ) \1 [ ]* (?= \n )
}xm', }xm',
@ -1468,7 +1474,7 @@ class MarkdownExtra extends \Michelf\Markdown {
$pre_attr_str = $this->code_attr_on_pre ? $attr_str : ''; $pre_attr_str = $this->code_attr_on_pre ? $attr_str : '';
$code_attr_str = $this->code_attr_on_pre ? '' : $attr_str; $code_attr_str = $this->code_attr_on_pre ? '' : $attr_str;
$codeblock = "<pre$pre_attr_str><code$code_attr_str>$codeblock</code></pre>"; $codeblock = "<pre$pre_attr_str><code$code_attr_str>$codeblock</code></pre>";
return "\n\n".$this->hashBlock($codeblock)."\n\n"; return "\n\n".$this->hashBlock($codeblock)."\n\n";
} }
@ -1478,7 +1484,7 @@ class MarkdownExtra extends \Michelf\Markdown {
* @return string * @return string
*/ */
protected function _doFencedCodeBlocks_newlines($matches) { protected function _doFencedCodeBlocks_newlines($matches) {
return str_repeat("<br$this->empty_element_suffix", return str_repeat("<br$this->empty_element_suffix",
strlen($matches[0])); strlen($matches[0]));
} }
@ -1518,27 +1524,27 @@ class MarkdownExtra extends \Michelf\Markdown {
// Wrap <p> tags and unhashify HTML blocks // Wrap <p> tags and unhashify HTML blocks
foreach ($grafs as $key => $value) { foreach ($grafs as $key => $value) {
$value = trim($this->runSpanGamut($value)); $value = trim($this->runSpanGamut($value));
// Check if this should be enclosed in a paragraph. // Check if this should be enclosed in a paragraph.
// Clean tag hashes & block tag hashes are left alone. // Clean tag hashes & block tag hashes are left alone.
$is_p = $wrap_in_p && !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value); $is_p = $wrap_in_p && !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value);
if ($is_p) { if ($is_p) {
$value = "<p>$value</p>"; $value = "<p>$value</p>";
} }
$grafs[$key] = $value; $grafs[$key] = $value;
} }
// Join grafs in one text, then unhash HTML tags. // Join grafs in one text, then unhash HTML tags.
$text = implode("\n\n", $grafs); $text = implode("\n\n", $grafs);
// Finish by removing any tag hashes still present in $text. // Finish by removing any tag hashes still present in $text.
$text = $this->unhash($text); $text = $this->unhash($text);
return $text; return $text;
} }
/** /**
* Footnotes - Strips link definitions from text, stores the URLs and * Footnotes - Strips link definitions from text, stores the URLs and
* titles in hash references. * titles in hash references.
@ -1554,15 +1560,15 @@ class MarkdownExtra extends \Michelf\Markdown {
[ ]* [ ]*
\n? # maybe *one* newline \n? # maybe *one* newline
( # text = $2 (no blank lines allowed) ( # text = $2 (no blank lines allowed)
(?: (?:
.+ # actual text .+ # actual text
| |
\n # newlines but \n # newlines but
(?!\[.+?\][ ]?:\s)# negative lookahead for footnote or link definition marker. (?!\[.+?\][ ]?:\s)# negative lookahead for footnote or link definition marker.
(?!\n+[ ]{0,3}\S)# ensure line is not blank and followed (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed
# by non-indented content # by non-indented content
)* )*
) )
}xm', }xm',
array($this, '_stripFootnotes_callback'), array($this, '_stripFootnotes_callback'),
$text); $text);
@ -1581,7 +1587,7 @@ class MarkdownExtra extends \Michelf\Markdown {
} }
/** /**
* Replace footnote references in $text [^id] with a special text-token * Replace footnote references in $text [^id] with a special text-token
* which will be replaced by the actual footnote marker in appendFootnotes. * which will be replaced by the actual footnote marker in appendFootnotes.
* @param string $text * @param string $text
* @return string * @return string
@ -1599,12 +1605,12 @@ class MarkdownExtra extends \Michelf\Markdown {
* @return string * @return string
*/ */
protected function appendFootnotes($text) { protected function appendFootnotes($text) {
$text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}', $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
array($this, '_appendFootnotes_callback'), $text); array($this, '_appendFootnotes_callback'), $text);
if (!empty($this->footnotes_ordered)) { if (!empty($this->footnotes_ordered)) {
$text .= "\n\n"; $text .= "\n\n";
$text .= "<div class=\"footnotes\">\n"; $text .= "<div class=\"footnotes\" role=\"doc-endnotes\">\n";
$text .= "<hr" . $this->empty_element_suffix . "\n"; $text .= "<hr" . $this->empty_element_suffix . "\n";
$text .= "<ol>\n\n"; $text .= "<ol>\n\n";
@ -1618,10 +1624,12 @@ class MarkdownExtra extends \Michelf\Markdown {
$title = $this->fn_backlink_title; $title = $this->fn_backlink_title;
$title = $this->encodeAttribute($title); $title = $this->encodeAttribute($title);
$attr .= " title=\"$title\""; $attr .= " title=\"$title\"";
$attr .= " aria-label=\"$title\"";
} }
$attr .= " role=\"doc-backlink\"";
$backlink_text = $this->fn_backlink_html; $backlink_text = $this->fn_backlink_html;
$num = 0; $num = 0;
while (!empty($this->footnotes_ordered)) { while (!empty($this->footnotes_ordered)) {
$footnote = reset($this->footnotes_ordered); $footnote = reset($this->footnotes_ordered);
$note_id = key($this->footnotes_ordered); $note_id = key($this->footnotes_ordered);
@ -1629,12 +1637,12 @@ class MarkdownExtra extends \Michelf\Markdown {
$ref_count = $this->footnotes_ref_count[$note_id]; $ref_count = $this->footnotes_ref_count[$note_id];
unset($this->footnotes_ref_count[$note_id]); unset($this->footnotes_ref_count[$note_id]);
unset($this->footnotes[$note_id]); unset($this->footnotes[$note_id]);
$footnote .= "\n"; // Need to append newline before parsing. $footnote .= "\n"; // Need to append newline before parsing.
$footnote = $this->runBlockGamut("$footnote\n"); $footnote = $this->runBlockGamut("$footnote\n");
$footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}', $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
array($this, '_appendFootnotes_callback'), $footnote); array($this, '_appendFootnotes_callback'), $footnote);
$attr = str_replace("%%", ++$num, $attr); $attr = str_replace("%%", ++$num, $attr);
$note_id = $this->encodeAttribute($note_id); $note_id = $this->encodeAttribute($note_id);
@ -1649,12 +1657,12 @@ class MarkdownExtra extends \Michelf\Markdown {
} else { } else {
$footnote .= "\n\n<p>$backlink</p>"; $footnote .= "\n\n<p>$backlink</p>";
} }
$text .= "<li id=\"fn:$note_id\">\n"; $text .= "<li id=\"fn:$note_id\" role=\"doc-endnote\">\n";
$text .= $footnote . "\n"; $text .= $footnote . "\n";
$text .= "</li>\n\n"; $text .= "</li>\n\n";
} }
$text .= "</ol>\n"; $text .= "</ol>\n";
$text .= "</div>"; $text .= "</div>";
} }
@ -1668,7 +1676,7 @@ class MarkdownExtra extends \Michelf\Markdown {
*/ */
protected function _appendFootnotes_callback($matches) { protected function _appendFootnotes_callback($matches) {
$node_id = $this->fn_id_prefix . $matches[1]; $node_id = $this->fn_id_prefix . $matches[1];
// Create footnote marker only if it has a corresponding footnote *and* // Create footnote marker only if it has a corresponding footnote *and*
// the footnote hasn't been used by another marker. // the footnote hasn't been used by another marker.
if (isset($this->footnotes[$node_id])) { if (isset($this->footnotes[$node_id])) {
@ -1695,20 +1703,21 @@ class MarkdownExtra extends \Michelf\Markdown {
$title = $this->encodeAttribute($title); $title = $this->encodeAttribute($title);
$attr .= " title=\"$title\""; $attr .= " title=\"$title\"";
} }
$attr .= " role=\"doc-noteref\"";
$attr = str_replace("%%", $num, $attr); $attr = str_replace("%%", $num, $attr);
$node_id = $this->encodeAttribute($node_id); $node_id = $this->encodeAttribute($node_id);
return return
"<sup id=\"fnref$ref_count_mark:$node_id\">". "<sup id=\"fnref$ref_count_mark:$node_id\">".
"<a href=\"#fn:$node_id\"$attr>$num</a>". "<a href=\"#fn:$node_id\"$attr>$num</a>".
"</sup>"; "</sup>";
} }
return "[^" . $matches[1] . "]"; return "[^" . $matches[1] . "]";
} }
/** /**
* Abbreviations - strips abbreviations from text, stores titles in hash * Abbreviations - strips abbreviations from text, stores titles in hash
* references. * references.
@ -1721,7 +1730,7 @@ class MarkdownExtra extends \Michelf\Markdown {
// Link defs are in the form: [id]*: url "optional title" // Link defs are in the form: [id]*: url "optional title"
$text = preg_replace_callback('{ $text = preg_replace_callback('{
^[ ]{0,' . $less_than_tab . '}\*\[(.+?)\][ ]?: # abbr_id = $1 ^[ ]{0,' . $less_than_tab . '}\*\[(.+?)\][ ]?: # abbr_id = $1
(.*) # text = $2 (no blank lines allowed) (.*) # text = $2 (no blank lines allowed)
}xm', }xm',
array($this, '_stripAbbreviations_callback'), array($this, '_stripAbbreviations_callback'),
$text); $text);
@ -1751,7 +1760,7 @@ class MarkdownExtra extends \Michelf\Markdown {
*/ */
protected function doAbbreviations($text) { protected function doAbbreviations($text) {
if ($this->abbr_word_re) { if ($this->abbr_word_re) {
// cannot use the /x modifier because abbr_word_re may // cannot use the /x modifier because abbr_word_re may
// contain significant spaces: // contain significant spaces:
$text = preg_replace_callback('{' . $text = preg_replace_callback('{' .
'(?<![\w\x1A])' . '(?<![\w\x1A])' .

View file

@ -4,14 +4,14 @@
* *
* @package php-markdown * @package php-markdown
* @author Michel Fortin <michel.fortin@michelf.com> * @author Michel Fortin <michel.fortin@michelf.com>
* @copyright 2004-2016 Michel Fortin <https://michelf.com/projects/php-markdown/> * @copyright 2004-2018 Michel Fortin <https://michelf.com/projects/php-markdown/>
* @copyright (Original Markdown) 2004-2006 John Gruber <https://daringfireball.net/projects/markdown/> * @copyright (Original Markdown) 2004-2006 John Gruber <https://daringfireball.net/projects/markdown/>
*/ */
namespace Michelf; namespace Michelf;
/** /**
* Markdown Parser Interface * Markdown Parser Interface
*/ */
interface MarkdownInterface { interface MarkdownInterface {
/** /**

View file

@ -1,7 +1,7 @@
PHP Markdown PHP Markdown
============ ============
PHP Markdown Lib 1.7.0 - 29 Oct 2016 PHP Markdown Lib 1.8.0 - 14 Jan 2018
by Michel Fortin by Michel Fortin
<https://michelf.ca/> <https://michelf.ca/>
@ -13,16 +13,16 @@ based on Markdown by John Gruber
Introduction Introduction
------------ ------------
This is a library package that includes the PHP Markdown parser and its This is a library package that includes the PHP Markdown parser and its
sibling PHP Markdown Extra with additional features. sibling PHP Markdown Extra with additional features.
Markdown is a text-to-HTML conversion tool for web writers. Markdown Markdown is a text-to-HTML conversion tool for web writers. Markdown
allows you to write using an easy-to-read, easy-to-write plain text allows you to write using an easy-to-read, easy-to-write plain text
format, then convert it to structurally valid XHTML (or HTML). format, then convert it to structurally valid XHTML (or HTML).
"Markdown" is actually two things: a plain text markup syntax, and a "Markdown" is actually two things: a plain text markup syntax, and a
software tool, originally written in Perl, that converts the plain text software tool, originally written in Perl, that converts the plain text
markup to HTML. PHP Markdown is a port to PHP of the original Markdown markup to HTML. PHP Markdown is a port to PHP of the original Markdown
program by John Gruber. program by John Gruber.
* [Full documentation of the Markdown syntax](<https://daringfireball.net/projects/markdown/>) * [Full documentation of the Markdown syntax](<https://daringfireball.net/projects/markdown/>)
@ -37,68 +37,77 @@ Requirement
This library package requires PHP 5.3 or later. This library package requires PHP 5.3 or later.
Note: The older plugin/library hybrid package for PHP Markdown and Note: The older plugin/library hybrid package for PHP Markdown and
PHP Markdown Extra is still maintained and will work with PHP 4.0.5 and later. PHP Markdown Extra is no longer maintained but will work with PHP 4.0.5 and
later.
Before PHP 5.3.7, pcre.backtrack_limit defaults to 100 000, which is too small Before PHP 5.3.7, pcre.backtrack_limit defaults to 100 000, which is too small
in many situations. You might need to set it to higher values. Later PHP in many situations. You might need to set it to higher values. Later PHP
releases defaults to 1 000 000, which is usually fine. releases defaults to 1 000 000, which is usually fine.
Usage Usage
----- -----
This library package is meant to be used with class autoloading. For autoloading To use this library with Composer, first install it with:
to work, your project needs have setup a PSR-0-compatible autoloader. See the
included Readme.php file for a minimal autoloader setup. (If you cannot use
autoloading, see below.)
With class autoloading in place, putting the 'Michelf' folder in your $ composer require michelf/php-markdown
include path should be enough for this to work:
use \Michelf\Markdown; Then include Composer's generated vendor/autoload.php to [enable autoloading]:
require 'vendor/autoload.php';
Without Composer, for autoloading to work, your project needs an autoloader
compatible with PSR-4 or PSR-0. See the included Readme.php file for a minimal
autoloader setup. (If you cannot use autoloading, see below.)
With class autoloading in place:
use Michelf\Markdown;
$my_html = Markdown::defaultTransform($my_text); $my_html = Markdown::defaultTransform($my_text);
Markdown Extra syntax is also available the same way: Markdown Extra syntax is also available the same way:
use \Michelf\MarkdownExtra; use Michelf\MarkdownExtra;
$my_html = MarkdownExtra::defaultTransform($my_text); $my_html = MarkdownExtra::defaultTransform($my_text);
If you wish to use PHP Markdown with another text filter function If you wish to use PHP Markdown with another text filter function
built to parse HTML, you should filter the text *after* the `transform` built to parse HTML, you should filter the text *after* the `transform`
function call. This is an example with [PHP SmartyPants][psp]: function call. This is an example with [PHP SmartyPants]:
use \Michelf\Markdown, \Michelf\SmartyPants; use Michelf\Markdown, Michelf\SmartyPants;
$my_html = Markdown::defaultTransform($my_text); $my_html = Markdown::defaultTransform($my_text);
$my_html = SmartyPants::defaultTransform($my_html); $my_html = SmartyPants::defaultTransform($my_html);
All these examples are using the static `defaultTransform` static function All these examples are using the static `defaultTransform` static function
found inside the parser class. If you want to customize the parser found inside the parser class. If you want to customize the parser
configuration, you can also instantiate it directly and change some configuration, you can also instantiate it directly and change some
configuration variables: configuration variables:
use \Michelf\MarkdownExtra; use Michelf\MarkdownExtra;
$parser = new MarkdownExtra; $parser = new MarkdownExtra;
$parser->fn_id_prefix = "post22-"; $parser->fn_id_prefix = "post22-";
$my_html = $parser->transform($my_text); $my_html = $parser->transform($my_text);
To learn more, see the full list of [configuration variables]. To learn more, see the full list of [configuration variables].
[enable autoloading]: https://getcomposer.org/doc/01-basic-usage.md#autoloading
[PHP SmartyPants]: https://michelf.ca/projects/php-smartypants/
[configuration variables]: https://michelf.ca/projects/php-markdown/configuration/ [configuration variables]: https://michelf.ca/projects/php-markdown/configuration/
### Usage without an autoloader ### Usage without an autoloader
If you cannot use class autoloading, you can still use `include` or `require` If you cannot use class autoloading, you can still use `include` or `require`
to access the parser. To load the `\Michelf\Markdown` parser, do it this way: to access the parser. To load the `Michelf\Markdown` parser, do it this way:
require_once 'Michelf/Markdown.inc.php'; require_once 'Michelf/Markdown.inc.php';
Or, if you need the `\Michelf\MarkdownExtra` parser: Or, if you need the `Michelf\MarkdownExtra` parser:
require_once 'Michelf/MarkdownExtra.inc.php'; require_once 'Michelf/MarkdownExtra.inc.php';
While the plain `.php` files depend on autoloading to work correctly, using the While the plain `.php` files depend on autoloading to work correctly, using the
`.inc.php` files instead will eagerly load the dependencies that would be `.inc.php` files instead will eagerly load the dependencies that would be
loaded on demand if you were using autoloading. loaded on demand if you were using autoloading.
@ -113,19 +122,19 @@ functions and their configuration variables. The public API is stable for
a given major version number. It might get additions when the minor version a given major version number. It might get additions when the minor version
number increments. number increments.
**Protected members are not considered public API.** This is unconventional **Protected members are not considered public API.** This is unconventional
and deserves an explanation. Incrementing the major version number every time and deserves an explanation. Incrementing the major version number every time
the underlying implementation of something changes is going to give the underlying implementation of something changes is going to give
nonessential version numbers for the vast majority of people who just use the nonessential version numbers for the vast majority of people who just use the
parser. Protected members are meant to create parser subclasses that behave in parser. Protected members are meant to create parser subclasses that behave in
different ways. Very few people create parser subclasses. I don't want to different ways. Very few people create parser subclasses. I don't want to
discourage it by making everything private, but at the same time I can't discourage it by making everything private, but at the same time I can't
guarantee any stable hook between versions if you use protected members. guarantee any stable hook between versions if you use protected members.
**Syntax changes** will increment the minor number for new features, and the **Syntax changes** will increment the minor number for new features, and the
patch number for small corrections. A *new feature* is something that needs a patch number for small corrections. A *new feature* is something that needs a
change in the syntax documentation. Note that since PHP Markdown Lib includes change in the syntax documentation. Note that since PHP Markdown Lib includes
two parsers, a syntax change for either of them will increment the minor two parsers, a syntax change for either of them will increment the minor
number. Also note that there is nothing perfectly backward-compatible with the number. Also note that there is nothing perfectly backward-compatible with the
Markdown syntax: all inputs are always valid, so new features always replace Markdown syntax: all inputs are always valid, so new features always replace
something that was previously legal, although generally nonsensical to do. something that was previously legal, although generally nonsensical to do.
@ -140,7 +149,7 @@ To file bug reports please send email to:
Please include with your report: (1) the example input; (2) the output you Please include with your report: (1) the example input; (2) the output you
expected; (3) the output PHP Markdown actually produced. expected; (3) the output PHP Markdown actually produced.
If you have a problem where Markdown gives you an empty result, first check If you have a problem where Markdown gives you an empty result, first check
that the backtrack limit is not too low by running `php --info | grep pcre`. that the backtrack limit is not too low by running `php --info | grep pcre`.
See Installation and Requirement above for details. See Installation and Requirement above for details.
@ -149,12 +158,12 @@ Development and Testing
----------------------- -----------------------
Pull requests for fixing bugs are welcome. Proposed new features are Pull requests for fixing bugs are welcome. Proposed new features are
going to be meticulously reviewed -- taking into account backward compatibility, going to be meticulously reviewed -- taking into account backward compatibility,
potential side effects, and future extensibility -- before deciding on potential side effects, and future extensibility -- before deciding on
acceptance or rejection. acceptance or rejection.
If you make a pull request that includes changes to the parser please add If you make a pull request that includes changes to the parser please add
tests for what is being changed to [MDTest][] and make a pull request there tests for what is being changed to [MDTest][] and make a pull request there
too. too.
[MDTest]: https://github.com/michelf/mdtest/ [MDTest]: https://github.com/michelf/mdtest/
@ -163,7 +172,7 @@ too.
Donations Donations
--------- ---------
If you wish to make a donation that will help me devote more time to If you wish to make a donation that will help me devote more time to
PHP Markdown, please visit [michelf.ca/donate] or send Bitcoin to PHP Markdown, please visit [michelf.ca/donate] or send Bitcoin to
[1HiuX34czvVPPdhXbUAsAu7pZcesniDCGH]. [1HiuX34czvVPPdhXbUAsAu7pZcesniDCGH].
@ -174,56 +183,72 @@ PHP Markdown, please visit [michelf.ca/donate] or send Bitcoin to
Version History Version History
--------------- ---------------
PHP Markdown Lib 1.8.0 (14 Jan 2018)
* Autoloading with Composer now uses PSR-4.
* HTML output for Markdown Extra footnotes now include `role` attributes
with values from [WAI-ARIA](https://www.w3.org/TR/dpub-aria/) to
make them more accessible.
(Thanks to Tobias Bengfort)
* In Markdown Extra, added the `hashtag_protection` configuration variable.
When set to `true` it prevents ATX-style headers with no space after the initial
hash from being interpreted as headers. This way your precious hashtags
are preserved.
(Thanks to Jaussoin Timothée for the implementation.)
PHP Markdown Lib 1.7.0 (29 Oct 2016) PHP Markdown Lib 1.7.0 (29 Oct 2016)
* Added a `hard_wrap` configuration variable to make all newline characters * Added a `hard_wrap` configuration variable to make all newline characters
in the text become `<br>` tags in the HTML output. By default, according in the text become `<br>` tags in the HTML output. By default, according
to the standard Markdown syntax these newlines are ignored unless they a to the standard Markdown syntax these newlines are ignored unless they a
preceded by two spaces. Thanks to Jonathan Cohlmeyer for the implementation. preceded by two spaces. Thanks to Jonathan Cohlmeyer for the implementation.
* Improved the parsing of list items to fix problematic cases that came to * Improved the parsing of list items to fix problematic cases that came to
light with the addition of `hard_wrap`. This should have no effect on the light with the addition of `hard_wrap`. This should have no effect on the
output except span-level list items that ended with two spaces (and thus output except span-level list items that ended with two spaces (and thus
ended with a line break). ended with a line break).
* Added a `code_span_content_func` configuration variable which takes a * Added a `code_span_content_func` configuration variable which takes a
function that will convert the content of the code span to HTML. This can function that will convert the content of the code span to HTML. This can
be useful to implement syntax highlighting. Although contrary to its be useful to implement syntax highlighting. Although contrary to its
code block equivalent, there is no syntax for specifying a language. code block equivalent, there is no syntax for specifying a language.
Credits to styxit for the implementation. Credits to styxit for the implementation.
* Fixed a Markdwon Extra issue where two-space-at-end-of-line hard breaks * Fixed a Markdown Extra issue where two-space-at-end-of-line hard breaks
wouldn't work inside of HTML block elements such as `<p markdown="1">` wouldn't work inside of HTML block elements such as `<p markdown="1">`
where the element expects only span-level content. where the element expects only span-level content.
* In the parser code, switched to PHPDoc comment format. Thanks to * In the parser code, switched to PHPDoc comment format. Thanks to
Robbie Averill for the help. Robbie Averill for the help.
PHP Markdown Lib 1.6.0 (23 Dec 2015) PHP Markdown Lib 1.6.0 (23 Dec 2015)
Note: this version was incorrectly released as 1.5.1 on Dec 22, a number Note: this version was incorrectly released as 1.5.1 on Dec 22, a number
that contradicted the versioning policy. that contradicted the versioning policy.
* For fenced code blocks in Markdown Extra, can now set a class name for the * For fenced code blocks in Markdown Extra, can now set a class name for the
code block's language before the special attribute block. Previously, this code block's language before the special attribute block. Previously, this
class name was only allowed in the absence of the special attribute block. class name was only allowed in the absence of the special attribute block.
* Added a `code_block_content_func` configuration variable which takes a * Added a `code_block_content_func` configuration variable which takes a
function that will convert the content of the code block to HTML. This is function that will convert the content of the code block to HTML. This is
most useful for syntax highlighting. For fenced code blocks in Markdown most useful for syntax highlighting. For fenced code blocks in Markdown
Extra, the function has access to the language class name (the one outside Extra, the function has access to the language class name (the one outside
of the special attribute block). Credits to Mario Konrad for providing the of the special attribute block). Credits to Mario Konrad for providing the
implementation. implementation.
* The curled arrow character for the backlink in footnotes is now followed * The curled arrow character for the backlink in footnotes is now followed
by a Unicode variant selector to prevent it from being displayed in emoji by a Unicode variant selector to prevent it from being displayed in emoji
form on iOS. form on iOS.
Note that in older browsers the variant selector is often interpreted as a Note that in older browsers the variant selector is often interpreted as a
separate character, making it visible after the arrow. So there is now a separate character, making it visible after the arrow. So there is now a
also a `fn_backlink_html` configuration variable that can be used to set also a `fn_backlink_html` configuration variable that can be used to set
the link text to something else. Credits to Dana for providing the the link text to something else. Credits to Dana for providing the
implementation. implementation.
* Fixed an issue in MarkdownExtra where long header lines followed by a * Fixed an issue in MarkdownExtra where long header lines followed by a
@ -235,13 +260,13 @@ PHP Markdown Lib 1.5.0 (1 Mar 2015)
* Added the ability start ordered lists with a number different from 1 and * Added the ability start ordered lists with a number different from 1 and
and have that reflected in the HTML output. This can be enabled with and have that reflected in the HTML output. This can be enabled with
the `enhanced_ordered_lists` configuration variable for the Markdown the `enhanced_ordered_lists` configuration variable for the Markdown
parser; it is enabled by default for Markdown Extra. parser; it is enabled by default for Markdown Extra.
Credits to Matt Gorle for providing the implementation. Credits to Matt Gorle for providing the implementation.
* Added the ability to insert custom HTML attributes with simple values * Added the ability to insert custom HTML attributes with simple values
everywhere an extra attribute block is allowed (links, images, headers). everywhere an extra attribute block is allowed (links, images, headers).
The value must be unquoted, cannot contains spaces and is limited to The value must be unquoted, cannot contains spaces and is limited to
alphanumeric ASCII characters. alphanumeric ASCII characters.
Credits to Peter Droogmans for providing the implementation. Credits to Peter Droogmans for providing the implementation.
@ -256,7 +281,7 @@ PHP Markdown Lib 1.5.0 (1 Mar 2015)
PHP Markdown Lib 1.4.1 (4 May 2014) PHP Markdown Lib 1.4.1 (4 May 2014)
* The HTML block parser will now treat `<figure>` as a block-level element * The HTML block parser will now treat `<figure>` as a block-level element
(as it should) and no longer wrap it in `<p>` or parse it's content with (as it should) and no longer wrap it in `<p>` or parse it's content with
the as Markdown syntax (although with Extra you can use `markdown="1"` the as Markdown syntax (although with Extra you can use `markdown="1"`
if you wish to use the Markdown syntax inside it). if you wish to use the Markdown syntax inside it).
@ -265,7 +290,7 @@ PHP Markdown Lib 1.4.1 (4 May 2014)
* Corrected an bug where some inline links with spaces in them would not * Corrected an bug where some inline links with spaces in them would not
work even when surounded with angle brackets: work even when surounded with angle brackets:
[link](<s p a c e s>) [link](<s p a c e s>)
* Fixed an issue where email addresses with quotes in them would not always * Fixed an issue where email addresses with quotes in them would not always
@ -281,9 +306,9 @@ PHP Markdown Lib 1.4.0 (29 Nov 2013)
* Added support for the `tel:` URL scheme in automatic links. * Added support for the `tel:` URL scheme in automatic links.
<tel:+1-111-111-1111> <tel:+1-111-111-1111>
It gets converted to this (note the `tel:` prefix becomes invisible): It gets converted to this (note the `tel:` prefix becomes invisible):
<a href="tel:+1-111-111-1111">+1-111-111-1111</a> <a href="tel:+1-111-111-1111">+1-111-111-1111</a>
* Added backtick fenced code blocks to MarkdownExtra, originally from * Added backtick fenced code blocks to MarkdownExtra, originally from
@ -294,16 +319,16 @@ PHP Markdown Lib 1.4.0 (29 Nov 2013)
you want to create a mockup parser object for unit testing. you want to create a mockup parser object for unit testing.
* For those of you who cannot use class autoloading, you can now * For those of you who cannot use class autoloading, you can now
include `Michelf/Markdown.inc.php` or `Michelf/MarkdownExtra.inc.php` (note include `Michelf/Markdown.inc.php` or `Michelf/MarkdownExtra.inc.php` (note
the `.inc.php` extension) to automatically include other files required the `.inc.php` extension) to automatically include other files required
by the parser. by the parser.
PHP Markdown Lib 1.3 (11 Apr 2013) PHP Markdown Lib 1.3 (11 Apr 2013)
This is the first release of PHP Markdown Lib. This package requires PHP This is the first release of PHP Markdown Lib. This package requires PHP
version 5.3 or later and is designed to work with PSR-0 autoloading and, version 5.3 or later and is designed to work with PSR-0 autoloading and,
optionally with Composer. Here is a list of the changes since optionally with Composer. Here is a list of the changes since
PHP Markdown Extra 1.2.6: PHP Markdown Extra 1.2.6:
* Plugin interface for WordPress and other systems is no longer present in * Plugin interface for WordPress and other systems is no longer present in
@ -323,22 +348,22 @@ PHP Markdown Extra 1.2.6:
* Added optional class and id attributes to images and links using the same * Added optional class and id attributes to images and links using the same
syntax as for headers: syntax as for headers:
[link](url){#id .class} [link](url){#id .class}
![img](url){#id .class} ![img](url){#id .class}
It work too for reference-style links and images. In this case you need It work too for reference-style links and images. In this case you need
to put those attributes at the reference definition: to put those attributes at the reference definition:
[link][linkref] or [linkref] [link][linkref] or [linkref]
![img][linkref] ![img][linkref]
[linkref]: url "optional title" {#id .class} [linkref]: url "optional title" {#id .class}
* Fixed a PHP notice message triggered when some table column separator * Fixed a PHP notice message triggered when some table column separator
markers are missing on the separator line below column headers. markers are missing on the separator line below column headers.
* Fixed a small mistake that could cause the parser to retain an invalid * Fixed a small mistake that could cause the parser to retain an invalid
state related to parsing links across multiple runs. This was never state related to parsing links across multiple runs. This was never
observed (that I know of), but it's still worth fixing. observed (that I know of), but it's still worth fixing.
@ -351,20 +376,20 @@ Copyright (c) 2004-2016 Michel Fortin
All rights reserved. All rights reserved.
Based on Markdown Based on Markdown
Copyright (c) 2003-2005 John Gruber Copyright (c) 2003-2005 John Gruber
<https://daringfireball.net/> <https://daringfireball.net/>
All rights reserved. All rights reserved.
Redistribution and use in source and binary forms, with or without Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are modification, are permitted provided that the following conditions are
met: met:
* Redistributions of source code must retain the above copyright * Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright * Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the documentation and/or other materials provided with the
distribution. distribution.
* Neither the name "Markdown" nor the names of its contributors may * Neither the name "Markdown" nor the names of its contributors may

View file

@ -4,13 +4,15 @@
// through the Markdown filter. You can adapt this sample code in any way // through the Markdown filter. You can adapt this sample code in any way
// you like. // you like.
// Install PSR-0-compatible class autoloader // Install PSR-4-compatible class autoloader
spl_autoload_register(function($class){ spl_autoload_register(function($class){
require preg_replace('{\\\\|_(?!.*\\\\)}', DIRECTORY_SEPARATOR, ltrim($class, '\\')).'.php'; require str_replace('\\', DIRECTORY_SEPARATOR, ltrim($class, '\\')).'.php';
}); });
// If using Composer, use this instead:
//require 'vendor/autoloader.php';
// Get Markdown class // Get Markdown class
use \Michelf\Markdown; use Michelf\Markdown;
// Read file and pass content through the Markdown parser // Read file and pass content through the Markdown parser
$text = file_get_contents('Readme.md'); $text = file_get_contents('Readme.md');

View file

@ -21,11 +21,6 @@
"php": ">=5.3.0" "php": ">=5.3.0"
}, },
"autoload": { "autoload": {
"psr-0": { "Michelf": "" } "psr-4": { "Michelf\\": "Michelf/" }
},
"extra": {
"branch-alias": {
"dev-lib": "1.4.x-dev"
}
} }
} }