blib/lib/Markdown/Parser.pm untested

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