-
Notifications
You must be signed in to change notification settings - Fork 6
/
Markdown.php
382 lines (338 loc) · 9.15 KB
/
Markdown.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
<?php
/**
* @copyright Copyright (c) 2014 Carsten Brandt
* @license https://github.com/cebe/markdown/blob/master/LICENSE
* @link https://github.com/cebe/markdown#readme
*/
namespace cebe\markdown\latex;
use cebe\markdown\block\CodeTrait;
use cebe\markdown\block\HeadlineTrait;
use cebe\markdown\block\ListTrait;
use cebe\markdown\block\QuoteTrait;
use cebe\markdown\block\RuleTrait;
use cebe\markdown\inline\CodeTrait as InlineCodeTrait;
use cebe\markdown\inline\EmphStrongTrait;
use cebe\markdown\inline\LinkTrait;
use MikeVanRiel\TextToLatex;
/**
* Markdown parser for the [initial markdown spec](http://daringfireball.net/projects/markdown/syntax).
*
* @author Carsten Brandt <mail@cebe.cc>
*/
class Markdown extends \cebe\markdown\Parser
{
// include block element parsing using traits
use CodeTrait;
use HeadlineTrait;
use ListTrait {
// Check Ul List before headline
identifyUl as protected identifyBUl;
consumeUl as protected consumeBUl;
}
use QuoteTrait;
use RuleTrait {
// Check Hr before checking lists
identifyHr as protected identifyAHr;
consumeHr as protected consumeAHr;
}
// include inline element parsing using traits
use InlineCodeTrait;
use EmphStrongTrait;
use LinkTrait;
/**
* @var string this string will be prefixed to all auto generated labels.
* This can be used to disambiguate labels when combining multiple markdown files into one document.
*/
public $labelPrefix = '';
const LINK_STYLE_FOOTNOTE = 'footnote';
const LINK_STYLE_HREF = 'href';
/**
* @var string link style defines how links are rendered in LaTeX, there are two different options:
*
* - `footnote` (default) - render all links with a footnote, which contains the full URL of the link. This is good for printing the PDF.
* - `href` - render all links with a hyperref, similar to HTML, the link target is not visible in this case.
*/
public $linkStyle = self::LINK_STYLE_FOOTNOTE;
/**
* @var array these are "escapeable" characters. When using one of these prefixed with a
* backslash, the character will be outputted without the backslash and is not interpreted
* as markdown.
*/
protected $escapeCharacters = [
'\\', // backslash
'`', // backtick
'*', // asterisk
'_', // underscore
'{', '}', // curly braces
'[', ']', // square brackets
'(', ')', // parentheses
'#', // hash mark
'+', // plus sign
'-', // minus sign (hyphen)
'.', // dot
'!', // exclamation mark
'<', '>',
];
/**
* @inheritDoc
*/
protected function prepare()
{
// reset references
$this->references = [];
}
/**
* Consume lines for a paragraph
*
* Allow headlines and code to break paragraphs
*/
protected function consumeParagraph($lines, $current)
{
// consume until newline
$content = [];
for ($i = $current, $count = count($lines); $i < $count; $i++) {
$line = $lines[$i];
if (!empty($line) && ltrim($line) !== '' &&
!($line[0] === "\t" || $line[0] === " " && strncmp($line, ' ', 4) === 0) &&
!$this->identifyHeadline($line, $lines, $i))
{
$content[] = $line;
} else {
break;
}
}
$block = [
'paragraph',
'content' => $this->parseInline(implode("\n", $content)),
];
return [$block, --$i];
}
// rendering adjusted for LaTeX output
/**
* @inheritdoc
*/
protected function renderParagraph($block)
{
return $this->renderAbsy($block['content']) . "\n\n";
}
/**
* @inheritdoc
*/
protected function renderQuote($block)
{
return '\begin{quote}' . $this->renderAbsy($block['content']) . "\\end{quote}\n";
}
/**
* @inheritdoc
*/
protected function renderCode($block)
{
$language = isset($block['language']) ? "\\lstset{language={$block['language']}}" : '\lstset{language={}}';
$content = $block['content'];
// replace No-Break Space characters in code block, which do not render in LaTeX
$content = preg_replace("/[\x{00a0}\x{202f}]/u", ' ', $content);
return "$language\\begin{lstlisting}\n{$content}\n\\end{lstlisting}\n";
}
/**
* @inheritdoc
*/
protected function renderList($block)
{
$type = ($block['list'] === 'ol') ? 'enumerate' : 'itemize';
$output = "\\begin{{$type}}\n";
foreach ($block['items'] as $item => $itemLines) {
$output .= '\item ' . $this->renderAbsy($itemLines). "\n";
}
return "$output\\end{{$type}}\n";
}
/**
* @inheritdoc
*/
protected function renderHeadline($block)
{
$content = $this->renderAbsy($block['content']);
switch($block['level']) {
case 1: return "\\section{{$content}}\n";
case 2: return "\\subsection{{$content}}\n";
case 3: return "\\subsubsection{{$content}}\n";
default: return "\\paragraph{{$content}}\n";
}
}
/**
* @inheritdoc
*/
protected function renderHr($block)
{
return "\n\\noindent\\rule{\\textwidth}{0.4pt}\n";
}
/**
* @inheritdoc
*/
protected function renderLink($block)
{
if (isset($block['refkey'])) {
if (($ref = $this->lookupReference($block['refkey'])) !== false) {
$block = array_merge($block, $ref);
} else {
return $block['orig'];
}
}
$url = $block['url'];
$text = $this->renderAbsy($block['text']);
if (strpos($url, '://') === false) {
// consider all non absolute links as relative in the document
// $title is ignored in this case.
if (isset($url[0]) && $url[0] === '#') {
$url = $this->labelPrefix . $url;
}
return '\hyperref['.str_replace('#', '::', $url).']{' . $text . '}';
} else {
if ($this->linkStyle === self::LINK_STYLE_HREF) {
return '\href{' . $this->escapeUrl($url) . '}{' . $text . '}';
}
return $text . '\\footnote{' . (empty($block['title']) ? '' : $this->escapeLatex($block['title']) . ': ') . '\url{' . $this->escapeUrl($url) . '}}';
}
}
/**
* @inheritdoc
*/
protected function renderImage($block)
{
if (isset($block['refkey'])) {
if (($ref = $this->lookupReference($block['refkey'])) !== false) {
$block = array_merge($block, $ref);
} else {
return $block['orig'];
}
}
// TODO create figure with caption with title
$replaces = [
'%' => '\\%',
'{' => '\\%7B',
'}' => '\\%7D',
'\\' => '\\\\',
'#' => '\\#',
'$' => '\\%24',
];
$url = str_replace(array_keys($replaces), array_values($replaces), $block['url']);
return "\\noindent\\includegraphics[width=\\textwidth]{{$url}}";
}
/**
* Parses <a name="..."></a> tags as reference labels
*/
private function parseInlineHtml($text)
{
if (strpos($text, '>') !== false) {
// convert a name markers to \labels
if (preg_match('~^<((a|span)) (name|id)="(.*?)">.*?</\1>~i', $text, $matches)) {
return [
['label', 'name' => str_replace('#', '::', $this->labelPrefix . $matches[4])],
strlen($matches[0])
];
}
}
return [['text', '<'], 1];
}
/**
* renders a reference label
*/
protected function renderLabel($block)
{
return "\\label{{$block['name']}}";
}
/**
* @inheritdoc
*/
protected function renderEmail($block)
{
$email = $this->escapeUrl($block[1]);
return "\\href{mailto:{$email}}{{$email}}";
}
/**
* @inheritdoc
*/
protected function renderUrl($block)
{
return '\url{' . $this->escapeUrl($block[1]) . '}';
}
/**
* @inheritdoc
*/
protected function renderInlineCode($block)
{
// replace No-Break Space characters in code block, which do not render in LaTeX
$content = preg_replace("/[\x{00a0}\x{202f}]/u", ' ', $block[1]);
if (strpos($content, '|') !== false) {
return '\\lstinline`' . str_replace("\n", ' ', $content) . '`'; // TODO make this more robust against code containing backticks
} else {
return '\\lstinline|' . str_replace("\n", ' ', $content) . '|';
}
}
/**
* @inheritdoc
*/
protected function renderStrong($block)
{
return '\textbf{' . $this->renderAbsy($block[1]) . '}';
}
/**
* @inheritdoc
*/
protected function renderEmph($block)
{
return '\textit{' . $this->renderAbsy($block[1]) . '}';
}
/**
* Parses escaped special characters.
* This allow a backslash to be interpreted as LaTeX
* @marker \
*/
protected function parseEscape($text)
{
if (isset($text[1]) && in_array($text[1], $this->escapeCharacters)) {
if ($text[1] === '\\') {
return [['backslash'], 2];
}
return [['text', $text[1]], 2];
}
return [['text', $text[0]], 1];
}
protected function renderBackslash()
{
return '\\';
}
private $_escaper;
/**
* Escape special characters in URLs
*/
protected function escapeUrl($string)
{
return str_replace('%', '\\%', $this->escapeLatex($string));
}
/**
* Escape special LaTeX characters
*/
protected function escapeLatex($string)
{
if ($this->_escaper === null) {
$this->_escaper = new TextToLatex();
}
return $this->_escaper->convert($string);
}
/**
* @inheritdocs
*
* Parses a newline indicated by two spaces on the end of a markdown line.
*/
protected function renderText($text)
{
$output = str_replace(" \n", "\\\\\n", $this->escapeLatex($text[1]));
// support No-Break Space in LaTeX
$output = preg_replace("/\x{00a0}/u", '~', $output);
// support Narrow No-Break Space spaces in LaTeX
// http://unicode-table.com/en/202F/
// http://tex.stackexchange.com/questions/76132/how-to-typeset-a-small-non-breaking-space
$output = preg_replace("/\x{202f}/u", '\nobreak\hspace{.16667em plus .08333em}', $output);
return $output;
}
}