xref: /dokuwiki/inc/Parsing/ParserMode/GfmQuote.php (revision dccbd514161d242fdd8495ae23b9690bc52463c9)
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
4113a62f81SAndreas Gohr * (`md`, `md+dw`) the sub-parser's paragraph wrapping survives:
42309a0852SAndreas Gohr * a quote with one paragraph emits `<blockquote><p>...</p></blockquote>`.
4313a62f81SAndreas 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     *
71*dccbd514SAndreas Gohr     * The first line uses (?:^|\n)> rather than \n> so the blockquote
72*dccbd514SAndreas Gohr     * can take over when a preceding block mode (a table or a list)
73*dccbd514SAndreas Gohr     * consumed the boundary \n on its way out. Those modes' exit
74*dccbd514SAndreas Gohr     * patterns are \n by structural necessity: at the boundary there
75*dccbd514SAndreas Gohr     * is no leading unmatched content for a zero-width lookahead exit
76*dccbd514SAndreas Gohr     * to attach to, and a pure-lookahead exit would trip the lexer's
77*dccbd514SAndreas Gohr     * no-advance safety check. Accepting either a literal \n or a line
78*dccbd514SAndreas Gohr     * start (^ in PCRE multiline mode, which also matches the position
79*dccbd514SAndreas Gohr     * immediately after a consumed \n) lets the blockquote start
80*dccbd514SAndreas Gohr     * regardless. Subsequent quote lines still anchor on \n> because
81*dccbd514SAndreas Gohr     * the previous line consumed up to but not including the \n, so
82*dccbd514SAndreas Gohr     * it is always available for them.
83*dccbd514SAndreas Gohr     *
84309a0852SAndreas Gohr     * @param string $mode the lexer state name to wire the pattern into
85309a0852SAndreas Gohr     */
86309a0852SAndreas Gohr    public function connectTo($mode)
87309a0852SAndreas Gohr    {
88*dccbd514SAndreas Gohr        $this->Lexer->addSpecialPattern('(?:^|\n)>[^\n]*(?:\n>[^\n]*)*', $mode, 'gfm_quote');
89309a0852SAndreas Gohr    }
90309a0852SAndreas Gohr
91309a0852SAndreas Gohr    /** @inheritdoc */
92309a0852SAndreas Gohr    public function handle($match, $state, $pos, Handler $handler)
93309a0852SAndreas Gohr    {
94309a0852SAndreas Gohr        $stripped = ltrim($match, "\n");
95309a0852SAndreas Gohr        $cursor = strlen($match) - strlen($stripped);
96309a0852SAndreas Gohr
97309a0852SAndreas Gohr        $parsed = [];
98309a0852SAndreas Gohr        foreach (explode("\n", $stripped) as $line) {
99309a0852SAndreas Gohr            $parsed[] = $this->parseLine($line, $pos + $cursor);
100309a0852SAndreas Gohr            $cursor += strlen($line) + 1; // +1 for the \n consumed by explode
101309a0852SAndreas Gohr        }
102309a0852SAndreas Gohr
103309a0852SAndreas Gohr        $currentDepth = 0;
104309a0852SAndreas Gohr        $buffer = [];
105309a0852SAndreas Gohr        $segmentStart = $pos;
106309a0852SAndreas Gohr
107309a0852SAndreas Gohr        foreach ($parsed as $p) {
108309a0852SAndreas Gohr            if ($p['depth'] !== $currentDepth) {
109309a0852SAndreas Gohr                if ($buffer) {
110309a0852SAndreas Gohr                    $this->emitBody($handler, $segmentStart, implode("\n", $buffer));
111309a0852SAndreas Gohr                    $buffer = [];
112309a0852SAndreas Gohr                }
113309a0852SAndreas Gohr                while ($currentDepth < $p['depth']) {
114309a0852SAndreas Gohr                    $handler->addCall('quote_open', [], $pos);
115309a0852SAndreas Gohr                    $currentDepth++;
116309a0852SAndreas Gohr                }
117309a0852SAndreas Gohr                while ($currentDepth > $p['depth']) {
118309a0852SAndreas Gohr                    $handler->addCall('quote_close', [], $pos);
119309a0852SAndreas Gohr                    $currentDepth--;
120309a0852SAndreas Gohr                }
121309a0852SAndreas Gohr            }
122309a0852SAndreas Gohr            if (!$buffer) $segmentStart = $p['offset'];
123309a0852SAndreas Gohr            $buffer[] = $p['content'];
124309a0852SAndreas Gohr        }
125309a0852SAndreas Gohr
126309a0852SAndreas Gohr        if ($buffer) {
127309a0852SAndreas Gohr            $this->emitBody($handler, $segmentStart, implode("\n", $buffer));
128309a0852SAndreas Gohr        }
129309a0852SAndreas Gohr        while ($currentDepth > 0) {
130309a0852SAndreas Gohr            $handler->addCall('quote_close', [], $pos + strlen($match));
131309a0852SAndreas Gohr            $currentDepth--;
132309a0852SAndreas Gohr        }
133309a0852SAndreas Gohr
134309a0852SAndreas Gohr        return true;
135309a0852SAndreas Gohr    }
136309a0852SAndreas Gohr
137309a0852SAndreas Gohr    /**
138309a0852SAndreas Gohr     * Parse one captured line into depth, content, and content offset.
139309a0852SAndreas Gohr     *
140309a0852SAndreas Gohr     * Counts leading `>` characters (each consuming one optional
141309a0852SAndreas Gohr     * trailing space) to compute the depth. The remainder of the line
142309a0852SAndreas Gohr     * is the content for that depth. The returned `offset` is the
143309a0852SAndreas Gohr     * absolute byte position of the content's first character within
144309a0852SAndreas Gohr     * the source (`$lineStart` plus the length of the consumed marker
145309a0852SAndreas Gohr     * prefix).
146309a0852SAndreas Gohr     *
147309a0852SAndreas Gohr     * `> > foo` → depth 2, content `foo`. `>>foo` → depth 2, content
148309a0852SAndreas Gohr     * `foo`. `>` alone → depth 1, content empty.
149309a0852SAndreas Gohr     *
150309a0852SAndreas Gohr     * @param string $line one line of captured blockquote text, with
151309a0852SAndreas Gohr     *     no surrounding newlines
152309a0852SAndreas Gohr     * @param int $lineStart absolute byte offset of the line's first
153309a0852SAndreas Gohr     *     character within the source
154309a0852SAndreas Gohr     * @return array{depth: int, content: string, offset: int}
155309a0852SAndreas Gohr     */
156309a0852SAndreas Gohr    protected function parseLine(string $line, int $lineStart): array
157309a0852SAndreas Gohr    {
158309a0852SAndreas Gohr        $depth = 0;
159309a0852SAndreas Gohr        $i = 0;
160309a0852SAndreas Gohr        $len = strlen($line);
161309a0852SAndreas Gohr        while ($i < $len && $line[$i] === '>') {
162309a0852SAndreas Gohr            $depth++;
163309a0852SAndreas Gohr            $i++;
164309a0852SAndreas Gohr            if ($i < $len && $line[$i] === ' ') $i++;
165309a0852SAndreas Gohr        }
166309a0852SAndreas Gohr        return [
167309a0852SAndreas Gohr            'depth'   => $depth,
168309a0852SAndreas Gohr            'content' => substr($line, $i),
169309a0852SAndreas Gohr            'offset'  => $lineStart + $i,
170309a0852SAndreas Gohr        ];
171309a0852SAndreas Gohr    }
172309a0852SAndreas Gohr
173309a0852SAndreas Gohr    /**
174309a0852SAndreas Gohr     * Sub-parse a body segment and emit its calls inside a Nest.
175309a0852SAndreas Gohr     *
176309a0852SAndreas Gohr     * Drops `document_start` / `document_end` from the sub-parser
177309a0852SAndreas Gohr     * output. Under DW-preferred syntax, also runs the linebreak
178309a0852SAndreas Gohr     * post-pass so paragraph wrapping is flattened into explicit
179309a0852SAndreas Gohr     * `linebreak` calls. Empty bodies emit nothing.
180309a0852SAndreas Gohr     *
181309a0852SAndreas Gohr     * `$segmentStart` is the absolute byte offset of the segment's
182309a0852SAndreas Gohr     * first content character within the source. Sub-handler positions
183309a0852SAndreas Gohr     * are relative to the sub-parsed body, which begins at the first
184309a0852SAndreas Gohr     * line of the segment, so adding `$segmentStart` to each
185309a0852SAndreas Gohr     * sub-handler position lands the call back on the right byte in
186309a0852SAndreas Gohr     * the source. Lines after the first drift slightly because the
187309a0852SAndreas Gohr     * `>[ ]?` prefix between source lines collapses to a single `\n`
188309a0852SAndreas Gohr     * in the sub-parsed body — drift is bounded by the prefix length
189309a0852SAndreas Gohr     * (one or two bytes per line skipped).
190309a0852SAndreas Gohr     *
191309a0852SAndreas Gohr     * @param Handler $handler outer handler to emit calls on
192309a0852SAndreas Gohr     * @param int $segmentStart absolute byte offset of the segment's
193309a0852SAndreas Gohr     *     first content character within the source
194309a0852SAndreas Gohr     * @param string $body concatenated content of the buffered lines,
195309a0852SAndreas Gohr     *     separated by `\n`
196309a0852SAndreas Gohr     */
197309a0852SAndreas Gohr    protected function emitBody(Handler $handler, int $segmentStart, string $body): void
198309a0852SAndreas Gohr    {
199309a0852SAndreas Gohr        $registry = ModeRegistry::getInstance();
200309a0852SAndreas Gohr        $calls = $registry->withSubParser(
201309a0852SAndreas Gohr            [ModeRegistry::CATEGORY_BASEONLY],
202309a0852SAndreas Gohr            ['gfm_quote'],
203309a0852SAndreas Gohr            static function ($subParser) use ($body) {
204309a0852SAndreas Gohr                $subParser->getHandler()->reset();
205309a0852SAndreas Gohr                $subParser->parse($body);
206309a0852SAndreas Gohr                return $subParser->getHandler()->calls;
207309a0852SAndreas Gohr            }
208309a0852SAndreas Gohr        );
209309a0852SAndreas Gohr
210309a0852SAndreas Gohr        if ($calls && $calls[0][0] === 'document_start') array_shift($calls);
211309a0852SAndreas Gohr        if ($calls && end($calls)[0] === 'document_end') array_pop($calls);
212309a0852SAndreas Gohr
213309a0852SAndreas Gohr        if ($registry->isDwPreferred()) {
214309a0852SAndreas Gohr            $calls = $this->flattenForDwRendering($calls);
215309a0852SAndreas Gohr        }
216309a0852SAndreas Gohr
217309a0852SAndreas Gohr        if (!$calls) return;
218309a0852SAndreas Gohr
219309a0852SAndreas Gohr        $outer = $handler->getCallWriter();
220309a0852SAndreas Gohr        $nest = new Nest($outer);
221309a0852SAndreas Gohr        $handler->setCallWriter($nest);
222309a0852SAndreas Gohr        foreach ($calls as $call) {
223309a0852SAndreas Gohr            $handler->addCall($call[0], $call[1], $segmentStart + $call[2]);
224309a0852SAndreas Gohr        }
225309a0852SAndreas Gohr        $handler->setCallWriter($nest->process());
226309a0852SAndreas Gohr    }
227309a0852SAndreas Gohr
228309a0852SAndreas Gohr    /**
229309a0852SAndreas Gohr     * Flatten paragraph structure into linebreak-separated cdata.
230309a0852SAndreas Gohr     *
231309a0852SAndreas Gohr     * DW Quote historically rendered each `>`-line as a separate visible
232309a0852SAndreas Gohr     * line via an explicit `<br/>` between same-depth markers. To
233309a0852SAndreas Gohr     * preserve that rendering for DW-preferred installs, this pass:
234309a0852SAndreas Gohr     *
235309a0852SAndreas Gohr     *   1. Replaces every `p_open` and `p_close` with a `linebreak`
236309a0852SAndreas Gohr     *      call. After this, paragraph boundaries become two adjacent
237309a0852SAndreas Gohr     *      linebreaks (the close-of-prev plus the open-of-next), which
238309a0852SAndreas Gohr     *      matches the DW two-`<br/>`-for-blank-line shape.
239309a0852SAndreas Gohr     *   2. Drops the first and last `linebreak` calls so the run starts
240309a0852SAndreas Gohr     *      and ends with content, not break markers.
241309a0852SAndreas Gohr     *   3. Splits any `cdata` containing `\n` into multiple `cdata`
242309a0852SAndreas Gohr     *      calls separated by `linebreak` — sub-parsed paragraphs may
243309a0852SAndreas Gohr     *      contain soft breaks that a renderer would otherwise collapse
244309a0852SAndreas Gohr     *      to a single space.
245309a0852SAndreas Gohr     *
246309a0852SAndreas Gohr     * Block-level calls inside the body (list_open from a list inside
247309a0852SAndreas Gohr     * a quote, code, etc.) are passed through unchanged.
248309a0852SAndreas Gohr     *
249309a0852SAndreas Gohr     * @param array $calls sub-parsed call list to flatten
250309a0852SAndreas Gohr     * @return array the flattened call list
251309a0852SAndreas Gohr     */
252309a0852SAndreas Gohr    protected function flattenForDwRendering(array $calls): array
253309a0852SAndreas Gohr    {
254309a0852SAndreas Gohr        $stage = [];
255309a0852SAndreas Gohr        foreach ($calls as $call) {
256309a0852SAndreas Gohr            if ($call[0] === 'p_open' || $call[0] === 'p_close') {
257309a0852SAndreas Gohr                $stage[] = ['linebreak', [], $call[2]];
258309a0852SAndreas Gohr            } else {
259309a0852SAndreas Gohr                $stage[] = $call;
260309a0852SAndreas Gohr            }
261309a0852SAndreas Gohr        }
262309a0852SAndreas Gohr
263309a0852SAndreas Gohr        while ($stage && $stage[0][0] === 'linebreak') array_shift($stage);
264309a0852SAndreas Gohr        while ($stage && end($stage)[0] === 'linebreak') array_pop($stage);
265309a0852SAndreas Gohr
266309a0852SAndreas Gohr        $out = [];
267309a0852SAndreas Gohr        foreach ($stage as $call) {
268309a0852SAndreas Gohr            if ($call[0] === 'cdata' && str_contains($call[1][0], "\n")) {
269309a0852SAndreas Gohr                $parts = explode("\n", $call[1][0]);
270309a0852SAndreas Gohr                foreach ($parts as $i => $part) {
271309a0852SAndreas Gohr                    if ($i > 0) $out[] = ['linebreak', [], $call[2]];
272309a0852SAndreas Gohr                    if ($part !== '') $out[] = ['cdata', [$part], $call[2]];
273309a0852SAndreas Gohr                }
274309a0852SAndreas Gohr            } else {
275309a0852SAndreas Gohr                $out[] = $call;
276309a0852SAndreas Gohr            }
277309a0852SAndreas Gohr        }
278309a0852SAndreas Gohr
279309a0852SAndreas Gohr        return $out;
280309a0852SAndreas Gohr    }
281309a0852SAndreas Gohr}
282