blib/lib/Text/Nimble.pm

filter: Statementstmt 57.8% 11 / 19 Branchbran 0.0% 0 / 12 Conditioncond 0.0% 0 / 18 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 80.0% 4 / 5 Podpod n/a totaltotal 24.1% 15 / 62 CC 13 SCAR 49.4
CC
13
Cov
22%
render
182.0
BEGIN
1.0
BEGIN
1.0
CRAP 139.4
↑ Summary
1 package Text::Nimble;
2  
3 1 ▶use 5.010; # for recursive regexes, but also using //
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 our $VERSION = '0.002001';
10 $VERSION = eval $VERSION;
11  
12  
13 my %renderer = (
14 html => \&_renderer_html,
15 );
16  
17  
18 0 ▶sub render {
Subroutine render: not called CC=13 SCAR=52.0
19 0 my ($format, $nimble) = @_;
20 0 ▶ croak "Text::Nimble::render takes two arguments but got ".(scalar @_) unless @_ == 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ == 2 0 0 0
21 0 ▶ croak "Text::Nimble::render takes a render format name as its first argument" unless defined $_[0] && $_[0] =~ /^\w+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] =~ /^\w+$/ 0 0 0
Condition0%0/3
defined $_[0] and $_[0] =~ /^\w+$/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_[0] and $_[0] =~ /^\w+$/
defined $_[0] $_[0] =~ /^\w+$/
Truth table0%0/3
A and B
A= defined $_[0]B= $_[0] =~ /^\w+$/
ABresult
0X0
100
111
22 0 ▶ croak "Text::Nimble::render takes Nimble text or a Nimble parse result as its second argument" unless defined $_[1] && (!ref $_[1] || ref $_[1] eq 'ARRAY' || (ref $_[1] eq 'HASH' && $_[1]{tree} && $_[1]{macro}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[1] and !ref($_[1]) || ref $_[1] eq "ARRAY" || ref $_[1] eq "HASH" && $_[1]{"tree"} && $_[1]{"macro"} 0 0 0
Condition0%0/15
defined $_[1] and !ref($_[1]) || ref $_[1] eq "ARRAY" || ref $_[1] eq "HASH" && $_[1]{"tree"} && $_[1]{"macro"}
!ll&&!rl&&r
000
not ref $_[1] or ref $_[1] eq "ARRAY" or ref $_[1] eq "HASH" and $_[1]{"tree"} and $_[1]{"macro"}
l!l&&r!l&&!r
000
not ref $_[1] or ref $_[1] eq "ARRAY"
l!l&&r!l&&!r
000
ref $_[1] eq "HASH" and $_[1]{"tree"} and $_[1]{"macro"}
!ll&&!rl&&r
000
ref $_[1] eq "HASH" and $_[1]{"tree"}
!ll&&!rl&&r
000
MC/DC0%0/6
defined $_[1] and !ref($_[1]) || ref $_[1] eq "ARRAY" || ref $_[1] eq "HASH" && $_[1]{"tree"} && $_[1]{"macro"}
defined $_[1] not ref $_[1] ref $_[1] eq "ARRAY" ref $_[1] eq "HASH" $_[1]{"tree"} $_[1]{"macro"}
Truth table0%0/7
A and not(B) or C or D and E and F
A= defined $_[1]B= not ref $_[1]C= ref $_[1] eq "ARRAY"D= ref $_[1] eq "HASH"E= $_[1]{"tree"}F= $_[1]{"macro"}
ABCDEFresult
0XXXXX0
1000XX0
10010X0
1001100
11XXXX1
101XXX1
1001111
23 0 ▶ croak "Text::Nimble::render was given an unknown render format '$_[0]'" unless $renderer{$format};
Branch: 1 branch
BranchTrueFalseTotal
unless $renderer{$format} 0 0 0
24  
25 0 ▶ $nimble = parse($nimble) unless ref $nimble eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $nimble eq "HASH" 0 0 0
26 0 my $output = $renderer{$format}($nimble);
27 0 ▶ return wantarray ? ($output, $nimble->{meta}, $nimble->{error}) : $output;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
28 }
29  
30 sub parse {
31 croak "Text::Nimble::parse takes one argument but got ".(scalar @_) unless @_ == 1;
32  
33 my (%meta, %macro, @error);
34  
35 local *_nimble_makelines = sub {
36 # break input into lines
37 croak "Text::Nimble::parse expects a string" unless @_==1 && defined $_[0] && !ref $_[0];
38 my $input = $_[0];
39 $input =~ s/\r//g;
40 my @lines = split(/\n/, $input, -1);
41  
42 my $next_indent;
43 for (my $i=$#lines; $i>=0; $i--) {
44 if ($lines[$i] =~ /^( *)\S/) {
45 $next_indent = $1;
46 } elsif (defined $next_indent && $lines[$i] =~ /^\s*$/) {
47 $lines[$i] = $next_indent;
48 }
49 }
50  
51 return \@lines;
52 };
53  
54 local *_macro_arg_preprocess = sub {
55 my ($type, $arg) = @_;
56  
57 if ($type eq 'nimble') {
58 return ref $arg ? _nimble_parse($arg) : _nimble_parse_inline($arg);
59 } elsif ($type eq 'raw') {
60 return ref $arg ? join("\n", @$arg) : $arg;
61 } else {
62 die "unreachable: _macro_arg_preprocess tried to decode a macro argument with unrecognized type '$type'";
63 }
64 };
65  
66 local *_macro_invocation_preprocess = sub {
67 my ($macro_name, $node) = @_;
68 foreach my $arg (keys %{$macro{$macro_name}{args}}) {
69 $node->{args}{$arg} =
70 defined $node->{args}{$arg}
71 ? _macro_arg_preprocess($macro{$macro_name}{args}{$arg}{type}, $node->{args}{$arg})
72 : $macro{$macro_name}{args}{$arg}{default};
73 }
74 };
75  
76 my %inlinestyle = (
77 '*' => 'strong',
78 '/' => 'emphasis',
79 );
80 my $inlinestyle_re = '['.quotemeta(join('', keys %inlinestyle)).']';
81  
82 my %entityshorthand = (
83 '--' => '–',
84 '---' => '—',
85 '<--' => '&larr;',
86 '-->' => '&rarr;',
87 '<==' => '&lArr;',
88 '==>' => '&rArr;',
89 );
90 my $entityshorthand_re = '(?:'.join('|', map {quotemeta} sort {length $b <=> length $a} keys %entityshorthand).')';
91  
92 my $inline_re = qr/
93 # start at pos(), then group for delimiter-matching recursion
94 # 1
95 \G(
96 # plain text or escapes
97 # 2
98 ((?:[\w\s\.\,\(\)\']+|\\.)+)
99 # inline code
100 # 3 4
101 | (\`+)\s*(.*?)\s*\g{-2}
102 # inline style
103 # 5 6
104 | ($inlinestyle_re)(?!\s)((?>(?1))+?)(?<!\s)\g{-2}
105 # entity literal
106 # 7
107 | (\&(?:\#(?:\d+|x[0-9a-fA-F]+)|\w+)\;)
108 # entity shorthand
109 # 8
110 | ($entityshorthand_re)
111 # brackets
112 # 9
113 | \[((?>(?1))+?)\]
114 # failure; take any one character
115 # 10
116 | (.)
117 )
118 /x;
119  
120 local *_nimble_parse_inline = sub {
121 my $text = shift;
122 croak "_nimble_parse_inline takes exactly one nonref defined argument" if @_ || !defined $text || ref $text;
123  
124 my @output;
125 my $append_text = sub {
126 if (@output && $output[-1]{type} eq 'text') {
127 $output[-1]{text} .= $_[0];
128 } else {
129 push @output, {type=>"text", text=>$_[0]};
130 }
131 };
132 while ($text =~ /$inline_re/g) {
133 my ($plain, $code, $styletype, $stylecontent, $entity_literal, $entity_shorthand, $bracketcontents, $char)
134 = ($2, $4, $5, $6, $7, $8, $9, $10 );
135  
136 if (defined $plain) {
137 $plain =~ s/\\(.)/$1/g;
138 $append_text->($plain);
139 } elsif (defined $code) {
140 push @output, {type=>"code", text=>$code};
141 } elsif (defined $styletype) {
142 push @output, {type=>$inlinestyle{$styletype}, content=>_nimble_parse_inline($stylecontent)};
143 } elsif (defined $entity_literal) {
144 push @output, {type=>"entity", html=>$entity_literal};
145 } elsif (defined $entity_shorthand) {
146 push @output, {type=>"entity", html=>$entityshorthand{$entity_shorthand}};
147 } elsif (defined $bracketcontents) {
148 if ($bracketcontents =~ /^\$(\w+)((?:\s+\w+\=(?:\S*|([\"\'])((?:(?!\\|\g{-2}).|\\.)*)\g{-2}))*)\s*$/) {
149 my ($macro_name, $macro_args) = ($1, $2);
150 my ($node, @errors);
151  
152 push @errors, "no macro by that name is defined" unless $macro{$macro_name};
153  
154 if (!@errors) {
155 $node = {type=>"macro", macro=>$macro_name, args=>{}};
156 while ($macro_args =~ /\G\s+(\w+)\=(?:(?![\"\'])(\S*)|([\"\'])((?:(?!\\|\g{-2}).|\\.)*)\g{-2})/g) {
157 my ($arg_name, $arg_value) = ($1, $2 // $4);
158 push @errors, "duplicate argument '$arg_name'" if $node->{args}{$arg_name};
159 push @errors, "unknown argument '$arg_name'" unless $macro{$macro_name}{args}{$arg_name};
160 next if @errors; #skip work if any errors have been seen, but keep parsing to find more errors
161 $arg_value =~ s/^\[|\]$//g if $arg_value =~ /^(\[(?:(?:(?-1)*?)|[^\[\]\\]+|\\.|.)*?\])$/;
162 $arg_value =~ s/\\(.)/$1/g;
163 $node->{args}{$arg_name} = $arg_value;
164 }
165 if (!@errors) {
166 _macro_invocation_preprocess($macro_name, $node);
167 }
168 }
169  
170 if (@errors) {
171 $node = {type=>"error", context=>"building inline macro '$macro_name' invocation", errors=>\@errors};
172 push @error, $node;
173 }
174 push @output, $node;
175 } elsif ($bracketcontents =~ /^raw\s+(\w+)\s+(.+?)\s*$/) {
176 my ($format, $content) = ($1, $2);
177 $content =~ s/\\(.)/$1/g;
178 push @output, {type=>"raw", format=>$format, content=>$content};
179 } elsif ($bracketcontents =~ /^img\s+(\S+)(?:\s+(.+?))?$/) {
180 my $url = $1;
181 my $alt = $2 // "";
182 $url =~ s/\\(.)/$1/g;
183 $alt =~ s/\\(.)/$1/g;
184 push @output, {type=>"img", src=>$url, alt=>$alt};
185 } elsif ($bracketcontents =~ /^(?:link\s+)?(\S+)(?:\s+(.+?))?$/) {
186 my $url = $1;
187 my $content = $2;
188 $url =~ s/\\(.)/$1/g;
189 push @output, {type=>"link", url=>$url, content=>(defined $content ? _nimble_parse_inline($content) : [{type=>"text", text=>$url}])};
190 } else {
191 $append_text->('[');
192 push @output, @{_nimble_parse_inline($bracketcontents)};
193 $append_text->(']');
194 }
195 } elsif (defined $char) {
196 $append_text->($char);
197 } else {
198 die "unreachable: _nimble_parse_inline matched an inline pattern but failed to determine which rule should handle it: " . substr($text, $-[0], $+[0] - $-[0]) . "\n";
199 }
200 }
201  
202 return \@output;
203 };
204  
205 local *_nimble_parse = sub {
206 croak "_nimble_parse takes 1-2 arguments but got ".(scalar @_) if @_ < 1 || @_ > 2;
207 croak "_nimble_parse expects an arrayref for its second argument" if @_==2 && !ref($_[1]) eq 'ARRAY';
208  
209 my @lines = @{$_[0]};
210  
211 my @extra_rules = $_[1] ? @{$_[1]} : ();
212  
213 my $section_depth = 0;
214  
215 # parse block-level syntaxes
216 my ($i, @output, $tail, $prev_i);
217 OUTER_LINE: for ($i=0; $i<@lines;) {
218 die "_nimble_parse: no rule advanced line index for lines[$i]" if defined $prev_i && $i == $prev_i;
219 $prev_i = $i;
220  
221 foreach my $extra_rule (@extra_rules) {
222 my ($extra_re, $extra_fn) = @$extra_rule;
223 my @extra_matches;
224 if (@extra_matches = $lines[$i] =~ $extra_re) {
225 push @output, $extra_fn->(\@extra_matches, \$i, \@lines);
226 next OUTER_LINE;
227 }
228 }
229  
230 if (0) {
231 # metadata
232 } elsif (my ($meta_key, $meta_value) = $lines[$i] =~ /^\@(\w+)(?:\s+(.*?))?\s*$/) {
233 $meta{$meta_key} = $meta_value // "";
234 $i++;
235 # codeblock
236 } elsif (my ($codeblock_marker, $codeblock_lang) = $lines[$i] =~ /^(\`{3,})(?:\s*(\w+))?\s*$/) {
237 my $node = {type=>"codeblock", lang=>$codeblock_lang, lines=>[]};
238 $i++;
239  
240 for (; $i<@lines; $i++) {
241 if ($lines[$i] =~ /^\Q$codeblock_marker\E\s*$/) {
242 $i++; last;
243 } else {
244 push @{$node->{lines}}, $lines[$i];
245 }
246 }
247 push @output, $node;
248 # ul
249 } elsif (my ($ul_indent, $ul_content) = $lines[$i] =~ /^\*( +)(.*?)$/) {
250 my $node = {type=>"ul", list=>[[$ul_content]]};
251 $i++;
252 for (; $i<@lines; $i++) {
253 if (($tail) = $lines[$i] =~ /^ $ul_indent(.*?)$/) {
254 push @{$node->{list}[-1]}, $tail;
255 } elsif (($ul_indent, $ul_content) = $lines[$i] =~ /^\*( +)(.*?)$/) {
256 push @{$node->{list}}, [$ul_content];
257 } else {
258 last;
259 }
260 }
261 $node->{list} = [ map { _nimble_parse($_) } @{$node->{list}} ];
262 push @output, $node;
263 # ol
264 } elsif (my ($ol_indent, $ol_value, $ol_content) = $lines[$i] =~ /^((?:(\d+)|\#)\. +)(.*?)$/) {
265 my $node = {type=>"ol", content=>[{type=>"li", value=>$ol_value, content=>[$ol_content]}]};
266 $i++;
267 $ol_indent = " " x length $ol_indent;
268 for (; $i<@lines; $i++) {
269 if (($tail) = $lines[$i] =~ /^$ol_indent(.*?)$/) {
270 push @{$node->{content}[-1]{content}}, $tail;
271 } elsif (($ol_value, $ol_content) = $lines[$i] =~ /^(?:(\d+)|\#)\. (.*?)$/) {
272 push @{$node->{content}}, {type=>"li", value=>$ol_value, content=>[$ol_content]};
273 $ol_indent = " " x ((defined $ol_value ? length $ol_value : 1) + 2);
274 } else {
275 last;
276 }
277 }
278 $_->{content} = _nimble_parse($_->{content}) for @{$node->{content}};
279 push @output, $node;
280 # dl
281 } elsif (my ($dl_indent, $dl_content) = $lines[$i] =~ /^\?( +)(.*?)$/) {
282 my $node = {type=>"dl", content=>[{type=>"dt",content=>[$dl_content]}]};
283 $i++;
284 for (; $i<@lines; $i++) {
285 if (($tail) = $lines[$i] =~ /^ $dl_indent(.*?)$/) {
286 push @{$node->{content}[-1]{content}}, $tail;
287 } elsif (($dl_indent, $dl_content) = $lines[$i] =~ /^\=( +)(.*?)$/) {
288 push @{$node->{content}}, {type=>"dd",content=>[$dl_content]};
289 } elsif (($dl_indent, $dl_content) = $lines[$i] =~ /^\?( +)(.*?)$/) {
290 push @{$node->{content}}, {type=>"dt",content=>[$dl_content]};
291 } else {
292 last;
293 }
294 }
295 $_->{content} = _nimble_parse($_->{content}) for @{$node->{content}};
296 push @output, $node;
297 # figure / figcaption
298 } elsif (my ($fig_indent, $fig_content) = $lines[$i] =~ /^\%( +)(.*?)$/) {
299 my $node = {type=>"figure", content=>[$fig_content]};
300 $i++;
301  
302 for (; $i<@lines; $i++) {
303 if (($tail) = $lines[$i] =~ /^ $fig_indent(.*?)$/) {
304 push @{$node->{content}}, $tail;
305 } else {
306 last;
307 }
308 }
309  
310 $node->{content} = _nimble_parse($node->{content}, [
311 [qr/^\=( +)(.*?)$/ => sub {
312 my ($matches, $i, $lines) = @_;
313 my ($figcap_indent, $figcap_content) = @$matches;
314 my $node = {type=>"figcaption", content=>[$figcap_content]};
315 $$i++;
316  
317 my $tail;
318 for (; $$i<@$lines; $$i++) {
319 if (($tail) = $lines->[$$i] =~ /^ $figcap_indent(.*?)$/) {
320 push @{$node->{content}}, $tail;
321 } else {
322 last;
323 }
324 }
325  
326 $node->{content} = _nimble_parse($node->{content});
327 return $node;
328 }],
329 ]);
330  
331 push @output, $node;
332 # h#
333 } elsif (my ($h_indent, $h_depth, $h_content) = $lines[$i] =~ /^(\!([123456]?) +)(.*?)$/) {
334 my $node = {type=>"h", content=>[$h_content], depth=>$h_depth||1};
335 $i++;
336  
337 $h_indent = " " x length $h_indent;
338 for (; $i<@lines; $i++) {
339 if (($tail) = $lines[$i] =~ /^$h_indent(.*?)$/) {
340 push @{$node->{content}}, $tail;
341 } else {
342 last;
343 }
344 }
345  
346 $node->{content} = _nimble_parse_inline(join(" ", @{$node->{content}}));
347 push @output, $node;
348 # blockquote
349 } elsif (my ($bq_indent, $bq_content) = $lines[$i] =~ /^\"( +)(.*?)$/) {
350 my $node = {type=>"blockquote", quote=>[$bq_content]};
351 $i++;
352  
353 my $section = 'quote';
354 for (; $i<@lines; $i++) {
355 if (($bq_content) = $lines[$i] =~ /^ $bq_indent(.*?)$/) {
356 push @{$node->{$section}}, $bq_content;
357 } elsif ($section eq 'quote' && (($bq_indent, $bq_content) = $lines[$i] =~ /^\-( +)(.*?)$/)) {
358 $section = 'cite';
359 $node->{$section} = [$bq_content];
360 } else {
361 last;
362 }
363 }
364  
365 $node->{$_} = _nimble_parse($node->{$_}) for grep { defined $node->{$_} } qw(quote cite);
366 push @output, $node;
367 # raw data
368 } elsif (my ($raw_format, $raw_inline) = $lines[$i] =~ /^\#raw\s+(\w+)(?:\s+(.*?))?\s*$/) {
369 my $node = {type=>"raw", format=>$raw_format, content=>[]};
370 $i++;
371  
372 if (defined $raw_inline) {
373 $node->{content} = $raw_inline;
374 } else {
375 for (; $i<@lines; $i++) {
376 if (my ($raw_line) = $lines[$i] =~ /^ +(.*?)\s*$/) {
377 push @{$node->{content}}, $raw_line;
378 } else {
379 last;
380 }
381 }
382 $node->{content} = join("\n", @{$node->{content}});
383 }
384  
385 push @output, $node;
386 # macro definition
387 } elsif (my ($macro_decl) = $lines[$i] =~ /^\#macro\s+(\w+)\s*$/) {
388 my $macro = {args=>{}, results=>{}};
389 $i++;
390  
391 my @errors;
392 push @errors, "a macro named '$macro_decl' already exists" if $macro{$macro_decl};
393 # we're building $macro as a temp variable, so no need to skip altering logic based on @errors
394  
395 my ($block_type, $block_name, $block_value, $block_indent, $block_internal_indent);
396 for (; $i<@lines; $i++) {
397 if (defined $block_type && (my ($block_line) = $lines[$i] =~ /^$block_indent( +.*?)\s*$/)) {
398 if (!defined $block_internal_indent) {
399 $block_line =~ /^( +)/;
400 $block_internal_indent = $1;
401 }
402 $block_line =~ s/^$block_internal_indent//;
403 push @{$macro->{$block_type}{$block_name}{$block_value}}, $block_line;
404 } elsif (my ($arg_indent, $arg_name, $arg_type, $arg_inline_default) = $lines[$i] =~ /^( +)\#arg\s+(\w+)\s+(\w+)(?:\s+(\S.*?))?\s*$/) {
405 push @errors, "duplicate definition for argument '$arg_name'" if $macro->{args}{$arg_name};
406 push @errors, "invalid type '$arg_type' for argument '$arg_name'" unless $arg_type =~ /^(?:nimble|raw)$/;
407 $macro->{args}{$arg_name} = {type=>$arg_type, default=>[]};
408 if (defined $arg_inline_default) {
409 $macro->{args}{$arg_name}{default} = $arg_inline_default;
410 $block_type = undef;
411 } else {
412 ($block_type, $block_name, $block_value, $block_indent, $block_internal_indent) = ("args", $arg_name, "default", $arg_indent, undef);
413 }
414 } elsif (my ($result_indent, $result_format, $result_inline_default) = $lines[$i] =~ /^( +)\#result\s+(\w+)(?:\s+(\S.*?))?\s*$/) {
415 push @errors, "duplicate definition of '$result_format'-format result" if $macro->{results}{$result_format};
416 $macro->{results}{$result_format} = {output=>[]};
417 if (defined $result_inline_default) {
418 $macro->{results}{$result_format}{output} = $result_inline_default;
419 $block_type = undef;
420 } else {
421 ($block_type, $block_name, $block_value, $block_indent, $block_internal_indent) = ("results", $result_format, "output", $result_indent, undef);
422 }
423 } else {
424 last;
425 }
426 }
427  
428 if (!@errors) {
429 foreach my $arg_name (keys %{$macro->{args}}) {
430 $macro->{args}{$arg_name}{default} = _macro_arg_preprocess($macro->{args}{$arg_name}{type}, $macro->{args}{$arg_name}{default});
431 }
432 foreach my $result_format (keys %{$macro->{results}}) {
433 $macro->{results}{$result_format}{output} = join("\n", @{$macro->{results}{$result_format}{output}}) if ref $macro->{results}{$result_format}{output};
434 }
435  
436 $macro{$macro_decl} = $macro;
437 } else {
438 my $node = {type=>"error", context=>"defining macro '$macro_decl'", errors=>\@errors};
439 push @error, $node;
440 push @output, $node;
441 }
442 # macro usage
443 } elsif (my ($macro_name) = $lines[$i] =~ /^\$\s*(\w+)\s*$/) {
444 my $node = {type=>"macro", macro=>$macro_name, args=>{}};
445 $i++;
446  
447 my @errors;
448 push @errors, "no macro by that name is defined" unless $macro{$macro_name};
449  
450 my ($block_indent, $arg_block_name, $block_internal_indent);
451 for (; $i<@lines; $i++) {
452 if (defined $arg_block_name && (my ($block_line) = $lines[$i] =~ /^$block_indent( +.*?)\s*$/)) {
453 if (!defined $block_internal_indent) {
454 $block_line =~ /^( +)/;
455 $block_internal_indent = $1;
456 }
457 $block_line =~ s/^$block_internal_indent//;
458 if (!@errors) {
459 push @{$node->{args}{$arg_block_name}}, $block_line;
460 }
461 } elsif (my ($arg_indent, $arg_name, $arg_inline_default) = $lines[$i] =~ /^( +)(\w+)\:(?:\s+(\S.*?))?\s*$/) {
462 push @errors, "duplicate argument '$arg_name'" if $node->{args}{$arg_name};
463 push @errors, "unknown argument '$arg_name'" unless $macro{$macro_name}{args}{$arg_name};
464 if (!@errors) {
465 $node->{args}{$arg_name} = [];
466 }
467 if (defined $arg_inline_default) {
468 if (!@errors) {
469 $node->{args}{$arg_name} = $arg_inline_default;
470 }
471 $arg_block_name = undef;
472 } else {
473 ($arg_block_name, $block_indent, $block_internal_indent) = ($arg_name, $arg_indent, undef);
474 }
475 } else {
476 last;
477 }
478 }
479  
480 if (!@errors) {
481 _macro_invocation_preprocess($macro_name, $node);
482 }
483  
484 if (@errors) {
485 $node = {type=>"error", context=>"building block macro '$macro_name' invocation", errors=>\@errors};
486 push @error, $node;
487 }
488 push @output, $node;
489 # space
490 } elsif ($lines[$i] =~ /^\s*$/) {
491 push @output, {type=>"space"} unless @output && $output[-1]{type} eq 'space';
492 $i++;
493 # section start/end markers; below 'space' so at least one half of the regex matches
494 } elsif (my ($section_end, $header_indent, $header_content) = $lines[$i] =~ /^(\}*)(?:(\{ +)(.*?))?$/) {
495 $i++;
496 if (defined $section_end) {
497 my $section_end_num = length($section_end);
498 if ($section_end_num > $section_depth) {
499 my $node = {type=>"error", context=>"processing section end makers", errors=>["tried to end a section which wasn't open"]};
500 push @error, $node;
501 push @output, $node;
502 $section_end_num = $section_depth;
503 }
504 push @output, {type=>"section_end"} for 1..$section_end_num;
505 $section_depth -= $section_end_num;
506 }
507 if (defined $header_content) {
508 my $node = {type=>"section_start", content=>[$header_content]};
509  
510 $header_indent = " " x (length($header_indent) + (defined $section_end ? length($section_end) : 0));
511 for (; $i<@lines; $i++) {
512 if (($tail) = $lines[$i] =~ /^$header_indent(.*?)$/) {
513 push @{$node->{content}}, $tail;
514 } else {
515 last;
516 }
517 }
518  
519 $node->{content} = _nimble_parse($node->{content});
520 push @output, $node;
521 $section_depth++;
522 }
523 # paragraph
524 } else {
525 my $line = $lines[$i];
526 $line =~ s/^\s+//; $line =~ s/\s+$//;
527 if (@output && $output[-1]{type} eq 'paragraph') {
528 $output[-1]{content} .= " $line";
529 } else {
530 push @output, {type=>"paragraph", content=>$line};
531 }
532 $i++;
533 }
534 }
535  
536 # clean up remaining sections
537 push @output, {type=>"section_end"} for 1..$section_depth;
538  
539 # drop spaces; they were just to delimit paragraphs
540 @output = grep {$_->{type} ne 'space'} @output;
541  
542 # parse text which has been collected into paragraphs
543 $_->{content} = _nimble_parse_inline($_->{content}) for grep {$_->{type} eq 'paragraph'} @output;
544  
545 return \@output;
546 };
547  
548 do {
549 my $lines = _nimble_makelines($_[0]);
550 my $tree = _nimble_parse($lines);
551 return {tree=>$tree, meta=>\%meta, macro=>\%macro, (@error ? (error=>\@error) : ())};
552 };
553 }
554  
555 sub _renderer_html {
556 croak "Text::Nimble::_renderer_html takes one argument but got ".(scalar @_) unless @_ == 1;
557 croak "Text::Nimble::_renderer_html got an argument that doesn't look like the result of Text::Nimble::parse" unless ref $_[0] eq 'HASH' && $_[0]{tree} && $_[0]{macro};
558  
559 my %macro = %{$_[0]{macro}};
560  
561 my %xmlenc = (
562 '&' => '&amp;',
563 '"' => '&quot;',
564 '<' => '&lt;',
565 '>' => '&gt;',
566 );
567 local *_xmlenc = sub {
568 my $s = $_[0];
569 $s =~ s/([\&\"\<\>])/$xmlenc{$1}/g;
570 return $s;
571 };
572  
573 local *_urlenc = sub {
574 my $s = $_[0];
575 $s =~ s/([^a-zA-Z0-9\ ])/sprintf("%%%02X",ord($1))/ge;
576 $s =~ s/\ /\+/g;
577 return $s;
578 };
579  
580 my %macro_filters = (
581 xmlenc => \&_xmlenc,
582 urlenc => \&_urlenc,
583 );
584  
585 local *_macro_var_interpolate = sub {
586 my ($macro, $arg_name, $filters) = @_;
587 my @filters = defined $filters ? split(/\|/, $filters) : ();
588 my @unknown_filters = grep {!$macro_filters{$_}} @filters;
589 return "[nimble macro error: unknown argument filters(s): " . join(", ", @unknown_filters) . "]" if @unknown_filters;
590 my $value = $macro->{args}{$arg_name};
591 $value = $macro_filters{$_}($value) for @filters;
592 return $value;
593 };
594  
595 local *_render_html = sub {
596 my $node = shift;
597  
598 # handle a list of nodes, especially the root level of Text::Nimble::parse
599 if (ref $node eq 'ARRAY') {
600 # a lone paragraph should just be plain text instead
601 if (@$node == 1 && $node->[0]{type} eq 'paragraph') {
602 return _render_html($node->[0]{content});
603 } else {
604 return join("", map { _render_html($_) } @$node) if ref $node eq 'ARRAY';
605 }
606 }
607  
608 my $type = $node->{type};
609 if (0) {}
610 elsif ($type eq 'paragraph' ) { return "<p>" ._render_html($node->{content})."</p\n>" }
611 elsif ($type eq 'dl' ) { return "<dl>" ._render_html($node->{content})."</dl\n>" }
612 elsif ($type eq 'dt' ) { return "<dt>" ._render_html($node->{content})."</dt>" }
613 elsif ($type eq 'dd' ) { return "<dd>" ._render_html($node->{content})."</dd>" }
614 elsif ($type eq 'emphasis' ) { return "<em>" ._render_html($node->{content})."</em>" }
615 elsif ($type eq 'ol' ) { return "<ol>" ._render_html($node->{content})."</ol\n>" }
616 elsif ($type eq 'figure' ) { return "<figure>"._render_html($node->{content})."</figure\n>" }
617 elsif ($type eq 'figcaption' ) { return "<figcaption>"._render_html($node->{content})."</figcaption\n>" }
618 elsif ($type eq 'h' ) { return "<h$node->{depth}>"._render_html($node->{content})."</h$node->{depth}\n>" }
619 elsif ($type eq 'strong' ) { return "<strong>"._render_html($node->{content})."</strong>" }
620 elsif ($type eq 'link' ) { return "<a href=\""._xmlenc($node->{url})."\">"._render_html($node->{content})."</a>" }
621 elsif ($type eq 'img' ) { return "<img src=\""._xmlenc($node->{src})."\" alt=\""._xmlenc($node->{alt})."\"/>" }
622 elsif ($type eq 'li' ) { return "<li".(defined $node->{value}?" value=\"$node->{value}\"":"").">"._render_html($node->{content})."</li>" }
623 elsif ($type eq 'code' ) { return "<code>"._xmlenc($node->{text})."</code>" }
624 elsif ($type eq 'codeblock' ) { return "<pre>".join("\n", map{_xmlenc($_)} @{$node->{lines}})."</pre\n>" }
625 elsif ($type eq 'text' ) { return _xmlenc($node->{text}) }
626 elsif ($type eq 'entity' ) { return $node->{html} }
627 elsif ($type eq 'ul' ) { return "<ul>".join("", map{"<li>"._render_html($_)."</li>"} @{$node->{list}})."</ul\n>" }
628 elsif ($type eq 'raw' ) { return $node->{format} eq 'html' ? $node->{content} : '' }
629 elsif ($type eq 'error' ) { return "<span class=\"nimble-error\">Nimble error while "._xmlenc($node->{context}).": ".join("; ", map{_xmlenc($_)} @{$node->{errors}})."</span\n>" }
630 elsif ($type eq 'blockquote' ) {
631 my $bq_html = "<blockquote>"._render_html($node->{quote})."</blockquote\n>";
632 $bq_html = "<figure class=\"quote\">$bq_html<figcaption>"._render_html($node->{cite})."</figcaption></figure\n>" if $node->{cite};
633 return $bq_html;
634 }
635 elsif ($type eq 'section_start') {
636 return "<section\n>"
637 . (@{$node->{content}}
638 ? "<header>"._render_html(
639 @{$node->{content}} == 1 && $node->{content}[0]{type} eq 'paragraph'
640 ? [{%{$node->{content}[0]}, type=>"h", depth=>1}]
641 : $node->{content}
642 )."</header\n>"
643 : ""
644 )
645 }
646 elsif ($type eq 'section_end') { return "</section\n>" }
647 elsif ($type eq 'macro') {
648 return "" unless $macro{$node->{macro}}{results}{html};
649  
650 $node->{args}{$_} = _render_html($node->{args}{$_}) for grep {ref $node->{args}{$_}} keys %{$node->{args}};
651  
652 my $output = $macro{$node->{macro}}{results}{html}{output};
653 $output =~ s/\{\{(\w+)(?:\|(\w+(?:\|\w+)*))?\}\}/_macro_var_interpolate($node, $1, $2)/ge;
654 return $output;
655 }
656 };
657  
658 do {
659 my $parse = $_[0];
660 return _render_html($parse->{tree});
661 };
662 }
663  
664 1; # End of Text::Nimble
665  
666 __END__
↑ Summary