|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* |
|
6
|
|
|
* This file is part of the league/commonmark package. |
|
7
|
|
|
* |
|
8
|
|
|
* (c) Colin O'Dell <[email protected]> |
|
9
|
|
|
* |
|
10
|
|
|
* Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) |
|
11
|
|
|
* - (c) John MacFarlane |
|
12
|
|
|
* |
|
13
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
14
|
|
|
* file that was distributed with this source code. |
|
15
|
|
|
*/ |
|
16
|
|
|
|
|
17
|
|
|
namespace League\CommonMark\Extension\CommonMark\Parser\Inline; |
|
18
|
|
|
|
|
19
|
|
|
use League\CommonMark\Extension\CommonMark\Node\Inline\Code; |
|
20
|
|
|
use League\CommonMark\Node\Inline\Text; |
|
21
|
|
|
use League\CommonMark\Parser\Inline\InlineParserInterface; |
|
22
|
|
|
use League\CommonMark\Parser\Inline\InlineParserMatch; |
|
23
|
|
|
use League\CommonMark\Parser\InlineParserContext; |
|
24
|
|
|
|
|
25
|
|
|
final class BacktickParser implements InlineParserInterface |
|
26
|
|
|
{ |
|
27
|
2874 |
|
public function getMatchDefinition(): InlineParserMatch |
|
28
|
|
|
{ |
|
29
|
2874 |
|
return InlineParserMatch::regex('`+'); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
150 |
|
public function parse(string $match, InlineParserContext $inlineContext): bool |
|
33
|
|
|
{ |
|
34
|
150 |
|
$ticks = $match; |
|
35
|
150 |
|
$cursor = $inlineContext->getCursor(); |
|
36
|
150 |
|
$cursor->advanceBy(\mb_strlen($ticks)); |
|
37
|
|
|
|
|
38
|
150 |
|
$currentPosition = $cursor->getPosition(); |
|
39
|
150 |
|
$previousState = $cursor->saveState(); |
|
40
|
|
|
|
|
41
|
150 |
|
while ($matchingTicks = $cursor->match('/`+/m')) { |
|
42
|
129 |
|
if ($matchingTicks !== $ticks) { |
|
43
|
24 |
|
continue; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
126 |
|
$code = $cursor->getSubstring($currentPosition, $cursor->getPosition() - $currentPosition - \strlen($ticks)); |
|
47
|
|
|
|
|
48
|
126 |
|
$c = \preg_replace('/\n/m', ' ', $code) ?? ''; |
|
49
|
|
|
|
|
50
|
|
|
if ( |
|
51
|
126 |
|
$c !== '' && |
|
52
|
126 |
|
$c[0] === ' ' && |
|
53
|
126 |
|
\substr($c, -1, 1) === ' ' && |
|
54
|
126 |
|
\preg_match('/[^ ]/', $c) |
|
55
|
|
|
) { |
|
56
|
27 |
|
$c = \substr($c, 1, -1); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
126 |
|
$inlineContext->getContainer()->appendChild(new Code($c)); |
|
60
|
|
|
|
|
61
|
126 |
|
return true; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
// If we got here, we didn't match a closing backtick sequence |
|
65
|
42 |
|
$cursor->restoreState($previousState); |
|
66
|
42 |
|
$inlineContext->getContainer()->appendChild(new Text($ticks)); |
|
67
|
|
|
|
|
68
|
42 |
|
return true; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|