-
Notifications
You must be signed in to change notification settings - Fork 141
/
MarkdownExtra.php
256 lines (226 loc) · 7.04 KB
/
MarkdownExtra.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
<?php
namespace cebe\markdown;
use cebe\markdown\block\TableTrait;
// work around https://github.com/facebook/hhvm/issues/1120
defined('ENT_HTML401') || define('ENT_HTML401', 0);
/**
* Markdown parser for the [markdown extra](http://michelf.ca/projects/php-markdown/extra/) flavor.
*
* @author Carsten Brandt <mail@cebe.cc>
* @license https://github.com/cebe/markdown/blob/master/LICENSE
* @link https://github.com/cebe/markdown#readme
*/
class MarkdownExtra extends Markdown
{
// include block element parsing using traits
use block\TableTrait;
use block\FencedCodeTrait;
// include inline element parsing using traits
// TODO
/**
* @var bool whether special attributes on code blocks should be applied on the `<pre>` element.
* The default behavior is to put them on the `<code>` element.
*/
public $codeAttributesOnPre = false;
/**
* @inheritDoc
*/
protected $escapeCharacters = [
// from Markdown
'\\', // backslash
'`', // backtick
'*', // asterisk
'_', // underscore
'{', '}', // curly braces
'[', ']', // square brackets
'(', ')', // parentheses
'#', // hash mark
'+', // plus sign
'-', // minus sign (hyphen)
'.', // dot
'!', // exclamation mark
'<', '>',
// added by MarkdownExtra
':', // colon
'|', // pipe
];
private $_specialAttributesRegex = '\{(([#\.][A-z0-9-_]+\s*)+)\}';
// TODO allow HTML intended 3 spaces
// TODO add markdown inside HTML blocks
// TODO implement definition lists
// TODO implement footnotes
// TODO implement Abbreviations
// block parsing
protected function identifyReference($line)
{
return ($line[0] === ' ' || $line[0] === '[') && preg_match('/^ {0,3}\[[^\[](.*?)\]:\s*([^\s]+?)(?:\s+[\'"](.+?)[\'"])?\s*('.$this->_specialAttributesRegex.')?\s*$/', $line);
}
/**
* Consume link references
*/
protected function consumeReference($lines, $current)
{
while (isset($lines[$current]) && preg_match('/^ {0,3}\[(.+?)\]:\s*(.+?)(?:\s+[\(\'"](.+?)[\)\'"])?\s*('.$this->_specialAttributesRegex.')?\s*$/', $lines[$current], $matches)) {
$label = strtolower($matches[1]);
$this->references[$label] = [
'url' => $this->replaceEscape($matches[2]),
];
if (isset($matches[3])) {
$this->references[$label]['title'] = $matches[3];
} else {
// title may be on the next line
if (isset($lines[$current + 1]) && preg_match('/^\s+[\(\'"](.+?)[\)\'"]\s*$/', $lines[$current + 1], $matches)) {
$this->references[$label]['title'] = $matches[1];
$current++;
}
}
if (isset($matches[5])) {
$this->references[$label]['attributes'] = $matches[5];
}
$current++;
}
return [false, --$current];
}
/**
* Consume lines for a fenced code block
*/
protected function consumeFencedCode($lines, $current)
{
// consume until ```
$block = [
'code',
];
$line = trim($lines[$current]);
if (($pos = strrpos($line, '`')) === false) {
$pos = strrpos($line, '~');
}
$fence = substr($line, 0, $pos + 1);
$block['attributes'] = substr($line, $pos);
$content = [];
for($i = $current + 1, $count = count($lines); $i < $count; $i++) {
if (($pos = strpos($line = $lines[$i], $fence)) === false || $pos > 3) {
$content[] = $line;
} else {
break;
}
}
$block['content'] = implode("\n", $content);
return [$block, $i];
}
protected function renderCode($block)
{
$attributes = $this->renderAttributes($block);
return ($this->codeAttributesOnPre ? "<pre$attributes><code>" : "<pre><code$attributes>")
. htmlspecialchars($block['content'] . "\n", ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8')
. "</code></pre>\n";
}
/**
* Renders a headline
*/
protected function renderHeadline($block)
{
foreach($block['content'] as $i => $element) {
if ($element[0] === 'specialAttributes') {
unset($block['content'][$i]);
$block['attributes'] = $element[1];
}
}
$tag = 'h' . $block['level'];
$attributes = $this->renderAttributes($block);
return "<$tag$attributes>" . rtrim($this->renderAbsy($block['content']), "# \t") . "</$tag>\n";
}
protected function renderAttributes($block)
{
$html = [];
if (isset($block['attributes'])) {
$attributes = preg_split('/\s+/', $block['attributes'], -1, PREG_SPLIT_NO_EMPTY);
foreach($attributes as $attribute) {
if ($attribute[0] === '#') {
$html['id'] = substr($attribute, 1);
} else {
$html['class'][] = substr($attribute, 1);
}
}
}
$result = '';
foreach($html as $attr => $value) {
if (is_array($value)) {
$value = trim(implode(' ', $value));
}
if (!empty($value)) {
$result .= " $attr=\"$value\"";
}
}
return $result;
}
// inline parsing
/**
* @marker {
*/
protected function parseSpecialAttributes($text)
{
if (preg_match("~$this->_specialAttributesRegex~", $text, $matches)) {
return [['specialAttributes', $matches[1]], strlen($matches[0])];
}
return [['text', '{'], 1];
}
protected function renderSpecialAttributes($block)
{
return '{' . $block[1] . '}';
}
protected function parseInline($text)
{
$elements = parent::parseInline($text);
// merge special attribute elements to links and images as they are not part of the final absy later
$relatedElement = null;
foreach($elements as $i => $element) {
if ($element[0] === 'link' || $element[0] === 'image') {
$relatedElement = $i;
} elseif ($element[0] === 'specialAttributes') {
if ($relatedElement !== null) {
$elements[$relatedElement]['attributes'] = $element[1];
unset($elements[$i]);
}
$relatedElement = null;
} else {
$relatedElement = null;
}
}
return $elements;
}
protected function renderLink($block)
{
if (isset($block['refkey'])) {
if (($ref = $this->lookupReference($block['refkey'])) !== false) {
$block = array_merge($block, $ref);
} else {
if (strncmp($block['orig'], '[', 1) === 0) {
return '[' . $this->renderAbsy($this->parseInline(substr($block['orig'], 1)));
}
return $block['orig'];
}
}
$attributes = $this->renderAttributes($block);
return '<a href="' . htmlspecialchars($block['url'], ENT_COMPAT | ENT_HTML401, 'UTF-8') . '"'
. (empty($block['title']) ? '' : ' title="' . htmlspecialchars($block['title'], ENT_COMPAT | ENT_HTML401 | ENT_SUBSTITUTE, 'UTF-8') . '"')
. $attributes . '>' . $this->renderAbsy($block['text']) . '</a>';
}
protected function renderImage($block)
{
if (isset($block['refkey'])) {
if (($ref = $this->lookupReference($block['refkey'])) !== false) {
$block = array_merge($block, $ref);
} else {
if (strncmp($block['orig'], '![', 2) === 0) {
return '![' . $this->renderAbsy($this->parseInline(substr($block['orig'], 2)));
}
return $block['orig'];
}
}
$attributes = $this->renderAttributes($block);
return '<img src="' . htmlspecialchars($block['url'], ENT_COMPAT | ENT_HTML401, 'UTF-8') . '"'
. ' alt="' . htmlspecialchars($block['text'], ENT_COMPAT | ENT_HTML401 | ENT_SUBSTITUTE, 'UTF-8') . '"'
. (empty($block['title']) ? '' : ' title="' . htmlspecialchars($block['title'], ENT_COMPAT | ENT_HTML401 | ENT_SUBSTITUTE, 'UTF-8') . '"')
. $attributes . ($this->html5 ? '>' : ' />');
}
}