• 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

95.35
/src/Texy/Modules/LinkReferenceModule.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, Helpers, NodeHelpers, Nodes, Patterns, Range, Syntax};
12
use Texy\Nodes\{DocumentNode, LinkDefinitionNode};
13
use Texy\Parsing\ParseContext;
14
use function in_array, strlen;
15

16

17
/**
18
 * Processes link references and generates link elements.
19
 */
20
final class LinkReferenceModule extends Texy\Module
21
{
22
        /** @var array<string, LinkDefinitionNode> link definitions */
23
        private array $definitions = [];
24

25
        /** @var array<string, LinkDefinitionNode> user-defined definitions (persist across process() calls) */
26
        private array $userDefinitions = [];
27

28

29
        public function __construct(
1 ✔
30
                private Texy\Texy $texy,
31
        ) {
32
                $texy->allowed[Syntax::LinkDefinition] = true;
1 ✔
33
                $texy->allowed[Syntax::LinkReference] = false;
1 ✔
34
                $texy->addPass($this->recognizeReferences(...), Texy\Stage::Syntax);
1 ✔
35
                $texy->addPass($this->resolveReferences(...));
1 ✔
36
        }
1 ✔
37

38

39
        public function beforeParse(): void
40
        {
41
                // [ref]: url label .(title)[class]{style}
42
                $this->texy->addBlockSyntax(
1 ✔
43
                        Syntax::LinkDefinition,
1 ✔
44
                        '~^
45
                                \[
46
                                ( [^\[\]#?*\n]{1,100} )           # reference (1)
47
                                ] : [ \t]++
48
                                ( \S{1,1000} )                    # URL (2)
49
                                ( [ \t] .{1,1000} )?              # optional label (3)
50
                                ' . Patterns::Modifier . '?       # modifier (4)
1 ✔
51
                                \s*
52
                        $~mUx',
53
                        $this->parseDefinition(...),
1 ✔
54
                );
55

56
                // [reference] - bare reference link (opt-in); the raw target is kept in
57
                // LinkNode::$ref for consumer resolution passes (wiki links etc.)
58
                $this->texy->addLineSyntax(
1 ✔
59
                        Syntax::LinkReference,
1 ✔
60
                        '~
1 ✔
61
                                (?<! [.\#\[] )        # exclude modifier .[class], PHP attribute \#[Attr] and nested [
62
                                \[
63
                                ( [^\[\]*|\n]++ )     # reference name (1); * would be an image, | a labeled form
64
                                ]
65
                        ~Ux',
66
                        $this->parseReference(...),
1 ✔
67
                );
68
        }
1 ✔
69

70

71
        /**
72
         * Parses bare [ref]
73
         * @param  array{string, string}  $matches
74
         * @param  array{int, int}  $offsets
75
         */
76
        public function parseReference(ParseContext $context, array $matches, array $offsets): Nodes\LinkNode
77
        {
78
                [, $mRef] = $matches;
1 ✔
79
                $refRange = new Range($offsets[1], strlen($mRef));
1 ✔
80
                return new Nodes\LinkNode(
1 ✔
81
                        content: new Nodes\ContentNode([new Nodes\TextNode(Helpers::decodeEntities($mRef), $refRange)]),
1 ✔
82
                        range: new Range($offsets[0], strlen($matches[0])),
1 ✔
83
                        ref: $mRef,
84
                        syntax: Syntax::LinkReference,
1 ✔
85
                        textRange: $refRange,
86
                        urlRange: $refRange,
87
                );
88
        }
89

90

91
        /**
92
         * Parses [ref]: url
93
         * @param  array{string, string, string, ?string, ?string}  $matches
94
         * @param  array{int, int, int, ?int, ?int}  $offsets
95
         */
96
        public function parseDefinition(ParseContext $context, array $matches, array $offsets): LinkDefinitionNode
97
        {
98
                [, $mRef, $mLink, $mLabel, $mMod] = $matches;
1 ✔
99
                if ($mMod || $mLabel) {
1 ✔
100
                        trigger_error('Modifiers and label in link definitions are deprecated.', E_USER_DEPRECATED);
×
101
                }
102
                return new LinkDefinitionNode(
1 ✔
103
                        $mRef,
104
                        Helpers::removeSoftHyphens($mLink),
1 ✔
105
                        new Range($offsets[0], strlen($matches[0])),
1 ✔
106
                );
107
        }
108

109

110
        /**
111
         * Adds a user-defined link definition (persists across process() calls).
112
         */
113
        public function addDefinition(string $name, string $url): void
114
        {
115
                $this->userDefinitions[Helpers::toLower($name)] = new LinkDefinitionNode($name, $url);
1 ✔
116
        }
1 ✔
117

118

119
        /**
120
         * Recognizes link targets written as a reference, [ref] or [*img*]: the name goes
121
         * to LinkNode::$ref and the URL is left to resolveReferences().
122
         */
123
        public function recognizeReferences(DocumentNode $doc): void
124
        {
125
                foreach (NodeHelpers::find($doc, Nodes\LinkNode::class) as $node) {
1 ✔
126
                        $url = $node->url ?? '';
1 ✔
127
                        $len = strlen($url);
1 ✔
128
                        if ($len > 4 && $url[0] === '[' && $url[1] === '*' && $url[$len - 1] === ']'
1 ✔
129
                                && in_array($url[$len - 2], ['*', '<', '>'], true)
1 ✔
130
                        ) {
131
                                $node->ref = trim(substr($url, 2, -2));
1 ✔
132
                                $node->isImageLink = true;
1 ✔
133
                                $node->url = null;
1 ✔
134

135
                        } elseif ($len > 2 && $url[0] === '[' && $url[$len - 1] === ']') {
1 ✔
136
                                $node->ref = substr($url, 1, -1);
1 ✔
137
                                $node->url = null;
1 ✔
138
                        }
139
                }
140
        }
1 ✔
141

142

143
        /**
144
         * Resolve link references in the document. A Transform pass, runs after the one of ImageModule.
145
         */
146
        public function resolveReferences(DocumentNode $doc): void
147
        {
148
                // Start with user-defined definitions
149
                $this->definitions = $this->userDefinitions;
1 ✔
150

151
                // Pass 1: Collect document definitions (overwrites user-defined)
152
                foreach (NodeHelpers::find($doc, LinkDefinitionNode::class) as $node) {
1 ✔
153
                        $this->definitions[Helpers::toLower($node->reference)] = $node;
1 ✔
154
                }
155

156
                // Pass 2: Resolve references in LinkNode.url
157
                foreach (NodeHelpers::find($doc, Nodes\LinkNode::class) as $node) {
1 ✔
158
                        $this->resolveLinkNodeUrl($node);
1 ✔
159
                }
160
        }
1 ✔
161

162

163
        /**
164
         * Resolves the URL of a link written as [ref] or [*img*]; a reference not found is used as the URL.
165
         * A %s in the URL stands for the link text, such as "strlen":[php] with php.net/%s.
166
         */
167
        private function resolveLinkNodeUrl(Nodes\LinkNode $node): void
168
        {
169
                if ($node->url === null && $node->ref !== null) {
1 ✔
170
                        if ($node->isImageLink) {
1 ✔
171
                                $node->url = $this->texy->imageModule->getDefinition($node->ref)->url ?? $node->ref;
1 ✔
172
                                return;
1 ✔
173
                        }
174
                        $node->url = $this->resolveDefinition($node->ref)->url ?? $node->ref;
1 ✔
175
                }
176

177
                if ($node->url !== null && $node->syntax !== Syntax::LinkReference && str_contains($node->url, '%s')) {
1 ✔
178
                        $node->url = str_replace('%s', urlencode(trim(Helpers::extractText($node->content))), $node->url);
1 ✔
179
                }
180

181
                $this->convertEmailUrl($node);
1 ✔
182
        }
1 ✔
183

184

185
        /**
186
         * Convert e-mail URLs to mailto: scheme. Requires a full e-mail address
187
         * (Patterns::Email) so that wiki-style targets containing @ are left alone.
188
         */
189
        private function convertEmailUrl(Nodes\LinkNode $node): void
190
        {
191
                if (
192
                        $node->url !== null
1 ✔
193
                        && !str_contains($node->url, '/')
1 ✔
194
                        && !preg_match('~^[a-z][a-z0-9+.-]*:~i', $node->url)
1 ✔
195
                        && Texy\Regexp::match($node->url, '~' . Patterns::Email . '(\?\S*)?$~A')
1 ✔
196
                ) { // optional ?subject=... query
197
                        $node->url = 'mailto:' . $node->url;
1 ✔
198
                }
199
        }
1 ✔
200

201

202
        /**
203
         * Find definition by identifier, supports #fragment and ?query.
204
         */
205
        private function resolveDefinition(string $identifier): ?LinkDefinitionNode
206
        {
207
                $key = Helpers::toLower($identifier);
1 ✔
208

209
                if (isset($this->definitions[$key])) {
1 ✔
210
                        return $this->definitions[$key];
1 ✔
211
                }
212

213
                // Support #fragment and ?query
214
                $hashPos = strpos($key, '#');
1 ✔
215
                $queryPos = strpos($key, '?');
1 ✔
216

217
                // Find the earliest delimiter
218
                $pos = null;
1 ✔
219
                if ($hashPos !== false && $queryPos !== false) {
1 ✔
UNCOV
220
                        $pos = min($hashPos, $queryPos);
×
221
                } elseif ($hashPos !== false) {
1 ✔
222
                        $pos = $hashPos;
1 ✔
223
                } elseif ($queryPos !== false) {
1 ✔
224
                        $pos = $queryPos;
1 ✔
225
                }
226

227
                if ($pos !== null) {
1 ✔
228
                        $baseKey = substr($key, 0, $pos);
1 ✔
229
                        if (isset($this->definitions[$baseKey])) {
1 ✔
230
                                $def = clone $this->definitions[$baseKey];
1 ✔
231
                                $def->url .= substr($identifier, $pos);
1 ✔
232
                                return $def;
1 ✔
233
                        }
234
                }
235

236
                return null;
1 ✔
237
        }
238

239

240
        /**
241
         * @deprecated use $texy->htmlOutput->linkRoot etc. instead
242
         */
243
        public function &__get(string $name): mixed
244
        {
UNCOV
245
                return Compat\Legacy::ref($this->texy, Compat\Legacy::OfModule['linkModule'], '$texy->linkModule', $name, 'read');
×
246
        }
247

248

249
        /**
250
         * @deprecated use $texy->htmlOutput->linkRoot etc. instead
251
         */
252
        public function __set(string $name, mixed $value): void
253
        {
254
                Compat\Legacy::set($this->texy, Compat\Legacy::OfModule['linkModule'], '$texy->linkModule', $name, $value);
1 ✔
255
        }
1 ✔
256

257

258
        public function __isset(string $name): bool
259
        {
UNCOV
260
                return Compat\Legacy::isSet($this->texy, Compat\Legacy::OfModule['linkModule'], $name);
×
261
        }
262
}
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