blib/lib/Markdown/Parser.pm untested

filter: Statementstmt 0.0% 0 / 872 Branchbran 0.0% 0 / 450 Conditioncond 0.0% 0 / 308 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 59 Podpod 0.0% 0 / 42 totaltotal 0.0% 0 / 1731 CC 226 SCAR 85.0
CC
226
Cov
0%
parse
11772.0
from_html
2256.0
parse_table_row
506.0
CRAP 4907.7
1 ##----------------------------------------------------------------------------
2 ## Markdown Parser Only - ~/lib/Markdown/Parser.pm
3 ## Version v0.5.1
4 ## Copyright(c) 2025 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/08/23
7 ## Modified 2025/10/25
8 ## All rights reserved
9 ##
10 ## This program is free software; you can redistribute it and/or modify it
11 ## under the same terms as Perl itself.
12 ##----------------------------------------------------------------------------
13 package Markdown::Parser;
14 BEGIN
15 {
16 use strict;
17 use warnings;
18 use parent qw( Module::Generic );
19 use vars qw( $ELEMENTS_DICTIONARY $ELEMENTS_DICTIONARY_EXTENDED $VERSION $DEBUG );
20 use POSIX ();
21 use Regexp::Common qw( Markdown );
22 use CSS::Object;
23 use Scalar::Util ();
24 our $DEBUG = 0;
25 our $VERSION = 'v0.5.1';
26 # Including vertical space like new lines
27 our $ELEMENTS_DICTIONARY =
28 {
29 block => [qw( blockquote code_block code_line header html line list paragraph )],
30 inline => [qw( abbr bold code_span emphasis image link_auto line_break link )],
31 };
32 $ELEMENTS_DICTIONARY->{all} = [@{$ELEMENTS_DICTIONARY->{block}}, @{$ELEMENTS_DICTIONARY->{inline}}];
33 our $ELEMENTS_DICTIONARY_EXTENDED =
34 {
35 block => [qw( code_block header katex )],
36 inline => [qw( abbr checkbox footnote insert katex strikethrough superscript subscript )],
37 };
38 $ELEMENTS_DICTIONARY_EXTENDED->{all} = [@{$ELEMENTS_DICTIONARY_EXTENDED->{block}}, @{$ELEMENTS_DICTIONARY_EXTENDED->{inline}}];
39 };
40  
41 use strict;
42 use warnings;
43  
44 sub init
45 {
46 my $self = shift( @_ );
47 $self->{abbreviation_case_sensitive} = 0;
48 $self->{charset} = 'utf8';
49 $self->{code_highlight} = 0;
50 $self->{css_grid} = 0;
51 $self->{debug} = $DEBUG;
52 # See Markdown::Parser::Link
53 $self->{default_email} = '';
54 $self->{document} = '';
55 $self->{email_obfuscate_class} = 'courriel';
56 $self->{email_obfuscate_data_host} = 'host';
57 $self->{email_obfuscate_data_user} = 'user';
58 $self->{encrypt_email} = 0;
59 $self->{footnote_ref_sequence} = 0;
60 $self->{callback} = undef;
61 $self->{katex_delimiter} = ['$$','$$','$','$','\[','\]','\(','\)'];
62 $self->{list_level} = 0;
63 $self->{mode} = 'all';
64 # Top scope as specified by the user
65 $self->{scope} = '';
66 $self->{_init_strict_use_sub} = 1;
67 use utf8;
68 $self->{colour_open} = '{';
69 $self->{colour_close} = '}';
70 $self->SUPER::init( @_ );
71 return( $self );
72 }
73  
74 sub abbreviation_case_sensitive { return( shift->_set_get_scalar( 'abbreviation_case_sensitive', @_ ) ); }
75  
76 sub callback { return( shift->_set_get_code( 'callback', @_ ) ); }
77  
78 sub charset { return( shift->_set_get_scalar( 'charset', @_ ) ); }
79  
80 sub code_highlight { return( shift->_set_get_boolean( 'code_highlight', @_ ) ); }
81  
82 sub create_document
83 {
84 my $self = shift( @_ );
85 my $class = ref( $self ) || $self;
86 $class .= '::Document';
87 $self->_load_class( $class ) || return;
88 return( $class->new( @_, debug => $self->debug ) );
89 }
90  
91 sub css
92 {
93 my $self = shift( @_ );
94 my $css = $self->_set_get_object( 'css', 'CSS::Object', @_ );
95 return( $css ) if( $css );
96 $css = CSS::Object->new;
97 $self->_set_get_object( 'css', 'CSS::Object', $css );
98 return( $css );
99 }
100  
101 sub css_builder { return( shift->css->builder ); }
102  
103 sub css_grid { return( shift->_set_get_boolean( 'css_grid', @_ ) ); }
104  
105 sub default_email { return( shift->_set_get_scalar_as_object( 'default_email', @_ ) ); }
106  
107 sub document { return( shift->_set_get_object( 'document', 'Markdown::Parser::Document', @_ ) ); }
108  
109 sub email_obfuscate_class { return( shift->_set_get_scalar_as_object( 'email_obfuscate_class', @_ ) ); }
110  
111 sub email_obfuscate_data_host
112 {
113 my $self = shift( @_ );
114 if( @_ )
115 {
116 if( $_[0] =~ /^[a-zA-Z]\w+$/ )
117 {
118 return( $self->_set_get_scalar_as_object( 'email_obfuscate_data_host', @_ ) );
119 }
120 else
121 {
122 return( $self->error( "Invalid value \"$_[0]\" for the email obfuscation data-host attribute name." ) );
123 }
124 }
125 return( $self->_set_get_scalar_as_object( 'email_obfuscate_data_host' ) );
126 }
127  
128 sub email_obfuscate_data_user
129 {
130 my $self = shift( @_ );
131 if( @_ )
132 {
133 if( $_[0] =~ /^[a-zA-Z]\w+$/ )
134 {
135 return( $self->_set_get_scalar_as_object( 'email_obfuscate_data_user', @_ ) );
136 }
137 else
138 {
139 return( $self->error( "Invalid value \"$_[0]\" for the email obfuscation data-user attribute name." ) );
140 }
141 }
142 return( $self->_set_get_scalar_as_object( 'email_obfuscate_data_user' ) );
143 }
144  
145 sub encrypt_email { return( shift->_set_get_scalar_as_object( 'encrypt_email', @_ ) ); }
146  
147 sub footnote_ref_sequence : lvalue { return( shift->_set_get_lvalue( 'footnote_ref_sequence', @_ ) ); }
148  
149 sub from_html
150 {
151 my $self = shift( @_ );
152 my $html = shift( @_ ) || return( $self->error( "No HTML::Object::Document was provided." ) );
153 if( !$self->_is_a( $html => 'HTML::Object::Document' ) )
154 {
155 return( $self->error( "Value provided (", overload::StrVal( $html ), ") is not an HTML::Object::Document object." ) );
156 }
157  
158 my $doc = $self->create_document(
159 abbreviation_case_sensitive => $self->abbreviation_case_sensitive,
160 default_email => $self->default_email,
161 email_obfuscate_class => $self->email_obfuscate_class,
162 email_obfuscate_data_host => $self->email_obfuscate_data_host,
163 email_obfuscate_data_user => $self->email_obfuscate_data_user,
164 css => $self->css,
165 debug => $self->debug,
166 tag_name => 'top',
167 );
168 # Sharing the parameter
169 $doc->katex_delimiter( $self->katex_delimiter );
170 $self->document( $doc ) if( !$self->document );
171
172 my $seen = {};
173 my $crawl;
174 $crawl = sub
175 {
176 my $e = shift( @_ );
177 # Markdown Element
178 my $me = shift( @_ );
179 my $addr = Scalar::Util::refaddr( $e );
180 # Duplicate
181 return if( ++$seen->{ $addr } > 1 );
182 my $tag = $e->tag;
183 my $top;
184 if( $tag eq 'abbr' )
185 {
186 my $name = $e->content->map( $_->as_string )->scalar;
187 my $val = $e->attr( 'title' );
188 my $elem = $doc->create_abbreviation({
189 name => $name,
190 value => $val,
191 }) || return( $self->pass_error );
192 $me->add_element( $elem ) || return( $self->pass_error );
193 }
194 elsif( $tag eq 'blockquote' )
195 {
196 $top = $doc->create_blockquote || return( $self->pass_error );
197 $me->add_element( $top ) || return( $self->pass_error );
198 }
199 elsif( $tag eq 'b' )
200 {
201 $top = $doc->create_bold || return( $self->pass_error );
202 $me->add_element( $top ) || return( $self->pass_error );
203 }
204 elsif( $tag eq 'checkbox' )
205 {
206 $top = $doc->create_checkbox({
207 checked => $e->attributes->exists( 'checked' ),
208 disabled => $e->attributes->exists( 'disabled' ),
209 }) || return( $self->pass_error );
210 $me->add_element( $top ) || return( $self->pass_error );
211 }
212 elsif( $tag eq 'code' )
213 {
214 my $test_str = $e->children->map(sub{ $_->as_string })->join( '' )->scalar;
215 my $is_fenced = ( CORE::index( $test_str, "\n" ) != -1 ) ? 1 : 0;
216 $top = $doc->create_code({
217 fenced => $is_fenced,
218 inline => !$is_fenced,
219 }) || return( $self->pass_error );
220 $me->add_element( $top ) || return( $self->pass_error );
221 }
222 elsif( $tag eq 'em' )
223 {
224 $top = $doc->create_em || return( $self->pass_error );
225 $me->add_element( $top ) || return( $self->pass_error );
226 }
227 elsif( $tag eq 'h1' ||
228 $tag eq 'h2' ||
229 $tag eq 'h3' ||
230 $tag eq 'h4' ||
231 $tag eq 'h5' ||
232 $tag eq 'h6' )
233 {
234 my $level = int( substr( $tag, -1, 1 ) );
235 $top = $doc->create_header({ level => $level }) || return( $self->pass_error );
236 $me->add_element( $top ) || return( $self->pass_error );
237 }
238 elsif( $tag eq 'img' )
239 {
240 $top = $doc->create_image({
241 ( $e->attr( 'alt' ) ? ( alt => $e->attr( 'alt' ) ) : () ),
242 ( $e->attr( 'id' ) ? ( id => $e->attr( 'id' ) ) : () ),
243 ( $e->attr( 'title' ) ? ( title => $e->attr( 'title' ) ) : () ),
244 ( $e->attr( 'src' ) ? ( url => $e->attr( 'src' ) ) : () ),
245 }) || return( $self->pass_error );
246 $me->add_element( $top ) || return( $self->pass_error );
247 }
248 elsif( $tag eq 'ins' )
249 {
250 $top = $doc->create_insertion || return( $self->pass_error );
251 $me->add_element( $top ) || return( $self->pass_error );
252 }
253 elsif( $tag eq 'hr' )
254 {
255 # <hr> cannot have children so use $elem instead of $top
256 my $elem = $doc->create_line || return( $self->pass_error );
257 $me->add_element( $elem ) || return( $self->pass_error );
258 }
259 elsif( $tag eq 'a' )
260 {
261 if( $e->attr( 'href' ) )
262 {
263 $top = $doc->create_link({
264 ( $e->attr( 'name' ) ? ( name => $e->attr( 'name' ) ) : () ),
265 ( $e->attr( 'id' ) ? ( id => $e->attr( 'id' ) ) : () ),
266 ( $e->attr( 'title' ) ? ( title => $e->attr( 'title' ) ) : () ),
267 url => $e->attr( 'href' ),
268 }) || return( $self->pass_error );
269 $me->add_element( $top ) || return( $self->pass_error );
270 }
271 # else, an anchor, and we ignore it, and move on to add it possible children directly here at the same level
272 }
273 elsif( $tag eq 'ul' ||
274 $tag eq 'ol' )
275 {
276 my $indent = 0;
277 my $is_ordered = ( $tag eq 'ol' ? 1 : 0 );
278 if( $me->tag_name eq 'list_item' )
279 {
280 $indent = $me->indent + 1;
281 }
282 $top = $doc->create_list({
283 indent => $indent,
284 order => $is_ordered,
285 }) || return( $self->pass_error );
286 $me->add_element( $top ) || return( $self->pass_error );
287 }
288 elsif( $tag eq 'li' )
289 {
290 my $indent = 0;
291 my $is_ordered = 0;
292 if( $me->tag_name eq 'list' )
293 {
294 $indent = $me->indent + 1;
295 $is_ordered = $me->order ? 1 : 0;
296 }
297 $top = $doc->create_list_item({
298 indent => $indent,
299 }) || return( $self->pass_error );
300 $me->add_element( $top ) || return( $self->pass_error );
301 }
302 elsif( $tag eq 'br' )
303 {
304 # <br> cannot have children so use $elem instead of $top
305 my $elem = $doc->create_new_line || return( $self->pass_error );
306 $me->add_element( $elem ) || return( $self->pass_error );
307 }
308 elsif( $tag eq 'p' )
309 {
310 $top = $doc->create_paragraph || return( $self->pass_error );
311 $me->add_element( $top ) || return( $self->pass_error );
312 }
313 elsif( $tag eq 's' || $tag eq 'del' )
314 {
315 $top = $doc->create_strikethrough || return( $self->pass_error );
316 $me->add_element( $top ) || return( $self->pass_error );
317 }
318 elsif( $tag eq 'sub' )
319 {
320 $top = $doc->create_subscript || return( $self->pass_error );
321 $me->add_element( $top ) || return( $self->pass_error );
322 }
323 elsif( $tag eq 'sup' )
324 {
325 $top = $doc->create_superscript || return( $self->pass_error );
326 $me->add_element( $top ) || return( $self->pass_error );
327 }
328 elsif( $tag eq 'table' )
329 {
330 $top = $doc->create_table || return( $self->pass_error );
331 $me->add_element( $top ) || return( $self->pass_error );
332 }
333 elsif( $tag eq 'tbody' )
334 {
335 $top = $doc->create_table_body || return( $self->pass_error );
336 if( $me->tag_name eq 'table' )
337 {
338 $me->add_body( $top ) || return( $self->pass_error );
339 }
340 else
341 {
342 $me->add_element( $top ) || return( $self->pass_error );
343 }
344 }
345 elsif( $tag eq 'thead' )
346 {
347 $top = $doc->create_table_header || return( $self->pass_error );
348 if( $me->tag_name eq 'table' )
349 {
350 $me->add_header( $top ) || return( $self->pass_error );
351 }
352 else
353 {
354 $me->add_element( $top ) || return( $self->pass_error );
355 }
356 }
357 elsif( $tag eq 'tr' )
358 {
359 $top = $doc->create_table_row || return( $self->pass_error );
360 $me->add_element( $top ) || return( $self->pass_error );
361 }
362 elsif( $tag eq 'td' )
363 {
364 $top = $doc->create_table_cell || return( $self->pass_error );
365 $me->add_element( $top ) || return( $self->pass_error );
366 }
367 elsif( $tag eq 'th' )
368 {
369 $top = $doc->create_table_cell({
370 tag_name => 'th',
371 }) || return( $self->pass_error );
372 $me->add_element( $top ) || return( $self->pass_error );
373 }
374 elsif( $tag eq 'caption' )
375 {
376 $top = $doc->create_table_caption || return( $self->pass_error );
377 $me->add_element( $top ) || return( $self->pass_error );
378 }
379 elsif( $tag eq '_text' || $tag eq '_space' )
380 {
381 # text chunk cannot have children so use $elem instead of $top
382 my $elem = $doc->create_text({
383 text => $e->value,
384 }) || return( $self->pass_error );
385 $me->add_element( $elem ) || return( $self->pass_error );
386 }
387 elsif( $tag eq '_document' )
388 {
389 $e->children->foreach(sub
390 {
391 $crawl->( $_[0] => $me );
392 });
393 }
394 # Anything else, and we save it as raw HTML, and we do not delve deeper
395 else
396 {
397 my $raw = $e->as_string;
398 my $elem = $doc->create_html({
399 object => $e,
400 raw => $raw,
401 }) || return( $self->pass_error );
402 $me->add_element( $elem ) || return( $self->pass_error );
403 }
404
405 if( defined( $top ) )
406 {
407 $e->children->foreach(sub
408 {
409 $crawl->( $_[0] => $top );
410 });
411 }
412 };
413 $crawl->( $html => $doc );
414 return( $doc );
415 }
416  
417 sub katex_delimiter { return( shift->_set_get_array_as_object( 'katex_delimiter', @_ ) ); }
418  
419 # Nothing fancy, and used internally so no chaining or anything
420 # We use it like $p->list_level++ or $p->list_level--;
421 sub list_level : lvalue { return( shift->_set_get_lvalue( 'list_level', @_ ) ); }
422  
423 sub mode
424 {
425 my $self = shift( @_ );
426 if( @_ )
427 {
428 my $mode = shift( @_ );
429 my $curr = $self->_set_get_scalar( 'mode' );
430 my $ref = $self->new_array( [split( /[[:blank:]]+/, $curr )] );
431 if( substr( $mode, 0, 1 ) eq '+' )
432 {
433 $mode =~ s/^\++//g;
434 $ref->push( $mode );
435 }
436 elsif( substr( $mode, 0, 1 ) eq '-' )
437 {
438 $mode =~ s/^\-+//g;
439 $ref->remove( $mode );
440 }
441 else
442 {
443 $ref->push( $mode );
444 }
445 $ref->unique(1);
446 $curr = $ref->join( ' ' )->scalar;
447 $self->_set_get_scalar( 'mode', $curr );
448 }
449 return( $self->_set_get_scalar( 'mode' ) );
450 }
451  
452 sub parse
453 {
454 my $self = shift( @_ );
455 # We accept empty data and we return empty elements array then
456 my $data = shift( @_ );
457 my $opts = $self->_get_args_as_hash( @_ );
458 my $cb = $self->callback;
459 if( !defined( $cb ) )
460 {
461 $cb = sub{1};
462 }
463 elsif( ref( $cb ) )
464 {
465 return( $self->error( "Callback set (${cb}) is not a code reference." ) );
466 }
467  
468 unless( $opts->{element} )
469 {
470 # Standardise the new lines characters
471 # $data =~ s/\cM/\n/gs;
472 # $data =~ s/\c@//g;
473 $data =~ s/\r\n/\n/gs;
474 $data =~ s/\r//gs;
475 # Clean up the empty lines as they do not matter
476 $data =~ s/^[[:blank:]\h]+$//gm;
477 # Detab
478 # Cribbed from a post by Bart Lateur:
479 # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154>
480 my $tab_width = 4;
481 $data =~ s{(.*?)\t}{$1 . ( ' ' x ( $tab_width - length( $1 ) % $tab_width ) )}ge;
482 # Make sure $text ends with a couple of newlines, unless this is sub parsing
483 my $trailing_nl = ( $data =~ /(\n+)$/ )[0];
484 my $nth_nl = defined( $trailing_nl ) ? length( $trailing_nl ) : 0;
485 unless( $nth_nl > 1 )
486 {
487 $data .= ( "\n" x ( 2 - $nth_nl ) );
488 }
489 }
490  
491  
492 pos( $data ) = 0;
493 # all excludes extended markdowns
494 my $mode = $self->mode || 'all';
495 my $space_re = qr/[[:blank:]\h]{1,3}/;
496 my $PH_PREFIX = 'OBJ{';
497 my $PH_SUFFIX = '}';
498 my $top;
499 if( !( $top = $opts->{element} ) )
500 {
501 my $doc = $self->create_document(
502 abbreviation_case_sensitive => $self->abbreviation_case_sensitive,
503 default_email => $self->default_email,
504 email_obfuscate_class => $self->email_obfuscate_class,
505 email_obfuscate_data_host => $self->email_obfuscate_data_host,
506 email_obfuscate_data_user => $self->email_obfuscate_data_user,
507 css => $self->css,
508 debug => $self->debug,
509 tag_name => 'top',
510 );
511 # Sharing the parameter
512 $doc->katex_delimiter( $self->katex_delimiter );
513 # First time called, we reset the top document, so the same parser can be called several times
514 $self->document( $doc );
515 $top = $doc;
516 };
517 $self->messagef_colour( 3, "%s %d bytes of data with mode set to '{green}%s{/}' with container being '{green}%s{/}'.", ( $opts->{element} ? "Sub-parsing" : "Parsing" ), length( $data ), $mode, $top->tag_name );
518  
519 # Previous element added. We store it here to keep track of context
520 my $context;
521 # pos( $data ) = 0;
522 pos( $data ) = $opts->{pos} if( length( $opts->{pos} ) && $opts->{pos} =~ /^\d+$/ );
523 $opts->{scope_cond} = 'any';
524 # If the 'scope' option has not been provided, or is not an array
525 if( !$self->_is_array( $opts->{scope} ) )
526 {
527 # Split the scope option to make it an array, or else split the object 'mode' option
528 $opts->{scope} = length( $opts->{scope} ) ? [split( /\s+/, $opts->{scope} )] : [split( /\s+/, $mode )];
529 }
530 # The option 'scope' is an array, but it is empty
531 elsif( $self->_is_array( $opts->{scope} ) &&
532 !$self->_to_array_object( $opts->{scope} )->length )
533 {
534 $opts->{scope} = $self->_is_empty( $mode ) ? [] : $self->_is_array( $mode ) ? $mode : ["$mode"];
535 }
536  
537 if( length( $opts->{scope} ) && $self->_is_array( $opts->{scope} ) )
538 {
539 my $scopes = $self->new_array;
540 $self->_to_array_object( $opts->{scope} )->foreach(sub
541 {
542 # OR
543 if( s/\|{1,2}/ /g )
544 {
545 $scopes->push( split( /\s+/, $_ ) );
546 $opts->{scope_cond} = 'any';
547 }
548 # AND
549 elsif( s/(?:\&{1,2}|\+)/ /g )
550 {
551 $scopes->push( split( /\s+/, $_ ) );
552 $opts->{scope_cond} = 'all';
553 }
554 # Scope term
555 else
556 {
557 $scopes->push( $_ );
558 }
559 });
560 $opts->{scope} = $scopes;
561 }
562  
563 my $scope = Markdown::Parser::Scope->new( $opts->{scope}, debug => $self->debug, condition => $opts->{scope_cond} );
564 $self->scope( $scope ) if( $top->tag_name eq 'top' && !$self->scope );
565
566 my $katex_re;
567 # We check for link definitions, but only if we are in the top element, since sub elements would not hold any of them and it would thus be pointless to process them
568 # Need to remove the link definition from the document
569 if( $top->tag_name eq 'top' )
570 {
571 # NOTE: html
572 # Need to isolate html code blocks, because their indentation can be mistaken for code blocks.
573 # Then, we parse for code block, we re-instate the html block found and isolated.
574 if( $scope->has( [qw( html )]) )
575 {
576 $data =~ s{$RE{Markdown}{Html}}
577 {
578 my $re = { %+ };
579 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
580 my $pos = pos( $data );
581 # my $html = $re->{tag_all};
582 # We save exactly what we caught
583 my $html = substr( $data, $-[0], $+[0] - $-[0] );
584 my $elem = $top->create_html({
585 pos => $pos,
586 raw => $html,
587 }) || die( $top->error );
588 my $id = $self->document->add_object( $elem ) || die( $top->error );
589 "!!HTML[$id]!!";
590 }xgems;
591 }
592  
593 # NOTE: extended code_block
594 # Code blocks trumps everything else, so they come first
595 # First, check the parts that are surrounded by backticks or equivalents
596 $self->message_colour( 3, "Does scope have '{green}extended code_block{/}' ? ", $scope->has( [qw( extended code_block )] ) ? '{green}yes{/}' : '{red}no{/}' );
597 if( $scope->has( [qw( extended code_block )] ) )
598 {
599 $data =~ s{$RE{Markdown}{ExtCodeBlock}}
600 {
601 my $re = { %+ };
602 $re->{capture} = substr( $data, $-[0], $+[0] - $-[0] );
603 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
604 my $pos = pos( $data );
605 my $code_def = $re->{code_attr};
606 my $code_class = $re->{code_class};
607 my $raw = $re->{code_all};
608 my $content = $re->{code_content};
609
610 # Restore any html that got caught previously
611 $content =~ s{\!{2}HTML\[(?<obj_id>\d+)\]\!{2}}
612 {
613 my $obj_id = $+{obj_id};
614 my $obj = $self->document->objects->get( $obj_id );
615 if( $obj )
616 {
617 $obj->raw->scalar;
618 }
619 else
620 {
621 "!!HTML[${obj_id}]!!";
622 }
623 }xgems;
624
625 $code_def =~ s/^[[:blank:]\h]+|[[:blank:]\h]+$//gs if( defined( $code_def ) );
626 $code_class =~ s/^[\.[:blank:]\h]+//gs if( defined( $code_class ) );
627
628 my $code = $top->create_code({
629 class => [split( /\./, $code_class )],
630 pos => $pos,
631 raw => $raw,
632 fenced => 1,
633 });
634 $code->add_element( $top->create_text({
635 text => $content,
636 pos => $pos,
637 }) ) || return( $self->pass_error( $code->error ) );
638 $code->add_attributes( $code_def ) if( length( $code_def ) );
639 my $id = $top->add_object( $code );
640 "${PH_PREFIX}${id}${PH_SUFFIX}\n";
641 }xgems;
642 }
643 # NOTE: code_block
644 elsif( $self->message_colour( 3, "Does scope have '{green}code_block{/}' ? ", $scope->has( 'code_block' ) ? '{green}yes{/}' : '{red}no{/}' ) && $scope->has( 'code_block' ) )
645 {
646 $data =~ s{$RE{Markdown}{CodeBlock}}
647 {
648 my $re = { %+ };
649 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
650 my $pos = pos( $data );
651 my $raw = $re->{code_all};
652 my $content = $re->{code_content};
653 # my $new_lines = $re->{code_trailing_new_line};
654
655 # Restore any html that got caught previously
656 $content =~ s{\!{2}HTML\[(?<obj_id>\d+)\]\!{2}}
657 {
658 my $obj_id = $+{obj_id};
659 my $obj = $self->document->objects->get( $obj_id );
660 if( $obj )
661 {
662 $obj->raw->scalar;
663 }
664 else
665 {
666 "!!HTML[${obj_id}]!!";
667 }
668 }xgems;
669
670 my $code = $top->create_code({
671 pos => $pos,
672 raw => $raw,
673 fenced => 1,
674 });
675 $code->add_element( $top->create_text({
676 text => $content,
677 pos => $pos,
678 }) ) || return( $self->pass_error( $code->error ) );
679 my $id = $top->add_object( $code );
680 "${PH_PREFIX}${id}${PH_SUFFIX}\n";
681 }xgems;
682 }
683  
684 # NOTE: code_line
685 $self->message_colour( 3, "Does scope have '{green}code_line{/}' ? ", $scope->has( 'code_line' ) ? '{green}yes{/}' : '{red}no{/}' );
686 # Code single line. If it is a series of them treat them as a block
687 if( $scope->has( 'code_line' ) )
688 {
689 $data =~ s{$RE{Markdown}{CodeLine}}
690 {
691 my $re = { %+ };
692 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
693 my $pos = pos( $data );
694 my $raw = $re->{code_all};
695 my $content = $re->{code_all};
696
697 ## Restore any html that got caught previously
698 $content =~ s{\!{2}HTML\[(?<obj_id>\d+)\]\!{2}}
699 {
700 my $obj_id = $+{obj_id};
701 my $obj = $self->document->objects->get( $obj_id );
702 if( $obj )
703 {
704 $obj->raw->scalar;
705 }
706 else
707 {
708 "!!HTML[${obj_id}]!!";
709 }
710 }xgems;
711
712 # trim leading newlines
713 $content =~ s/\A\n+//;
714 # trim trailing whitespace
715 $content =~ s/\s+\z//;
716 my $trailing_nl = $self->_total_trailing_new_lines( $raw );
717 my $code = $top->create_code({
718 # Setting this to true will have the leading 4 spaces or tab removed
719 fenced => 1,
720 pos => $pos,
721 raw => $re->{code_all},
722 });
723 $code->add_element( $top->create_text({
724 text => $content,
725 pos => $pos,
726 }) ) || return( $self->pass_error( $code->error ) );
727 my $id = $top->add_object( $code );
728 # Move back before the trailing new lines as they may be important for the next check
729 "${PH_PREFIX}${id}${PH_SUFFIX}\n";
730 }xgems;
731 }
732  
733 # NOTE: Restore any html blocks if any
734 # Restore any html blocks if any
735 $data =~ s{\!{2}HTML\[(?<obj_id>\d+)\]\!{2}}
736 {
737 my $obj_id = $+{obj_id};
738 my $obj = $self->document->objects->get( $obj_id );
739 if( $obj )
740 {
741 $obj->raw->scalar;
742 }
743 else
744 {
745 "!!HTML[${obj_id}]!!";
746 }
747 }xgems;
748  
749
750 pos( $data ) = 0;
751 # NOTE: code_span
752 # Inline code `some thing`
753 if( $scope->has( 'code_span' ) )
754 {
755 $data =~ s{$RE{Markdown}{CodeSpan}}
756 {
757 my $re = { %+ };
758 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
759 my $pos = pos( $data );
760 my $raw = $re->{code_all};
761 my $content = $re->{code_content};
762 $self->message_colour( 3, $self->whereami( \$data, $pos, { text => "Found an inline code '$raw' at pos '$pos' with content:\n'{green}" . $content . "{/}' and with capture: " . $self->dump( $re ), return => 1 } ) );
763 # leading whitespace
764 $content =~ s/^[ \t]*//g;
765 # trailing whitespace
766 $content =~ s/[ \t]*$//g;
767 my $code = $top->create_code({
768 inline => 1,
769 pos => $pos,
770 raw => $raw,
771 });
772 $code->add_element( $top->create_text({
773 text => $content,
774 pos => $pos,
775 }) );
776 my $id = $top->add_object( $code );
777 "${PH_PREFIX}${id}${PH_SUFFIX}";
778 }xgems;
779 }
780
781 $self->messagef_colour( 3, "%d objects found so far.", $top->objects->length );
782
783 # NOTE: extended link
784 $self->message_colour( 3, "Processing possible {green}link{/} definitions." );
785 $data =~ s{$RE{Markdown}{ExtLinkDefinition}}
786 {
787 my $re = { %+ };
788 my $id = $re->{link_id};
789 my $url = $re->{link_url};
790 my $title = $re->{link_title};
791 my $link_def = $re->{link_attr};
792 my $raw = $re->{link_all};
793 my $end = pos( $data );
794 my $start = $end - length( $re->{link_all} );
795 $self->message_colour( 3, $self->whereami( \$data, pos( $data ), { text => "Found link definition with id '{green}" . $re->{link_id} . "{/}', url '{green}" . $re->{link_url} . "{/}', title '{green}" . $re->{link_title} . "{/}', all '{green}" . $re->{link_all} . "{/}' at position '" . $start . "' until position '" . $end . "'.", return => 1 } ) );
796 my $lnk = $top->create_link_definition({
797 link_id => $id,
798 pos => pos( $data ),
799 raw => $raw,
800 title => $title,
801 url => $url,
802 });
803 $link_def =~ s/^[[:blank:]\h]+|[[:blank:]\h]+$//gs;
804 $lnk->add_attributes( $link_def ) if( length( $link_def ) );
805 ## Just register the link definition, but do not add it to the document
806 $top->register_link_definition( $lnk );
807 '';
808 }gme;
809  
810 # NOTE: link
811 $data =~ s{$RE{Markdown}{LinkDefinition}}
812 {
813 my $re = { %+ };
814 my $id = $re->{link_id};
815 my $url = $re->{link_url};
816 my $title = $re->{link_title};
817 my $raw = $re->{link_all};
818 my $end = pos( $data );
819 my $start = $end - length( $re->{link_all} );
820 $self->message_colour( 3, $self->whereami( \$data, pos( $data ), { text => "Found link definition with id '{green}" . $re->{link_id} . "{/}', url '{green}" . $re->{link_url} . "{/}', title '{green}" . $re->{link_title} . "{/}', all '{green}" . $re->{link_all} . "{/}' at position '" . $start . "' until position '" . $end . "'.", return => 1 } ) );
821 my $lnk = $top->create_link_definition({
822 link_id => $id,
823 pos => pos( $data ),
824 raw => $raw,
825 title => $title,
826 url => $url,
827 });
828 # Just register the link definition, but do not add it to the document
829 $top->register_link_definition( $lnk );
830 '';
831 }gme;
832  
833 pos( $data ) = 0;
834 # NOTE: extended abbr
835 $self->message_colour( 3, "Does scope have '{green}abbr{/}' ? ", $scope->has( [qw( extended abbr )] ) ? '{green}yes{/}' : '{red}no{/}' );
836 if( $scope->has( [qw( extended abbr )] ) )
837 {
838 $data =~ s{^[[:blank:]\h]{0,3}$RE{Markdown}{ExtAbbr}}
839 {
840 my $re = { %+ };
841 my $end = pos( $data );
842 my $start = $end - length( $re->{abbr_all} );
843 $self->message_colour( 3, $self->whereami( \$data, pos( $data ), { text => "Found abbreviation \"{green}" . $re->{abbr_all} . "{/}\" with name '{green}" . $re->{abbr_name} . "{/}' with capture: " . $self->dump( $re ), return => 1 } ) );
844 my $abbr = $top->create_abbreviation({
845 name => $re->{abbr_name},
846 value => $re->{abbr_value},
847 parent => $top,
848 pos => pos( $data ),
849 raw => $re->{abbr_all},
850 });
851 $top->register_abbreviation( $abbr, { case_sensitive => $self->abbreviation_case_sensitive } );
852 '';
853 }gme;
854 }
855  
856 # NOTE: extended footnote
857 $self->message_colour( 3, "Does scope have '{green}footnote{/}' ? ", $scope->has( [qw( extended footnote )] ) ? '{green}yes{/}' : '{red}no{/}' );
858 if( $scope->has( [qw( extended footnote )] ) )
859 {
860 $data =~ s{$RE{Markdown}{ExtFootnote}}
861 {
862 my $re = { %+ };
863 my $end = pos( $data );
864 my $start = $end - length( $re->{footnote_all} );
865 $self->message_colour( 3, $self->whereami( \$data, pos( $data ), { text => "Found footnote \"{green}" . $re->{footnote_all} . "{/}\" with id '{green}" . $re->{footnote_id} . "{/}' with capture: " . $self->dump( $re ), return => 1 } ) );
866 my $content = $re->{footnote_text} . ' !!FN!!';
867 my $footnote = $top->create_footnote({
868 id => $re->{footnote_id},
869 unparsed => $content,
870 parent => $top,
871 pos => pos( $data ),
872 raw => $re->{footnote_all},
873 }) || die( "Unable to create footnote object: ", $top->error, "\n" );
874 $top->register_footnote( $footnote );
875 '';
876 }gme;
877 }
878  
879 # NOTE: footnote reference extended
880 $self->message_colour( 3, "Does scope have '{green}footnote{/}' ? ", $scope->has( [qw( footnote extended )] ) ? '{green}yes{/}' : '{red}no{/}' );
881 if( $scope->has( [qw( footnote extended )] ) )
882 {
883 $data =~ s{$RE{Markdown}{ExtFootnoteReference}}
884 {
885 my $re = { %+ };
886 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
887 my $pos = pos( $data );
888 my $id = $re->{footnote_id};
889 my $text = $re->{footnote_text};
890 my $footnote;
891 # Auto-generated id for inline footnote
892 # Example:
893 # I met Jack [^](Co-founder of Angels, Inc) at the meet-up.
894 # Here is an inline note.^[Inlines notes are easier to write]
895 # Inline footnote, i.e. text provided
896 # We cannot just do if( !$id ) because a valid id could be '0'
897 my $object_id;
898 if( !length( $id ) )
899 {
900 $id = $self->document->footnotes->length + 1;
901 }
902
903 if( length( $text ) )
904 {
905 $footnote = $top->create_footnote({
906 id => $id,
907 text => $text,
908 parent => $top,
909 pos => $pos,
910 raw => $re->{footnote_all},
911 });
912 $top->register_footnote( $footnote );
913 }
914 # Cannot find an id matching this footnote, so we just add this footnote reference as a text
915 elsif( !( $footnote = $self->document->get_footnote( $id ) ) )
916 {
917 warn( "Unable to find a matching footnote with the footnote id \"$id\".\nAvailable footnotes ids are: '", $self->document->footnotes->map(sub{ $_->id })->join( "', '" ), "'." );
918 $object_id = $self->document->add_object( $top->create_text(
919 {
920 text => $re->{footnote_all},
921 pos => $pos,
922 }) );
923 }
924
925 if( $footnote )
926 {
927 # Create a footnote reference and associate this footnote id with this reference
928 # The footnote reference id will be set by add_reference()
929 my $ref = $top->create_footnote_ref({
930 footnote => $footnote,
931 raw => $re->{footnote_all},
932 sequence => ++$self->footnote_ref_sequence,
933 pos => $pos,
934 });
935 ## add_reference will take care of setting the id used for backlink for this footnote reference
936 $footnote->add_reference( $ref );
937 $object_id = $self->document->add_object( $ref );
938 }
939 "${PH_PREFIX}${object_id}${PH_SUFFIX}";
940 }xgems;
941 }
942
943 $self->message_colour( 3, "After processing {green}link{/} definition, {green}abbreviations{/} and {green}footnotes{/}, data is now '$data'." );
944 }
945
946 # NOTE: extended katex
947 if( $scope->has( [qw( extended katex )] ) )
948 {
949 if( $self->katex_delimiter->length > 0 )
950 {
951 $katex_re = $RE{Markdown}{ExtKatex}{-delimiter => $self->katex_delimiter->join( ',' )};
952 }
953 else
954 {
955 $katex_re = $RE{Markdown}{ExtKatex};
956 }
957 }
958
959 my $abbr_re;
960 if( $self->document->dict->length > 0 )
961 {
962 $abbr_re = '(?' . ( $self->abbreviation_case_sensitive ? '' : 'i' ) . ':' . $self->document->dict->keys->join( '|' )->scalar . ')';
963 $abbr_re = qr/$abbr_re/;
964 }
965 pos( $data ) = 0;
966
967
968 if( $top->tag_name ne 'top' )
969 {
970 # NOTE: extended code block
971 $self->message_colour( 3, "Does scope have '{green}extended code_block{/}' ? ", $scope->has( [qw( extended code_block )] ) ? '{green}yes{/}' : '{red}no{/}' );
972 if( $scope->has( [qw( extended code_block )] ) )
973 {
974 $data =~ s{$RE{Markdown}{ExtCodeBlock}}
975 {
976 my $re = { %+ };
977 $re->{capture} = substr( $data, $-[0], $+[0] - $-[0] );
978 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
979 my $pos = pos( $data );
980 my $code_def = $re->{code_attr};
981 my $code_class = $re->{code_class};
982 my $raw = $re->{code_all};
983 my $content = $re->{code_content};
984
985 $code_def =~ s/^[[:blank:]\h]+|[[:blank:]\h]+$//gs;
986 $code_class =~ s/^[\.[:blank:]\h]+//gs;
987
988 my $code = $top->create_code({
989 class => [split( /\./, $code_class )],
990 pos => $pos,
991 raw => $raw,
992 fenced => 1,
993 });
994 $code->add_element( $top->create_text({
995 text => $content,
996 pos => $pos,
997 }) ) || return( $self->pass_error( $code->error ) );
998 $code->add_attributes( $code_def ) if( length( $code_def ) );
999 my $id = $self->document->add_object( $code );
1000 "${PH_PREFIX}${id}${PH_SUFFIX}\n";
1001 }xgems;
1002 }
1003
1004 # NOTE: code block
1005 $self->message_colour( 3, "Does scope have '{green}code_block{/}' ? ", $scope->has( 'code_block' ) ? '{green}yes{/}' : '{red}no{/}' );
1006 # Code blocks trumps everything else, so they come first
1007 if( $scope->has( 'code_block' ) )
1008 {
1009 $data =~ s{$RE{Markdown}{CodeBlock}}
1010 {
1011 my $re = { %+ };
1012 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1013 my $pos = pos( $data );
1014 my $raw = $re->{code_all};
1015 my $content = $re->{code_content};
1016 # my $new_lines = $re->{code_trailing_new_line};
1017 my $code = $top->create_code({
1018 pos => $pos,
1019 raw => $raw,
1020 fenced => 1,
1021 });
1022 $code->add_element( $top->create_text({
1023 text => $content,
1024 pos => $pos,
1025 }) ) || return( $self->pass_error( $code->error ) );
1026 my $id = $self->document->add_object( $code );
1027 "${PH_PREFIX}${id}${PH_SUFFIX}\n";
1028 }xgems;
1029 }
1030
1031 # NOTE: code line
1032 $self->message_colour( 3, "Does scope have '{green}code_line{/}' ? ", $scope->has( 'code_line' ) ? '{green}yes{/}' : '{red}no{/}' );
1033 # Code single line. If it is a series of them treat them as a block
1034 if( $scope->has( 'code_line' ) )
1035 {
1036 $data =~ s{$RE{Markdown}{CodeLine}}
1037 {
1038 my $re = { %+ };
1039 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1040 my $pos = pos( $data );
1041 my $raw = $re->{code_all};
1042 my $content = $re->{code_all};
1043 # trim leading newlines
1044 $content =~ s/\A\n+//;
1045 # trim trailing whitespace
1046 $content =~ s/\s+\z//;
1047 my $trailing_nl = $self->_total_trailing_new_lines( $raw );
1048 my $code = $top->create_code({
1049 ## Setting this to true will have the leading 4 spaces or tab removed
1050 fenced => 1,
1051 pos => $pos,
1052 raw => $re->{code_all},
1053 });
1054 $code->add_element( $top->create_text({
1055 text => $content,
1056 pos => $pos,
1057 }) ) || return( $self->pass_error( $code->error ) );
1058 my $id = $self->document->add_object( $code );
1059 # Move back before the trailing new lines as they may be important for the next check
1060 "${PH_PREFIX}${id}${PH_SUFFIX}\n";
1061 }xgems;
1062 }
1063 }
1064  
1065 # NOTE: table extended
1066 $self->message_colour( 3, "Does scope have '{green}table extended{/}' ? ", $scope->has( [qw( table extended )] ) ? '{green}yes{/}' : '{red}no{/}' );
1067 if( $scope->has( 'table extended' ) )
1068 {
1069 $data =~ s{$RE{Markdown}{ExtTable}}
1070 {
1071 my $re = { %+ };
1072 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1073 my $pos = pos( $data );
1074 my $tbl = $self->parse_table( $re, { doc => $top } );
1075 my $id = $tbl->object_id;
1076 # pos( $data ) = $pos + length( $re->{table} );
1077 "${PH_PREFIX}${id}${PH_SUFFIX}\n";
1078 }xgems;
1079 }
1080  
1081 # NOTE: html
1082 $self->message_colour( 3, "Does scope have '{green}html{/}' ? ", $scope->has( 'html' ) ? '{green}yes{/}' : '{red}no{/}' );
1083 # HTML blocks MUST be start and end on their own lines
1084 if( $scope->has( 'html' ) )
1085 {
1086 $data =~ s{$RE{Markdown}{Html}}
1087 {
1088 my $re = { %+ };
1089 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1090 my $pos = pos( $data );
1091 my $html = $re->{tag_all};
1092 $html =~ s{$RE{Markdown}{ExtHtmlMarkdown}}
1093 {
1094 my $ct = $+{content};
1095 my $open = $+{div_open};
1096 my $close = $+{div_close};
1097 my $tag_name = $+{tag_name};
1098 my $leading_space = $+{leading_space};
1099 ## Remove the markdown attribute
1100 $open =~ s/[[:blank:]\h]+markdown[[:blank:]\h]*\=[[:blank:]\h]*(?<quote>["']?)1\g{quote}//;
1101 ## Need to remove indentation at begining of line
1102 if( length( $leading_space ) )
1103 {
1104 $ct =~ s/^$leading_space//gm;
1105 }
1106 my $p = $top->create_paragraph({
1107 parent => $top,
1108 pos => $pos,
1109 });
1110 $self->parse( $ct, { element => $p });
1111 my $res = $p->children->map(sub{ $_->as_string })->join( '' )->scalar;
1112 "${open}${res}\n${close}\n";
1113 }xgems;
1114
1115 my $elem = $top->create_html({
1116 pos => $pos,
1117 raw => $html,
1118 }) || die( $top->error );
1119 my $id = $self->document->add_object( $elem ) || die( $top->error );
1120 "${PH_PREFIX}${id}${PH_SUFFIX}\n";
1121 }xgemsi;
1122 }
1123  
1124 # NOTE: blockquote
1125 $self->message_colour( 3, "Does scope have '{green}blockquote{/}' ? ", $scope->has( 'blockquote' ) ? '{green}yes{/}' : '{red}no{/}' );
1126 # Blockquote
1127 if( $scope->has( 'blockquote' ) )
1128 {
1129 $data =~ s{$RE{Markdown}{Blockquote}}
1130 {
1131 my $re = { %+ };
1132 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1133 my $pos = pos( $data );
1134 $self->message_colour( 3, $self->whereami( \$data, $pos, { text => "Found a blockquote '{green}" . $re->{bquote_all} . "{/}' at pos '$pos' with capture: " . $self->dump( $re ), return => 1 } ) );
1135 my $raw = $re->{bquote_all};
1136 my $bq = $raw;
1137 $bq =~ s/^[ \t]*>[ \t]?//gm; # trim one level of quoting
1138 $bq =~ s/^[ \t]+$//mg; # trim whitespace-only lines
1139 my $block = $top->create_blockquote({
1140 pos => $pos,
1141 raw => $raw,
1142 });
1143 my $id = $self->document->add_object( $block );
1144 $self->parse( $bq, { scope => $self->scope_block, element => $block } );
1145 "${PH_PREFIX}${id}${PH_SUFFIX}\n";
1146 }xgems;
1147 }
1148  
1149 # NOTE: line
1150 # Now, the line elements
1151  
1152 # Setext-style headers:
1153 # Header 1 {.main .shine #the-site lang=fr}
1154 # ========
1155 #
1156 # Header 2 {.main .shine #the-site lang=fr}
1157 # --------
1158 #
1159 # This is to be on a single line of its own
1160 $self->message_colour( 3, "Does scope have '{green}header extended{/}' ? ", $scope->has( 'header extended' ) ? '{green}yes{/}' : '{red}no{/}' );
1161 if( $scope->has( 'header extended' ) )
1162 {
1163 $data =~ s{$RE{Markdown}{ExtHeader}}
1164 {
1165 my $re = { %+ };
1166 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1167 my $pos = pos( $data );
1168 $self->message_colour( 3, $self->whereami( \$data, $pos, { text => "Found an extended header '{green}" . $re->{header_all} . "{/}' with header level '{green}" . length( $re->{header_level} ) . "{/}' and attributes '{green}" . $re->{header_attr} . "{/}' at pos '$pos' with capture: " . $self->dump( $re ), return => 1 } ) );
1169 my $text = $re->{header_content};
1170 my $attr = $re->{header_attr};
1171 my $header = $top->create_header({
1172 level => length( $re->{header_level} ),
1173 pos => $pos,
1174 raw => $re->{header_all},
1175 });
1176 # Further process the text capture
1177 # If there are any elements, they will be placed inside the header element as children
1178 my $id = $self->document->add_object( $header );
1179 $self->parse( $text, { scope => 'inline extended', element => $header } );
1180 $header->add_attributes( $attr );
1181 "${PH_PREFIX}${id}${PH_SUFFIX}\n";
1182 }xgem;
1183 }
1184  
1185 # NOTE: header
1186 # Checking for headers
1187 # atx-style headers:
1188 # # Header 1
1189 # ## Header 2
1190 # ## Header 2 with closing hashes ##
1191 # ...
1192 # ###### Header 6
1193 $self->message_colour( 3, "Does scope have '{green}header{/}' ? ", $scope->has( 'header' ) ? '{green}yes{/}' : '{red}no{/}' );
1194 if( $scope->has( 'header' ) )
1195 {
1196 $data =~ s{$RE{Markdown}{Header}}
1197 {
1198 my $re = { %+ };
1199 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1200 my $pos = pos( $data );
1201 $self->message_colour( 3, $self->whereami( \$data, $pos, { text => "Found a vanilla header '{green}" . $re->{header_all} . "{/}' with header level '{green}" . length( $re->{header_level} ) . "{/}' at pos '$pos' with capture: " . $self->dump( $re ), return => 1 } ) );
1202 my $text = $re->{header_content};
1203 my $header = $top->create_header({
1204 level => length( $re->{header_level} ),
1205 pos => $pos,
1206 raw => $re->{header_all},
1207 });
1208 # Further process the text capture
1209 # If there are any elements, they will be placed inside the header element as children
1210 my $id = $self->document->add_object( $header );
1211 $self->parse( $text, { scope => $self->scope_inline, element => $header } );
1212 "${PH_PREFIX}${id}${PH_SUFFIX}\n";
1213 }xgem;
1214 }
1215  
1216 # NOTE: list
1217 # List goes before header line because a list with a 2nd empty element could be confused as an header line.
1218 # For example:
1219 # - HIJ
1220 # -
1221  
1222 # List
1223 my $list_re = $self->list_level ? $RE{Markdown}{ListNthLevel} : $RE{Markdown}{ListFirstLevel};
1224 $self->message_colour( 3, "Does scope have '{bold green}list{/}' ? ", $scope->has( 'list' ) ? '{green}yes{/}' : '{red}no{/}', " for scope '", $opts->{scope}->as_string, "'." );
1225 $self->message_colour( 3, "List level is '{green}", $self->list_level, "{/}'." );
1226 # If I do the following it does not work witht he regexp, but if I do substr( $data, $pos ) it works.
1227 # I am puzzled as to why, and I give up.
1228 # if( $scope->has( 'list' ) && $data =~ /\G$list_re/gmcs )
1229 # if( $scope->has( 'list' ) && substr( $data, $pos ) =~ /\G$list_re/gmcs )
1230 if( $scope->has( 'list' ) )
1231 {
1232 $data =~ s{$list_re}
1233 {
1234 my $re = { %+ };
1235 my $list = $re->{list_all};
1236 # my $list = $re->{list_content};
1237 # my $trailing_nl = ( $list =~ s/(\n+)$// )[0];
1238 # my $nth_nl = length( $trailing_nl );
1239 my $nth_nl = $self->_total_trailing_new_lines( $re->{list_all} );
1240 my $content = $re->{list_prefix} . $re->{list_content};
1241 my $post_nl_id;
1242 if( $nth_nl )
1243 {
1244 my $post_nl = $top->create_text({ text => "\n" x $nth_nl });
1245 $post_nl_id = $self->document->add_object( $post_nl );
1246 }
1247
1248 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1249 my $pos = pos( $data );
1250 my $list_type = $re->{list_type_ordered} ? 'ol' : 'ul';
1251 # Corollary from using substr( $daata, $pos ). We ned to update the position in the string manually
1252 # pos( $data ) = $pos + length( substr( $data, $-[0], $+[0]-$-[0] ) );
1253 # TODO With this new way of processing list, I do not know the indent level anymore. Might want to look into that.
1254 my $indent_level = 0;
1255 # Turn double returns into triple returns, so that we can make a
1256 # paragraph for the last item in a list, if necessary:
1257 $self->message_colour( 3, $self->whereami( \$data, $pos, { text => "Found a list of type '" . $list_type . "' and {green}${nth_nl}{/} trailing new lines at pos '" . $pos . "':\n'{bold orange}" . $list . "{/}' with capture: " . $self->dump( $re ), return => 1 } ) );
1258 my $new_list = $top->create_list({
1259 indent => $indent_level,
1260 pos => $pos,
1261 raw => "${content}\n",
1262 order => $list_type eq 'ol' ? 1 : 0,
1263 });
1264 my $id = $self->document->add_object( $new_list );
1265 # $list =~ s/\n{2,}/\n\n\n/g;
1266 $self->parse_list_item( $list, { doc => $new_list, pos => pos( $data ) } );
1267 # $nth_nl-- if( $nth_nl > 1 );
1268 # Trailing new lines are also preceding new lines for the next element if more than 1
1269 "${PH_PREFIX}${id}${PH_SUFFIX}" . ( defined( $post_nl_id ) ? "${PH_PREFIX}${post_nl_id}${PH_SUFFIX}" : '' );
1270 }xgems;
1271 }
1272
1273 # NOTE: header line extended
1274 # Ex: Some thing\n
1275 # ==========\n
1276 $self->message_colour( 3, "Does scope have '{green}header line extended{/}' ? ", $scope->has( 'header extended' ) ? '{green}yes{/}' : '{red}no{/}' );
1277 if( $scope->has( 'header extended' ) )
1278 {
1279 $data =~ s{$RE{Markdown}{ExtHeaderLine}}
1280 {
1281 my $re = { %+ };
1282 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1283 my $pos = pos( $data );
1284 $self->message_colour( 3, $self->whereami( \$data, $pos, { text => "Found an extended header line '{green}" . $re->{header_all} . "{/}' with text '{green}" . $re->{header_content} . "{/}' at pos '$pos' with capture: " . $self->dump( $re ), return => 1 } ) );
1285 my $text = $re->{header_content};
1286 my $raw = $re->{header_all};
1287 my $attr = $re->{header_attr};
1288 my $levels =
1289 {
1290 '=' => 1,
1291 '-' => 2,
1292 };
1293 my $header = $top->create_header({
1294 level => $levels->{ substr( $re->{header_type}, 0, 1 ) },
1295 parent => $top,
1296 pos => $pos,
1297 raw => $raw,
1298 });
1299 $header->add_attributes( $attr );
1300
1301 # Further process the text capture
1302 # If there are any elements, they will be placed inside the header element as children
1303 my $id = $self->document->add_object( $header );
1304 $self->parse( $text, { scope => 'inline extended', element => $header } );
1305 "${PH_PREFIX}${id}${PH_SUFFIX}\n";
1306 }xgems;
1307 }
1308  
1309 # NOTE: header line
1310 # Ex: Some thing\n
1311 # ==========\n
1312 $self->message_colour( 3, "Does scope have '{green}header line{/}' ? ", $scope->has( 'header' ) ? '{green}yes{/}' : '{red}no{/}' );
1313 if( $scope->has( 'header' ) )
1314 {
1315 $data =~ s{$RE{Markdown}{HeaderLine}}
1316 {
1317 my $re = { %+ };
1318 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1319 my $pos = pos( $data );
1320 $self->message_colour( 3, $self->whereami( \$data, $pos, { text => "Found a vanilla header line '{green}" . $re->{header_all} . "{/}' with text '{green}" . $re->{header_content} . "{/}' at pos '$pos' with capture: " . $self->dump( $re ), return => 1 } ) );
1321 my $text = $re->{header_content};
1322 my $raw = $re->{header_all};
1323 my $levels =
1324 {
1325 '=' => 1,
1326 '-' => 2,
1327 };
1328 my $header = $top->create_header({
1329 level => $levels->{ substr( $re->{header_type}, 0, 1 ) },
1330 parent => $top,
1331 pos => $pos,
1332 raw => $raw,
1333 });
1334 # Further process the text capture
1335 # If there are any elements, they will be placed inside the header element as children
1336 $self->parse( $text, { scope => $self->scope_inline, element => $header } );
1337 my $id = $self->document->add_object( $header );
1338 "${PH_PREFIX}${id}${PH_SUFFIX}\n";
1339 }xgems;
1340 }
1341  
1342 # NOTE: line
1343 # Horizontal lines
1344 # * * *
1345 #
1346 # ***
1347 #
1348 # *****
1349 #
1350 # - - -
1351 #
1352 # ---------------------------------------
1353 $self->message_colour( 3, "Does scope have '{green}line{/}' ? ", $scope->has( 'line' ) ? '{green}yes{/}' : '{red}no{/}' );
1354 if( $scope->has( 'line' ) )
1355 {
1356 $data =~ s{$RE{Markdown}{Line}}
1357 {
1358 my $re = { %+ };
1359 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1360 my $pos = pos( $data );
1361 $self->message_colour( 3, $self->whereami( \$data, $pos, { text => "Found new horizontal line at pos '$pos': '{green}" . $re->{line_all} . "'{/} with capture: " . $self->dump( $re ), return => 1 } ) );
1362 my $id = $self->document->add_object( $top->create_line({
1363 pos => $pos,
1364 raw => $re->{line_all},
1365 }) );
1366 "${PH_PREFIX}${id}${PH_SUFFIX}";
1367 }xgem;
1368 }
1369  
1370 # NOTE: paragraph
1371 $self->message_colour( 3, "Does scope have '{green}paragraph{/}' ? ", $scope->has( 'paragraph' ) ? '{green}yes{/}' : '{red}no{/}' );
1372 if( $scope->has( 'paragraph' ) )
1373 {
1374 $data =~ s{$RE{Markdown}{Paragraph}}
1375 {
1376 my $re = { %+ };
1377 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1378 my $pos = pos( $data );
1379 my $text = $re->{para_all};
1380 my $raw = $re->{para_all};
1381 my $nth_nl = $self->_total_trailing_new_lines( $text );
1382 my $post_nl_id;
1383 if( $nth_nl )
1384 {
1385 my $post_nl = $top->create_text({ text => "\n" x $nth_nl });
1386 $post_nl_id = $self->document->add_object( $post_nl );
1387 }
1388 $text =~ s/^\n+|\n+$//gs;
1389 # Replace new lines that are not preceded by 2 space or more with 1 space.
1390 $text =~ s/(?<![ ]{2})\n/ /gs;
1391 $self->message_colour( 3, "Found {green}${nth_nl}{/} trailing new line(s)." );
1392 my $p = $top->create_paragraph({
1393 pos => $pos,
1394 raw => $raw,
1395 });
1396 # Position ourself before the trailing new lines
1397 my $id = $self->document->add_object( $p );
1398 # $self->message_colour( 3, "Sub parsing paragraph content '{green}", quotemeta( $text ), "{/}'" );
1399 $self->parse( $text, { scope => $self->scope_inline, element => $p } );
1400 # We remove one new line to account for the new line added by as_markdown() method
1401 # $trailing_nl-- if( $trailing_nl > 1 );
1402 # "${PH_PREFIX}${id}${PH_SUFFIX}";
1403 "${PH_PREFIX}${id}${PH_SUFFIX}" . ( defined( $post_nl_id ) ? "${PH_PREFIX}${post_nl_id}${PH_SUFFIX}" : '' );
1404 }xgems;
1405 }
1406 # End of block elements parsing
1407
1408 # NOTE: link extended
1409 # Now the inline elements
1410 $self->message_colour( 3, "Does scope have '{green}link extended{/}' ? ", $scope->has( [qw( link extended )] ) ? '{green}yes{/}' : '{red}no{/}' );
1411 if( $scope->has( [qw( link extended )] ) )
1412 {
1413 $data =~ s{$RE{Markdown}{ExtLink}}
1414 {
1415 my $re = { %+ };
1416 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1417 my $pos = pos( $data );
1418 my $raw = $re->{link_all};
1419 my $id = $re->{link_id};
1420 my $name = $re->{link_name};
1421 my $title = $re->{link_title};
1422 my $url = $re->{link_url};
1423 my $def = $re->{link_attr};
1424 my $link = $top->create_link({
1425 pos => $pos,
1426 raw => $raw,
1427 });
1428 if( length( $def ) )
1429 {
1430 $def =~ s/^[[:blank:]\h]+|[[:blank:]\h]+$//gs;
1431 $link->add_attributes( $def ) if( length( $def ) );
1432 }
1433 my $object_id = $self->document->add_object( $link );
1434 ## An url has been provided, we sub-parse the link name for inline markdown, and especially abbreviations
1435 if( $url )
1436 {
1437 $link->url( $url );
1438 }
1439 ## as in [Example][] instead of [Example][site_id]
1440 else
1441 {
1442 $id = $name if( !length( $id ) );
1443 $link->link_id( $id );
1444 my $link_def = $self->document->get_link_by_id( $id );
1445 if( $link_def )
1446 {
1447 $title = $link_def->title->scalar;
1448 $url = $link_def->url;
1449 $link->copy_from( $link_def );
1450 }
1451 else
1452 {
1453 }
1454 $link->url( $url );
1455 }
1456 $link->title( $title );
1457 $self->parse( $name, { element => $link, scope => $self->scope_inline });
1458 "${PH_PREFIX}${object_id}${PH_SUFFIX}";
1459 }xgems;
1460 }
1461
1462 # NOTE: link
1463 $self->message_colour( 3, "Does scope have '{green}link{/}' ? ", $scope->has( [qw( link )] ) ? '{green}yes{/}' : '{red}no{/}' );
1464 if( $scope->has( 'link' ) )
1465 {
1466 $data =~ s{$RE{Markdown}{Link}}
1467 {
1468 my $re = { %+ };
1469 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1470 my $pos = pos( $data );
1471 my $raw = $re->{link_all};
1472 my $id = $re->{link_id};
1473 my $name = $re->{link_name};
1474 my $title = $re->{link_title};
1475 my $url = $re->{link_url};
1476 my $link = $top->create_link({
1477 pos => $pos,
1478 raw => $raw,
1479 });
1480 my $object_id = $self->document->add_object( $link );
1481 # An url has been provided, we sub-parse the link name for inline markdown, and especially abbreviations
1482 if( $url )
1483 {
1484 $link->url( $url );
1485 }
1486 # as in [Example][] instead of [Example][site_id]
1487 else
1488 {
1489 $id = $name if( !length( $id ) );
1490 $link->link_id( $id );
1491 my $link_def = $self->document->get_link_by_id( $id );
1492 if( $link_def )
1493 {
1494 $title = $link_def->title;
1495 $url = $link_def->url;
1496 $link->copy_from( $link_def );
1497 }
1498 else
1499 {
1500 }
1501 $link->url( $url );
1502 }
1503 $link->title( $title );
1504 $self->parse( $name, { element => $link, scope => $self->scope_inline });
1505 "${PH_PREFIX}${object_id}${PH_SUFFIX}";
1506 }xgems;
1507 }
1508  
1509 # NOTE: auto-link
1510 # Automatic link like <https://example.com> or <news://news.example.com> or <mailto://john@example.com> or <john@example.com>, etc...
1511 $self->message_colour( 3, "Does scope have '{green}auto-link{/}' ? ", $scope->has( [qw( link )] ) ? '{green}yes{/}' : '{red}no{/}' );
1512 if( $scope->has( 'link' ) )
1513 {
1514 $data =~ s{$RE{Markdown}{LinkAuto}}
1515 {
1516 my $re = { %+ };
1517 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1518 my $pos = pos( $data );
1519 my $raw = $re->{link_all};
1520 my $url = $re->{link_url};
1521 # Add the mailto: scheme if it's an e-mail address and the scheme is missing
1522 substr( $url, 0, 0 ) = 'mailto:' if( length( $re->{link_mailto} ) && substr( $re->{link_mailto}, 0, 7 ) ne 'mailto:' );
1523 my $link = $top->create_link({
1524 encrypt => $self->encrypt_email,
1525 # We save the original as URI may alter it by url-encoding characters
1526 original => $re->{link_url},
1527 pos => $pos,
1528 raw => $raw,
1529 url => $url,
1530 });
1531 # $link->add_element( $link->create_text({
1532 # pos => $pos,
1533 # text => $re->{link_url},
1534 # }) );
1535 my $id = $self->document->add_object( $link );
1536 "${PH_PREFIX}${id}${PH_SUFFIX}";
1537 }xgems;
1538 }
1539  
1540 # NOTE: image extended
1541 $self->message_colour( 3, "Does scope have '{green}image extended{/}' ? ", $scope->has( [qw( image extended )] ) ? '{green}yes{/}' : '{red}no{/}' );
1542 if( $scope->has( [qw( image extended )] ) )
1543 {
1544 $data =~ s{$RE{Markdown}{ExtImage}}
1545 {
1546 my $re = { %+ };
1547 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1548 my $pos = pos( $data );
1549 my $raw = $re->{img_all};
1550 my $url = $re->{img_url};
1551 my $id = $re->{img_id};
1552 my $alt = $re->{img_alt};
1553 my $attr = $re->{img_attr};
1554 my $title = $re->{img_title};
1555 my $img = $top->create_image({
1556 alt => $alt,
1557 pos => $pos,
1558 raw => $raw,
1559 });
1560 if( !$url )
1561 {
1562 $id = $alt if( !length( $id ) );
1563 my $img_def = $self->document->get_link_by_id( $id );
1564 if( $img_def )
1565 {
1566 $title = $img_def->title;
1567 $url = $img_def->url;
1568 $img->copy_from( $img_def );
1569 }
1570 }
1571 $img->url( $url );
1572 $img->title( $title );
1573 $img->link_id( $id ) if( length( $id ) );
1574 $img->add_attributes( $attr );
1575 my $object_id = $self->document->add_object( $img );
1576 "${PH_PREFIX}${object_id}${PH_SUFFIX}";
1577 }xgems;
1578 }
1579  
1580 # NOTE: image
1581 $self->message_colour( 3, "Does scope have '{green}image{/}' ? ", $scope->has( [qw( image )] ) ? '{green}yes{/}' : '{red}no{/}' );
1582 if( $scope->has( 'image' ) )
1583 {
1584 $data =~ s{$RE{Markdown}{Image}}
1585 {
1586 my $re = { %+ };
1587 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1588 my $pos = pos( $data );
1589 my $raw = $re->{img_all};
1590 my $url = $re->{img_url};
1591 my $id = $re->{img_id};
1592 my $alt = $re->{img_alt};
1593 my $title = $re->{img_title};
1594 my $img = $top->create_image({
1595 alt => $alt,
1596 pos => $pos,
1597 raw => $raw,
1598 });
1599 if( !$url )
1600 {
1601 $id = $alt if( !length( $id ) );
1602 my $img_def = $self->document->get_link_by_id( $id );
1603 if( $img_def )
1604 {
1605 $title = $img_def->title;
1606 $url = $img_def->url;
1607 $img->copy_from( $img_def );
1608 }
1609 }
1610 $img->url( $url );
1611 $img->title( $title );
1612 $img->link_id( $id ) if( length( $id ) );
1613 my $object_id = $self->document->add_object( $img );
1614 "${PH_PREFIX}${object_id}${PH_SUFFIX}";
1615 }xgems;
1616 }
1617  
1618 # NOTE: bold
1619 # Bold check comes before emphasis one
1620 $self->message_colour( 3, "Does scope have '{green}bold{/}' ? ", $scope->has( 'bold' ) ? '{green}yes{/}' : '{red}no{/}' );
1621 if( $scope->has( 'bold' ) )
1622 {
1623 $data =~ s{$RE{Markdown}{Bold}}
1624 {
1625 my $re = { %+ };
1626 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1627 my $pos = pos( $data );
1628 my $content = $re->{bold_text};
1629 my $bold = $top->create_bold({
1630 pos => pos( $data ),
1631 raw => $re->{bold_all},
1632 type => $re->{bold_type},
1633 });
1634 $self->parse( $content, { element => $bold, scope => $self->scope_inline });
1635 my $id = $self->document->add_object( $bold );
1636 "${PH_PREFIX}${id}${PH_SUFFIX}";
1637 }xgems;
1638 }
1639  
1640 # NOTE: emphasis
1641 $self->message_colour( 3, "Does scope have '{green}emphasis{/}' ? ", $scope->has( 'emphasis' ) ? '{green}yes{/}' : '{red}no{/}' );
1642 if( $scope->has( 'emphasis' ) )
1643 {
1644 $data =~ s{$RE{Markdown}{Em}}
1645 {
1646 my $re = { %+ };
1647 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1648 my $pos = pos( $data );
1649 my $em = $top->create_em({
1650 pos => $pos,
1651 raw => $re->{em_all},
1652 type => $re->{em_type},
1653 });
1654 my $content = $re->{em_text};
1655 $self->parse( $content, { element => $em, scope => $self->scope_inline });
1656 my $id = $self->document->add_object( $em );
1657 "${PH_PREFIX}${id}${PH_SUFFIX}";
1658 }gexms;
1659 }
1660
1661 # NOTE: code span
1662 # Inline code `some thing`
1663 $self->message_colour( 3, "Does scope have '{green}code span{/}' ? ", $scope->has( [qw( code_span )] ) ? '{green}yes{/}' : '{red}no{/}' );
1664 if( $scope->has( 'code_span' ) )
1665 {
1666 $data =~ s{$RE{Markdown}{CodeSpan}}
1667 {
1668 my $re = { %+ };
1669 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1670 my $pos = pos( $data );
1671 my $raw = $re->{code_all};
1672 my $content = $re->{code_content};
1673 $self->message_colour( 3, $self->whereami( \$data, $pos, { text => "Found an inline code '$raw' at pos '$pos' with content:\n'{green}" . $content . "{/}' and with capture: " . $self->dump( $re ), return => 1 } ) );
1674 ## leading whitespace
1675 $content =~ s/^[ \t]*//g;
1676 ## trailing whitespace
1677 $content =~ s/[ \t]*$//g;
1678 my $code = $top->create_code({
1679 inline => 1,
1680 pos => $pos,
1681 raw => $raw,
1682 });
1683 $code->add_element( $top->create_text({
1684 text => $content,
1685 pos => $pos,
1686 }) );
1687 my $id = $top->add_object( $code );
1688 "${PH_PREFIX}${id}${PH_SUFFIX}";
1689 }xgems;
1690 }
1691
1692 # NOTE: checkbox extended
1693 $self->message_colour( 3, "Does scope have '{green}checkbox{/}' ? ", $scope->has( [qw( checkbox extended )] ) ? '{green}yes{/}' : '{red}no{/}' );
1694 if( $scope->has( [qw( checkbox extended )] ) )
1695 {
1696 $data =~ s{$RE{Markdown}{ExtCheckbox}}
1697 {
1698 my $re = { %+ };
1699 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1700 my $pos = pos( $data );
1701 my $check = $top->create_checkbox({
1702 checked => lc( $re->{check_content} ) eq 'x',
1703 raw => $re->{check_all},
1704 pos => $pos,
1705 });
1706 my $id = $self->document->add_object( $check );
1707 "${PH_PREFIX}${id}${PH_SUFFIX}";
1708 }xgems;
1709 }
1710
1711 # NOTE: katex
1712 $self->message_colour( 3, "Does scope have '{green}katex{/}' ? ", ( $scope->has( [qw( katex extended )] ) ? '{green}yes{/}' : '{red}no{/}' ) );
1713 if( length( $katex_re ) && $scope->has( [qw( katex extended )] ) )
1714 {
1715 $data =~ s{$katex_re}
1716 {
1717 my $re = { %+ };
1718 my $raw = $re->{katex_all};
1719 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1720 my $pos = pos( $data );
1721 ## There is at least one new line, so this is a block, we use paragraph
1722 my $id;
1723 if( index( $raw, "\n" ) != -1 )
1724 {
1725 my $p = $top->create_paragraph({
1726 pos => $pos,
1727 raw => $raw,
1728 });
1729 $p->add_element( $p->create_text({
1730 pos => $pos,
1731 text => $re->{katex_all},
1732 }) );
1733 $id = $self->document->add_object( $p );
1734 }
1735 ## Inline style
1736 else
1737 {
1738 $id = $self->document->add_object( $top->create_text({
1739 pos => $pos,
1740 text => $re->{katex_all},
1741 }) );
1742 }
1743 $self->document->setup_katex;
1744 "${PH_PREFIX}${id}${PH_SUFFIX}";
1745 }xgems;
1746 }
1747
1748 # NOTE: strikethrough
1749 $self->message_colour( 3, "Does scope have '{green}strikethrough{/}' ? ", $scope->has( [qw( strikethrough extended )] ) ? '{green}yes{/}' : '{red}no{/}' );
1750 if( $scope->has( [qw( strikethrough extended )] ) )
1751 {
1752 $data =~ s{$RE{Markdown}{ExtStrikeThrough}}
1753 {
1754 my $re = { %+ };
1755 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1756 my $pos = pos( $data );
1757 my $text = $re->{strike_content};
1758 my $strike = $top->create_strikethrough({
1759 raw => $re->{strike_all},
1760 pos => $pos,
1761 });
1762 $strike->add_element( $strike->create_text({
1763 pos => $pos,
1764 text => $text,
1765 }) );
1766 my $id = $self->document->add_object( $strike );
1767 "${PH_PREFIX}${id}${PH_SUFFIX}";
1768 }xgems;
1769 }
1770
1771 # NOTE: insertion
1772 $self->message_colour( 3, "Does scope have '{green}insertion{/}' ? ", $scope->has( [qw( insertion extended )] ) ? '{green}yes{/}' : '{red}no{/}' );
1773 if( $scope->has( [qw( insertion extended )] ) )
1774 {
1775 $data =~ s{$RE{Markdown}{ExtInsertion}}
1776 {
1777 my $re = { %+ };
1778 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1779 my $pos = pos( $data );
1780 my $text = $re->{ins_content};
1781 my $ins = $top->create_insertion({
1782 raw => $re->{ins_all},
1783 pos => $pos,
1784 });
1785 $ins->add_element( $ins->create_text({
1786 pos => $pos,
1787 text => $text,
1788 }) );
1789 my $id = $self->document->add_element( $ins );
1790 "${PH_PREFIX}${id}${PH_SUFFIX}";
1791 }xgems;
1792 }
1793
1794 # NOTE: subscript
1795 $self->message_colour( 3, "Does scope have '{green}subscript{/}' ? ", $scope->has( [qw( subscript extended )] ) ? '{green}yes{/}' : '{red}no{/}' );
1796 if( $scope->has( [qw( subscript extended )] ) )
1797 {
1798 $data =~ s{$RE{Markdown}{ExtSubscript}}
1799 {
1800 my $re = { %+ };
1801 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1802 my $pos = pos( $data );
1803 my $text = $re->{sub_text};
1804 my $sub = $top->create_subscript({
1805 raw => $re->{sub_all},
1806 pos => $pos,
1807 });
1808 $sub->add_element( $sub->create_text({
1809 pos => $pos,
1810 text => $text,
1811 }) );
1812 my $id = $self->document->add_object( $sub );
1813 "${PH_PREFIX}${id}${PH_SUFFIX}";
1814 }xgems;
1815 }
1816
1817 # NOTE: superscript
1818 $self->message_colour( 3, "Does scope have '{green}superscript{/}' ? ", $scope->has( [qw( superscript extended )] ) ? '{green}yes{/}' : '{red}no{/}' );
1819 if( $scope->has( [qw( superscript extended )] ) )
1820 {
1821 $data =~ s{$RE{Markdown}{ExtSuperscript}}
1822 {
1823 my $re = { %+ };
1824 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1825 my $pos = pos( $data );
1826 my $text = $re->{sup_text};
1827 my $sup = $top->create_superscript({
1828 raw => $re->{sup_all},
1829 pos => $pos,
1830 });
1831 $sup->add_element( $sup->create_text({
1832 pos => $pos,
1833 text => $text,
1834 }) );
1835 my $id = $self->document->add_object( $sup );
1836 "${PH_PREFIX}${id}${PH_SUFFIX}";
1837 }xgems;
1838 }
1839
1840 # $self->message_colour( 3, "Does scope have '{green}line break extended{/}' ? ", $scope->has( [qw( line_break extended )] ) ? '{green}yes{/}' : '{red}no{/}' );
1841 # if( $scope->has( [qw( line_break extended )] ) )
1842 # {
1843 # $data =~ s{$RE{Markdown}{ExtLineBreak}}
1844 # {
1845 # my $re = { %+ };
1846 # # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1847 # my $pos = pos( $data );
1848 # $self->message_colour( 3, $self->whereami( \$data, $pos, { text => "Found an extended {green}line break{/} (end of line possibly prepended by 2 or more spaces) at pos '" . $pos . "' with capture: " . $self->dump( $re ), return => 1 } ) );
1849 # my $id = $self->document->add_object( $top->create_new_line({
1850 # break => 1,
1851 # pos => $pos,
1852 # }) );
1853 # "${PH_PREFIX}${id}${PH_SUFFIX}";
1854 # }xgems;
1855 # }
1856  
1857 # NOTE: line break
1858 $self->message_colour( 3, "Does scope have '{green}line break{/}' ? ", $scope->has( [qw( line_break )] ) ? '{green}yes{/}' : '{red}no{/}' );
1859 if( $scope->has( 'line_break' ) )
1860 {
1861 $data =~ s{$RE{Markdown}{LineBreak}}
1862 {
1863 my $re = { %+ };
1864 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1865 my $pos = pos( $data );
1866 $self->message_colour( 3, $self->whereami( \$data, $pos, { text => "Found a {green}line break{/} (end of line prepended by 2 or more spaces) at pos '" . $pos . "' with capture: " . $self->dump( $re ), return => 1 } ) );
1867 my $id = $self->document->add_object( $top->create_new_line({
1868 break => 1,
1869 pos => $pos,
1870 }) );
1871 "${PH_PREFIX}${id}${PH_SUFFIX}";
1872 }xgems;
1873 }
1874  
1875 # NOTE: footnote backreference
1876 # This is a placeholder added at the end of the footnote text where we will insert a back reference link
1877 $data =~ s{(?<fn_backref>[ ]+\!{2}FN\!{2})}
1878 {
1879 my $re = { %+ };
1880 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1881 my $pos = pos( $data );
1882 my $id = $self->document->add_object( $top->create_text({
1883 pos => $pos,
1884 text => $re->{fn_backref},
1885 }) );
1886 "${PH_PREFIX}${id}${PH_SUFFIX}";
1887 }xgems;
1888  
1889 # NOTE: abbreviation
1890 $self->message_colour( 3, "Does scope have '{green}abbr{/}' ? ", $scope->has( [qw( extended abbr )] ) ? '{green}yes{/}' : '{red}no{/}' );
1891 # Now find and replace any match with its corresponding expanded name
1892 if( length( $abbr_re ) && $scope->has( [qw( extended abbr )] ) )
1893 {
1894 $data =~ s{\b(?<abbr_name>$abbr_re)\b}
1895 {
1896 my $re = { %+ };
1897 # my $pos = pos( $data ) - length( substr( $data, $-[0], $+[0] - $-[0] ) );
1898 my $pos = pos( $data );
1899 ## We save what we caught to put it back in case the abbreviation lookup failed
1900 my $catch = substr( $data, $-[0], $+[0] - $-[0] );
1901 if( defined( my $abbr = $self->document->get_abbreviation( $re->{abbr_name} ) ) )
1902 {
1903 my $id = $self->document->add_object( $abbr->clone );
1904 "${PH_PREFIX}${id}${PH_SUFFIX}";
1905 }
1906 # Failed somehow
1907 else
1908 {
1909 "$catch";
1910 }
1911 }xge;
1912 }
1913  
1914 $self->message_colour( 3, "{orange}", ( $top->tag_name eq 'top' ? 'Parsing' : 'Sub-parsing' ), " done.{/}" );
1915  
1916 if( $top->tag_name eq 'top' )
1917 {
1918 # We need to separate parsing of footnotes' text in a second step, so we do this here
1919 $top->footnotes->foreach(sub
1920 {
1921 $_->parse( $self );
1922 });
1923 }
1924  
1925 # NOTE: ultra fast parsing
1926 my $object_re = qr/\Q${PH_PREFIX}\E(?<object_id>\d+)\Q${PH_SUFFIX}\E/;
1927 my $parts = [ split( m/${object_re}\n?/, $data ) ];
1928 $self->message( 3, "Parts are: '", join( "', '", @$parts ), "'." );
1929 my $objects = $self->document->objects;
1930 for( my $n = 0; $n < scalar( @$parts ); $n++ )
1931 {
1932 # When $n is an even number, it means this is a text, otherwise it is an object id
1933 # If this is a text, we create a text object and add it to the tree
1934 if( $n % 2 )
1935 {
1936 my $id = $parts->[ $n ];
1937 next if( !length( $id ) );
1938 my $obj = $objects->get( $id );
1939 if( ref( $obj ) )
1940 {
1941 $cb->( $obj );
1942 $top->add_element( $obj );
1943 }
1944 else
1945 {
1946 $self->message_colour( 3, "{bold red}No object found for id \"", $id, "\"!{/}" );
1947 }
1948 }
1949 else
1950 {
1951 my $obj = $top->create_text({
1952 text => $parts->[ $n ],
1953 });
1954 $cb->( $obj );
1955 $top->add_element( $obj );
1956 }
1957 }
1958  
1959 # Depth-first expansion, repeat until no changes (handles cascades)
1960 my $changed = 1;
1961  
1962 my $walk;
1963 $walk = sub
1964 {
1965 my( $node ) = @_;
1966  
1967 # Recurse into container children first (depth-first)
1968 if( $node->can( 'children' ) && $node->children->length )
1969 {
1970 # Children list may mutate while we insert; iterate by index
1971 my $i = 0;
1972 while( $i < $node->children->length )
1973 {
1974 my $child = $node->children->get( $i );
1975 $walk->( $child );
1976 # If structure changed, do not increment blindly
1977 $i++;
1978 }
1979 }
1980  
1981 # Only interested in Text nodes that might contain placeholders
1982 return if( !$node->isa( 'Markdown::Parser::Text' ) );
1983  
1984 my $txt = $node->text->scalar // '';
1985 return if( $txt !~ /$object_re/ );
1986  
1987 # Split into text / id / text / id / ... / text
1988 my @parts = split( /$object_re/, $txt );
1989  
1990 # First piece stays in current node
1991 my $head = shift( @parts );
1992 $node->text( $head );
1993  
1994 my $cursor = $node;
1995 while( @parts )
1996 {
1997 my $id = shift( @parts );
1998 # may be undef at end
1999 my $after = shift( @parts );
2000  
2001 my $obj = $self->document->objects->get( $id );
2002  
2003 if( $obj )
2004 {
2005 # Splice the referenced object right after the cursor
2006 $node->parent->insert_after( $cursor, $obj );
2007 $cursor = $obj;
2008 $changed = 1;
2009 }
2010 else
2011 {
2012 # Unknown id: keep literal placeholder (safer than dropping)
2013 my $lit = $node->parent->create_text({ text => "${PH_PREFIX}${id}${PH_SUFFIX}" });
2014 $node->parent->insert_after( $cursor, $lit );
2015 $cursor = $lit;
2016 }
2017  
2018 if( defined( $after ) && length( $after ) )
2019 {
2020 my $tail = $node->parent->create_text({ text => $after });
2021 $node->parent->insert_after( $cursor, $tail );
2022 $cursor = $tail;
2023 # will be caught next pass
2024 $changed = 1 if( $after =~ /$object_re/ );
2025 }
2026 }
2027 };
2028  
2029 while( $changed )
2030 {
2031 $changed = 0;
2032 $walk->( $top );
2033 }
2034 return( $top );
2035 }
2036  
2037 sub parse_file
2038 {
2039 my $self = shift( @_ );
2040 my $file = shift( @_ ) || return( $self->error( "No file to parse was provided." ) );
2041 return( $self->error( "Markdown file provided \"$file\" does not exist." ) ) if( !-e( $file ) );
2042 return( $self->error( "Markdown file provided \"$file\" is actually a directory." ) ) if( -d( $file ) );
2043 return( $self->error( "Markdown file provided \"$file\" is empty." ) ) if( -z( $file ) );
2044 return( $self->error( "Markdown file provided \"$file\" does not have read permission." ) ) if( !-r( $file ) );
2045 my $io = IO::File->new( "<$file" ) || return( $self->error( "Unable to open markdown file \"$file\": $!" ) );
2046 my $charset = $self->charset;
2047 $io->binmode( ":encode(${charset})" ) if( length( $charset ) );
2048 my $data = join( '', $io->getlines );
2049 $io->close;
2050 return( $self->parse( $data, @_ ) );
2051 }
2052  
2053 sub parse_list_item
2054 {
2055 my $self = shift( @_ );
2056 my $text = shift( @_ ) || '';
2057 my $opts = {};
2058 $opts = shift( @_ ) if( $self->_is_hash( $opts ) );
2059 my $top = $opts->{doc} || do
2060 {
2061 warn( "No element object provided as a container.\n" );
2062 return( $self->error( "No element object provided as a container." ) );
2063 };
2064 $opts->{pos} = int( $opts->{pos} );
2065 $self->message_colour( 3, "Parsing list item '{bold green}", $text, "{/}' with options: ", sub{ $self->dump( $opts, {
2066 filter => sub
2067 {
2068 my( $ctx, $ref ) = @_;
2069 if( $ctx->class eq 'Markdown::Parser::Document' )
2070 {
2071 return({ dump => overload::StrVal( $ref ) });
2072 }
2073 elsif( $ctx->is_blessed && $ref->isa( 'Markdown::Parser::Element' ) )
2074 {
2075 return({ dump => overload::StrVal( $ref ) });
2076 }
2077 }
2078 }) } );
2079 # If more than 1 trailing new lines, our caller should hae dealt with it be putting back any excess of 1, because those are the preceding new lines for the next element and it is important for parsing.
2080 $text =~ s/\n{2,}\z/\n/;
2081 # my @post_nl = ();
2082 # $text =~ s{(\n{2,})\z}
2083 # {
2084 # my $n = length( $1 );
2085 # $n--;
2086 # $self->message_colour( 4, "Adding {green}${n}{/} new lines at end of list." );
2087 # if( $n > 0 )
2088 # {
2089 # for( my $i = 0; $i < $n; $i++ )
2090 # {
2091 # my $nl = $top->create_new_line({ break => 1 });
2092 # push( @post_nl, $nl );
2093 # }
2094 # }
2095 # "\n";
2096 # }xgems;
2097 $self->list_level++;
2098 $text =~ s{$RE{Markdown}{ListItem}}
2099 {
2100 my $re = { %+ };
2101 my $item = $re->{li_content};
2102 my $leading_line = $re->{li_lead_line};
2103 my $leading_space = $re->{li_lead_space};
2104 my $list_type = $re->{list_type_any};
2105 my $list_line = $re->{li_all};
2106
2107 my $indent = $leading_space;
2108 $indent =~ s/\t/ /gs;
2109 # int() because length on undef produces undef
2110 my $total_spaces = int( length( $indent ) );
2111 my $indent_level = POSIX::ceil( $total_spaces / 4 );
2112 $self->message_colour( 3, "Found a list item of type '{green}", $list_type, "{/}' with indent level '{green}", $indent_level, "{/}' (total spaces found = '", $total_spaces, "') and list item line '{green}", $re->{list_line}, "{/}' list item '{green}", $item, "{/}'. List indentation is '", $indent, "'" );
2113
2114 my $li = $top->create_list_item({
2115 indent => ( $indent_level + 1 ),
2116 pos => $opts->{pos} + pos( $text ),
2117 raw => $list_line,
2118 type => $list_type,
2119 # Alternatively
2120 # order => 1, # or 0
2121 });
2122 $top->add_element( $li );
2123  
2124 if( $leading_line || ( $item =~ m/\n{2,}/) )
2125 {
2126 $item =~ s/^(\t|[ ]{1,4})//gm;
2127 $self->message_colour( 3, "{white on blue}Processing list content: '$item'{/} with list level '", $self->list_level, "'" );
2128 $self->parse( $item, { scope => $self->scope_block, element => $li } );
2129 }
2130 else
2131 {
2132 # Recursion for sub-lists:
2133 $item =~ s/^(\t|[ ]{1,4})//gm;
2134 $self->message_colour( 3, "{white on orange}Processing sub list with content: '$item'{/} with list level '", $self->list_level, "'" );
2135 $self->parse( $item, { scope => [qw( extended list||inline )], element => $li } );
2136 }
2137 }xgems;
2138 # for( @post_nl )
2139 # {
2140 # $top->add_element( $_ );
2141 # }
2142 $self->list_level++;
2143 return( $self );
2144 }
2145  
2146 sub parse_table
2147 {
2148 my $self = shift( @_ );
2149 # Hash reference of capture groups: %-
2150 # See perlvar for more information
2151 my $re = shift( @_ );
2152 my $opts = {};
2153 $opts = shift( @_ ) if( $self->_is_hash( $opts ) );
2154 my $top = $opts->{doc} || do
2155 {
2156 warn( "No element object provided as a container.\n" );
2157 return( $self->error( "No element object provided as a container." ) );
2158 };
2159 my $tbl = $top->create_table(
2160 use_css_grid => $self->css_grid,
2161 ## shared css object
2162 css => $self->css,
2163 );
2164 $self->document->add_object( $tbl );
2165 my $info =
2166 {
2167 cols => {},
2168 rows => {},
2169 };
2170 my $seps = $self->new_array;
2171 my $headers = [split( /\n/, $re->{table_headers}->[0] )];
2172 for my $i ( 0..$#$headers )
2173 {
2174 ## This is a separator, store our data to the array $headers
2175 if( $headers->[$i] =~ /^[\|\-\+\: ]+$/ )
2176 {
2177 splice( @$headers, $i, 1 );
2178 $i--;
2179 }
2180 }
2181 # We check for leading space (up to 3), otherwise this would be code
2182 # and we use this leading space when parsing rows to factor in leading empty cells, i.e.
2183 # -------
2184 # | # <- this is an empty cell, but
2185 # ----
2186 # | A | # <- the space before the leading pipe is not
2187 my $leading_space = 0;
2188 # Check the space at the beginning of separator line as reference
2189 if( $re->{table_header_sep}->[0] =~ /^([[:blank:]\h]+)/ )
2190 {
2191 $leading_space = length( $leading_space );
2192 }
2193
2194 # Process the separator(s) in the header to find
2195 for my $i ( 0..1 )
2196 {
2197 $seps->push( $re->{table_header_sep}->[$i] ) if( length( $re->{table_header_sep}->[$i] ) );
2198 }
2199 my $cell_align = $self->new_array;
2200 $seps->for(sub
2201 {
2202 my( $n, $s ) = @_;
2203 $s =~ s/^[\+\|\-][[:blank:]\h]+|[[:blank:]\h]+[\+\|\-]$//g;
2204 return if( index( $s, ':' ) == -1 );
2205 my $cells = $self->new_array( [split( /[\+\|]/, $s )] );
2206 $cells->for(sub
2207 {
2208 my( $i, $c ) = @_;
2209 $c =~ s/^[[:blank:]\h\v]+|[[:blank:]\h\v]+$//g;
2210 return if( !length( $c ) );
2211 my( $left, $right );
2212 $left = 1 if( substr( $c, 0, 1 ) eq ':' );
2213 $right = 1 if( substr( $c, -1, 1 ) eq ':' );
2214 ## First row, so we just assign the value
2215 if( $n == 0 )
2216 {
2217 $cell_align->push({ left => $left, right => $right });
2218 }
2219 else
2220 {
2221 my $prev = $cell_align->index( $i );
2222 if( !defined( $prev ) )
2223 {
2224 $cell_align->[ $i ] = { left => $left, right => $right };
2225 }
2226 }
2227 });
2228 });
2229
2230 my $caption;
2231 if( $re->{table_caption}->[0] || $re->{table_caption}->[1] )
2232 {
2233 $caption = $re->{table_caption}->[0] // $re->{table_caption}->[1];
2234 $caption =~ s/^[[:blank:]\h]*\[|\][[:blank:]\h\v]*$//gs;
2235 if( length( $caption ) )
2236 {
2237 my $cap = $tbl->create_table_caption;
2238 $self->parse( $caption, { element => $cap, scope => 'inline' });
2239 # $cap->add_element( $cap->create_text({ text => $caption }) );
2240 $tbl->caption( $cap );
2241 $cap->position( $re->{table_caption_bottom}->[0] ? 'bottom' : 'top' );
2242 }
2243 }
2244
2245 ## Getting an array ref of array ref containing row objects
2246 my $hdrs_rows = $self->parse_table_row( $headers, { doc => $top, alignment => $cell_align, leading_space => $leading_space });
2247 my $header = $top->create_table_header;
2248 ## Possibly multiple rows in the header, but only one table header
2249 foreach my $rows ( @$hdrs_rows )
2250 {
2251 $header->children->push( @$rows );
2252 }
2253 $tbl->header( $header );
2254
2255 my $body_rows = $self->parse_table_row( $re->{table_rows}->[0], { doc => $top, alignment => $cell_align });
2256 ## Possibly multiple table body
2257 foreach my $rows ( @$body_rows )
2258 {
2259 my $body = $top->create_table_body;
2260 $body->children->push( @$rows );
2261 $tbl->add_body( $body ) || return( $self->error( "Could not add body: ", $tbl->error ) );
2262 }
2263
2264 foreach my $this ( $hdrs_rows, $body_rows )
2265 {
2266 for my $i ( 0..$#$this )
2267 {
2268 $info->{rows}->{total} += scalar( @{$this->[$i]} );
2269 }
2270 }
2271 $info->{cols}->{total} = scalar( keys( %{$info->{cols}} ) );
2272 $tbl->stat( $info );
2273 return( $tbl );
2274 }
2275  
2276 sub parse_table_row
2277 {
2278 my $self = shift( @_ );
2279 my $str = shift( @_ );
2280 my $opts = {};
2281 $opts = shift( @_ ) if( $self->_is_hash( $opts ) );
2282 my $top = $opts->{doc} || do
2283 {
2284 warn( "No element object provided as a container.\n" );
2285 return( $self->error( "No element object provided as a container." ) );
2286 };
2287 ## Leading space in length
2288 my $lead_space = int( $opts->{leading_space} );
2289 ## my $cols = [];
2290 my $body = [];
2291 my $rows = [];
2292 my $info =
2293 {
2294 cols => {},
2295 rows => {},
2296 };
2297 # A Module::Generic::Array object containing hash references with left and right keys
2298 my $al = $opts->{alignment};
2299 # Removing trailing new lines
2300 $str =~ s/\n+$//gs;
2301 my $row_n = 0;
2302 my $lines = ref( $str ) eq 'ARRAY' ? $str : [split( /\n/, $str )];
2303 foreach my $l ( @$lines )
2304 {
2305 ## Get rid of leading (up to 3) and trailing spaces
2306 ## If there are remaining leading space to the pipe, we use it to determine this is an empty cell
2307 $l =~ s/^[[:blank:]\h]{$lead_space}|[[:blank:]\h]+$//gs;
2308 if( $l =~ /^[[:blank:]\h]*$/ )
2309 {
2310 push( @$body, $rows );
2311 $rows = [];
2312 next;
2313 }
2314
2315 my $row = $top->create_table_row;
2316 # Make sure there is a leading and trailing | to standardise our parsing
2317 substr( $l, 0, 0 ) = '|' if( $l !~ /^[\|\:]/ );
2318 $l .= '|' if( $l !~ /[\|\:]$/ );
2319 my $is_prev_row = substr( $l, 0, 1 ) eq ':' ? 1 : 0;
2320 # Skip the leading pipe
2321 $l = substr( $l, 1 );
2322 my $col_n = 0;
2323 while( $l =~ s/^(?<col_content>[^\|\:]+)(?<sep>[\|\:]+)// )
2324 {
2325 my $re = { %+ };
2326 my $cell = $top->create_table_cell;
2327 # print( "Regexp: ", dump( $re ), "\n" );
2328 $is_prev_row = 1 if( substr( $re->{sep}, 0, 1 ) eq ':' );
2329 my $content = $re->{col_content};
2330 # If we do not have information about this column and this is not a colspan
2331 # then, store the column width
2332 if( !length( $info->{cols}->{ $col_n + 1 } ) &&
2333 length( $re->{sep} ) == 1 )
2334 {
2335 $info->{cols}->{ $col_n + 1 } = length( $content );
2336 }
2337 # In the cell width we include the additional pipes on the right, if any, that represent spawned columns
2338 $cell->width( length( $content ) + ( length( $re->{sep} ) > 1 ? ( length( $re->{sep} ) - 1 ) : 0 ) );
2339 $cell->colspan( length( $re->{sep} ) );
2340 $content =~ s/^([[:blank:]\h]*)(.*?)([[:blank:]\h]*)$/$2/gs;
2341 my $left = $+[1];
2342 my $right = $+[3] - $-[3];
2343 ## $cell->add_element( $cell->create_text( $content ) );
2344 $self->parse( $content, { element => $cell });
2345 my $al_def = $al->[ $col_n ];
2346 ## Alignment was provided for this table using ":"
2347 if( $self->_is_hash( $al_def ) &&
2348 ( length( $al_def->{left} ) || length( $al_def->{right} ) ) )
2349 {
2350 if( $al_def->{left} && $al_def->{right} )
2351 {
2352 $cell->align( 'center' );
2353 }
2354 elsif( $al_def->{left} )
2355 {
2356 $cell->align( 'left' );
2357 }
2358 elsif( $al_def->{right} )
2359 {
2360 $cell->align( 'right' );
2361 }
2362 }
2363 elsif( $left <= 1 )
2364 {
2365 $cell->align( 'left' );
2366 }
2367 elsif( $right <= 1 )
2368 {
2369 $cell->align( 'right' );
2370 }
2371 elsif( $left == $right ||
2372 ( $left && $right &&
2373 ( int( ( $left + $right ) / 2 ) == $left || int( ( $left + $right ) / 2 ) == $right )
2374 ) ||
2375 ( $left >= 2 && $right >= 2 )
2376 )
2377 {
2378 $cell->align( 'center' );
2379 }
2380 if( $is_prev_row )
2381 {
2382 if( length( $content ) )
2383 {
2384 ## Check for the cell above
2385 my $prev_cell = $rows->[-1]->children->get( $col_n );
2386 if( $prev_cell )
2387 {
2388 $prev_cell->add_element( $cell->create_text({ text => $content }) );
2389 # $prev_cell->children->push( $cell->create_text( $content ) );
2390 }
2391 else
2392 {
2393 warn( "This cell $col_n at row $row_n is marked as continuity, but there is no record of previous upper cell.\n" );
2394 }
2395 }
2396 ## Empty cell and this row is a continuity from the previous row, so we skip
2397 else
2398 {
2399 next;
2400 }
2401 }
2402 else
2403 {
2404 # push( @$cols, $cell );
2405 $row->add_element( $cell );
2406 }
2407 $col_n++;
2408 }
2409
2410 unless( $is_prev_row )
2411 {
2412 $row_n++;
2413 push( @$rows, $row );
2414 }
2415 }
2416 push( @$body, $rows ) if( scalar( @$rows ) );
2417 ## Return body of rows set, which is an array of array reference containing row objects.
2418 return( $body );
2419 }
2420  
2421 sub scope { return( shift->_set_get_object( 'scope', 'Markdown::Parser::Scope', @_ ) ); }
2422  
2423 sub scope_block
2424 {
2425 my $self = shift( @_ );
2426 my $opts = {};
2427 if( scalar( @_ ) && $self->_is_array( $_[0] ) )
2428 {
2429 $opts = $self->new_array( shift( @_ ) )->as_hash({ start_from => 1 });
2430 }
2431 else
2432 {
2433 $opts = $self->new_hash;
2434 }
2435 my $res = $self->new_array( [qw( block )] );
2436 if( !$opts->exists( '-extended' ) && $self->scope->has( 'extended' ) )
2437 {
2438 $res->push( 'extended' );
2439 }
2440 elsif( $opts->exists( '+extended' ) )
2441 {
2442 $res->push( 'extended' );
2443 }
2444 return( $res );
2445 }
2446  
2447 sub scope_inline
2448 {
2449 my $self = shift( @_ );
2450 my $opts = {};
2451 if( scalar( @_ ) && $self->_is_array( $_[0] ) )
2452 {
2453 $opts = $self->new_array( shift( @_ ) )->as_hash({ start_from => 1 });
2454 }
2455 else
2456 {
2457 $opts = $self->new_hash;
2458 }
2459 my $res = $self->new_array( [qw( inline )] );
2460 if( !$opts->exists( '-extended' ) && $self->scope->has( 'extended' ) )
2461 {
2462 $res->push( 'extended' );
2463 }
2464 elsif( $opts->exists( '+extended' ) )
2465 {
2466 $res->push( 'extended' );
2467 }
2468 return( $res );
2469 }
2470  
2471 # Used for debugging
2472 sub whereami
2473 {
2474 my $self = shift( @_ );
2475 my( $ref, $pos, $opts ) = @_;
2476 return if( $self->debug < 4 );
2477 my $text = $opts->{text} || "Cusrsor is now here at position '$pos':";
2478 ## How far back should we look?
2479 my $lookback = 10;
2480 $lookback = $pos if( $pos < $lookback );
2481 my $lookahed = 20;
2482 my $start = $pos - $lookback;
2483 my $first_line = substr( $$ref, $start, $lookback + $lookahed );
2484 $lookback += () = substr( $$ref, $start, $lookback ) =~ /\n/gs;
2485 $first_line =~ s/\n/\\n/gs;
2486 my $sec_line = ( '.' x $lookback ) . '^' . ( '.' x $lookahed );
2487 return( "$text\n$first_line\n$sec_line" ) if( $opts->{return} );
2488 $self->message_colour( 3, "$text\n$first_line\n$sec_line" );
2489 }
2490  
2491 sub _total_trailing_new_lines
2492 {
2493 my $self = shift( @_ );
2494 my $text = shift( @_ );
2495 my $trailing_nl = ( $text =~ /(\n+)$/ )[0];
2496 return( defined( $trailing_nl ) ? length( $trailing_nl ) : 0 );
2497 }
2498  
2499 # NOTE: Markdown::Parser::Scope package
2500 package Markdown::Parser::Scope;
2501 BEGIN
2502 {
2503 use strict;
2504 use warnings;
2505 use parent qw( Module::Generic );
2506 use vars qw( $ELEMENTS_DICTIONARY $ELEMENTS_DICTIONARY_EXTENDED $VERSION );
2507 our $VERSION = 'v0.1.0';
2508 our $ELEMENTS_DICTIONARY = $Markdown::Parser::ELEMENTS_DICTIONARY;
2509 our $ELEMENTS_DICTIONARY_EXTENDED = $Markdown::Parser::ELEMENTS_DICTIONARY_EXTENDED;
2510 };
2511  
2512 use strict;
2513 use warnings;
2514  
2515 sub init
2516 {
2517 my $self = shift( @_ );
2518 my $scope = shift( @_ );
2519 $self->{cache} = {};
2520 $self->{condition} = 'any';
2521 $self->{extended} = 0;
2522 $self->{scope} = {};
2523 $self->{_init_strict_use_sub} = 1;
2524 $self->SUPER::init( @_ );
2525 if( $self->_is_array( $scope ) )
2526 {
2527 $self->{scope} = $self->_to_array_object( $scope )->as_hash;
2528 }
2529 return( $self );
2530 }
2531  
2532 sub all { return( shift->_set_get_prop( 'all', @_ ) ); }
2533  
2534 sub as_string { return( shift->scope->as_string ); }
2535  
2536 sub cache { return( shift->_set_get_hash_as_mix_object( 'cache', @_ ) ); }
2537  
2538 sub condition { return( shift->_set_get_scalar_as_object( 'condition', @_ ) ); }
2539  
2540 sub extended { return( shift->_set_get_prop( 'extended', @_ ) ); }
2541  
2542 sub extended_only { return( shift->_set_get_prop( 'extended_only', @_ ) ); }
2543  
2544 sub has
2545 {
2546 my $self = shift( @_ );
2547 my $check = shift( @_ ) || return;
2548 # We clone the object, because we might modify it for the purpose of our checks
2549 my $scope = $self->scope->clone;
2550 my $what = $self->new_array( $self->_is_array( $check ) ? $check : [ $check ] );
2551 my $cache = $self->cache;
2552 my $scope_cond = $self->condition || 'any';
2553 my $term_cond = 'all';
2554 my $new = $self->new_array;
2555 # Go through the required tokens
2556 $what->foreach(sub
2557 {
2558 if( s/\|{1,2}/ /g )
2559 {
2560 $new->push( split( /\s+/, $_ ) );
2561 $term_cond = 'any';
2562 }
2563 if( s/\+{1,2}/ /g )
2564 {
2565 $new->push( split( /\s+/, $_ ) );
2566 $term_cond = 'all';
2567 }
2568 else
2569 {
2570 $new->push( $_ );
2571 }
2572 });
2573 my $cache_key = join( ':', $scope_cond, $term_cond, $what->join( '|' )->scalar );
2574 return( $cache->{ $cache_key } ) if( exists( $cache->{ $cache_key } ) );
2575 $new->for(sub
2576 {
2577 my( $i, $val ) = @_;
2578 if( substr( $val, 0, 4 ) eq 'ext_' )
2579 {
2580 $new->splice( $i, 1, substr( $val, 4 ) );
2581 $new->push( 'extended' ) unless( $new->has( 'extended' ) );
2582 }
2583 });
2584 $what = $new;
2585 # Expected positive hits should be equal to the number of array elements for the scope terms being checked
2586 # Ex: [qw( header extended )] requires 2 hits, but
2587 # [qw( header||extended )] requires just 1 hit
2588 my $expect = $what->length;
2589 my $hits = 0;
2590 my $is_ext = $scope->has( 'extended' );
2591  
2592 my $dict;
2593 if( $is_ext )
2594 {
2595 $dict = $ELEMENTS_DICTIONARY_EXTENDED;
2596 # We remove it so it does not interfere. It is ok, since $scope here is a clone.
2597 $scope->delete( 'extended' );
2598 }
2599 else
2600 {
2601 $dict = $ELEMENTS_DICTIONARY;
2602 }
2603  
2604 $scope->foreach(sub
2605 {
2606 my $scope_key = shift( @_ );
2607 $what->foreach(sub
2608 {
2609 my $scope_check = shift( @_ );
2610 # If the scope is explicitly included; or
2611 # if the scope is all, but excluding extended features and the query item is not an extended feature; or
2612 # if the scope is extended ONLY and the query item is an extended feature; or
2613 # if the scope is extended and it does not matter what the query item is
2614  
2615 if( $scope_key eq $scope_check ||
2616 (
2617 ( $scope_key eq 'all' || $scope_key eq 'block' || $scope_key eq 'inline' ) &&
2618 exists( $dict->{ $scope_key } ) &&
2619 ref( $dict->{ $scope_key } ) eq 'ARRAY' &&
2620 scalar( grep( /^$scope_check$/i, @{$dict->{ $scope_key }} ) )
2621 )
2622 ||
2623 (
2624 $scope_key eq 'all' &&
2625 ( $scope_check eq 'block' || $scope_check eq 'inline' ) &&
2626 exists( $dict->{ $scope_check } )
2627 )
2628 ||
2629 ( $scope_check ne 'extended' && $scope_key eq 'all' )
2630 ||
2631 ( $is_ext && $scope_check eq 'extended' ) )
2632 {
2633 $hits++;
2634 }
2635 else
2636 {
2637 # No match
2638 }
2639 });
2640 });
2641 $cache->{ $cache_key } = ( ( $term_cond eq 'all' && $expect == $hits ) || ( $term_cond eq 'any' && $hits ) ) ? 1 : 0;
2642 return( ( ( $term_cond eq 'all' && $expect == $hits ) || ( $term_cond eq 'any' && $hits ) ) ? 1 : 0 );
2643 }
2644  
2645 sub scope { return( shift->_set_get_hash_as_mix_object( 'scope', @_ ) ); }
2646  
2647 sub _set_get_prop
2648 {
2649 my $self = shift( @_ );
2650 my $key = shift( @_ );
2651 my $scope = $self->scope;
2652 $scope->{ $key } = shift( @_ ) if( @_ );
2653 return( $scope->{ $key } );
2654 }
2655  
2656 1;
2657 # NOTE: POD
2658 __END__