Debian Codegraph @

lib/Markdown/Perl/Inlines.pm

raw
1 # Package to process the inline structure of Markdown.
2
3 package Markdown::Perl::Inlines;
4
5 use strict;
6 use warnings;
7 use utf8;
8 use feature ':5.24';
9
10 use Carp;
11 use English;
12 use List::MoreUtils 'first_index', 'last_index';
13 use List::Util 'min';
14 use List::Util 1.45 'uniq';
15 use Markdown::Perl::InlineTree ':all';
16 use Markdown::Perl::Util 'normalize_label';
17 use Markdown::Perl::HTML 'remove_disallowed_tags';
18
19 our $VERSION = 0.01;
20
21 # Everywhere here, $that is a Markdown::Perl instance that we carry everywhere
22 # because it contains the options that we are using.
23 sub render {
24 my ($that, $linkrefs, @lines) = @_;
25
26 my $text = join("\n", @lines);
27 my $tree = find_code_and_tag_runs($that, $text);
28
29 # At this point, @runs contains only 'text', 'code', or 'link' elements, that
30 # can’t have any children (yet).
31
32 $tree->map(sub { process_char_escaping($that, $_) });
33
34 # At this point, @runs can also contain 'literal' elements, that don’t have
35 # children.
36
37 process_links($that, $linkrefs, $tree);
38
39 # This removes the spurious white-space at the beginning and end of lines and
40 # also inserts hard line break as required.
41 process_whitespaces($that, $tree);
42
43 # Now, there are more link elements and they can have children instead of
44 # content.
45
46 if ($that->get_use_extended_autolinks) {
47 $tree->map(sub { create_extended_autolinks($that, $_) });
48 $tree->map(sub { create_extended_email_autolinks($that, $_) });
49 }
50
51 process_styles($that, $tree);
52
53 # At this point we have added the emphasis, strong emphasis, etc. in the tree.
54
55 $tree->apply(
56 sub {
57 $_->escape_content($that->get_html_escaped_characters,
58 $that->get_html_escaped_code_characters);
59 });
60
61 my $out = $tree->render_html();
62
63 return $out;
64 }
65
66 # TODO: share these regex with Perl.pm (but note that we are not matching the
67 # open and close < > characters here).
68 my $html_tag_name_re = qr/[a-zA-Z][-a-zA-Z0-9]*/;
69 my $html_attribute_name_re = qr/[a-zA-Z_:][-a-zA-Z0-9_.:]*/;
70 my $html_space_re = qr/\n[ \t]*|[ \t][ \t]*\n?[ \t]*/; # Spaces, tabs, and up to one line ending.
71 my $opt_html_space_re = qr/[ \t]*\n?[ \t]*/; # Optional spaces.
72 my $html_attribute_value_re = qr/ [^ \t\n"'=<>`]+ | '[^']*' | "[^"]*" /x;
73 my $html_attribute_re =
74 qr/ ${html_space_re} ${html_attribute_name_re} (?: ${opt_html_space_re} = ${opt_html_space_re} ${html_attribute_value_re} )? /x;
75
76 my $html_open_tag_re = qr/ ${html_tag_name_re} ${html_attribute_re}* ${opt_html_space_re} \/? /x;
77 my $html_close_tag_re = qr/ \/ ${html_tag_name_re} ${opt_html_space_re} /x;
78 my $html_comment_re = qr/!--|!---|!--.*?--/s;
79 my $html_proc_re = qr/\?.*?\?/s;
80 my $html_decl_re = qr/![a-zA-Z].*?/s;
81 my $html_cdata_re = qr/!\[CDATA\[.*?\]\]/s;
82
83 my $html_tag_re =
84 qr/ ${html_open_tag_re} | ${html_close_tag_re} | ${html_comment_re} | ${html_proc_re} | ${html_decl_re} | ${html_cdata_re}/x;
85
86 # Bug: there is a bug in that backslash escapes don’t work inside autolinks. But
87 # we can turn our autolinks into full-links later (where the escape should
88 # work). However, the spec does not test this corner case so we’re fine.
89
90 sub find_code_and_tag_runs {
91 my ($that, $text) = @_;
92
93 my $tree = Markdown::Perl::InlineTree->new();
94
95 # We match code-spans and autolinks first as they bind strongest. Raw HTML
96 # should be here too, but we don’t support it yet.
97 # https://spec.commonmark.org/0.30/#code-spans
98 # TODO: https://spec.commonmark.org/0.30/#autolinks
99 # TODO: https://spec.commonmark.org/0.30/#raw-html
100 # while ($text =~ m/(?<code>\`+)|(?<html>\<)/g) {
101 # We are manually handling the backslash escaping here because they are not
102 # interpreted inside code blocks. We will then process all the others
103 # afterward.
104 while ($text =~ m/(?<! \\) (?<backslashes> (?:\\\\)*) (?: (?<code>\`+) | < )/gx) {
105 my ($start_before, $start_after) =
106 ($LAST_MATCH_START[0] + length($+{backslashes}), $LAST_MATCH_END[0]);
107 if ($+{code}) {
108 my $fence = $+{code};
109 # We’re searching for a fence of the same length, without any backtick
110 # before or after.
111 if ($text =~ m/(?<!\`)${fence}(?!\`)/gc) {
112 my ($end_before, $end_after) = ($LAST_MATCH_START[0], $LAST_MATCH_END[0]);
113 $tree->push(new_text(substr($text, 0, $start_before)))
114 if $start_before > 0;
115 $tree->push(new_code(substr($text, $start_after, ($end_before - $start_after))));
116 substr $text, 0, $end_after, ''; # This resets pos($text) as we want it to.
117 } # in the else clause, pos($text) == $start_after (because of the /c modifier).
118 } else {
119 # We matched a single < character.
120 my $re = $that->get_autolinks_regex;
121 my $email_re = $that->get_autolinks_email_regex;
122 # We’re not using /gc in these to regex because this confuses the ProhibitUnusedCapture
123 # PerlCritic policy. Anyway, as we are always resetting pos() in case of
124 # successful match, it’s not important to update it.
125 if ($text =~ m/\G(?<link>${re})>/) {
126 $tree->push(new_text(substr($text, 0, $start_before)))
127 if $start_before > 0;
128 $tree->push(new_link($+{link}, type => 'autolink', target => $+{link}));
129 substr $text, 0, $+[0], ''; # This resets pos($text) as we want it to.
130 } elsif ($text =~ m/\G(?<link>${email_re})>/) {
131 $tree->push(new_text(substr($text, 0, $start_before)))
132 if $start_before > 0;
133 # TODO: we have a bug in to_source_text, that will assume that the
134 # mailto: was part of the source text.
135 $tree->push(new_link($+{link}, type => 'autolink', target => 'mailto:'.$+{link}));
136 substr $text, 0, $+[0], ''; # This resets pos($text) as we want it to.
137 } elsif ($text =~ m/\G(?:${html_tag_re})>/) {
138 # This resets pos($text) as we want it to.
139 $tree->push(new_text(substr($text, 0, $start_before, '')))
140 if $start_before > 0;
141 my $html = substr($text, 0, $LAST_MATCH_END[0] - $start_before, '');
142 remove_disallowed_tags($html, $that->get_disallowed_html_tags);
143 $tree->push(new_html($html));
144 }
145 }
146 }
147 $tree->push(new_text($text)) if length($text) > 0;
148
149 return $tree;
150 }
151
152 sub process_char_escaping {
153 my ($that, $node) = @_;
154
155 # This is executed after
156 if ($node->{type} eq 'code' || $node->{type} eq 'link') {
157 # At this stage, link nodes are only autolinks, in which back-slash escaping
158 # is not processed.
159 return $node;
160 } elsif ($node->{type} eq 'text') {
161 # TODO: with the current code for map, this could just be @nodes.
162 my $new_tree = Markdown::Perl::InlineTree->new();
163 # TODO: make this regex configurable (the set of characters that can be
164 # escaped). Note that the regex has to be updated in Perl.pm unescape_char
165 # method too.
166 while ($node->{content} =~ m/\\(\p{PosixPunct})/g) {
167 # Literal parsing is OK here (even if we will later create label reference
168 # which distinguish between escaped and non-escaped literals) because we
169 # can always invert it (and it makes the rest of the processing be much
170 # simpler because we don’t need to check whether we have escaped text or
171 # not).
172 $new_tree->push(new_text(substr $node->{content}, 0, $LAST_MATCH_START[0]))
173 if $LAST_MATCH_START[0] > 0;
174 $new_tree->push(new_literal($1));
175 substr $node->{content}, 0, $LAST_MATCH_END[0], ''; # This resets pos($node->{content}) as we want it to.
176 }
177 $new_tree->push($node) if length($node->{content}) > 0;
178 return $new_tree;
179 } elsif ($node->{type} eq 'html') {
180 return $node;
181 } else {
182 confess 'Unexpected node type in process_char_escaping: '.$node->{type};
183 }
184 }
185
186 # We find all the links in the tree.
187 #
188 # We are mostly implementing the recommended algorithm from
189 # https://spec.commonmark.org/0.31.2/#phase-2-inline-structure
190 # Except that we don’t do the inline parsing at this stage.
191 #
192 # Overall, this methods implement this whole section of the spec:
193 # https://spec.commonmark.org/0.30/#links
194 sub process_links {
195 my ($that, $linkrefs, $tree) = @_;
196
197 my @open_link;
198 for (my $i = 0; $i < @{$tree->{children}}; $i++) {
199 my $n = $tree->{children}[$i];
200 next if $n->{type} ne 'text';
201 while ($n->{content} =~ m/(?<open>!?\[)|\]/g) {
202 my @pos = ($i, $LAST_MATCH_START[0], $LAST_MATCH_END[0]);
203 if ($+{open}) {
204 my $type = $pos[2] - $pos[1] > 1 ? 'img' : 'link';
205 push @open_link, {type => $type, active => 1, pos => \@pos};
206 } else {
207 next unless @open_link;
208 my %open = %{pop @open_link};
209 next unless $open{active};
210 my @text_span = ($open{pos}[0], $open{pos}[2], $pos[0], $pos[1]);
211 my $cur_pos = pos($n->{content});
212 my %target =
213 find_link_destination_and_title($that, $linkrefs, $tree, $pos[0], $pos[2], @text_span);
214 pos($n->{content}) = $cur_pos;
215 next unless %target;
216 my $text_tree = $tree->extract(@text_span);
217 my (undef, $dest_node_index) =
218 $tree->extract($open{pos}[0], $open{pos}[1], $open{pos}[0] + 1, 1);
219 my $link = new_link($text_tree, type => $open{type}, %target);
220 $tree->insert($dest_node_index, $link);
221
222 if ($open{type} eq 'link') {
223 for (@open_link) {
224 $_->{active} = 0 if $_->{type} eq 'link';
225 }
226 }
227 $i = $dest_node_index;
228 last; # same as a next OUTER, but without the need to define the OUTER label.
229 }
230 }
231 }
232 return;
233 }
234
235 # @text_span is the span of the link definition text, used in case we have a
236 # collapsed link reference call.
237 sub find_link_destination_and_title {
238 my ($that, $linkrefs, $tree, $child_start, $text_start, @text_span) = @_;
239 # We assume that the beginning of the link destination must be just after the
240 # link text and in the same child, as there can be no other constructs
241 # in-between.
242
243 my $cur_child = $child_start;
244 my $n = $tree->{children}[$cur_child];
245 confess 'Unexpected link destination search in a non-text element: '.$n->{type}
246 unless $n->{type} eq 'text';
247 pos($n->{content}) = $text_start;
248 $n->{content} =~ m/ \G (?<space> [ \t\n]+ )? (?: (?<inline> \( ) | (?<reference> \[\]? ) )? /x;
249 my @start = ($child_start, $text_start, $child_start, $LAST_MATCH_END[0]);
250
251 my $has_space = exists $+{space};
252 my $type;
253 if (exists $+{inline}) {
254 $type = 'inline';
255 } elsif (exists $+{reference}) {
256 if ($+{reference} eq '[') {
257 $type = 'reference';
258 } else {
259 $type = 'collapsed';
260 }
261 } else {
262 $type = 'shortcut';
263 }
264
265 my $mode = $that->get_allow_spaces_in_links;
266 if ($has_space) {
267 # 'reference' mode is the mode that emulates Markdown.pl which is kind of
268 # weird and probably does not intend this exact behavior (at most one space
269 # then an optional new line and, if you have it, then any number of spaces).
270 if ( $mode eq 'reference'
271 && ($type eq 'reference' || $type eq 'collapsed')
272 && $+{space} =~ m/^ ?(?:\n[ \t]*)?$/) {
273 # ok, do nothing
274 } else {
275 # We have forbidden spaces, so we treat this as a tentative shortcut link.
276 $type = 'shortcut';
277 }
278 }
279
280 if ($type eq 'inline') {
281 my @target = parse_inline_link($tree, @start);
282 return @target if @target;
283 # pass-through intended if we can’t parse a valid target, we will try a
284 # shortcut link.
285 } elsif ($type eq 'reference') {
286 my %target = parse_reference_link($that, $linkrefs, $tree, @start);
287 return %target if exists $target{target};
288 # no pass-through here if this was a valid reference link syntax. This is
289 # not fully specified by the spec but matches what the reference
290 # implementation does.
291 return if %target;
292 # Otherwise, pass-through.
293 }
294 # This is either a collapsed or a shortcut reference link (or something that
295 # might be one).
296 my $ref = $tree->span_to_source_text(@text_span, UNESCAPE_LITERAL);
297 $ref = normalize_label($ref) if $ref;
298 if (my $l = get_linkref($that, $linkrefs, $ref)) {
299 $tree->extract(@start) if $type eq 'collapsed';
300 return %{$l};
301 }
302 return;
303 }
304
305 sub parse_inline_link {
306 my ($tree, @start) = @_; # ($child_start, $text_start, $child_start, $text_start + 1);
307 # @start points to before and after the '(' character opening the link.
308
309 # $cur_child is advanced through the tree while we parse the link destination
310 # and title, it always point to the node that we are currently looking into
311 # (the one containing the end of the element that was previously found).
312 # $n is the node at index $cur_child.
313 my $cur_child = $start[0];
314 my $n = $tree->{children}[$cur_child];
315
316 pos($n->{content}) = $start[3];
317 $n->{content} =~ m/\G[ \t]*\n?[ \t]*/;
318 my $search_start = $LAST_MATCH_END[0];
319
320 # TODO: first check if we have a destination between <>, that may have already
321 # been matched as an autolink or as a closing HTML tag :-(
322
323 my @target;
324 my $ok_to_have_title = 1;
325
326 my $has_bracket =
327 $tree->find_in_text(qr/</, $cur_child, $search_start, $cur_child, $search_start + 1);
328
329 # We have this variable early because we may be filling it soon if the link
330 # destination was already parsed as an autolink or an html element.
331 my $target = undef;
332
333 if ($has_bracket) {
334 if (my @end_target = $tree->find_in_text(qr/>/, $cur_child, $search_start + 1)) {
335 @target = ($cur_child, $search_start + 1, $end_target[0], $end_target[1]);
336 return if $tree->find_in_text(qr/<|\n/, @target);
337 }
338 } elsif (
339 length($n->{content}) <= $search_start
340 && @{$tree->{children}} > $cur_child + 1
341 && ( $tree->{children}[$cur_child + 1]{type} eq 'html'
342 || $tree->{children}[$cur_child + 1]{type} eq 'link')
343 ) {
344 # The element inside was already parsed as an autolink or an html element,
345 # we use it as-is for the link destination. However, we need at least one
346 # element after in the tree for this to be valid (otherwise we know that the
347 # syntax can’t be a real tree, so we return from here).
348 return if @{$tree->{children}} <= $cur_child + 2;
349 @target = ($cur_child + 1, 0, $cur_child + 2, 0);
350 my $link_node = $tree->{children}[$cur_child + 1];
351 if ($link_node->{type} eq 'html') {
352 $target = $link_node->{content};
353 $target =~ s/^<|>$//g;
354 } else {
355 $target = $link_node->{target};
356 }
357 return if $target =~ m/\n/; # No new lines in link targets are allowed.
358 } elsif (
359 my @end_target = $tree->find_in_text_with_balanced_content(
360 qr/\(/, qr/\)/, qr/[ [:cntrl:]]/,
361 $cur_child, $search_start)
362 ) {
363 @target = ($cur_child, $search_start, $end_target[0], $end_target[1]);
364 }
365 if (@target) {
366 # We can’t extract the target just yet, because the parsing can still fail
367 # in which case we must not modify the tree.
368 $cur_child = $target[2];
369 $n = $tree->{children}[$cur_child];
370 # On the next line, [1] and not [2] because if there was a control character
371 # we will fail the whole method. So we restart the search before the end
372 # condition of the find... method above.
373 pos($n->{content}) = $target[3] + ($has_bracket ? 1 : 0);
374 $n->{content} =~ m/\G[ \t]*\n?[ \t]*/;
375 $search_start = $LAST_MATCH_END[0];
376 $ok_to_have_title = $LAST_MATCH_END[0] != $LAST_MATCH_START[0]; # target and title must be separated.
377 }
378
379 # The first character of the title must be ", ', or ( and so can’t be another
380 # inline construct. As such, using a normal regex is fine (and not an
381 # InlineTree method).
382 pos($n->{content}) = $search_start;
383 my @end_title;
384 if ($n->{content} =~ m/\G"/gc) {
385 @end_title = $tree->find_in_text(qr/"/, $cur_child, $search_start + 1);
386 } elsif ($n->{content} =~ m/\G'/gc) {
387 @end_title = $tree->find_in_text(qr/'/, $cur_child, $search_start + 1);
388 } elsif ($n->{content} =~ m/\G\(/gc) {
389 @end_title = $tree->find_balanced_in_text(qr/\(/, qr/\)/, $cur_child, $search_start + 1);
390 }
391 my @title;
392 if (@end_title) {
393 return unless $ok_to_have_title;
394 @title = ($cur_child, $search_start + 1, $end_title[0], $end_title[1]);
395 $cur_child = $end_title[0];
396 $n = $tree->{children}[$cur_child];
397 pos($n->{content}) = $end_title[2]; # This time, we look after the closing character.
398 $n->{content} =~ m/\G[ \t]*\n?[ \t]*/;
399 $search_start = $LAST_MATCH_END[0];
400 }
401
402 # TODO: call a new InlineTree method to turn (child, offset_at_end) into
403 # (child + 1, 0). This needs to be called also at the beginning of this
404 # method.
405 pos($n->{content}) = $search_start;
406 return unless $n->{content} =~ m/\G\)/;
407
408 # Now we have a valid title, we can start to rewrite the tree (beginning from
409 # the end, to not alter the node index before we touch them).
410 {
411 my @last_item = (@title, @target, @start);
412 # We remove the spaces after the last item and also the closing paren.
413 $tree->extract($last_item[2], $last_item[3], $cur_child, $search_start + 1);
414 }
415
416 my $title;
417 if (@title) {
418 my $title_tree = $tree->extract(@title);
419 $title = $title_tree->to_source_text();
420 my @last_item = (@target, @start);
421 $tree->extract($last_item[2], $last_item[3], $title[0], $title[1]);
422 }
423
424 if (@target) {
425 my $target_tree = $tree->extract(@target);
426 $target = $target_tree->to_source_text() unless defined $target;
427 $tree->extract($start[2], $start[3], $target[0], $target[1]);
428 }
429
430 $tree->extract(@start);
431
432 # A link with no destination at all, like [foo](), has an empty target.
433 return (target => $target // '', (defined $title ? (title => $title) : ()));
434 }
435
436 sub parse_reference_link {
437 my ($that, $linkrefs, $tree, @start) = @_; # ($child_start, $text_start, $child_start, $text_start + 1);
438
439 my $cur_child = $start[0];
440 my $n = $tree->{children}[$cur_child];
441
442 my $ref_start = $start[3];
443
444 if (my @end_ref = $tree->find_in_text(qr/]/, $cur_child, $start[3])) {
445 my $ref =
446 normalize_label($tree->span_to_source_text(@start[2, 3], @end_ref[0, 1], UNESCAPE_LITERAL));
447 if (my $l = get_linkref($that, $linkrefs, $ref)) {
448 $tree->extract(@start[0, 1], @end_ref[0, 2]);
449 return %{$l};
450 } else {
451 # TODO: we should only return this if the span was indeed a valid
452 # reference link label (not longer than 1000 characters mostly).
453 # This is used to notice that we had a proper reference link syntax and
454 # not fallback to trying a shortcut link.
455 return (ignored_valid_value => 1);
456 }
457 }
458 return;
459 }
460
461 # Returns a hashref with (title and dest) or undef.
462 sub get_linkref {
463 my ($that, $linkrefs, $ref) = @_;
464 if (exists $linkrefs->{$ref}) {
465 return $linkrefs->{$ref};
466 } elsif (exists $that->{hooks}{resolve_link_ref}) {
467 return $that->{hooks}{resolve_link_ref}->($ref);
468 }
469 return;
470 }
471
472 # This methods remove line break at the beginning and end of lines (inside text
473 # nodes only), and add hard line breaks as required.
474 #
475 # $not_root is set when we recurse inside sub-tree, to indicate that the first
476 # and last node of the the tree are not, in fact, the beginning and and of the
477 # paragraph.
478 sub process_whitespaces {
479 my ($that, $tree, $not_root) = @_;
480
481 for (my $i = 0; $i < @{$tree->{children}}; $i++) {
482 my $n = $tree->{children}[$i];
483 process_whitespaces($that, $n->{subtree}, 1) if exists $n->{subtree};
484 next unless $n->{type} eq 'text';
485 # TODO: add tests for the fact that we don’t want hard break at the end of a
486 # paragraph.
487 my $re;
488 if ($that->get_two_spaces_hard_line_breaks) {
489 $re = qr/(?: {2,}|\\)\n(?=.) */s;
490 } else {
491 $re = qr/\\\n(?=.) */s;
492 }
493 my @hard_breaks = split($re, $n->{content}, -1);
494 for (my $j = 0; $j < @hard_breaks; $j++) {
495 # $hard_breaks[$j] = '' unless defined($hard_breaks[$j]);
496 $hard_breaks[$j] =~ s/^ +// if !$not_root && $i == 0 && $j == 0;
497 $hard_breaks[$j] =~ s/(\n|\r) +/$1/g;
498 $hard_breaks[$j] =~ s/ +$//gm
499 if !$not_root && $i == $#{$tree->{children}} && $j == $#hard_breaks;
500 if ($j == 0) {
501 $n->{content} = $hard_breaks[0];
502 } else {
503 $tree->insert($i + 1, new_html('<br />'), new_text("\n".$hard_breaks[$j]));
504 $i += 2;
505 }
506 }
507 }
508 return;
509 }
510
511 # This methods adds "style", that is it parses the emphasis (* and _) and also
512 # strike-through (~). To do so, we process each level of the tree independently
513 # because a style-run can’t cross another HTML construct (but it can span over
514 # it).
515 #
516 # We first find all the possible delimiters and insert them in the tree instead
517 # of their text. And then decide whether they are actually opening, closing, or
518 # neither.
519 #
520 # This methods implement all of:
521 # https://spec.commonmark.org/0.30/#emphasis-and-strong-emphasis
522 sub process_styles {
523 my ($that, $tree) = @_;
524
525 # We recurse first as there are less children to iterate over than after.
526 for my $c (@{$tree->{children}}) {
527 process_styles($that, $c->{subtree}) if exists $c->{subtree};
528 }
529
530 # TODO: only search for characters that are actually used by our current
531 # options.
532 my $current_child = 0;
533 my @delimiters;
534 my $delim = delim_characters($that);
535 my %max_delim_run_length = %{$that->get_inline_delimiters_max_run_length};
536 while (my @match = $tree->find_in_text(qr/([${delim}])\1*/, $current_child, 0)) {
537 # We extract the delimiter run into a new node, that will be at $index.
538 my ($delim_tree, $index) = $tree->extract($match[0], $match[1], $match[0], $match[2]);
539 # We use the type literal so that if we do nothing with the delimiter it
540 # will be rendered correctly. We keep track of which literals might be
541 # delimiters using the @delimiters array.
542 $delim_tree->{children}[0]{type} = 'literal';
543 $tree->insert($index, $delim_tree);
544 my $d = classify_delimiter($that, $tree, $index);
545 if (!exists $max_delim_run_length{$d->{delim}}
546 || $d->{len} <= $max_delim_run_length{$d->{delim}}) {
547 push @delimiters, $d;
548 }
549 $current_child = $index + 1;
550 }
551
552 match_delimiters($that, $tree, @delimiters);
553 return;
554 }
555
556 # Decides whether the delimiter run at the given index in the tree can open or
557 # close emphasis (or any other style).
558 sub classify_delimiter {
559 my ($that, $tree, $index) = @_;
560 my $pred_type = classify_flank($that, $tree, $index, 'left');
561 my $succ_type = classify_flank($that, $tree, $index, 'right');
562 my $is_left = $succ_type ne 'space' && ($succ_type ne 'punct' || $pred_type ne 'none');
563 my $is_right = $pred_type ne 'space' && ($pred_type ne 'punct' || $succ_type ne 'none');
564 my $len = length($tree->{children}[$index]{content});
565 my $delim = substr $tree->{children}[$index]{content}, 0, 1;
566 my $can_open = 0;
567 my $can_close = 0;
568 # This is implementing the first 8 rules (out of 17...) of
569 # https://spec.commonmark.org/0.31.2/#emphasis-and-strong-emphasis
570 # The rules are more complex for '_' than for '*' because it is assuming that
571 # underscores can appear within word. So we apply the star rules to all other
572 # delimiters (that is, we only check for underscore here). Currently our only
573 # other delimiter is '~'.
574 # TODO: add an option to decide which rule to apply per delimiter.
575 if ($delim eq '_') {
576 $can_open = $is_left && (!$is_right || $pred_type eq 'punct');
577 $can_close = $is_right && (!$is_left || $succ_type eq 'punct');
578 } else {
579 $can_open = $is_left;
580 $can_close = $is_right;
581 }
582 return {
583 index => $index,
584 can_open => $can_open,
585 can_close => $can_close,
586 len => $len,
587 delim => $delim,
588 orig_len => $len
589 };
590 }
591
592 # Computes whether the type of the "flank" of the delimiter run at the given
593 # index in the tree (looking either at the "left" or "right" side). This returns
594 # one of 'none', 'punct', or 'space' following the rule given in
595 # https://spec.commonmark.org/0.31.2/#emphasis-and-strong-emphasis.
596 # The purpose is to decide whether the delimiter run is left flanking and/or
597 # right flanking (that decision happens in classify_delimiter).
598 sub classify_flank {
599 my ($that, $tree, $index, $side) = @_;
600 return 'space' if $index == 0 && $side eq 'left';
601 return 'space' if $index == $#{$tree->{children}} && $side eq 'right';
602 my $node = $tree->{children}[$index + ($side eq 'left' ? -1 : 1)];
603 # If the node before the delimiters is not text, let’s assume that we had some
604 # punctuation characters that delimited it.
605 return 'punct' if $node->{type} ne 'text' && $node->{type} ne 'literal';
606 my $space_re = $side eq 'left' ? qr/\s$/u : qr/^\s/u;
607 return 'space' if $node->{content} =~ m/${space_re}/;
608 my $punct_re = $side eq 'left' ? qr/[\p{Punct}\p{Symbol}]$/u : qr/^[\p{Punct}\p{Symbol}]/u;
609 return 'punct' if $node->{content} =~ m/${punct_re}/;
610 return 'none';
611 }
612
613 # We match the pair of delimiters together as much as we can, following the
614 # rules of the CommonMark spec.
615 sub match_delimiters {
616 my ($that, $tree, @delimiters) = @_;
617
618 for (my $close_index = 1; $close_index < @delimiters; $close_index++) {
619 my %c = %{$delimiters[$close_index]};
620 next if !$c{can_close};
621 # We have a closing delimiter, now we backtrack and find the tighter match
622 # for this closing delimiter. This is because "*foo _bar* baz_" will only
623 # match the * (that comes first) but "*foo *bar*"" will match the second
624 # and third star, that are the tightest match. This is for rule 15 and 16 of
625 # https://spec.commonmark.org/0.31.2/#emphasis-and-strong-emphasis
626 # We also apply rules 9 and 10 here. Rules 1-8 have already been computed in
627 # classify_delimiter.
628 my $open_index =
629 last_index { $_->{can_open} && $_->{delim} eq $c{delim} && valid_rules_9_10($_, \%c) }
630 @delimiters[0 .. $close_index - 1];
631 # TODO: here there are a lot of optimization that we could apply, based on
632 # the "process emphasis" method from the spec (like removing our closing
633 # delimiter if it is not an opener, and keeping track of the fact that
634 # we have no delimiter in the 0..close_index-1 range that can match a
635 # delimiter of the same type as %c).
636 # This does not seem very important for reasonable inputs. So, instead, we
637 # just check the next potential closer.
638 next if $open_index == -1;
639
640 $close_index = apply_delimiters($that, $tree, \@delimiters, $open_index, $close_index);
641 }
642
643 return;
644 }
645
646 # Given a tree, its delimiters and the index of two delimiters, rewrite the
647 # tree with the style applied by these delimiters (we’re assuming here that they
648 # are of a matching type).
649 #
650 # The delimiter may not be consumed entirely (but we will consume as much as
651 # possible).
652 sub apply_delimiters {
653 my ($that, $tree, $delimiters, $open_index, $close_index) = @_;
654 my %o = %{$delimiters->[$open_index]};
655 my %c = %{$delimiters->[$close_index]};
656
657 # We rewrite the tree in between our two delimiters.
658 # TODO: maybe we need a splice method in InlineTree.
659 my @styled_subnodes = splice @{$tree->{children}}, $o{index} + 1, $c{index} - $o{index} - 1;
660 my $styled_tree = Markdown::Perl::InlineTree->new();
661 $styled_tree->push(@styled_subnodes);
662 # With our current algorithm in match_delimiters we know that there is no
663 # reasons to recurse (because the closing delimiter here was the first
664 # closing delimiter with a matching opener.)
665 # my @styled_delimiters = map { $_->{index} -= $o{index} + 1; $_ } splice @{$delimiters},
666 # $open_index + 1, $close_index - $open_index - 1;
667 # match_delimiters($that, $styled_tree, @styled_delimiters);
668 splice @{$delimiters}, $open_index + 1, $close_index - $open_index - 1;
669
670 # And now we rebuild our own tree around the new one.
671 my $len = min($o{len}, $c{len}, max_delim_length($that, $o{delim}));
672 my $styled_node = new_style($styled_tree, tag => delim_to_html_tag($that, $o{delim} x $len));
673 my $style_start = $o{index};
674 my $style_length = 2;
675 $close_index = $open_index + 1;
676 if ($len < $o{len}) {
677 substr($tree->{children}[$o{index}]{content}, $o{len} - $len) = ''; ## no critic (ProhibitLvalueSubstr)
678 $delimiters->[$open_index]{len} -= $len;
679 $style_start++;
680 $style_length--;
681 } else {
682 splice @{$delimiters}, $open_index, 1;
683 $close_index--;
684 }
685 if ($len < $c{len}) {
686 # The closing node is now just after the opening one.
687 substr($tree->{children}[$o{index} + 1]{content}, $c{len} - $len) = ''; ## no critic (ProhibitLvalueSubstr)
688 $delimiters->[$close_index]{len} -= $len;
689 $style_length--;
690 } else {
691 splice @{$delimiters}, $close_index, 1; # We remove our closing delimiter.
692 }
693 splice @{$tree->{children}}, $style_start, $style_length, $styled_node;
694 for my $i ($close_index .. $#{$delimiters}) {
695 $delimiters->[$i]{index} -= $c{index} - $o{index} - 2 + $style_length;
696 }
697 return $open_index - ($len < $o{len} ? 0 : 1);
698 }
699
700 # Returns true if the given delimiters can be an open/close pair without
701 # breaking rules 9 and 10 of
702 # https://spec.commonmark.org/0.31.2/#emphasis-and-strong-emphasis.
703 sub valid_rules_9_10 {
704 my ($o, $c) = @_;
705 # TODO: BUG: there is a probable bug here in that the length of the delimiter
706 # to consider is not its current length but the length of the original span
707 # of which it was a part.
708 return
709 (!$o->{can_close} && !$c->{can_open})
710 || (($o->{orig_len} + $c->{orig_len}) % 3 != 0)
711 || ($o->{orig_len} % 3 == 0 && $c->{orig_len} % 3 == 0);
712 }
713
714 # TODO: use ^ and ˇ to represent sup and sub
715 # TODO: add support for MathML in some way.
716 sub delim_to_html_tag {
717 my ($that, $delim) = @_;
718 # TODO: sort what to do if a given delimiter does not have a variant with
719 # two characters (we must backtrack somewhere in match_delimiters probably).
720 # TODO: add support for <span class="foo"> when the value in the map is ".foo"
721 # instead of just "foo".
722 return $that->get_inline_delimiters()->{$delim};
723 }
724
725 # Return the list of characters that can be delimiters (using the regex
726 # character class syntax).
727 sub delim_characters {
728 my ($that) = @_;
729 # TODO: memo-ize this function inside $that (but clear it when the options
730 # change).
731 my @c = map { substr $_, 0, 1 } keys %{$that->get_inline_delimiters()};
732 return join('', uniq @c);
733 }
734
735 # Returns the max defined delim
736 sub max_delim_length {
737 my ($that, $delim) = @_;
738 # TODO: memo-ize this function
739 # We assume that the $delim is in the map because it reached this point and
740 # also that the map can contains only delimiters not repeated or repeated
741 # once.
742 return exists $that->get_inline_delimiters()->{$delim x 2} ? 2 : 1;
743 }
744
745 sub create_extended_autolinks {
746 my ($that, $n) = @_;
747 if ($n->{type} ne 'text') {
748 return $n;
749 }
750
751 my @nodes;
752
753 # TODO: technically we should forbid the presence of _ in the last two parts
754 # of the domain, according to the gfm spec.
755 ## no critic (ProhibitComplexRegexes)
756 while (
757 $n->{content} =~ m/
758 (?<prefix> ^ | [ \t\n*_~\(] ) # The link must start after a whitespace or some specific delimiters.
759 (?<url>
760 (?: (?<scheme>https?:\/\/) | www\. ) # It must start by a scheme or the string wwww.
761 [-_a-zA-Z0-9]+ (?: \. [-_a-zA-Z0-9]+ )* # Then there must be something that looks like a domain
762 (?: \/ [^ \t\n<]*? )? # Some characters are forbidden in the link.
763 )
764 [?!.,:*_~]* (?: [ \t\n<] | $) # We remove some punctuation from the end of the link.
765 /x
766 ## use critic
767 ) {
768 my $url = $+{url};
769 my $match_start = $LAST_MATCH_START[0] + length($LAST_PAREN_MATCH{prefix});
770 my $match_end = $match_start + length($url);
771 my $has_scheme = exists $LAST_PAREN_MATCH{scheme};
772 if ($url =~ m/\)+$/) {
773 my $nb_final_closing_parens = $LAST_MATCH_END[0] - $LAST_MATCH_START[0];
774 my $open = 0;
775 () = $url =~ m/ \( (?{$open++}) | \) (?{$open--}) /gx;
776 my $remove = min($nb_final_closing_parens, -$open);
777 if ($remove > 0) {
778 $match_end -= $remove;
779 substr $url, -$remove, $remove, '';
780 }
781 }
782 if ($url =~ m/\&[a-zA-Z0-9]+;$/) {
783 my $len = $LAST_MATCH_END[0] - $LAST_MATCH_START[0];
784 $match_end -= $len;
785 substr $url, -$len, $len, '';
786 }
787 if ($match_start > 0) {
788 push @nodes, new_text(substr $n->{content}, 0, $match_start);
789 }
790 my $scheme = $has_scheme ? '' : $that->get_default_extended_autolinks_scheme.'://';
791 push @nodes,
792 new_link($url, type => 'autolink', target => $scheme.$url, debug => 'extended autolink');
793 $n = new_text(substr $n->{content}, $match_end);
794 }
795 push @nodes, $n if length($n->{content}) > 0;
796 return @nodes;
797 }
798
799 sub create_extended_email_autolinks {
800 my ($that, $n) = @_;
801 if ($n->{type} ne 'text') {
802 return $n;
803 }
804
805 my @nodes;
806
807 # TODO: We’re not handling links with prefix protocol (mailto: or xmpp:) but
808 # these are not tested by the spec present in the current repo (although they
809 # are documented online).
810 ## no critic (ProhibitComplexRegexes)
811 while (
812 $n->{content} =~ m/
813 (?<prefix> ^ | [ \t\n*_~\(] ) # The link must start after a whitespace or some specific delimiters.
814 (?<email>
815 (?<scheme> mailto:\/\/ )?
816 [-_.+a-zA-Z0-9]+ @ [-_a-zA-Z0-9]+ (?: \. [-_a-zA-Z0-9]+ )+ (?<= [a-zA-Z0-9] )
817 )
818 (?: [ \t\n.<] | $ ) # We remove some punctuation from the end of the link.
819 /x
820 ## use critic
821 ) {
822 my $email = $+{email};
823 my $match_start = $LAST_MATCH_START[0] + length($LAST_PAREN_MATCH{prefix});
824 my $match_end = $match_start + length($email);
825 my $has_scheme = exists $LAST_PAREN_MATCH{scheme};
826 if ($match_start > 0) {
827 push @nodes, new_text(substr $n->{content}, 0, $match_start);
828 }
829 my $scheme = $has_scheme ? '' : 'mailto:';
830 push @nodes,
831 new_link(
832 $email,
833 type => 'autolink',
834 target => $scheme.$email,
835 debug => 'extended autolink');
836 $n = new_text(substr $n->{content}, $match_end);
837 }
838 push @nodes, $n if length($n->{content}) > 0;
839 return @nodes;
840 }
841
842 1;