environment = $environment; } public function getMatchDefinition(): InlineParserMatch { return InlineParserMatch::string('*'); } public function parse(InlineParserContext $inlineContext): bool { $processor = $this->environment->getDelimiterProcessors()->getDelimiterProcessor('*'); if ($processor === null) { return false; } $cursor = $inlineContext->getCursor(); $charBefore = $cursor->peek(-1) ?? "\n"; $count = 0; while ($cursor->peek($count) === '*') { $count++; } if ($count < $processor->getMinLength()) { return false; } $cursor->advanceBy($count); $charAfter = $cursor->getCurrentCharacter() ?? "\n"; [$canOpen, $canClose] = self::flanking($charBefore, $charAfter); $canOpen = $canOpen && $processor->getOpeningCharacter() === '*'; $canClose = $canClose && $processor->getClosingCharacter() === '*'; if (! $canOpen && ! $canClose) { $inlineContext->getContainer()->appendChild(new Text(str_repeat('*', $count))); return true; } $node = new Text(str_repeat('*', $count), ['delim' => true]); $inlineContext->getContainer()->appendChild($node); $inlineContext->getDelimiterStack()->push( new Delimiter('*', $count, $node, $canOpen, $canClose, $cursor->getPosition()) ); return true; } /** * 左贴合(能开)与右贴合(能闭)。与 CommonMark 的区别只在各自第二个条件里多了「或者另一侧是 CJK 字符」。 * * @return array{0: bool, 1: bool} */ public static function flanking(string $before, string $after): array { $afterSpace = preg_match(RegexHelper::REGEX_UNICODE_WHITESPACE_CHAR, $after) === 1; $afterPunct = preg_match(RegexHelper::REGEX_PUNCTUATION, $after) === 1; $beforeSpace = preg_match(RegexHelper::REGEX_UNICODE_WHITESPACE_CHAR, $before) === 1; $beforePunct = preg_match(RegexHelper::REGEX_PUNCTUATION, $before) === 1; $beforeCjk = preg_match(self::CJK, $before) === 1; $afterCjk = preg_match(self::CJK, $after) === 1; $left = ! $afterSpace && (! $afterPunct || $beforeSpace || $beforePunct || $beforeCjk); $right = ! $beforeSpace && (! $beforePunct || $afterSpace || $afterPunct || $afterCjk); return [$left, $right]; } }