xref: /dokuwiki/inc/Parsing/ParserMode/GfmQuote.php (revision 13a62f810fbd091d15ab734b467eaec0a6bf829a)
1309a0852SAndreas Gohr<?php
2309a0852SAndreas Gohr
3309a0852SAndreas Gohrnamespace dokuwiki\Parsing\ParserMode;
4309a0852SAndreas Gohr
5309a0852SAndreas Gohruse dokuwiki\Parsing\Handler;
6309a0852SAndreas Gohruse dokuwiki\Parsing\Handler\Nest;
7309a0852SAndreas Gohruse dokuwiki\Parsing\ModeRegistry;
8309a0852SAndreas Gohr
9309a0852SAndreas Gohr/**
10309a0852SAndreas Gohr * Block quotes — single mode covering both DokuWiki and GFM dialects.
11309a0852SAndreas Gohr *
12309a0852SAndreas Gohr * Captures one or more consecutive column-0 `>`-prefixed lines via
13309a0852SAndreas Gohr * addSpecialPattern. Nesting is resolved at this level by counting
14309a0852SAndreas Gohr * leading `>` markers per line and emitting `quote_open` / `quote_close`
15309a0852SAndreas Gohr * pairs around per-depth body segments — sub-parser recursion is
16309a0852SAndreas Gohr * deliberately not used because each sub-parser invocation needs its
17309a0852SAndreas Gohr * own Handler instance and threading the nesting through the registry
18309a0852SAndreas Gohr * pool would only buy us back what depth-walking already provides.
19309a0852SAndreas Gohr *
20309a0852SAndreas Gohr * Each per-depth segment's body is sub-parsed via
21309a0852SAndreas Gohr * ModeRegistry::withSubParser() so block content (lists, fenced code,
22309a0852SAndreas Gohr * tables) works inside the body. The sub-parser excludes BASEONLY so
23309a0852SAndreas Gohr * headers do not fire inside a blockquote — same rationale as
24309a0852SAndreas Gohr * GfmListblock: header instructions drive TOC entries, section-edit
25309a0852SAndreas Gohr * anchors, and section_open/section_close ranges that don't compose
26309a0852SAndreas Gohr * with a `<blockquote>` container. The sub-parser also excludes
27309a0852SAndreas Gohr * gfm_quote itself; nesting is handled at this level, not via
28309a0852SAndreas Gohr * sub-parser recursion. When a list inside a quote re-fires gfm_quote
29309a0852SAndreas Gohr * during the list-item sub-parse, the registry's pool hands the
30309a0852SAndreas Gohr * inner call a different parser instance for the same exclusion key,
31309a0852SAndreas Gohr * so the outer parse state is not corrupted.
32309a0852SAndreas Gohr *
33309a0852SAndreas Gohr * Lazy continuation is deliberately not supported. Every quote line
34309a0852SAndreas Gohr * must begin with `>` at column 0; the first non-`>` line ends the
35309a0852SAndreas Gohr * quote. This matches the policy GfmListblock enforces for lists —
36309a0852SAndreas Gohr * markers required on every line. Trade-off: a few CommonMark
37309a0852SAndreas Gohr * blockquote spec examples that rely on lazy continuation stay red,
38309a0852SAndreas Gohr * but the parser stays single-pass and predictable.
39309a0852SAndreas Gohr *
40309a0852SAndreas Gohr * Rendering shape depends on syntax preference. Under MD-preferred
41*13a62f81SAndreas Gohr * (`md`, `md+dw`) the sub-parser's paragraph wrapping survives:
42309a0852SAndreas Gohr * a quote with one paragraph emits `<blockquote><p>...</p></blockquote>`.
43*13a62f81SAndreas Gohr * Under DW-preferred (`dw`, `dw+md`) a post-pass flattens
44309a0852SAndreas Gohr * paragraph wrapping into explicit `linebreak` calls so existing DW
45309a0852SAndreas Gohr * pages keep their `<blockquote>...line1<br/>line2...</blockquote>`
46309a0852SAndreas Gohr * rendering. Same `quote_open` / `quote_close` instructions in both
47309a0852SAndreas Gohr * modes — no renderer change required.
48309a0852SAndreas Gohr */
49309a0852SAndreas Gohrclass GfmQuote extends AbstractMode
50309a0852SAndreas Gohr{
51309a0852SAndreas Gohr    /** @inheritdoc */
52309a0852SAndreas Gohr    public function getSort()
53309a0852SAndreas Gohr    {
54309a0852SAndreas Gohr        return 220;
55309a0852SAndreas Gohr    }
56309a0852SAndreas Gohr
57309a0852SAndreas Gohr    /** @inheritdoc */
58309a0852SAndreas Gohr    public function preConnect()
59309a0852SAndreas Gohr    {
60309a0852SAndreas Gohr        ModeRegistry::getInstance()->registerBlockEolMode('gfm_quote');
61309a0852SAndreas Gohr    }
62309a0852SAndreas Gohr
63309a0852SAndreas Gohr    /**
64309a0852SAndreas Gohr     * Capture an entire blockquote in one match.
65309a0852SAndreas Gohr     *
66309a0852SAndreas Gohr     * The pattern requires a column-0 `>` on every line. The first
67309a0852SAndreas Gohr     * non-`>` line ends the capture (no lazy continuation). A bare `>`
68309a0852SAndreas Gohr     * with no body is valid — it represents an empty paragraph break
69309a0852SAndreas Gohr     * inside the quote (spec 240) or an empty quote (spec 239).
70309a0852SAndreas Gohr     *
71309a0852SAndreas Gohr     * @param string $mode the lexer state name to wire the pattern into
72309a0852SAndreas Gohr     */
73309a0852SAndreas Gohr    public function connectTo($mode)
74309a0852SAndreas Gohr    {
75309a0852SAndreas Gohr        $this->Lexer->addSpecialPattern('\n>[^\n]*(?:\n>[^\n]*)*', $mode, 'gfm_quote');
76309a0852SAndreas Gohr    }
77309a0852SAndreas Gohr
78309a0852SAndreas Gohr    /** @inheritdoc */
79309a0852SAndreas Gohr    public function handle($match, $state, $pos, Handler $handler)
80309a0852SAndreas Gohr    {
81309a0852SAndreas Gohr        $stripped = ltrim($match, "\n");
82309a0852SAndreas Gohr        $cursor = strlen($match) - strlen($stripped);
83309a0852SAndreas Gohr
84309a0852SAndreas Gohr        $parsed = [];
85309a0852SAndreas Gohr        foreach (explode("\n", $stripped) as $line) {
86309a0852SAndreas Gohr            $parsed[] = $this->parseLine($line, $pos + $cursor);
87309a0852SAndreas Gohr            $cursor += strlen($line) + 1; // +1 for the \n consumed by explode
88309a0852SAndreas Gohr        }
89309a0852SAndreas Gohr
90309a0852SAndreas Gohr        $currentDepth = 0;
91309a0852SAndreas Gohr        $buffer = [];
92309a0852SAndreas Gohr        $segmentStart = $pos;
93309a0852SAndreas Gohr
94309a0852SAndreas Gohr        foreach ($parsed as $p) {
95309a0852SAndreas Gohr            if ($p['depth'] !== $currentDepth) {
96309a0852SAndreas Gohr                if ($buffer) {
97309a0852SAndreas Gohr                    $this->emitBody($handler, $segmentStart, implode("\n", $buffer));
98309a0852SAndreas Gohr                    $buffer = [];
99309a0852SAndreas Gohr                }
100309a0852SAndreas Gohr                while ($currentDepth < $p['depth']) {
101309a0852SAndreas Gohr                    $handler->addCall('quote_open', [], $pos);
102309a0852SAndreas Gohr                    $currentDepth++;
103309a0852SAndreas Gohr                }
104309a0852SAndreas Gohr                while ($currentDepth > $p['depth']) {
105309a0852SAndreas Gohr                    $handler->addCall('quote_close', [], $pos);
106309a0852SAndreas Gohr                    $currentDepth--;
107309a0852SAndreas Gohr                }
108309a0852SAndreas Gohr            }
109309a0852SAndreas Gohr            if (!$buffer) $segmentStart = $p['offset'];
110309a0852SAndreas Gohr            $buffer[] = $p['content'];
111309a0852SAndreas Gohr        }
112309a0852SAndreas Gohr
113309a0852SAndreas Gohr        if ($buffer) {
114309a0852SAndreas Gohr            $this->emitBody($handler, $segmentStart, implode("\n", $buffer));
115309a0852SAndreas Gohr        }
116309a0852SAndreas Gohr        while ($currentDepth > 0) {
117309a0852SAndreas Gohr            $handler->addCall('quote_close', [], $pos + strlen($match));
118309a0852SAndreas Gohr            $currentDepth--;
119309a0852SAndreas Gohr        }
120309a0852SAndreas Gohr
121309a0852SAndreas Gohr        return true;
122309a0852SAndreas Gohr    }
123309a0852SAndreas Gohr
124309a0852SAndreas Gohr    /**
125309a0852SAndreas Gohr     * Parse one captured line into depth, content, and content offset.
126309a0852SAndreas Gohr     *
127309a0852SAndreas Gohr     * Counts leading `>` characters (each consuming one optional
128309a0852SAndreas Gohr     * trailing space) to compute the depth. The remainder of the line
129309a0852SAndreas Gohr     * is the content for that depth. The returned `offset` is the
130309a0852SAndreas Gohr     * absolute byte position of the content's first character within
131309a0852SAndreas Gohr     * the source (`$lineStart` plus the length of the consumed marker
132309a0852SAndreas Gohr     * prefix).
133309a0852SAndreas Gohr     *
134309a0852SAndreas Gohr     * `> > foo` → depth 2, content `foo`. `>>foo` → depth 2, content
135309a0852SAndreas Gohr     * `foo`. `>` alone → depth 1, content empty.
136309a0852SAndreas Gohr     *
137309a0852SAndreas Gohr     * @param string $line one line of captured blockquote text, with
138309a0852SAndreas Gohr     *     no surrounding newlines
139309a0852SAndreas Gohr     * @param int $lineStart absolute byte offset of the line's first
140309a0852SAndreas Gohr     *     character within the source
141309a0852SAndreas Gohr     * @return array{depth: int, content: string, offset: int}
142309a0852SAndreas Gohr     */
143309a0852SAndreas Gohr    protected function parseLine(string $line, int $lineStart): array
144309a0852SAndreas Gohr    {
145309a0852SAndreas Gohr        $depth = 0;
146309a0852SAndreas Gohr        $i = 0;
147309a0852SAndreas Gohr        $len = strlen($line);
148309a0852SAndreas Gohr        while ($i < $len && $line[$i] === '>') {
149309a0852SAndreas Gohr            $depth++;
150309a0852SAndreas Gohr            $i++;
151309a0852SAndreas Gohr            if ($i < $len && $line[$i] === ' ') $i++;
152309a0852SAndreas Gohr        }
153309a0852SAndreas Gohr        return [
154309a0852SAndreas Gohr            'depth'   => $depth,
155309a0852SAndreas Gohr            'content' => substr($line, $i),
156309a0852SAndreas Gohr            'offset'  => $lineStart + $i,
157309a0852SAndreas Gohr        ];
158309a0852SAndreas Gohr    }
159309a0852SAndreas Gohr
160309a0852SAndreas Gohr    /**
161309a0852SAndreas Gohr     * Sub-parse a body segment and emit its calls inside a Nest.
162309a0852SAndreas Gohr     *
163309a0852SAndreas Gohr     * Drops `document_start` / `document_end` from the sub-parser
164309a0852SAndreas Gohr     * output. Under DW-preferred syntax, also runs the linebreak
165309a0852SAndreas Gohr     * post-pass so paragraph wrapping is flattened into explicit
166309a0852SAndreas Gohr     * `linebreak` calls. Empty bodies emit nothing.
167309a0852SAndreas Gohr     *
168309a0852SAndreas Gohr     * `$segmentStart` is the absolute byte offset of the segment's
169309a0852SAndreas Gohr     * first content character within the source. Sub-handler positions
170309a0852SAndreas Gohr     * are relative to the sub-parsed body, which begins at the first
171309a0852SAndreas Gohr     * line of the segment, so adding `$segmentStart` to each
172309a0852SAndreas Gohr     * sub-handler position lands the call back on the right byte in
173309a0852SAndreas Gohr     * the source. Lines after the first drift slightly because the
174309a0852SAndreas Gohr     * `>[ ]?` prefix between source lines collapses to a single `\n`
175309a0852SAndreas Gohr     * in the sub-parsed body — drift is bounded by the prefix length
176309a0852SAndreas Gohr     * (one or two bytes per line skipped).
177309a0852SAndreas Gohr     *
178309a0852SAndreas Gohr     * @param Handler $handler outer handler to emit calls on
179309a0852SAndreas Gohr     * @param int $segmentStart absolute byte offset of the segment's
180309a0852SAndreas Gohr     *     first content character within the source
181309a0852SAndreas Gohr     * @param string $body concatenated content of the buffered lines,
182309a0852SAndreas Gohr     *     separated by `\n`
183309a0852SAndreas Gohr     */
184309a0852SAndreas Gohr    protected function emitBody(Handler $handler, int $segmentStart, string $body): void
185309a0852SAndreas Gohr    {
186309a0852SAndreas Gohr        $registry = ModeRegistry::getInstance();
187309a0852SAndreas Gohr        $calls = $registry->withSubParser(
188309a0852SAndreas Gohr            [ModeRegistry::CATEGORY_BASEONLY],
189309a0852SAndreas Gohr            ['gfm_quote'],
190309a0852SAndreas Gohr            static function ($subParser) use ($body) {
191309a0852SAndreas Gohr                $subParser->getHandler()->reset();
192309a0852SAndreas Gohr                $subParser->parse($body);
193309a0852SAndreas Gohr                return $subParser->getHandler()->calls;
194309a0852SAndreas Gohr            }
195309a0852SAndreas Gohr        );
196309a0852SAndreas Gohr
197309a0852SAndreas Gohr        if ($calls && $calls[0][0] === 'document_start') array_shift($calls);
198309a0852SAndreas Gohr        if ($calls && end($calls)[0] === 'document_end') array_pop($calls);
199309a0852SAndreas Gohr
200309a0852SAndreas Gohr        if ($registry->isDwPreferred()) {
201309a0852SAndreas Gohr            $calls = $this->flattenForDwRendering($calls);
202309a0852SAndreas Gohr        }
203309a0852SAndreas Gohr
204309a0852SAndreas Gohr        if (!$calls) return;
205309a0852SAndreas Gohr
206309a0852SAndreas Gohr        $outer = $handler->getCallWriter();
207309a0852SAndreas Gohr        $nest = new Nest($outer);
208309a0852SAndreas Gohr        $handler->setCallWriter($nest);
209309a0852SAndreas Gohr        foreach ($calls as $call) {
210309a0852SAndreas Gohr            $handler->addCall($call[0], $call[1], $segmentStart + $call[2]);
211309a0852SAndreas Gohr        }
212309a0852SAndreas Gohr        $handler->setCallWriter($nest->process());
213309a0852SAndreas Gohr    }
214309a0852SAndreas Gohr
215309a0852SAndreas Gohr    /**
216309a0852SAndreas Gohr     * Flatten paragraph structure into linebreak-separated cdata.
217309a0852SAndreas Gohr     *
218309a0852SAndreas Gohr     * DW Quote historically rendered each `>`-line as a separate visible
219309a0852SAndreas Gohr     * line via an explicit `<br/>` between same-depth markers. To
220309a0852SAndreas Gohr     * preserve that rendering for DW-preferred installs, this pass:
221309a0852SAndreas Gohr     *
222309a0852SAndreas Gohr     *   1. Replaces every `p_open` and `p_close` with a `linebreak`
223309a0852SAndreas Gohr     *      call. After this, paragraph boundaries become two adjacent
224309a0852SAndreas Gohr     *      linebreaks (the close-of-prev plus the open-of-next), which
225309a0852SAndreas Gohr     *      matches the DW two-`<br/>`-for-blank-line shape.
226309a0852SAndreas Gohr     *   2. Drops the first and last `linebreak` calls so the run starts
227309a0852SAndreas Gohr     *      and ends with content, not break markers.
228309a0852SAndreas Gohr     *   3. Splits any `cdata` containing `\n` into multiple `cdata`
229309a0852SAndreas Gohr     *      calls separated by `linebreak` — sub-parsed paragraphs may
230309a0852SAndreas Gohr     *      contain soft breaks that a renderer would otherwise collapse
231309a0852SAndreas Gohr     *      to a single space.
232309a0852SAndreas Gohr     *
233309a0852SAndreas Gohr     * Block-level calls inside the body (list_open from a list inside
234309a0852SAndreas Gohr     * a quote, code, etc.) are passed through unchanged.
235309a0852SAndreas Gohr     *
236309a0852SAndreas Gohr     * @param array $calls sub-parsed call list to flatten
237309a0852SAndreas Gohr     * @return array the flattened call list
238309a0852SAndreas Gohr     */
239309a0852SAndreas Gohr    protected function flattenForDwRendering(array $calls): array
240309a0852SAndreas Gohr    {
241309a0852SAndreas Gohr        $stage = [];
242309a0852SAndreas Gohr        foreach ($calls as $call) {
243309a0852SAndreas Gohr            if ($call[0] === 'p_open' || $call[0] === 'p_close') {
244309a0852SAndreas Gohr                $stage[] = ['linebreak', [], $call[2]];
245309a0852SAndreas Gohr            } else {
246309a0852SAndreas Gohr                $stage[] = $call;
247309a0852SAndreas Gohr            }
248309a0852SAndreas Gohr        }
249309a0852SAndreas Gohr
250309a0852SAndreas Gohr        while ($stage && $stage[0][0] === 'linebreak') array_shift($stage);
251309a0852SAndreas Gohr        while ($stage && end($stage)[0] === 'linebreak') array_pop($stage);
252309a0852SAndreas Gohr
253309a0852SAndreas Gohr        $out = [];
254309a0852SAndreas Gohr        foreach ($stage as $call) {
255309a0852SAndreas Gohr            if ($call[0] === 'cdata' && str_contains($call[1][0], "\n")) {
256309a0852SAndreas Gohr                $parts = explode("\n", $call[1][0]);
257309a0852SAndreas Gohr                foreach ($parts as $i => $part) {
258309a0852SAndreas Gohr                    if ($i > 0) $out[] = ['linebreak', [], $call[2]];
259309a0852SAndreas Gohr                    if ($part !== '') $out[] = ['cdata', [$part], $call[2]];
260309a0852SAndreas Gohr                }
261309a0852SAndreas Gohr            } else {
262309a0852SAndreas Gohr                $out[] = $call;
263309a0852SAndreas Gohr            }
264309a0852SAndreas Gohr        }
265309a0852SAndreas Gohr
266309a0852SAndreas Gohr        return $out;
267309a0852SAndreas Gohr    }
268309a0852SAndreas Gohr}
269