xref: /dokuwiki/inc/Parsing/ParserMode/GfmQuote.php (revision 95f694202286c1add4c442936a5caa38db0dd603)
1<?php
2
3namespace dokuwiki\Parsing\ParserMode;
4
5use dokuwiki\Parsing\Handler;
6use dokuwiki\Parsing\Handler\Nest;
7use dokuwiki\Parsing\ModeRegistry;
8
9/**
10 * Block quotes — single mode covering both DokuWiki and GFM dialects.
11 *
12 * Captures one or more consecutive column-0 `>`-prefixed lines via
13 * addSpecialPattern. Nesting is resolved at this level by counting
14 * leading `>` markers per line and emitting `quote_open` / `quote_close`
15 * pairs around per-depth body segments — sub-parser recursion is
16 * deliberately not used because each sub-parser invocation needs its
17 * own Handler instance and threading the nesting through the registry
18 * pool would only buy us back what depth-walking already provides.
19 *
20 * Each per-depth segment's body is sub-parsed via
21 * ModeRegistry::withSubParser() so block content (lists, fenced code,
22 * tables) works inside the body. The sub-parser excludes BASEONLY so
23 * headers do not fire inside a blockquote — same rationale as
24 * GfmListblock: header instructions drive TOC entries, section-edit
25 * anchors, and section_open/section_close ranges that don't compose
26 * with a `<blockquote>` container. The sub-parser also excludes
27 * gfm_quote itself; nesting is handled at this level, not via
28 * sub-parser recursion. When a list inside a quote re-fires gfm_quote
29 * during the list-item sub-parse, the registry's pool hands the
30 * inner call a different parser instance for the same exclusion key,
31 * so the outer parse state is not corrupted.
32 *
33 * Lazy continuation is deliberately not supported. Every quote line
34 * must begin with `>` at column 0; the first non-`>` line ends the
35 * quote. This matches the policy GfmListblock enforces for lists —
36 * markers required on every line. Trade-off: a few CommonMark
37 * blockquote spec examples that rely on lazy continuation stay red,
38 * but the parser stays single-pass and predictable.
39 *
40 * Rendering shape depends on syntax preference. Under MD-preferred
41 * (`md`, `md+dw`) the sub-parser's paragraph wrapping survives:
42 * a quote with one paragraph emits `<blockquote><p>...</p></blockquote>`.
43 * Under DW-preferred (`dw`, `dw+md`) a post-pass flattens
44 * paragraph wrapping into explicit `linebreak` calls so existing DW
45 * pages keep their `<blockquote>...line1<br/>line2...</blockquote>`
46 * rendering. Same `quote_open` / `quote_close` instructions in both
47 * modes — no renderer change required.
48 */
49class GfmQuote extends AbstractMode
50{
51    /** @inheritdoc */
52    public function getSort()
53    {
54        return 220;
55    }
56
57    /** @inheritdoc */
58    public function preConnect()
59    {
60        ModeRegistry::getInstance()->registerBlockEolMode('gfm_quote');
61    }
62
63    /**
64     * Capture an entire blockquote in one match.
65     *
66     * The pattern requires a column-0 `>` on every line. The first
67     * non-`>` line ends the capture (no lazy continuation). A bare `>`
68     * with no body is valid — it represents an empty paragraph break
69     * inside the quote (spec 240) or an empty quote (spec 239).
70     *
71     * @param string $mode the lexer state name to wire the pattern into
72     */
73    public function connectTo($mode)
74    {
75        $this->Lexer->addSpecialPattern('\n>[^\n]*(?:\n>[^\n]*)*', $mode, 'gfm_quote');
76    }
77
78    /** @inheritdoc */
79    public function handle($match, $state, $pos, Handler $handler)
80    {
81        $stripped = ltrim($match, "\n");
82        $cursor = strlen($match) - strlen($stripped);
83
84        $parsed = [];
85        foreach (explode("\n", $stripped) as $line) {
86            $parsed[] = $this->parseLine($line, $pos + $cursor);
87            $cursor += strlen($line) + 1; // +1 for the \n consumed by explode
88        }
89
90        $currentDepth = 0;
91        $buffer = [];
92        $segmentStart = $pos;
93
94        foreach ($parsed as $p) {
95            if ($p['depth'] !== $currentDepth) {
96                if ($buffer) {
97                    $this->emitBody($handler, $segmentStart, implode("\n", $buffer));
98                    $buffer = [];
99                }
100                while ($currentDepth < $p['depth']) {
101                    $handler->addCall('quote_open', [], $pos);
102                    $currentDepth++;
103                }
104                while ($currentDepth > $p['depth']) {
105                    $handler->addCall('quote_close', [], $pos);
106                    $currentDepth--;
107                }
108            }
109            if (!$buffer) $segmentStart = $p['offset'];
110            $buffer[] = $p['content'];
111        }
112
113        if ($buffer) {
114            $this->emitBody($handler, $segmentStart, implode("\n", $buffer));
115        }
116        while ($currentDepth > 0) {
117            $handler->addCall('quote_close', [], $pos + strlen($match));
118            $currentDepth--;
119        }
120
121        return true;
122    }
123
124    /**
125     * Parse one captured line into depth, content, and content offset.
126     *
127     * Counts leading `>` characters (each consuming one optional
128     * trailing space) to compute the depth. The remainder of the line
129     * is the content for that depth. The returned `offset` is the
130     * absolute byte position of the content's first character within
131     * the source (`$lineStart` plus the length of the consumed marker
132     * prefix).
133     *
134     * `> > foo` → depth 2, content `foo`. `>>foo` → depth 2, content
135     * `foo`. `>` alone → depth 1, content empty.
136     *
137     * @param string $line one line of captured blockquote text, with
138     *     no surrounding newlines
139     * @param int $lineStart absolute byte offset of the line's first
140     *     character within the source
141     * @return array{depth: int, content: string, offset: int}
142     */
143    protected function parseLine(string $line, int $lineStart): array
144    {
145        $depth = 0;
146        $i = 0;
147        $len = strlen($line);
148        while ($i < $len && $line[$i] === '>') {
149            $depth++;
150            $i++;
151            if ($i < $len && $line[$i] === ' ') $i++;
152        }
153        return [
154            'depth'   => $depth,
155            'content' => substr($line, $i),
156            'offset'  => $lineStart + $i,
157        ];
158    }
159
160    /**
161     * Sub-parse a body segment and emit its calls inside a Nest.
162     *
163     * Drops `document_start` / `document_end` from the sub-parser
164     * output. Under DW-preferred syntax, also runs the linebreak
165     * post-pass so paragraph wrapping is flattened into explicit
166     * `linebreak` calls. Empty bodies emit nothing.
167     *
168     * `$segmentStart` is the absolute byte offset of the segment's
169     * first content character within the source. Sub-handler positions
170     * are relative to the sub-parsed body, which begins at the first
171     * line of the segment, so adding `$segmentStart` to each
172     * sub-handler position lands the call back on the right byte in
173     * the source. Lines after the first drift slightly because the
174     * `>[ ]?` prefix between source lines collapses to a single `\n`
175     * in the sub-parsed body — drift is bounded by the prefix length
176     * (one or two bytes per line skipped).
177     *
178     * @param Handler $handler outer handler to emit calls on
179     * @param int $segmentStart absolute byte offset of the segment's
180     *     first content character within the source
181     * @param string $body concatenated content of the buffered lines,
182     *     separated by `\n`
183     */
184    protected function emitBody(Handler $handler, int $segmentStart, string $body): void
185    {
186        $registry = ModeRegistry::getInstance();
187        $calls = $registry->withSubParser(
188            [ModeRegistry::CATEGORY_BASEONLY],
189            ['gfm_quote'],
190            static function ($subParser) use ($body) {
191                $subParser->getHandler()->reset();
192                $subParser->parse($body);
193                return $subParser->getHandler()->calls;
194            }
195        );
196
197        if ($calls && $calls[0][0] === 'document_start') array_shift($calls);
198        if ($calls && end($calls)[0] === 'document_end') array_pop($calls);
199
200        if ($registry->isDwPreferred()) {
201            $calls = $this->flattenForDwRendering($calls);
202        }
203
204        if (!$calls) return;
205
206        $outer = $handler->getCallWriter();
207        $nest = new Nest($outer);
208        $handler->setCallWriter($nest);
209        foreach ($calls as $call) {
210            $handler->addCall($call[0], $call[1], $segmentStart + $call[2]);
211        }
212        $handler->setCallWriter($nest->process());
213    }
214
215    /**
216     * Flatten paragraph structure into linebreak-separated cdata.
217     *
218     * DW Quote historically rendered each `>`-line as a separate visible
219     * line via an explicit `<br/>` between same-depth markers. To
220     * preserve that rendering for DW-preferred installs, this pass:
221     *
222     *   1. Replaces every `p_open` and `p_close` with a `linebreak`
223     *      call. After this, paragraph boundaries become two adjacent
224     *      linebreaks (the close-of-prev plus the open-of-next), which
225     *      matches the DW two-`<br/>`-for-blank-line shape.
226     *   2. Drops the first and last `linebreak` calls so the run starts
227     *      and ends with content, not break markers.
228     *   3. Splits any `cdata` containing `\n` into multiple `cdata`
229     *      calls separated by `linebreak` — sub-parsed paragraphs may
230     *      contain soft breaks that a renderer would otherwise collapse
231     *      to a single space.
232     *
233     * Block-level calls inside the body (list_open from a list inside
234     * a quote, code, etc.) are passed through unchanged.
235     *
236     * @param array $calls sub-parsed call list to flatten
237     * @return array the flattened call list
238     */
239    protected function flattenForDwRendering(array $calls): array
240    {
241        $stage = [];
242        foreach ($calls as $call) {
243            if ($call[0] === 'p_open' || $call[0] === 'p_close') {
244                $stage[] = ['linebreak', [], $call[2]];
245            } else {
246                $stage[] = $call;
247            }
248        }
249
250        while ($stage && $stage[0][0] === 'linebreak') array_shift($stage);
251        while ($stage && end($stage)[0] === 'linebreak') array_pop($stage);
252
253        $out = [];
254        foreach ($stage as $call) {
255            if ($call[0] === 'cdata' && str_contains($call[1][0], "\n")) {
256                $parts = explode("\n", $call[1][0]);
257                foreach ($parts as $i => $part) {
258                    if ($i > 0) $out[] = ['linebreak', [], $call[2]];
259                    if ($part !== '') $out[] = ['cdata', [$part], $call[2]];
260                }
261            } else {
262                $out[] = $call;
263            }
264        }
265
266        return $out;
267    }
268}
269