xref: /dokuwiki/inc/Parsing/ParserMode/GfmCode.php (revision 1e28e406b358f79221c515b2a56520d5dbbfb6c8)
1b1c59bedSAndreas Gohr<?php
2b1c59bedSAndreas Gohr
3b1c59bedSAndreas Gohrnamespace dokuwiki\Parsing\ParserMode;
4b1c59bedSAndreas Gohr
5b1c59bedSAndreas Gohruse dokuwiki\Parsing\Handler;
6*1e28e406SAndreas Gohruse dokuwiki\Parsing\Helpers\Code as CodeHelper;
7b1c59bedSAndreas Gohr
8b1c59bedSAndreas Gohr/**
9b1c59bedSAndreas Gohr * GFM fenced code block with backtick fences: ```...```
10b1c59bedSAndreas Gohr *
11b1c59bedSAndreas Gohr * Emits the same `code` handler instruction DokuWiki's `<code>` mode
12b1c59bedSAndreas Gohr * emits, so renderers, indexing, and syntax highlighting reuse the
13b1c59bedSAndreas Gohr * existing pipeline.
14b1c59bedSAndreas Gohr *
15b1c59bedSAndreas Gohr * The info string after the opening fence accepts DokuWiki's full
16b1c59bedSAndreas Gohr * code-tag attribute vocabulary — language, optional filename, and
17b1c59bedSAndreas Gohr * optional [key=value,...] highlight options — parsed via
18*1e28e406SAndreas Gohr * Helpers\Code::parseAttributes. Markdown authors pasting to GitHub
19b1c59bedSAndreas Gohr * will see the extras render as part of the language class; the
20b1c59bedSAndreas Gohr * divergence is intentional, for feature parity with DokuWiki's
21b1c59bedSAndreas Gohr * <code>...</code> blocks.
22b1c59bedSAndreas Gohr *
23b1c59bedSAndreas Gohr * Column-0 fences only (no indent tolerance, no body dedent). The close
24b1c59bedSAndreas Gohr * fence is any run of 3+ fence chars at column 0 with only trailing
25b1c59bedSAndreas Gohr * whitespace on the line — the opener's length is not paired with the
26b1c59bedSAndreas Gohr * closer's, because ParallelRegex does not support backreferences.
27b1c59bedSAndreas Gohr *
28b1c59bedSAndreas Gohr * Unclosed fences stay literal text. GFM's spec says an unclosed fence
29b1c59bedSAndreas Gohr * runs to end of input (and any enclosing container's end), but that
30b1c59bedSAndreas Gohr * rule is part of CommonMark's two-pass block-then-inline parser where
31b1c59bedSAndreas Gohr * "any container boundary closes" is the uniform termination rule. Our
32b1c59bedSAndreas Gohr * single-pass regex lexer has no notion of container boundaries, so the
33b1c59bedSAndreas Gohr * best we could do is "close at EOF" — a partial implementation that
34b1c59bedSAndreas Gohr * already leaks (spec example 98, fence inside a blockquote, stays red
35b1c59bedSAndreas Gohr * because we can't close at the blockquote boundary). Doing a degraded
36b1c59bedSAndreas Gohr * version of the rule just moves the broken edge case somewhere less
37b1c59bedSAndreas Gohr * obvious.
38b1c59bedSAndreas Gohr *
39b1c59bedSAndreas Gohr * Requiring a closer is also consistent with every other inline GFM
40b1c59bedSAndreas Gohr * mode in this codebase (all of which use entry-pattern lookaheads to
41b1c59bedSAndreas Gohr * verify a matching closer exists) and with DokuWiki's own <code> tag
42b1c59bedSAndreas Gohr * parsing (<code\b(?=.*</code>)>). And it has a safer failure mode: a
43b1c59bedSAndreas Gohr * stray ``` at the top of a document stays as literal text rather than
44b1c59bedSAndreas Gohr * swallowing everything below it into a code block. Spec examples 96
45b1c59bedSAndreas Gohr * and 97 are in skip.php with this rationale.
46b1c59bedSAndreas Gohr *
47b1c59bedSAndreas Gohr * @see GfmFile
48b1c59bedSAndreas Gohr */
49b1c59bedSAndreas Gohrclass GfmCode extends AbstractMode
50b1c59bedSAndreas Gohr{
51b1c59bedSAndreas Gohr    /** @var string The call type used in addCall ('code' or 'file') */
52b1c59bedSAndreas Gohr    protected $type = 'code';
53b1c59bedSAndreas Gohr
54b1c59bedSAndreas Gohr    /** @var string The fence character (`` ` `` or `~`). */
55b1c59bedSAndreas Gohr    protected $fenceChar = '`';
56b1c59bedSAndreas Gohr
57b1c59bedSAndreas Gohr    /**
58b1c59bedSAndreas Gohr     * Info-string character class. Backtick fences forbid backticks in
59b1c59bedSAndreas Gohr     * the info string (spec example 115); tilde fences allow anything
60b1c59bedSAndreas Gohr     * except newline (spec example 116).
61b1c59bedSAndreas Gohr     */
62b1c59bedSAndreas Gohr    protected $infoClass = '[^\n`]*';
63b1c59bedSAndreas Gohr
64b1c59bedSAndreas Gohr    public function __construct()
65b1c59bedSAndreas Gohr    {
66b1c59bedSAndreas Gohr        $this->allowedModes = [];
67b1c59bedSAndreas Gohr    }
68b1c59bedSAndreas Gohr
69b1c59bedSAndreas Gohr    /** @inheritdoc */
70b1c59bedSAndreas Gohr    public function getSort()
71b1c59bedSAndreas Gohr    {
72b1c59bedSAndreas Gohr        return 200;
73b1c59bedSAndreas Gohr    }
74b1c59bedSAndreas Gohr
75b1c59bedSAndreas Gohr    /** The lexer state / mode name. Subclasses override for tildes. */
76b1c59bedSAndreas Gohr    protected function getModeName(): string
77b1c59bedSAndreas Gohr    {
78b1c59bedSAndreas Gohr        return 'gfm_code';
79b1c59bedSAndreas Gohr    }
80b1c59bedSAndreas Gohr
81b1c59bedSAndreas Gohr    /** @inheritdoc */
82b1c59bedSAndreas Gohr    public function connectTo($mode)
83b1c59bedSAndreas Gohr    {
84b1c59bedSAndreas Gohr        // Entry pattern breakdown (F = fence char, INFO = info-string class):
85b1c59bedSAndreas Gohr        //   \n                      — line start (Parser prepends a newline)
86b1c59bedSAndreas Gohr        //   F{3,}                   — opener: 3+ fence chars at column 0
87b1c59bedSAndreas Gohr        //   INFO                    — info-string (language etc.)
88b1c59bedSAndreas Gohr        //   (?=\n)                  — opener line must end at a newline;
89b1c59bedSAndreas Gohr        //                             without this anchor `` ``` aa ``` ``
90b1c59bedSAndreas Gohr        //                             on one line would parse as a fence
91b1c59bedSAndreas Gohr        //   (?:(?!CLOSE).)*         — body: any char (DOTALL) that isn't
92b1c59bedSAndreas Gohr        //                             the start of a close-fence line
93b1c59bedSAndreas Gohr        //   CLOSE = \nF{3,}[ \t]*(?=\n)  — close fence, required.
94b1c59bedSAndreas Gohr        //                             No `\z` fallback: unclosed fences stay
95b1c59bedSAndreas Gohr        //                             literal (see class docblock)
96b1c59bedSAndreas Gohr        $close = '\n' . $this->fenceChar . '{3,}[ \t]*(?=\n)';
97b1c59bedSAndreas Gohr        $this->Lexer->addSpecialPattern(
98b1c59bedSAndreas Gohr            '\n' . $this->fenceChar . '{3,}' . $this->infoClass . '(?=\n)'
99b1c59bedSAndreas Gohr                . '(?:(?!' . $close . ').)*' . $close,
100b1c59bedSAndreas Gohr            $mode,
101b1c59bedSAndreas Gohr            $this->getModeName()
102b1c59bedSAndreas Gohr        );
103b1c59bedSAndreas Gohr    }
104b1c59bedSAndreas Gohr
105b1c59bedSAndreas Gohr    /** @inheritdoc */
106b1c59bedSAndreas Gohr    public function handle($match, $state, $pos, Handler $handler)
107b1c59bedSAndreas Gohr    {
108b1c59bedSAndreas Gohr        $c = $this->fenceChar;
109b1c59bedSAndreas Gohr
110b1c59bedSAndreas Gohr        // Shed the pattern's leading \n, the opener fence run, and the
111b1c59bedSAndreas Gohr        // close-fence run with its trailing whitespace.
112b1c59bedSAndreas Gohr        $text = rtrim(ltrim(substr($match, 1), $c), " \t" . $c);
113b1c59bedSAndreas Gohr
114b1c59bedSAndreas Gohr        // The opener ended at a newline (required by the pattern's `(?=\n)`
115b1c59bedSAndreas Gohr        // anchor), so an explode split always has two parts.
116b1c59bedSAndreas Gohr        [$info, $body] = explode("\n", $text, 2);
117b1c59bedSAndreas Gohr
118*1e28e406SAndreas Gohr        [$language, $filename, $options] = CodeHelper::parseAttributes($info);
119b1c59bedSAndreas Gohr
120b1c59bedSAndreas Gohr        $param = [$body, $language, $filename];
121b1c59bedSAndreas Gohr        if ($options !== null) $param[] = $options;
122b1c59bedSAndreas Gohr        $handler->addCall($this->type, $param, $pos);
123b1c59bedSAndreas Gohr        return true;
124b1c59bedSAndreas Gohr    }
125b1c59bedSAndreas Gohr}
126