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