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

dg / texy / 42887648368

10 Nov 2026 01:51PM UTC coverage: 96.622% (-0.1%) from 96.735%
42887648368

push

github

dg
Config::$locales: each locale is a list of four quotes (BC break)

Opening and closing double quotes, then the single ones, instead of the pairs
singleQuotes and doubleQuotes. The compatibility layer converts the old table.

cabae8f0-9dec-45ab-a919-45e6dadc3ad6

8 of 8 new or added lines in 3 files covered. (100.0%)

73 existing lines in 18 files now uncovered.

3719 of 3849 relevant lines covered (96.62%)

0.97 hits per line

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

99.35
/src/Modules/TableModule.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\{ContentNode, TableCellNode, TableNode, TableRowNode};
13
use Texy\Parsing\ParseContext;
14
use function count, strlen;
15

16

17
/**
18
 * Table module.
19
 */
20
final class TableModule extends Texy\Module
21
{
22
        private bool $disableTables = false;
23

24

25
        public function register(Texy\Parsing\Registry $registry): void
26
        {
27
                $registry->addBlock(
1 ✔
28
                        Syntax::Table,
1 ✔
29
                        '~^
30
                                (?:' . Patterns::ModifierHVAlign . '\n)? # modifier (1)
1 ✔
31
                                \|                                   # table start
32
                                .*                                   # content
33
                        $~mUx',
34
                        $this->parseTable(...),
1 ✔
35
                );
36
        }
1 ✔
37

38

39
        /**
40
         * Parses tables.
41
         * @param  array{string, ?string}  $matches
42
         * @param  array{int, ?int}  $offsets
43
         */
44
        public function parseTable(ParseContext $context, array $matches, array $offsets): ?TableNode
45
        {
46
                if ($this->disableTables) {
1 ✔
47
                        return null;
1 ✔
48
                }
49

50
                [, $mMod] = $matches;
1 ✔
51

52
                $startOffset = $offsets[0];
1 ✔
53

54
                $context->getBlockParser()->moveBackward();
1 ✔
55

56
                $caption = $this->parseCaption($context);
1 ✔
57

58
                $rows = [];
1 ✔
59
                $isHead = false;
1 ✔
60
                /** @var array<int, array{node: TableCellNode, text: string}> $prevRow */
61
                $prevRow = [];
1 ✔
62
                $colModifier = [];
1 ✔
63
                $colCounter = 0;
1 ✔
64
                /** @var \SplObjectStorage<TableCellNode, list<array{content: string, offset: int}>> $cellTexts */
65
                $cellTexts = new \SplObjectStorage;
1 ✔
66

67
                $end = $startOffset + strlen($matches[0]);
1 ✔
68

69
                while (true) {
1 ✔
70
                        $lineMatches = null;
1 ✔
71
                        $lineOffsets = null;
1 ✔
72
                        if ($context->getBlockParser()->next('~^ \| ([=-]) [+|=-]{2,} $~Umx', $lineMatches, $lineOffsets)) {
1 ✔
73
                                $isHead = !$isHead;
1 ✔
74
                                $prevRow = [];
1 ✔
75
                                $end = $this->getLineEnd($lineMatches, $lineOffsets);
1 ✔
76
                                continue;
1 ✔
77
                        }
78

79
                        if ($context->getBlockParser()
1 ✔
80
                                ->next('~^ ( \| ) (.*) (?: | \| [ \t]* ' . Patterns::ModifierHVAlign . '?)$~Ux', $lineMatches, $lineOffsets)) {
1 ✔
81
                                // smarter head detection: if first row is followed by separator line, it's a head row
82
                                if ($rows === [] && !$isHead && $context->getBlockParser()->next('~^ \| [=-] [+|=-]{2,} $~Umx', $foo)) {
1 ✔
83
                                        $isHead = true;
1 ✔
84
                                        $context->getBlockParser()->moveBackward();
1 ✔
85
                                }
86

87
                                // groups 1 and 2 always participate in a successful match, but next() cannot type that
88
                                $mContent = $lineMatches[2] ?? throw new \LogicException('Match without group 2.');
1 ✔
89
                                $mRowMod = $lineMatches[3] ?? null;
1 ✔
90
                                $lineBaseOffset = $lineOffsets[2] ?? throw new \LogicException('Match without group 2.'); // content after first |
1 ✔
91

92
                                $cells = [];
1 ✔
93
                                $originalContent = $mContent;
1 ✔
94
                                $content = str_replace('\|', "\x13", $mContent);
1 ✔
95
                                $content = Regexp::replace($content, '~(\[[^]]*)\|~', "$1\x13");
1 ✔
96

97
                                $col = 0;
1 ✔
98
                                $lastCell = null;
1 ✔
99
                                $cellOffset = 0; // position within $content
1 ✔
100

101
                                foreach (explode('|', $content) as $cellIndex => $cell) {
1 ✔
102
                                        $originalCell = $cell;
1 ✔
103
                                        $cell = strtr($cell, "\x13", '|');
1 ✔
104
                                        $cellAbsoluteOffset = $lineBaseOffset + $cellOffset;
1 ✔
105

106
                                        // rowSpan: ^ at end of cell or cell is just ^
107
                                        if (isset($prevRow[$col]) && ($m = Regexp::match($cell, '~\^[ \t]*$|\*??(.*)[ \t]+\^$~AU', captureOffset: true))) {
1 ✔
108
                                                $prevRow[$col]['node']->rowspan++;
1 ✔
109
                                                /** @var non-empty-array<array{?string, int}> $m */
110
                                                $cellText = $m[1][0] ?? '';
1 ✔
111
                                                $cellTextOffset = ($m[1][1] ?? -1) >= 0 ? $cellAbsoluteOffset + $m[1][1] : $cellAbsoluteOffset;
1 ✔
112
                                                // Append text to the cell above
113
                                                $lines = $cellTexts[$prevRow[$col]['node']];
1 ✔
114
                                                $lines[] = ['content' => (string) $cellText, 'offset' => $cellTextOffset];
1 ✔
115
                                                $cellTexts[$prevRow[$col]['node']] = $lines;
1 ✔
116
                                                $col += $prevRow[$col]['node']->colspan;
1 ✔
117
                                                $lastCell = null;
1 ✔
118
                                                $cellOffset += strlen($originalCell) + 1; // +1 for |
1 ✔
119
                                                continue;
1 ✔
120
                                        }
121

122
                                        // colSpan: empty cell extends previous cell
123
                                        if ($cell === '' && $lastCell !== null) {
1 ✔
124
                                                $lastCell->colspan++;
1 ✔
125
                                                unset($prevRow[$col]);
1 ✔
126
                                                $col++;
1 ✔
127
                                                $cellOffset += strlen($originalCell) + 1;
1 ✔
128
                                                continue;
1 ✔
129
                                        }
130

131
                                        // common cell
132
                                        $cellMatches = Regexp::match($cell, '~
1 ✔
133
                                                ( \*?? )                          # head mark (1)
134
                                                [ \t]*
135
                                                ' . Patterns::ModifierHVAlign . '??   # modifier (2)
136
                                                (.*)                              # content (3)
137
                                                ' . Patterns::ModifierHVAlign . '?    # modifier (4)
1 ✔
138
                                                [ \t]*
139
                                        $~AUx', captureOffset: true);
1 ✔
140

141
                                        if ($cellMatches) {
1 ✔
142
                                                $mHead = $cellMatches[1][0];
1 ✔
143
                                                $mModCol = $cellMatches[2][0];
1 ✔
144
                                                // group 3 is (.*), so it always participates
145
                                                $mCellContent = $cellMatches[3][0] ?? throw new \LogicException('Cell without group 3.');
1 ✔
146
                                                $mCellContentOffset = $cellMatches[3][1];
1 ✔
147
                                                $mCellMod = $cellMatches[4][0];
1 ✔
148

149
                                                $cellIsHeader = $isHead || ($mHead === '*');
1 ✔
150

151
                                                // column modifier inheritance
152
                                                if ($mModCol) {
1 ✔
153
                                                        $colModifier[$col] = Modifier::parse(
1 ✔
UNCOV
154
                                                                $mModCol,
×
155
                                                                $cellMatches[2][1] >= 0 ? $cellAbsoluteOffset + $cellMatches[2][1] : null,
1 ✔
156
                                                        );
157
                                                }
158
                                                $cellMod = isset($colModifier[$col]) ? clone $colModifier[$col] : new Modifier;
1 ✔
159
                                                $cellMod->setProperties($mCellMod);
1 ✔
160
                                                if ($mCellMod !== null) { // the range covers the modifier only when it is written as a single part
1 ✔
161
                                                        $cellMod->range = isset($colModifier[$col])
1 ✔
162
                                                                ? null
1 ✔
163
                                                                : new Range($cellAbsoluteOffset + $cellMatches[4][1], strlen($mCellMod));
1 ✔
164
                                                } elseif (!$mModCol) { // inherited from the column, not written here
1 ✔
165
                                                        $cellMod->range = null;
1 ✔
166
                                                }
167

168
                                                // Calculate absolute offset of cell content
169
                                                $contentAbsoluteOffset = $cellAbsoluteOffset + $mCellContentOffset;
1 ✔
170

171
                                                // Create cell node - text will be parsed later
172
                                                $lastCell = new TableCellNode(
1 ✔
173
                                                        new ContentNode,
1 ✔
174
                                                        1,
1 ✔
175
                                                        1,
1 ✔
176
                                                        $cellIsHeader,
177
                                                        $cellMod,
178
                                                        new Range($cellAbsoluteOffset, strlen($originalCell)),
1 ✔
179
                                                );
180
                                                $cells[] = $lastCell;
1 ✔
181
                                                $cellTexts[$lastCell] = [['content' => $mCellContent, 'offset' => $contentAbsoluteOffset]];
1 ✔
182
                                                $prevRow[$col] = ['node' => $lastCell, 'text' => $mCellContent];
1 ✔
183
                                                $col++;
1 ✔
184
                                        }
185

186
                                        $cellOffset += strlen($originalCell) + 1; // +1 for |
1 ✔
187
                                }
188

189
                                // even up with empty cells
190
                                while ($col < $colCounter) {
1 ✔
191
                                        $cellMod = isset($colModifier[$col]) ? clone $colModifier[$col] : new Modifier;
1 ✔
192
                                        $emptyCell = new TableCellNode(new ContentNode, 1, 1, $isHead, $cellMod);
1 ✔
193
                                        $cells[] = $emptyCell;
1 ✔
194
                                        $cellTexts[$emptyCell] = [['content' => '', 'offset' => 0]];
1 ✔
195
                                        $prevRow[$col] = ['node' => $emptyCell, 'text' => ''];
1 ✔
196
                                        $col++;
1 ✔
197
                                }
198

199
                                $colCounter = $col;
1 ✔
200
                                $end = $this->getLineEnd($lineMatches, $lineOffsets);
1 ✔
201

202
                                if ($cells) {
1 ✔
203
                                        $rowMod = Modifier::parse($mRowMod, $lineOffsets[3] ?? null);
1 ✔
204
                                        $rowOffset = $lineOffsets[0] ?? throw new \LogicException('Match without group 0.');
1 ✔
205
                                        $rows[] = new TableRowNode($cells, $isHead, $rowMod, new Range($rowOffset, $end - $rowOffset));
1 ✔
206
                                } else {
207
                                        // redundant row - decrement rowspan
208
                                        foreach ($prevRow as $item) {
1 ✔
209
                                                $item['node']->rowspan--;
1 ✔
210
                                        }
211
                                }
212

213
                                continue;
1 ✔
214
                        }
215

216
                        break;
1 ✔
217
                }
218

219
                if (!$rows) {
1 ✔
220
                        return null;
1 ✔
221
                }
222

223
                // Parse cell text content after rowspan/colspan is determined
224
                foreach ($rows as $row) {
1 ✔
225
                        foreach ($row->cells as $cell) {
1 ✔
226
                                if (isset($cellTexts[$cell])) {
1 ✔
227
                                        $lines = $cellTexts[$cell];
1 ✔
228

229
                                        // right-trim: drop blank trailing fragments, trim the last one
230
                                        while ($lines && rtrim($lines[count($lines) - 1]['content']) === '') {
1 ✔
231
                                                array_pop($lines);
1 ✔
232
                                        }
233
                                        if ($lines) {
1 ✔
234
                                                $last = count($lines) - 1;
1 ✔
235
                                                $lines[$last]['content'] = rtrim($lines[$last]['content']);
1 ✔
236
                                        }
237

238
                                        if (count($lines) > 1) {
1 ✔
239
                                                // multiline - parse as block (disable nested tables)
240
                                                [$outdented, $map] = Texy\Parsing\OffsetMap::outdentLines($lines);
1 ✔
241
                                                $this->disableTables = true;
1 ✔
242
                                                try {
243
                                                        $parsed = $context->parseBlock($outdented);
1 ✔
244
                                                } finally {
1 ✔
245
                                                        $this->disableTables = false;
1 ✔
246
                                                }
247
                                                $map->applyTo($parsed);
1 ✔
248
                                                $cell->content->children = $parsed->children;
1 ✔
249
                                        } else {
250
                                                // single line - parse as inline
251
                                                $text = $lines[0]['content'] ?? '';
1 ✔
252
                                                $trimmed = ltrim($text);
1 ✔
253
                                                $trimOffset = strlen($text) - strlen($trimmed);
1 ✔
254
                                                $baseOffset = ($lines[0]['offset'] ?? 0) + $trimOffset;
1 ✔
255
                                                $cell->content->children = $context->parseInline($trimmed, $baseOffset)->children;
1 ✔
256
                                        }
257

258
                                        // empty cell gets &nbsp;
259
                                        if ($cell->content->children === []) {
1 ✔
260
                                                $cell->content->children = [new Texy\Nodes\TextNode("\u{A0}")];
1 ✔
261
                                        }
262
                                }
263
                        }
264
                }
265

266
                return new TableNode(
1 ✔
267
                        $rows,
1 ✔
268
                        Modifier::parse($mMod, $offsets[1]),
1 ✔
269
                        new Range($startOffset, $end - $startOffset),
1 ✔
270
                        $caption,
271
                );
272
        }
273

274

275
        /**
276
         * Returns the source offset where a line matched by the block parser ends.
277
         * @param  array<?string>  $matches
278
         * @param  array<?int>  $offsets
279
         */
280
        private function getLineEnd(array $matches, array $offsets): int
281
        {
282
                // group 0 always participates in a successful match, but next() cannot type that
283
                $offset = $offsets[0] ?? throw new \LogicException('Match without group 0.');
1 ✔
284
                return $offset + strlen($matches[0] ?? '');
1 ✔
285
        }
286

287

288
        /** Parses the optional caption line |## Text preceding the first row. */
289
        private function parseCaption(ParseContext $context): ?ContentNode
290
        {
291
                $matches = $offsets = null;
1 ✔
292
                $context->getBlockParser()->next(
1 ✔
293
                        '~^
1 ✔
294
                                \|                            # opening pipe
295
                                ( [\#=] ){2,}  (?! [|\#=+] )  # opening chars (1)
296
                                (.+)                          # caption (2)
297
                                \1*                           # matching closing chars
298
                                \|? [ \t]*                    # optional closing pipe and spaces
299
                        $~Umx',
300
                        $matches,
301
                        $offsets,
302
                );
303

304
                if (!isset($matches[2], $offsets[2])) {
1 ✔
305
                        return null;
1 ✔
306
                }
307

308
                // space after the opening chars is a separator, not content
309
                $text = rtrim($matches[2]);
1 ✔
310
                $trimmed = ltrim($text);
1 ✔
311
                $offset = $offsets[2] + strlen($text) - strlen($trimmed);
1 ✔
312

313
                return $context->parseInline($trimmed, $offset);
1 ✔
314
        }
315
}
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