forked from cebe/markdown
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMarkdownExtra.php
More file actions
273 lines (234 loc) · 7.69 KB
/
MarkdownExtra.php
File metadata and controls
273 lines (234 loc) · 7.69 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
<?php
namespace cebe\markdown;
use cebe\markdown\block\TableTrait;
/**
* 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
{
use TableTrait;
/**
* @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
protected function inlineMarkers()
{
return parent::inlineMarkers() + [
'|' => 'parseTd',
];
}
// block parsing
/**
* @inheritDoc
*/
protected function identifyLine($lines, $current)
{
if (isset($lines[$current]) && (strncmp($lines[$current], '~~~', 3) === 0 || strncmp($lines[$current], '```', 3) === 0)) {
return 'fencedCode';
}
if (preg_match('/^ {0,3}\[(.+?)\]:\s*([^\s]+?)(?:\s+[\'"](.+?)[\'"])?\s*('.$this->_specialAttributesRegex.')?\s*$/', $lines[$current])) {
return 'reference';
}
if ($this->identifyTable($lines, $current)) {
return 'table';
}
return parent::identifyLine($lines, $current);
}
/**
* Consume lines for a headline
*/
protected function consumeHeadline($lines, $current)
{
list($block, $nextLine) = parent::consumeHeadline($lines, $current);
if (($pos = strpos($block['content'], '{')) !== false && preg_match("~$this->_specialAttributesRegex~", $block['content'], $matches)) {
$block['content'] = substr($block['content'], 0, $pos);
$block['content'] = trim($block['content'], "# \t");
$block['attributes'] = $matches[1];
}
return [$block, $nextLine];
}
/**
* Consume lines for a fenced code block
*/
protected function consumeFencedCode($lines, $current)
{
// consume until ```
$block = [
'type' => 'code',
'content' => [],
];
$line = rtrim($lines[$current]);
if (($pos = strrpos($line, '`')) === false) {
$pos = strrpos($line, '~');
}
$fence = substr($line, 0, $pos + 1);
$block['attributes'] = substr($line, $pos);
for($i = $current + 1, $count = count($lines); $i < $count; $i++) {
if (rtrim($line = $lines[$i]) !== $fence) {
$block['content'][] = $line;
} else {
break;
}
}
return [$block, $i];
}
/**
* 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' => $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];
}
protected function renderCode($block)
{
$attributes = $this->renderAttributes($block);
return ($this->codeAttributesOnPre ? "<pre$attributes><code>" : "<pre><code$attributes>")
. htmlspecialchars(implode("\n", $block['content']) . "\n", ENT_NOQUOTES, 'UTF-8')
. '</code></pre>';
}
protected function renderHeadline($block)
{
$tag = 'h' . $block['level'];
$attributes = $this->renderAttributes($block);
return "<$tag$attributes>" . $this->parseInline($block['content']) . "</$tag>";
}
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
/**
* Parses a link indicated by `[`.
*/
protected function parseLink($markdown)
{
if (!in_array('parseLink', array_slice($this->context, 1)) && ($parts = $this->parseLinkOrImage($markdown)) !== false) {
list($text, $url, $title, $offset, $refKey) = $parts;
$attributes = '';
if (isset($this->references[$refKey])) {
$attributes = $this->renderAttributes($this->references[$refKey]);
}
if (isset($markdown[$offset]) && $markdown[$offset] === '{' && preg_match("~^$this->_specialAttributesRegex~", substr($markdown, $offset), $matches)) {
$attributes = $this->renderAttributes(['attributes' => $matches[1]]);
$offset += strlen($matches[0]);
}
$title = strtr($title, array("'"=>'','"'=>''));
preg_match_all('/[A-z0-9]+=[A-z0-9:_-\s]+/', $title, $linkAttributes);
if(count($linkAttributes[0])){
$_titleReplacements = array('"'=>'',"'"=>'',','=>'');
foreach($linkAttributes[0] as $_attrib) {
list($_prop, $_val) = explode('=', $_attrib);
if($_prop == 'title'){
$title = $_val;
} else {
$attributes .= ' '.$_prop.'="'.$_val.'"';
$_titleReplacements[$_attrib] = '';
}
}
$title = strtr($title, $_titleReplacements);
}
$link = '<a href="' . htmlspecialchars($url, ENT_COMPAT | ENT_HTML401, 'UTF-8') . '"'
. (empty($title) ? '' : ' title="' . htmlspecialchars($title, ENT_COMPAT | ENT_HTML401, 'UTF-8') . '"')
. $attributes . '>' . $this->parseInline($text) . '</a>';
return [$link, $offset];
} else {
return parent::parseLink($markdown);
}
}
/**
* Parses an image indicated by `![`.
*/
protected function parseImage($markdown)
{
if (($parts = $this->parseLinkOrImage(substr($markdown, 1))) !== false) {
list($text, $url, $title, $offset, $refKey) = $parts;
$attributes = '';
if (isset($this->references[$refKey])) {
$attributes = $this->renderAttributes($this->references[$refKey]);
}
if (isset($markdown[$offset + 1]) && $markdown[$offset + 1] === '{' && preg_match("~^$this->_specialAttributesRegex~", substr($markdown, $offset + 1), $matches)) {
$attributes = $this->renderAttributes(['attributes' => $matches[1]]);
$offset += strlen($matches[0]);
}
$image = '<img src="' . htmlspecialchars($url, ENT_COMPAT | ENT_HTML401, 'UTF-8') . '"'
. ' alt="' . htmlspecialchars($text, ENT_COMPAT | ENT_HTML401, 'UTF-8') . '"'
. (empty($title) ? '' : ' title="' . htmlspecialchars($title, ENT_COMPAT | ENT_HTML401, 'UTF-8') . '"')
. $attributes . ($this->html5 ? '>' : ' />');
return [$image, $offset + 1];
} else {
return parent::parseImage($markdown);
}
}
}