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

dg / texy / 43784404972

24 Sep 2026 04:37PM UTC coverage: 97.162% (-0.06%) from 97.217%
43784404972

push

github

dg
compatibility layer for Texy 3

The layer lives in Texy\Compatibility. Configuration code written for Texy 3 keeps running,
applyTypography() included, with a deprecation that names the new place. A setting without
a replacement only warns, and results of parsing that used to live on modules throw with
guidance. Removed methods throw, addReference() of the link and image modules included;
the extension API of Texy 3 is not emulated.

The quote table of Texy 3, pairs of singleQuotes and doubleQuotes, is converted to lists
of four, and the keys of phraseTags of Texy 3, which are names of syntaxes, are converted
to what the phrases mean, both when parsing and when creating the HTML renderer.

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

100 of 111 new or added lines in 4 files covered. (90.09%)

30 existing lines in 7 files now uncovered.

3868 of 3981 relevant lines covered (97.16%)

0.97 hits per line

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

98.81
/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\{OffsetMap, 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\Engine $engine): void
26
        {
27
                $engine->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, TableCellNode> $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
                                // group 1 always participates in a successful match, but next() cannot type that
88
                                $mContent = $lineMatches[1] ?? throw new \LogicException('Match without group 1.');
1 ✔
89
                                $mRowMod = $lineMatches[2] ?? null;
1 ✔
90
                                $lineBaseOffset = $lineOffsets[1] ?? throw new \LogicException('Match without group 1.'); // content after first |
1 ✔
91

92
                                $cells = [];
1 ✔
93
                                $col = 0;
1 ✔
94
                                $lastCell = null;
1 ✔
95

96
                                // a | divides cells unless it is escaped or stands inside [brackets]
97
                                foreach (Regexp::split(
1 ✔
UNCOV
98
                                        $mContent,
×
99
                                        '~(?: \\\\\| | \[ [^]]*+ ] ) (*SKIP)(*FAIL) | \|~x',
1 ✔
100
                                        captureOffset: true,
1 ✔
101
                                ) as [$cell, $cellOffset]) {
1 ✔
102
                                        $cellAbsoluteOffset = $lineBaseOffset + $cellOffset;
1 ✔
103

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

119
                                        // colSpan: empty cell extends previous cell
120
                                        if ($cell === '' && $lastCell !== null) {
1 ✔
121
                                                $lastCell->colspan++;
1 ✔
122
                                                unset($prevRow[$col]);
1 ✔
123
                                                $col++;
1 ✔
124
                                                continue;
1 ✔
125
                                        }
126

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

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

145
                                                $cellIsHeader = $isHead || ($mHead === '*');
1 ✔
146

147
                                                // column modifier inheritance; the modifiers are parsed unescaped, their ranges are of the source
148
                                                if ($mModCol) {
1 ✔
149
                                                        $colModifier[$col] = new Modifier;
1 ✔
150
                                                        $colModifier[$col]->setProperties(str_replace('\|', '|', $mModCol));
1 ✔
151
                                                        $colModifier[$col]->range = $cellMatches[2][1] >= 0
1 ✔
152
                                                                ? new Range($cellAbsoluteOffset + $cellMatches[2][1], strlen($mModCol))
1 ✔
UNCOV
153
                                                                : null;
×
154
                                                }
155
                                                $cellMod = isset($colModifier[$col]) ? clone $colModifier[$col] : new Modifier;
1 ✔
156
                                                $cellMod->setProperties($mCellMod === null ? null : str_replace('\|', '|', $mCellMod));
1 ✔
157
                                                if ($mCellMod !== null) { // the range covers the modifier only when it is written as a single part
1 ✔
158
                                                        $cellMod->range = isset($colModifier[$col])
1 ✔
159
                                                                ? null
1 ✔
160
                                                                : new Range($cellAbsoluteOffset + $cellMatches[4][1], strlen($mCellMod));
1 ✔
161
                                                } elseif (!$mModCol) { // inherited from the column, not written here
1 ✔
162
                                                        $cellMod->range = null;
1 ✔
163
                                                }
164

165
                                                // Calculate absolute offset of cell content
166
                                                $contentAbsoluteOffset = $cellAbsoluteOffset + $mCellContentOffset;
1 ✔
167

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

184
                                // even up with empty cells
185
                                while ($col < $colCounter) {
1 ✔
186
                                        $cellMod = isset($colModifier[$col]) ? clone $colModifier[$col] : new Modifier;
1 ✔
187
                                        $emptyCell = new TableCellNode(new ContentNode, 1, 1, $isHead, $cellMod);
1 ✔
188
                                        $cells[] = $emptyCell;
1 ✔
189
                                        $cellTexts[$emptyCell] = [['content' => '', 'offset' => 0]];
1 ✔
190
                                        $prevRow[$col] = $emptyCell;
1 ✔
191
                                        $col++;
1 ✔
192
                                }
193

194
                                $colCounter = $col;
1 ✔
195
                                $end = $this->getLineEnd($lineMatches, $lineOffsets);
1 ✔
196

197
                                if ($cells) {
1 ✔
198
                                        $rowMod = Modifier::parse($mRowMod, $lineOffsets[2] ?? null);
1 ✔
199
                                        $rowOffset = $lineOffsets[0] ?? throw new \LogicException('Match without group 0.');
1 ✔
200
                                        $rows[] = new TableRowNode($cells, $isHead, $rowMod, new Range($rowOffset, $end - $rowOffset));
1 ✔
201
                                } else {
202
                                        // redundant row - decrement rowspan
203
                                        foreach ($prevRow as $cell) {
1 ✔
204
                                                $cell->rowspan--;
1 ✔
205
                                        }
206
                                }
207

208
                                continue;
1 ✔
209
                        }
210

211
                        break;
1 ✔
212
                }
213

214
                if (!$rows) {
1 ✔
215
                        return null;
1 ✔
216
                }
217

218
                // Parse cell text content after rowspan/colspan is determined
219
                foreach ($rows as $row) {
1 ✔
220
                        foreach ($row->cells as $cell) {
1 ✔
221
                                if (isset($cellTexts[$cell])) {
1 ✔
222
                                        $lines = $cellTexts[$cell];
1 ✔
223

224
                                        // right-trim: drop blank trailing fragments, trim the last one
225
                                        while ($lines && rtrim($lines[count($lines) - 1]['content']) === '') {
1 ✔
226
                                                array_pop($lines);
1 ✔
227
                                        }
228
                                        if ($lines) {
1 ✔
229
                                                $last = count($lines) - 1;
1 ✔
230
                                                $lines[$last]['content'] = rtrim($lines[$last]['content']);
1 ✔
231
                                        }
232

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

256
                                        $cell->content->children = $parsed->children;
1 ✔
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
         * Replaces \| with | and maps offsets in the result to the source, where $text starts at $offset.
277
         * @return array{string, ?OffsetMap}  the map is null when nothing was escaped
278
         */
279
        private static function unescapePipes(string $text, int $offset = 0): array
280
        {
281
                $parts = explode('\|', $text);
1 ✔
282
                $last = array_pop($parts);
1 ✔
283
                if (!$parts) {
1 ✔
284
                        return [$text, null];
1 ✔
285
                }
286

287
                $map = [0 => $offset];
1 ✔
288
                $local = 0;
1 ✔
289
                foreach ($parts as $part) {
1 ✔
290
                        $local += strlen($part);
1 ✔
291
                        $offset += strlen($part) + 1;
1 ✔
292
                        $map[$local] = $offset; // the | written behind a backslash
1 ✔
293
                        $local++;
1 ✔
294
                        $offset++;
1 ✔
295
                }
296

297
                return [implode('|', $parts) . '|' . $last, new OffsetMap($map)];
1 ✔
298
        }
299

300

301
        /**
302
         * Returns the source offset where a line matched by the block parser ends.
303
         * @param  array<?string>  $matches
304
         * @param  array<?int>  $offsets
305
         */
306
        private function getLineEnd(array $matches, array $offsets): int
307
        {
308
                // group 0 always participates in a successful match, but next() cannot type that
309
                $offset = $offsets[0] ?? throw new \LogicException('Match without group 0.');
1 ✔
310
                return $offset + strlen($matches[0] ?? '');
1 ✔
311
        }
312

313

314
        /** Parses the optional caption line |## Text preceding the first row. */
315
        private function parseCaption(ParseContext $context): ?ContentNode
316
        {
317
                $matches = $offsets = null;
1 ✔
318
                $context->getBlockParser()->next(
1 ✔
319
                        '~^
1 ✔
320
                                \|                            # opening pipe
321
                                ( [\#=] ){2,}  (?! [|\#=+] )  # opening chars (1)
322
                                (.+)                          # caption (2)
323
                                \1*                           # matching closing chars
324
                                \|? [ \t]*                    # optional closing pipe and spaces
325
                        $~Umx',
326
                        $matches,
327
                        $offsets,
328
                );
329

330
                if (!isset($matches[2], $offsets[2])) {
1 ✔
331
                        return null;
1 ✔
332
                }
333

334
                // space after the opening chars is a separator, not content
335
                $text = rtrim($matches[2]);
1 ✔
336
                $trimmed = ltrim($text);
1 ✔
337
                $offset = $offsets[2] + strlen($text) - strlen($trimmed);
1 ✔
338

339
                return $context->parseInline($trimmed, $offset);
1 ✔
340
        }
341
}
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