• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

dg / texy / 43760211708

15 Nov 2026 08:43PM UTC coverage: 97.217% (+0.3%) from 96.951%
43760211708

push

github

dg
cs

3 of 5 new or added lines in 1 file covered. (60.0%)

45 existing lines in 12 files now uncovered.

3878 of 3989 relevant lines covered (97.22%)

0.97 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.58
/src/Modules/ListModule.php
1
<?php declare(strict_types=1);
2

3
/**
4
 * This file is part of the Texy! (https://texy.deegee.dev)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
namespace Texy\Modules;
9

10
use Texy;
11
use Texy\{Modifier, Patterns, Range, Regexp, Syntax};
12
use Texy\Nodes\{DefinitionListNode, ListItemNode, ListNode, ListType};
13
use Texy\Parsing\ParseContext;
14
use function count, strlen;
15

16

17
/**
18
 * Processes ordered, unordered, and definition lists with nesting.
19
 */
20
final class ListModule extends Texy\Module
21
{
22
        /** bullets [regex, type, next-regex?] by the syntax that switches them, in the order they are tried */
23
        private const Bullets = [
24
                Syntax::List => [
25
                        '*' => ['\* [ \t]', ListType::Unordered],
26
                        '-' => ['[\x{2013}-] (?! [>-] )', ListType::Unordered],
27
                        '+' => ['\+ [ \t]', ListType::Unordered],
28
                ],
29
                Syntax::ListDecimal => [
30
                        '1.' => ['1 \. [ \t]' /* not \d! */, ListType::Decimal, '\d{1,3} \. [ \t]'],
31
                        '1)' => ['\d{1,3} \) [ \t]', ListType::Decimal],
32
                ],
33
                Syntax::ListRoman => [
34
                        'I.' => ['I \. [ \t]', ListType::UpperRoman, '[IVX]{1,4} \. [ \t]'],
35
                        'I)' => ['[IVX]+ \) [ \t]', ListType::UpperRoman], // before A) !
36
                ],
37
                Syntax::ListAlpha => [
38
                        'a)' => ['[a-z] \) [ \t]', ListType::LowerAlpha],
39
                        'A)' => ['[A-Z] \) [ \t]', ListType::UpperAlpha],
40
                ],
41
        ];
42

43

44
        public function register(Texy\Parsing\Engine $engine): void
45
        {
46
                $re = [];
1 ✔
47
                foreach (self::Bullets as $name => $bullets) {
1 ✔
48
                        $engine->declare($name);
1 ✔
49
                        array_push($re, ...array_column($bullets, 0));
1 ✔
50
                }
51

52
                $engine->addBlock(
1 ✔
53
                        Syntax::List,
1 ✔
54
                        '~^
55
                                (?:' . Patterns::ModifierHAlign . '\n)? # modifier (1)
56
                                (' . implode('|', $re) . ')         # list marker (2)
1 ✔
57
                                [ \t]*+
58
                                \S .*                               # content
59
                        $~mUx',
60
                        $this->parseList(...),
1 ✔
61
                );
62

63
                $engine->addBlock(
1 ✔
64
                        Syntax::DefinitionList,
1 ✔
65
                        '~^
66
                                (?:' . Patterns::ModifierHAlign . '\n)?   # modifier (1)
67
                                ( \S .{0,2000} )                      # definition term (2)
68
                                : [ \t]*                              # colon separator
69
                                ' . Patterns::ModifierHAlign . '?         # modifier (3)
70
                                \n
71
                                ([ \t]++)                             # indentation (4)
72
                                (' . implode('|', array_column(self::Bullets[Syntax::List], 0)) . ') # description marker (5)
1 ✔
73
                                [ \t]*+
74
                                \S .*                                 # content
75
                        $~mUx',
76
                        $this->parseDefList(...),
1 ✔
77
                );
78
        }
1 ✔
79

80

81
        /**
82
         * Parses list.
83
         * @param  array{string, ?string, string}  $matches
84
         * @param  array{int, ?int, int}  $offsets
85
         */
86
        public function parseList(ParseContext $context, array $matches, array $offsets): ?ListNode
87
        {
88
                [, $mMod, $mBullet] = $matches;
1 ✔
89

90
                $bullet = null;
1 ✔
91
                $min = 1;
1 ✔
92
                $start = null;
1 ✔
93
                $listType = ListType::Unordered;
1 ✔
94

95
                foreach ($this->getBullets($context) as $key => $desc) {
1 ✔
96
                        if (Regexp::match($mBullet, '~' . $desc[0] . '~Ax')) {
1 ✔
97
                                $bullet = $desc[2] ?? $desc[0];
1 ✔
98
                                $min = isset($desc[2]) ? 2 : 1;
1 ✔
99
                                $listType = $desc[1];
1 ✔
100
                                if ($listType->isOrdered()) {
1 ✔
101
                                        if ($key[0] === '1' && (int) $mBullet > 1) {
1 ✔
102
                                                $start = (int) $mBullet;
1 ✔
103
                                        } elseif ($key[0] === 'a' && $mBullet[0] > 'a') {
1 ✔
UNCOV
104
                                                $start = ord($mBullet[0]) - 96;
×
105
                                        } elseif ($key[0] === 'A' && $mBullet[0] > 'A') {
1 ✔
106
                                                $start = ord($mBullet[0]) - 64;
1 ✔
107
                                        }
108
                                }
109
                                break;
1 ✔
110
                        }
111
                }
112

113
                if ($bullet === null) {
1 ✔
114
                        return null;
1 ✔
115
                }
116

117
                $context->getBlockParser()->moveBackward();
1 ✔
118

119
                $items = [];
1 ✔
120
                while ($item = $this->parseItem($context, $bullet, false)) {
1 ✔
121
                        $items[] = $item;
1 ✔
122
                }
123

124
                if (count($items) < $min) {
1 ✔
125
                        return null;
1 ✔
126
                }
127

128
                return new ListNode(
1 ✔
129
                        $items,
130
                        $listType,
131
                        $start,
132
                        Modifier::parse($mMod, $offsets[1]),
1 ✔
133
                        $this->createRange($offsets[0], $items),
1 ✔
134
                );
135
        }
136

137

138
        /**
139
         * Parses definition list.
140
         * @param  array{string, ?string, string, ?string, string, string}  $matches
141
         * @param  array{int, ?int, int, ?int, int, int}  $offsets
142
         */
143
        public function parseDefList(ParseContext $context, array $matches, array $offsets): ?DefinitionListNode
144
        {
145
                [, $mMod, , , , $mBullet] = $matches;
1 ✔
146

147
                $bullet = null;
1 ✔
148

149
                foreach (self::Bullets[Syntax::List] as $desc) {
1 ✔
150
                        if (Regexp::match($mBullet, '~' . $desc[0] . '~Ax')) {
1 ✔
151
                                $bullet = $desc[0];
1 ✔
152
                                break;
1 ✔
153
                        }
154
                }
155

156
                if ($bullet === null) {
1 ✔
UNCOV
157
                        return null;
×
158
                }
159

160
                $context->getBlockParser()->moveBackward(2);
1 ✔
161

162
                $items = [];
1 ✔
163
                $patternTerm = '~^
1 ✔
164
                        \n?
165
                        ( \S .* )                       # term content
166
                        : [ \t]*                        # colon separator
167
                        ' . Patterns::ModifierHAlign . '?
168
                $~mUAx';
169

170
                while (true) {
1 ✔
171
                        if ($item = $this->parseItem($context, $bullet, true)) {
1 ✔
172
                                $items[] = $item;
1 ✔
173
                                continue;
1 ✔
174
                        }
175

176
                        $termMatches = null;
1 ✔
177
                        $termOffsets = null;
1 ✔
178
                        if ($context->getBlockParser()->next($patternTerm, $termMatches, $termOffsets)) {
1 ✔
179
                                /** @var array{string, string, ?string} $termMatches */
180
                                [, $mContent, $mTermMod] = $termMatches;
1 ✔
181
                                $termMod = Modifier::parse($mTermMod, $termOffsets[2] ?? null);
1 ✔
182
                                // groups 0 and 1 always participate in a successful match, but next() cannot type that
183
                                $termOffset = $termOffsets[0] ?? throw new \LogicException('Match without group 0.');
1 ✔
184
                                $contentOffset = $termOffsets[1] ?? throw new \LogicException('Match without group 1.');
1 ✔
185
                                $termContent = $context->parseInline($mContent, $contentOffset);
1 ✔
186
                                $items[] = new ListItemNode($termContent, true, $termMod, new Range($termOffset, strlen($termMatches[0])));
1 ✔
187
                                continue;
1 ✔
188
                        }
189

190
                        break;
1 ✔
191
                }
192

193
                if (!$items) {
1 ✔
UNCOV
194
                        return null;
×
195
                }
196

197
                return new DefinitionListNode(
1 ✔
198
                        $items,
199
                        Modifier::parse($mMod, $offsets[1]),
1 ✔
200
                        $this->createRange($offsets[0], $items),
1 ✔
201
                );
202
        }
203

204

205
        /**
206
         * Parses single list item.
207
         */
208
        private function parseItem(ParseContext $context, string $bullet, bool $indented): ?ListItemNode
209
        {
210
                $spacesBase = $indented ? ('[\ \t]{1,}') : '';
1 ✔
211
                $patternItem = "~^
1 ✔
212
                        \\n?
213
                        ($spacesBase)                            # base indentation (1)
1 ✔
214
                        ({$bullet})                              # bullet character (2)
1 ✔
215
                        [ \\t]*
216
                        ( \\S .* )?                              # content (3)
217
                        " . Patterns::ModifierHAlign . '?           # modifier (4)
1 ✔
218
                $~mAUx';
219

220
                $matches = null;
1 ✔
221
                $offsets = null;
1 ✔
222
                if (!$context->getBlockParser()->next($patternItem, $matches, $offsets)) {
1 ✔
223
                        return null;
1 ✔
224
                }
225

226
                /** @var array{string, string, string, ?string, ?string} $matches */
227
                [, $mIndent, $mBullet, $mContent, $mMod] = $matches;
1 ✔
228
                // groups 0 and 2 always participate in a successful match, but next() cannot type that
229
                $itemOffset = $offsets[0] ?? throw new \LogicException('Match without group 0.');
1 ✔
230
                $bulletRange = new Range($offsets[2] ?? throw new \LogicException('Match without group 2.'), strlen(rtrim($mBullet)));
1 ✔
231
                $modOffset = $offsets[4] ?? null;
1 ✔
232
                $itemEnd = $itemOffset + strlen($matches[0]);
1 ✔
233

234
                // Assemble content and map local line starts to absolute source offsets
235
                $map = [];
1 ✔
236
                $content = ' ' . ($mContent ?? '');
1 ✔
237
                if ($mContent !== null) {
1 ✔
238
                        // content matched, so group 3 participated and carries an offset
239
                        $map[1] = $offsets[3] ?? throw new \LogicException('Content without group 3.'); // 1 = the leading space
1 ✔
240
                }
241

242
                // a bullet opening the first line is text, - * text is no nested list; the leading space keeps it so
243
                $isBullet = Regexp::match(
1 ✔
244
                        $mContent ?? '',
1 ✔
245
                        '~(?:' . implode('|', array_column($this->getBullets($context), 0)) . ')~Ax',
1 ✔
246
                ) !== null;
1 ✔
247

248
                // next lines
249
                $spaces = '';
1 ✔
250
                while ($context->getBlockParser()->next('~^
1 ✔
251
                        (\n*)
252
                        ' . Regexp::quote($mIndent) . '
1 ✔
253
                        ([ \t]{1,' . $spaces . '})
1 ✔
254
                        (.*)                                     # content (3)
255
                $~Amx', $matches, $offsets)) {
256
                        /** @var array{string, string, string, string} $matches */
257
                        [, $mBlank, $mSpaces, $mContent] = $matches;
1 ✔
258

259
                        if ($spaces === '') {
1 ✔
260
                                $spaces = strlen($mSpaces);
1 ✔
261
                        }
262

263
                        if ($mContent !== '' && $offsets[3] !== null) {
1 ✔
264
                                $map[strlen($content) + 1 + strlen($mBlank)] = $offsets[3]; // 1 = "\n"
1 ✔
265
                        }
266

267
                        $content .= "\n" . $mBlank . $mContent;
1 ✔
268
                        $itemEnd = ($offsets[0] ?? throw new \LogicException('Match without group 0.')) + strlen($matches[0]);
1 ✔
269
                }
270

271
                $text = $isBullet ? rtrim($content) : trim($content);
1 ✔
272
                $parsed = $context->parseBlock($text);
1 ✔
273
                if ($map) {
1 ✔
274
                        new Texy\Parsing\OffsetMap($map, strlen(rtrim($content)) - strlen($text))->applyTo($parsed);
1 ✔
275
                }
276

277
                return new ListItemNode(
1 ✔
278
                        $parsed,
1 ✔
279
                        false,
1 ✔
280
                        Modifier::parse($mMod, $modOffset),
1 ✔
281
                        new Range($itemOffset, $itemEnd - $itemOffset),
1 ✔
282
                        rtrim($mBullet),
1 ✔
283
                        $bulletRange,
284
                );
285
        }
286

287

288
        /**
289
         * Bullets of the kinds switched on in the context.
290
         * @return array<string, array{string, ListType, 2?: string}>
291
         */
292
        private function getBullets(ParseContext $context): array
293
        {
294
                $bullets = [];
1 ✔
295
                foreach (self::Bullets as $name => $kind) {
1 ✔
296
                        if ($name === Syntax::List || !empty($context->allowedSyntaxes[$name])) {
1 ✔
297
                                $bullets += $kind;
1 ✔
298
                        }
299
                }
300

301
                return $bullets;
1 ✔
302
        }
303

304

305
        /**
306
         * Range of a whole list, from its start to the end of its last item.
307
         * @param  non-empty-list<ListItemNode>  $items
308
         */
309
        private function createRange(int $offset, array $items): Range
310
        {
311
                $last = $items[count($items) - 1]->range ?? throw new \LogicException('List item without range.');
1 ✔
312
                return new Range($offset, $last->offset + $last->length - $offset);
1 ✔
313
        }
314
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc