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

dg / texy / 42150856071

06 Nov 2026 01:24AM UTC coverage: 96.113% (+0.3%) from 95.817%
42150856071

push

github

dg
Output\Texy\Renderer: a text written nowhere is read by the inline parser

A text node without a range had only its & and < escaped, so the text
"*foo*" of a consumer printed as an emphasis. Such a text is now read by
the inline parser of the given Texy, and the first character of whatever
it finds there besides plain text and the addresses it links by itself
is escaped, until it finds nothing. A text alone cannot see its
neighbours, so a paragraph or heading holding one is read back as a
whole, and where its text differs, it is printed again with every
character escaped that Texy syntax could start with. The mechanism comes
from TexyConverter of texy/markdown, which can drop it.

Parsed documents print as before: the prints of the 16201 valid
documents of the reference corpus are byte-identical.

8f49b3e4-2f59-4596-83cb-a4ee32148a48

40 of 40 new or added lines in 1 file covered. (100.0%)

58 existing lines in 7 files now uncovered.

3610 of 3756 relevant lines covered (96.11%)

0.96 hits per line

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

97.78
/src/Texy/Modules/PhraseModule.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\{Compat, Modifier, Patterns, Range, Syntax};
12
use Texy\Nodes\{ContentNode, LinkNode, PhraseNode, RawTextNode, TextNode};
13
use Texy\Parsing\ParseContext;
14
use function strlen;
15

16

17
/**
18
 * Processes inline text formatting (bold, italic, code, etc.).
19
 */
20
final class PhraseModule extends Texy\Module
21
{
22
        /**
23
         * Paired phrases: a delimiter, some content, an optional modifier, the same
24
         * delimiter again. They all share one skeleton (see buildPhrasePattern()),
25
         * so a row only says what the delimiters are and which characters must not
26
         * touch them:
27
         *
28
         *   char        the delimiter character, as it appears inside a class
29
         *   guard       characters that must not precede either delimiter
30
         *   guardAfter  characters that must not follow either delimiter
31
         *   link        the phrase can carry a :link suffix
32
         *   multiline   the content may span lines
33
         *
34
         * The remaining keys are overrides for the places where a syntax deviates
35
         * from the skeleton; each one is commented, because the deviations are the
36
         * only interesting thing here.
37
         */
38
        private const Phrases = [
39
                Syntax::StrongEmphasis => ['open' => '\*\*\*', 'char' => '\*', 'guard' => '\\\\', 'link' => true, 'multiline' => true],
40
                Syntax::Strong => ['open' => '\*\*', 'char' => '\*', 'guard' => '\\\\', 'link' => true, 'multiline' => true],
41
                // : guards the // in http://
42
                Syntax::Emphasis => ['open' => '//', 'char' => '/', 'guard' => ':', 'link' => true, 'multiline' => true],
43
                Syntax::EmphasisSingleAsterisk => [
44
                        'open' => '\*', 'char' => '\*', 'guard' => '\\\\', 'link' => true, 'multiline' => true,
45
                        'content' => '\s\*', 'contentPair' => '\*', // a single * phrase holds no whitespace at all
46
                ],
47
                Syntax::EmphasisSingleAsterisk2 => [
48
                        'open' => '\*', 'char' => '\*', 'guard' => '\\\\', 'link' => true, 'multiline' => true,
49
                        'beforeOpen' => '[^\s.,;:<>()"\'-]',    // must stand at a word boundary, ...
50
                        'afterClose' => '[^\s.,;:<>()"?!\'-]',  // ... hence the inverted classes
51
                ],
52
                Syntax::Inserted => ['open' => '\+\+', 'char' => '\+'],
53
                // < and > guard the arrows <-- and -->
54
                Syntax::Deleted => ['open' => '--', 'char' => '\-', 'guard' => '<', 'guardAfter' => '>'],
55
                Syntax::Superscript => ['open' => '\^\^', 'char' => '\^'],
56
                Syntax::Subscript => ['open' => '__', 'char' => '_'],
57
                Syntax::SpanQuotes => [
58
                        'open' => '"', 'char' => '"', 'link' => true,
59
                        'afterOpen' => '\s', 'beforeClose' => '\s', // the delimiter may touch itself: ""quoted""
60
                        'content' => '\r "', 'contentPair' => ' ',  // and the content may span lines
61
                ],
62
                Syntax::SpanTilde => [
63
                        'open' => '\~', 'char' => '\~', 'link' => true,
64
                        'afterOpen' => '\s', 'beforeClose' => '\s',
65
                        'content' => '\r \~', 'contentPair' => ' ',
66
                ],
67
                Syntax::Quote => ['open' => '>>', 'close' => '<<', 'char' => '>', 'closeChar' => '<', 'link' => true],
68
        ];
69

70
        public bool $linksAllowed = true;
71

72

73
        public function __construct(
1 ✔
74
                private Texy\Texy $texy,
75
        ) {
76
                $texy->allowed[Syntax::Inserted] = false;
1 ✔
77
                $texy->allowed[Syntax::Deleted] = false;
1 ✔
78
                $texy->allowed[Syntax::Superscript] = false;
1 ✔
79
                $texy->allowed[Syntax::Subscript] = false;
1 ✔
80
        }
1 ✔
81

82

83
        public function beforeParse(): void
84
        {
85
                $texy = $this->texy;
1 ✔
86

87
                foreach (self::Phrases as $syntax => $spec) {
1 ✔
88
                        $texy->addLineSyntax($syntax, self::buildPhrasePattern($spec), $this->parsePhrase(...));
1 ✔
89
                }
90

91
                // m^2 alternative superscript
92
                $texy->addLineSyntax(
1 ✔
93
                        Syntax::SuperscriptShort,
1 ✔
94
                        '~
1 ✔
95
                                (?<= [a-z0-9] )                  # preceded by letter or number
96
                                \^
97
                                ( [n0-9+-]{1,4}? )               # 1-4 digits, n, + or - (1)
98
                                (?! [a-z0-9] )                   # not followed by letter or number
99
                        ~Uix',
100
                        $this->parseSupSub(...),
1 ✔
101
                );
102

103
                // m_2 alternative subscript
104
                $texy->addLineSyntax(
1 ✔
105
                        Syntax::SubscriptShort,
1 ✔
106
                        '~
1 ✔
107
                                (?<= [a-z] )                     # preceded by letter
108
                                _
109
                                ( [n0-9]{1,3} )                  # 1-3 digits or n (1)
110
                                (?! [a-z0-9] )                   # not followed by letter or number
111
                        ~Uix',
112
                        $this->parseSupSub(...),
1 ✔
113
                );
114

115
                // acronym/abbr "et al."((and others))
116
                $texy->addLineSyntax(
1 ✔
117
                        Syntax::AbbreviationQuotes,
1 ✔
118
                        '~
119
                                (?<! " )                         # not preceded by "
120
                                "
121
                                (?! \s )                         # not followed by space
122
                                ( (?: [^\r\n "]++ | [ ] )+ )     # content (1)
123
                                ' . Patterns::Modifier . '?      # modifier (2)
1 ✔
124
                                (?<! \s )                        # not preceded by space
125
                                "
126
                                (?! " )                          # not followed by "
127
                                \(\(
128
                                ( .+ )                           # explanation (3)
129
                                \)\)
130
                        ~Ux',
131
                        $this->parseAcronym(...),
1 ✔
132
                );
133

134
                // acronym/abbr NATO((North Atlantic Treaty Organisation))
135
                $texy->addLineSyntax(
1 ✔
136
                        Syntax::Abbreviation,
1 ✔
137
                        '~
138
                                (?<! [' . Patterns::Letter . '] )  # not preceded by char
139
                                ( [' . Patterns::Letter . ']{2,} ) # at least 2 chars (1)
1 ✔
140
                                ()                               # modifier placeholder (2)
141
                                \(\(
142
                                ( (?: [^\n )]++ | [ )] )+ )      # explanation (3)
143
                                \)\)
144
                        ~Ux',
145
                        $this->parseAcronym(...),
1 ✔
146
                );
147

148
                // ''notexy''
149
                $texy->addLineSyntax(
1 ✔
150
                        Syntax::Raw,
1 ✔
151
                        '~
1 ✔
152
                                (?<! \' )                         # not preceded by quote
153
                                \'\'
154
                                (?! [\s\'] )                      # not followed by space or quote
155
                                ( (?: [^\r\n\']++ | \' )+ )       # content (1)
156
                                (?<! [\s\'] )                     # not preceded by space or quote
157
                                \'\'
158
                                (?! \' )                          # not followed by quote
159
                        ~Ux',
160
                        $this->parseNoTexy(...),
1 ✔
161
                );
162

163
                // `code`
164
                $texy->addLineSyntax(
1 ✔
165
                        Syntax::Code,
1 ✔
166
                        '~
167
                                `
168
                                ( \S (?: [^\r\n `]++ | [ `] )* )        # content (1)
169
                                ' . Patterns::Modifier . '?             # modifier (2)
170
                                (?<! \s )                               # not preceded by space
171
                                `
172
                                (?: : (' . Patterns::LinkUrl . ') )??  # optional link (3)
1 ✔
173
                        ~Ux',
174
                        $this->parsePhrase(...),
1 ✔
175
                );
176

177
                // ....:LINK
178
                $texy->addLineSyntax(
1 ✔
179
                        Syntax::QuickLink,
1 ✔
180
                        '~
181
                                ( [' . Patterns::Letter . '0-9@#$%&.,_-]++ )  # allowed chars (1)
182
                                ()                                    # modifier placeholder (2)
183
                                : (?= \[ )                            # followed by :[
184
                                (' . Patterns::LinkUrl . ')          # link (3)
1 ✔
185
                        ~Ux',
186
                        $this->parseLink(...),
1 ✔
187
                );
188

189
                // [text |link]
190
                $texy->addLineSyntax(
1 ✔
191
                        Syntax::WikiLink,
1 ✔
192
                        '~
193
                                (?<! \[ )                        # not preceded by [
194
                                \[
195
                                (?! [\s*] )                      # not followed by space or *
196
                                ( [^|\r\n\]]++ )                 # text (1)
197
                                \|
198
                                ( (?: [^|\r\n \]]++ | [ ] )+ )   # link (2)
199
                                ' . Patterns::Modifier . '?      # modifier (3)
1 ✔
200
                                (?<! \s )                        # not preceded by space
201
                                ]
202
                                (?! ] )                          # not followed by ]
203
                        ~Ux',
204
                        $this->parseWikilink(...),
1 ✔
205
                );
206

207
                // [text](link)
208
                $texy->addLineSyntax(
1 ✔
209
                        Syntax::MarkdownLink,
1 ✔
210
                        '~
211
                                (?<! [[.] )                     # not preceded by [ or .
212
                                \[
213
                                (?! [\s*] )                     # not followed by space or *
214
                                ( (?: [^|\r\n \]]++ | [ ] )+ )  # text (1)
215
                                ' . Patterns::Modifier . '?     # modifier (2)
1 ✔
216
                                (?<! \s )                       # not preceded by space
217
                                ]
218
                                \(
219
                                ( (?: [^\r )]++ | [ ] )+ )      # link (3)
220
                                \)
221
                        ~Ux',
222
                        $this->parseLink(...),
1 ✔
223
                );
224

225
                // \* escaped asterisk
226
                $texy->addLineSyntax(
1 ✔
227
                        Syntax::EscapedAsterisk,
1 ✔
228
                        '~\\\\\*~',
1 ✔
229
                        fn($context, $matches, $offsets) => new TextNode('*', new Range($offsets[0], 2)),
1 ✔
230
                );
231
        }
1 ✔
232

233

234
        /**
235
         * Builds the pattern of a paired phrase from its delimiter spec:
236
         *
237
         *   (?<! guard ) open (?! space or char ) content modifier? (?<! space or guard ) close (?! char ) (:link)??
238
         *
239
         * @param  array<string, string|bool>  $spec
240
         */
241
        private static function buildPhrasePattern(array $spec): string
242
        {
243
                $char = (string) $spec['char'];
1 ✔
244
                $closeChar = (string) ($spec['closeChar'] ?? $char);
1 ✔
245
                $guard = (string) ($spec['guard'] ?? '');
1 ✔
246
                $guardAfter = (string) ($spec['guardAfter'] ?? '');
1 ✔
247

248
                $beforeOpen = $spec['beforeOpen'] ?? self::charClass($char . $guard);
1 ✔
249
                $afterOpen = $spec['afterOpen'] ?? self::charClass('\s' . $char . $guardAfter);
1 ✔
250
                $beforeClose = $spec['beforeClose'] ?? self::charClass('\s' . $closeChar . $guard);
1 ✔
251
                $afterClose = $spec['afterClose'] ?? self::charClass($closeChar . $guardAfter);
1 ✔
252
                $content = $spec['content'] ?? (empty($spec['multiline']) ? '\r\n' : '') . ' ' . $closeChar;
1 ✔
253
                $contentPair = $spec['contentPair'] ?? ' ' . $closeChar;
1 ✔
254

255
                return '~
256
                                (?<! ' . $beforeOpen . ' ) ' . $spec['open'] . ' (?! ' . $afterOpen . ' )  # opening delimiter
1 ✔
257
                                ( (?: [^' . $content . ']++ | [' . $contentPair . '] )+ )  # content (1)
1 ✔
258
                                ' . Patterns::Modifier . '?  # modifier (2)
1 ✔
259
                                (?<! ' . $beforeClose . ' ) ' . ($spec['close'] ?? $spec['open']) . ' (?! ' . $afterClose . ' )  # closing delimiter'
1 ✔
260
                        . (empty($spec['link'])
1 ✔
261
                                ? ''
1 ✔
262
                                : '
263
                                (?: :(' . Patterns::LinkUrl . ') )??  # optional link (3)')
1 ✔
264
                        . '
1 ✔
265
                        ~U' . (empty($spec['multiline']) ? '' : 's') . 'x';
1 ✔
266
        }
267

268

269
        /**
270
         * Wraps characters in a class, unless a single (possibly escaped) one speaks for itself.
271
         */
272
        private static function charClass(string $chars): string
273
        {
274
                return preg_match('#^(\\\.|[^\\\])$#D', $chars)
1 ✔
275
                        ? $chars
1 ✔
276
                        : '[' . $chars . ']';
1 ✔
277
        }
278

279

280
        /**
281
         * Parses phrase patterns. Phrases without a link part (ins, del, sup, sub) have
282
         * only two groups, hence the optional third one.
283
         * @param  array{string, string, ?string, 3?: ?string}  $matches
284
         * @param  array{int, int, ?int, 3?: ?int}  $offsets
285
         */
286
        public function parsePhrase(
287
                ParseContext $context,
288
                array $matches,
289
                array $offsets,
290
                string $phrase,
291
        ): PhraseNode|LinkNode|null
292
        {
293
                [, $mContent, $mMod, $mLink] = $matches + [3 => null];
1 ✔
294
                $range = new Range($offsets[0], strlen($matches[0]));
1 ✔
295
                $contentOffset = $offsets[1];
1 ✔
296
                $textRange = self::trimRange($mContent, $contentOffset);
1 ✔
297
                $urlRange = $mLink === null ? null : new Range($offsets[3] ?? throw new \LogicException('Link without group 3.'), strlen($mLink));
1 ✔
298

299
                // For phrase/span and phrase/span-alt, URL makes it a link
300
                if ($phrase === Syntax::SpanQuotes || $phrase === Syntax::SpanTilde) {
1 ✔
301
                        if ($mLink !== null && $this->linksAllowed) {
1 ✔
302
                                return new LinkNode(
1 ✔
303
                                        url: Texy\Helpers::removeSoftHyphens($mLink),
1 ✔
304
                                        content: $context->parseInline(trim($mContent), $contentOffset),
1 ✔
305
                                        modifier: Modifier::parse($mMod, $offsets[2] ?? null),
1 ✔
306
                                        range: $range,
307
                                        syntax: $phrase,
308
                                        textRange: $textRange,
309
                                        urlRange: $urlRange,
310
                                );
311

312
                        } elseif ($mLink === null && $mMod === null) {
1 ✔
313
                                return null;
1 ✔
314
                        }
315
                }
316

317
                $mod = Modifier::parse($mMod, $offsets[2] ?? null);
1 ✔
318
                $content = $phrase === Syntax::Code
1 ✔
319
                        ? new ContentNode([new TextNode(trim($mContent), $textRange)]) // code content is not parsed recursively
1 ✔
320
                        : $context->parseInline(trim($mContent), $contentOffset);
1 ✔
321

322
                // Other phrases with link
323
                if ($mLink !== null && $this->linksAllowed) {
1 ✔
324
                        return new LinkNode(
1 ✔
325
                                url: Texy\Helpers::removeSoftHyphens($mLink),
1 ✔
326
                                content: new ContentNode([new PhraseNode($content, $phrase, $mod, $range)]),
1 ✔
327
                                range: $range,
328
                                syntax: $phrase,
329
                                textRange: $textRange,
330
                                urlRange: $urlRange,
331
                        );
332
                }
333

334
                return new PhraseNode($content, $phrase, $mod, $range);
1 ✔
335
        }
336

337

338
        /**
339
         * Parses superscript/subscript alternative (m^2, H_2O).
340
         * @param  array{string, string}  $matches
341
         * @param  array{int, int}  $offsets
342
         */
343
        public function parseSupSub(ParseContext $context, array $matches, array $offsets, string $phrase): PhraseNode
344
        {
345
                [, $mContent] = $matches;
1 ✔
346
                $mContent = str_replace('-', "\u{2212}", $mContent); // &minus;
1 ✔
347
                $content = [new TextNode(Texy\Helpers::decodeEntities($mContent), new Range($offsets[1], strlen($matches[1])))];
1 ✔
348
                return new PhraseNode(
1 ✔
349
                        new ContentNode($content),
1 ✔
350
                        $phrase,
351
                        null,
1 ✔
352
                        new Range($offsets[0], strlen($matches[0])),
1 ✔
353
                );
354
        }
355

356

357
        /**
358
         * Parses acronym/abbr.
359
         * @param  array{string, string, ?string, string}  $matches
360
         * @param  array{int, int, ?int, int}  $offsets
361
         */
362
        public function parseAcronym(ParseContext $context, array $matches, array $offsets, string $phrase): PhraseNode
363
        {
364
                [, $mContent, $mMod, $mTitle] = $matches;
1 ✔
365
                $contentOffset = $offsets[1];
1 ✔
366

367
                $mod = Modifier::parse($mMod, $offsets[2] ?? null) ?? new Modifier;
1 ✔
368
                $mod->title = trim(Texy\Helpers::unescapeHtml($mTitle));
1 ✔
369
                $content = [new TextNode(Texy\Helpers::decodeEntities(trim($mContent)), new Range($contentOffset, strlen(trim($mContent))))];
1 ✔
370

371
                return new PhraseNode(new ContentNode($content), $phrase, $mod, new Range($offsets[0], strlen($matches[0])));
1 ✔
372
        }
373

374

375
        /**
376
         * Parses ''notexy''.
377
         * @param  array{string, string}  $matches
378
         * @param  array{int, int}  $offsets
379
         */
380
        public function parseNoTexy(ParseContext $context, array $matches, array $offsets): RawTextNode
381
        {
382
                [, $mContent] = $matches;
1 ✔
383
                return new RawTextNode($mContent, new Range($offsets[0], strlen($matches[0])));
1 ✔
384
        }
385

386

387
        /**
388
         * Parses links (phrase/quicklink, phrase/markdown).
389
         * Note: Markdown links don't support modifiers - modifier is intentionally ignored.
390
         * @param  array{string, string, ?string, string}  $matches
391
         * @param  array{int, int, ?int, int}  $offsets
392
         */
393
        public function parseLink(ParseContext $context, array $matches, array $offsets, string $name): LinkNode|ContentNode
394
        {
395
                [, $mContent, $mMod, $mLink] = $matches;
1 ✔
396
                $content = $context->parseInline(trim($mContent), $offsets[1]);
1 ✔
397
                if (!$this->linksAllowed) {
1 ✔
398
                        return $content;
1 ✔
399
                }
400

401
                return new LinkNode(
1 ✔
402
                        Texy\Helpers::removeSoftHyphens(trim($mLink)),
1 ✔
403
                        $content,
404
                        null,  // quicklink and markdown links don't support modifiers
1 ✔
405
                        new Range($offsets[0], strlen($matches[0])),
1 ✔
406
                        syntax: $name,
407
                        textRange: self::trimRange($mContent, $offsets[1]),
1 ✔
408
                        urlRange: self::trimRange($mLink, $offsets[3]),
1 ✔
409
                );
410
        }
411

412

413
        /**
414
         * Parses wikilink [text|link].
415
         * Note: Wikilinks don't support modifiers - modifier is intentionally ignored.
416
         * @param  array{string, string, string, ?string}  $matches
417
         * @param  array{int, int, int, ?int}  $offsets
418
         */
419
        public function parseWikilink(ParseContext $context, array $matches, array $offsets, string $name): LinkNode|ContentNode
420
        {
421
                [, $mContent, $mLink] = $matches;
1 ✔
422
                $content = $context->parseInline(trim($mContent), $offsets[1]);
1 ✔
423
                if (!$this->linksAllowed) {
1 ✔
424
                        return $content;
1 ✔
425
                }
426

427
                return new LinkNode(
1 ✔
428
                        Texy\Helpers::removeSoftHyphens(trim($mLink)),
1 ✔
429
                        $content,
430
                        null,  // wikilinks don't support modifiers
1 ✔
431
                        new Range($offsets[0], strlen($matches[0])),
1 ✔
432
                        syntax: $name,
433
                        textRange: self::trimRange($mContent, $offsets[1]),
1 ✔
434
                        urlRange: self::trimRange($mLink, $offsets[2]),
1 ✔
435
                );
436
        }
437

438

439
        /** Range of the text without its surrounding whitespace. */
440
        private static function trimRange(string $text, int $offset): Range
441
        {
442
                return new Range($offset + strlen($text) - strlen(ltrim($text)), strlen(trim($text)));
1 ✔
443
        }
444

445

446
        /**
447
         * @deprecated use $texy->htmlOutput->phraseTags etc. instead
448
         */
449
        public function &__get(string $name): mixed
450
        {
451
                return Compat\Legacy::ref($this->texy, Compat\Legacy::OfModule['phraseModule'], '$texy->phraseModule', $name, 'read');
1 ✔
452
        }
453

454

455
        /**
456
         * @deprecated use $texy->htmlOutput->phraseTags etc. instead
457
         */
458
        public function __set(string $name, mixed $value): void
459
        {
UNCOV
460
                Compat\Legacy::set($this->texy, Compat\Legacy::OfModule['phraseModule'], '$texy->phraseModule', $name, $value);
×
UNCOV
461
        }
×
462

463

464
        public function __isset(string $name): bool
465
        {
UNCOV
466
                return Compat\Legacy::isSet($this->texy, Compat\Legacy::OfModule['phraseModule'], $name);
×
467
        }
468
}
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