Debian Codegraph @

lib/Markdown/Perl/Options.pm

raw
1 package Markdown::Perl::Options;
2
3 use strict;
4 use warnings;
5 use utf8;
6 use feature ':5.24';
7
8 use Carp;
9 use English;
10 use Exporter 'import';
11 use List::Util 'any', 'all', 'pairs';
12
13 our $VERSION = '0.02';
14
15 our @EXPORT_OK = qw(validate_options);
16 our %EXPORT_TAGS = (all => \@EXPORT_OK);
17
18 =pod
19
20 =encoding utf8
21
22 =head1 NAME
23
24 Configuration options for pmarkdown and Markdown::Perl
25
26 =head1 SYNOPSIS
27
28 This document describes the existing configuration options for the
29 L<Markdown::Perl> library and the L<pmarkdown> program. Please refer to their
30 documentation to know how to set and use these options.
31
32 =head1 MODES
33
34 In addition to setting individual options, you can set bundle of options
35 together using I<modes>. See the L<pmarkdown/MODES> documentation for a list
36 of available modes. And see the documentation for L<Markdown::Perl> or
37 L<pmarkdown> to learn how to set a mode.
38
39 Note that all options are applied I<on top> of the selected mode. Even if the
40 options are passed before the mode, the mode will not override the options.
41
42 Note also that only the modes are tested as coherent selves. Setting individual
43 options on top of a given mode might result in inconsistent behavior.
44
45 =head1 OPTIONS
46
47 =cut
48
49 sub new {
50 my ($class, %options) = @_;
51
52 my $this = bless \%options, $class;
53 $this->{memoized} = {}; # TODO: use this.
54 return $this;
55 }
56
57 my %options_modes;
58 my %validation;
59
60 # Undocumented for now, used in tests.
61 our @valid_modes = (qw(default cmark github markdown));
62 my %valid_modes = map { $_ => 1 } @valid_modes;
63
64 my $err_str;
65
66 sub set_options {
67 my ($this, $dest, @options) = @_;
68 # We don’t put the options into a hash, to preserve the order in which they
69 # are passed.
70 for my $p (pairs @options) {
71 my ($k, $v) = @{$p};
72 if ($k eq 'mode') {
73 $this->Markdown::Perl::Options::set_mode($dest, $v);
74 } else {
75 carp "Unknown option ignored: ${k}" unless exists $validation{$k};
76 my $validated_value = $validation{$k}($v);
77 croak "Invalid value for option '${k}': ${err_str}" unless defined $validated_value;
78 $this->{$dest}{$k} = $validated_value;
79 }
80 }
81 return;
82 }
83
84 # returns nothing but dies if the options are not valid. Useful to call before
85 # set_options to get error messages without stack-traces in context where this
86 # is not needed (while set_options will use carp/croak).
87 sub validate_options {
88 my (%options) = @_;
89 while (my ($k, $v) = each %options) {
90 if ($k eq 'mode') {
91 die "Unknown mode '${v}'\n" unless exists $options_modes{$v};
92 } else {
93 die "Unknown option: ${k}\n" unless exists $validation{$k};
94 my $validated = $validation{$k}($v);
95 die "Invalid value for option '${k}': ${err_str}\n" unless defined $validated;
96 }
97 }
98 return;
99 }
100
101 sub set_mode {
102 my ($this, $dest, $mode) = @_;
103 carp "Setting mode '${mode}' overriding already set mode '$this->{$dest}{mode}'"
104 if defined $this->{$dest}{mode};
105 croak "Unknown mode '${mode}'" unless exists $valid_modes{$mode};
106 $this->{$dest}{mode} = $mode;
107 return;
108 }
109
110 # This method is called below to "create" each option. In particular, it
111 # populate an accessor method in this package to reach the option value.
112 sub _make_option {
113 my ($opt, $default, $validation, %mode) = @_;
114 while (my ($k, $v) = each %mode) {
115 confess "Unknown mode '${k}' when creating option '${opt}'" unless exists $valid_modes{$k};
116 $options_modes{$k}{$opt} = $v;
117 }
118 $validation{$opt} = $validation;
119
120 {
121 no strict 'refs';
122 *{"get_${opt}"} = sub {
123 my ($this) = @_;
124 return $this->{local_options}{$opt} if exists $this->{local_options}{$opt};
125 return $this->{options}{$opt} if exists $this->{options}{$opt};
126 if (defined $this->{local_options}{mode}) {
127 # We still enter here if the mode is 'default', to not enter the global
128 # mode (a local mode entirely shadows a global mode).
129 return $options_modes{$this->{local_options}{mode}}{$opt}
130 if exists $options_modes{$this->{local_options}{mode}}{$opt};
131 } elsif (defined $this->{options}{mode}) {
132 return $options_modes{$this->{options}{mode}}{$opt}
133 if exists $options_modes{$this->{options}{mode}}{$opt};
134 }
135 return $default;
136 };
137 }
138
139 return;
140 }
141
142 sub _boolean {
143 return sub {
144 return 0 if $_[0] eq 'false' || $_[0] eq '' || $_[0] eq '0';
145 return 1 if $_[0] eq 'true' || $_[0] eq '1';
146 $err_str = 'must be a boolean value (0 or 1)';
147 return;
148 };
149 }
150
151 sub _enum {
152 my @valid = @_;
153 return sub {
154 return $_[0] if any { $_ eq $_[0] } @valid;
155 $err_str = "must be one of '".join("', '", @valid)."'";
156 return;
157 };
158 }
159
160 sub _regex {
161 return sub {
162 my $re = eval { qr/$_[0]/ };
163 return $re if defined $re;
164 $err_str = 'cannot be parsed as a Perl regex ($@)';
165 return;
166 };
167 }
168
169 sub _word_list {
170 return sub {
171 my @a = ref $_[0] eq 'ARRAY' ? @{$_[0]} : split(/,/, $_[0]);
172 # TODO: validate the values of a.
173 return \@a;
174 };
175 }
176
177 =pod
178
179 =head2 Options controlling which top-level blocks are used
180
181 =head3 B<parse_file_metadata> I<(enum, default: yaml)>
182
183 This option controls whether the parser accepts optional metadata at the
184 beginning of the file. The module currently does nothing with the metadata
185 itself but you can configure a hook to receive the YAML content.
186
187 The possible values are:
188
189 =over 4
190
191 =item B<none>
192
193 No file metadata is accepted, any structure in the document must be in Markdown.
194
195 =item B<yaml> I<(default)>
196
197 The parser accepts a YAML table as the very beginning of the document. This
198 table must start with a line containing just C<---> and ends with another line
199 containing C<---> or C<...>. The content between these two markers must be valid
200 a valid, non-empty YAML sequence and it cannot contain any empty line.
201
202 =back
203
204 =cut
205
206 _make_option(
207 parse_file_metadata => 'yaml',
208 _enum(qw(none yaml)),
209 cmark => 'none',
210 github => 'none',
211 markdown => 'none',);
212
213 =head3 B<use_fenced_code_blocks> I<(boolean, default: true)>
214
215 This option controls whether fenced code blocks are recognised in the document
216 structure.
217
218 =cut
219
220 _make_option(use_fenced_code_blocks => 1, _boolean, (markdown => 0));
221
222 =pod
223
224 =head3 B<use_table_blocks> I<(boolean, default: true)>
225
226 This options controls whether table blocks can be used.
227
228 =cut
229
230 _make_option(use_table_blocks => 1, _boolean, (cmark => 0, markdown => 0));
231
232 =pod
233
234 =head3 B<use_setext_headings> I<(boolean, default: false)>
235
236 This options controls whether table blocks can be used.
237
238 =cut
239
240 _make_option(use_setext_headings => 0, _boolean, (cmark => 1, markdown => 1, github => 1));
241
242 =pod
243
244 =head3 B<use_directive_blocks> I<(boolean, default: true)>
245
246 This options controls whether directive blocks can be used.
247
248 =cut
249
250 _make_option(use_directive_blocks => 1, _boolean, (cmark => 0, markdown => 0, github => 0));
251
252 =pod
253
254 =head2 Options controlling the parsing of top-level blocks
255
256 =head3 B<fenced_code_blocks_must_be_closed> I<(boolean, default: true)>
257
258 By default, a fenced code block with no closing fence will run until the end of
259 the document. With this setting, the opening fence will be treated as normal
260 text, rather than the start of a code block, if there is no matching closing
261 fence.
262
263 =cut
264
265 _make_option(fenced_code_blocks_must_be_closed => 1, _boolean, (cmark => 0, github => 0));
266
267 =pod
268
269 =head3 B<multi_lines_setext_headings> I<(enum, default: multi_line)>
270
271 The default behavior of setext headings in the CommonMark spec is that they can
272 have multiple lines of text preceding them (forming the heading itself).
273
274 This option allows to change this behavior. And is illustrated with this example
275 of Markdown:
276
277 Foo
278 bar
279 ---
280 baz
281
282 The possible values are:
283
284 =over 4
285
286 =item B<single_line>
287
288 Only the last line of text is kept as part of the heading. The preceding lines
289 are a paragraph of themselves. The result on the example would be:
290 paragraph C<Foo>, heading C<bar>, paragraph C<baz>
291
292 =item B<break>
293
294 If the heading underline can be interpreted as a thematic break, then it is
295 interpreted as such (normally the heading interpretation takes precedence). The
296 result on the example would be: paragraph C<Foo bar>, thematic break,
297 paragraph C<baz>.
298
299 If the heading underline cannot be interpreted as a thematic break, then the
300 heading will use the default B<multi_line> behavior.
301
302 =item B<multi_line> I<(default)>
303
304 This is the default CommonMark behavior where all the preceding lines are part
305 of the heading. The result on the example would be:
306 heading C<Foo bar>, paragraph C<baz>
307
308 =item B<ignore>
309
310 The heading is ignored, and form just one large paragraph. The result on the
311 example would be: paragraph C<Foo bar --- baz>.
312
313 Note that this actually has an impact on the interpretation of the thematic
314 breaks too.
315
316 =back
317
318 =cut
319
320 _make_option(
321 multi_lines_setext_headings => 'multi_line',
322 _enum(qw(single_line break multi_line ignore)));
323
324 =pod
325
326 =head3 B<lists_can_interrupt_paragraph> I<(enum, default: strict)>
327
328 Specify whether and how a list can interrupt a paragraph.
329
330 =over 4
331
332 =item B<never>
333
334 A list can never interrupt a paragraph.
335
336 =item B<within_list>
337
338 A list can interrupt a paragraph only when we are already inside another list.
339
340 =item B<strict> I<(default)>
341
342 A list can interrupt a paragraph but only with some non ambiguous list markers.
343
344 =item B<always>
345
346 A list can always interrupt a paragraph.
347
348 =back
349
350 =cut
351
352 _make_option(
353 lists_can_interrupt_paragraph => 'strict',
354 _enum(qw(never within_list strict always)), (
355 markdown => 'within_list',
356 ));
357
358 =pod
359
360 =head3 B<allow_task_list_markers> I<(enum, default: list)>
361
362 Specify whether task list markers (rendered as check boxes) are recognised in
363 the input. The possible values are as follow:
364
365 =over 4
366
367 =item B<never>
368
369 Task list marker are never recognised
370
371 =item B<list> I<(default)>
372
373 Task list markers are recognised only as the first element at the beginning of
374 a list item.
375
376 =item B<always>
377
378 Task list markers are recognised at the beginning of any paragraphs, inside any
379 type of block.
380
381 =back
382
383 =cut
384
385 _make_option(
386 allow_task_list_markers => 'list',
387 _enum(qw(never list always)), (
388 markdown => 'never',
389 cmark => 'never',
390 ));
391
392 =pod
393
394 =head3 B<table_blocks_can_interrupt_paragraph> I<(boolean, default: false)>
395
396 Allow a table top level block to interrupt a paragraph.
397
398 =cut
399
400 _make_option(
401 table_blocks_can_interrupt_paragraph => 0,
402 _boolean, (
403 github => 1,
404 ));
405
406 =pod
407
408 =head3 B<table_blocks_pipes_requirements> I<(enum, default: strict)>
409
410 Defines how strict is the parsing of table top level blocks when the leading or
411 trailing pipes of a given line are missing.
412
413 =over 4
414
415 =item B<strict> I<(default)>
416
417 Leading and trailing pipes are always required for all the lines of the table.
418
419 =item B<loose>
420
421 Leading and trailing pipes can be omitted when the table is not interrupting a
422 paragraph, if it has at least two columns, and if the delimiter row uses
423 delimiters with more than one character.
424
425 =item B<lenient>
426
427 Leading and trailing pipes can be omitted when the table has at least two
428 columns, and if the delimiter row uses delimiters with more than one character.
429
430 =item B<lax>
431
432 Leading and trailing pipes can always be omitted, except on the header line of
433 a table, if it has a single column.
434
435 =back
436
437 =cut
438
439 _make_option(
440 table_blocks_pipes_requirements => 'strict',
441 _enum(qw(strict loose lenient lax)), (
442 github => 'loose',
443 ));
444
445 =pod
446
447 =head3 B<yaml_file_metadata_allows_empty_lines> I<(boolean, default: false)>
448
449 YAML document at the beginning of a Markdown file can contain empty lines. Note
450 that with this some reasonable Markdown documents can be interpreted as YAML so
451 you should set this value to true only if you expect to use YAML metadata with
452 your files.
453
454 =cut
455
456 _make_option(yaml_file_metadata_allows_empty_lines => 0, _boolean);
457
458 =pod
459
460 =head3 B<yaml_parser> I<(enum, default: YAML::Tiny)>
461
462 Defines the YAML parser being used for the YAML metadata. Only the default
463 L<YAML::Tiny> is installed by default with this program so if you use any other
464 value you should make sure that the corresponding module is installed.
465
466 Supported values: L<YAML::Tiny>, L<YAML::PP>, and L<YAML::PP::LibYAML>.
467
468 =cut
469
470 _make_option(
471 yaml_parser => 'YAML::Tiny',
472 _enum(qw(YAML::Tiny YAML::PP YAML::PP::LibYAML)));
473
474 =pod
475
476 =head2 Options controlling the rendering of top-level blocks
477
478 =head3 B<code_blocks_info> I<(enum, default: language)>
479
480 Fenced code blocks can have info strings on their opening lines (any text after
481 the C<```> or C<~~~> fence). This option controls what is done with that text.
482
483 The possible values are:
484
485 =over 4
486
487 =item B<ignored>
488
489 The info text is ignored.
490
491 =item B<language> I<(default)>
492
493 =back
494
495 =cut
496
497 _make_option(code_blocks_info => 'language', _enum(qw(ignored language)));
498
499 =pod
500
501 =head3 B<code_blocks_convert_tabs_to_spaces> I<(boolean, default: false)>
502
503 By default, tabs are preserved inside code blocks. With this option, all tabs (at
504 the beginning of the lines or inside) are turned into spaces, aligned with the
505 tab stops (currently always a multiple of 4).
506
507 =cut
508
509 _make_option(code_blocks_convert_tabs_to_spaces => 0, _boolean, (markdown => 1));
510
511 =pod
512
513 =head3 B<table_blocks_have_cells_for_missing_data> I<(boolean, default: false)>
514
515 Whether a table will have a cell in HTML for a missing cell in the markdown
516 input.
517
518 =cut
519
520 _make_option(
521 table_blocks_have_cells_for_missing_data => 0,
522 _boolean, (
523 github => 1,
524 ));
525
526 =pod
527
528 =head3 B<render_naked_paragraphs> I<(boolean, default: false)>
529
530 When this is set to true, the C<E<lt>pE<gt>> tag is always skipped around a
531 paragraph. This is mostly meant to render short amount of text as pure Markdown
532 inline content, without a surrounding block structure.
533
534 =cut
535
536 _make_option(render_naked_paragraphs => 0, _boolean);
537
538 =pod
539
540 =head2 Options controlling which inline elements are used
541
542 =head3 B<use_extended_autolinks> I<(boolean, default: true)>
543
544 Allow some links to be recognised when they appear in plain text. These links
545 must start by C<http://>, C<https://>, or C<www.>.
546
547 =cut
548
549 _make_option(
550 use_extended_autolinks => 1,
551 _boolean, (
552 markdown => 0,
553 cmark => 0
554 ));
555
556 =pod
557
558 =head2 Options controlling the parsing of inline elements
559
560 =head3 B<autolinks_regex> I<(regex string)>
561
562 The regex that an autolink must match. This is for CommonMark autolinks, that
563 are recognized only if they appear between brackets C<\<I<link>\>>.
564
565 The default value is meant to match the
566 L<spec|https://spec.commonmark.org/0.30/#autolinks>. Basically it requires a
567 scheme (e.g. C<https:>) followed by mostly anything else except that spaces and
568 the bracket symbols (C<\<> and C<\>>) must be escaped.
569
570 =cut
571
572 _make_option(autolinks_regex => '(?i)[a-z][-+.a-z0-9]{1,31}:[^ <>[:cntrl:]]*', _regex);
573
574 =pod
575
576 =head3 B<autolinks_email_regex> I<(regex string)>
577
578 The regex that an autolink must match to be recognised as an email address. This
579 allows to omit the C<mailto:> scheme that would be needed to be recognised as
580 an autolink otherwise.
581
582 The default value is exactly the regex specified by the
583 L<spec|https://spec.commonmark.org/0.30/#autolinks>.
584
585 =cut
586
587 _make_option(
588 autolinks_email_regex =>
589 q{[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*},
590 _regex);
591
592 =pod
593
594 =head3 B<inline_delimiters> I<(map)>
595
596 This option provides a map from delimiter symbols to the matching HTML tags.
597 This option should be passed as a comma-separated list of C<delimiter=tag_name>
598 values. For example, the original Markdown syntax map could be specified as
599 C<*=em,**=strong,_=em,__=strong>. The delimiters can only be made of a single
600 unicode character or of twice the same unicode character. The values should be
601 either HTML tag names (for example C<em>, C<strong>, etc.) or they can be
602 arbitrary HTML class names, prefixed by a single dot (C<.>). In the latter case
603 the delimiters will be used to insert a C<E<lt>spanE<gt>> element, with the
604 given class.
605
606 When using the programmatic interface, this map can be passed directly as a
607 hash-reference, with the same content as described above.
608
609 =cut
610
611 sub _delimiters_map {
612 return sub {
613 my %m = ref $_[0] eq 'HASH' ? %{$_[0]} : map { split(/=/, $_, 2) } split(/,/, $_[0]);
614 # TODO: validate the keys and values of m.
615 if (!all { m/^(.)\1?$/ } keys %m) {
616 $err_str = sprintf 'keys must be a single character, optionally repeated once';
617 return;
618 }
619 if (!all { m/^\.?[a-z][-_a-z0-9]*$/i } values %m) {
620 $err_str = sprintf 'values must be a valid HTML tag or class names';
621 return;
622 }
623 return \%m if %m;
624 return {"\N{NULL}" => 'p'} # this can’t trigger but the code fails with an empty map otherwise.
625 };
626 }
627
628 _make_option(
629 inline_delimiters => {
630 '*' => 'em',
631 '**' => 'strong',
632 '_' => 'em',
633 '__' => 'strong',
634 '~' => 's',
635 '~~' => 'del',
636 },
637 _delimiters_map,
638 markdown => {
639 '*' => 'em',
640 '**' => 'strong',
641 '_' => 'em',
642 '__' => 'strong',
643 },
644 cmark => {
645 '*' => 'em',
646 '**' => 'strong',
647 '_' => 'em',
648 '__' => 'strong',
649 },
650 github => {
651 '*' => 'em',
652 '**' => 'strong',
653 '_' => 'em',
654 '__' => 'strong',
655 '~' => 'del',
656 '~~' => 'del',
657 });
658
659 =pod
660
661 =head3 B<inline_delimiters_max_run_length> I<(map)>
662
663 TODO: document
664
665 =cut
666
667 sub _delimiters_max_run_length_map {
668 return sub {
669 my %m = ref $_[0] eq 'HASH' ? %{$_[0]} : map { split(/=/, $_, 2) } split(/,/, $_[0]);
670 # TODO: validate the keys and values of m.
671 return \%m;
672 };
673 }
674
675 _make_option(
676 inline_delimiters_max_run_length => {},
677 _delimiters_max_run_length_map,
678 github => {
679 '~' => 2,
680 });
681
682 =pod
683
684 =head3 B<allow_spaces_in_links> I<(enum, default: none)>
685
686 This option controls whether spaces are allowed between the link text and the
687 link destination (between the closing bracket of the text and the opening
688 parenthesis or bracket of the destination).
689
690 =over 4
691
692 =item B<none> I<(default)>
693
694 No space is allowed between the link text and the link target.
695
696 =item B<reference>
697
698 This allows at most one space between the two sets of brackets in a
699 reference link.
700
701 =back
702
703 =cut
704
705 _make_option(
706 allow_spaces_in_links => 'none',
707 _enum(qw(none reference)),
708 (markdown => 'reference'));
709
710 =pod
711
712 =head3 B<two_spaces_hard_line_breaks> I<(boolean, default: false)>
713
714 Controls if a hard line break can be generated by ending a line with two spaces.
715
716 =cut
717
718 _make_option(
719 two_spaces_hard_line_breaks => 0,
720 _boolean,
721 (markdown => 1, cmark => 1, github => 1));
722
723 =pod
724
725 =head2 Options controlling the rendering of inline elements
726
727 =head3 B<html_escaped_characters> I<(character_class)>
728
729 This option specifies the list of characters that will be escaped in the HTML
730 output. This should be a string containing the characters to escapes. Only the
731 following characters are supported and can be passed in the string: C<">, C<'>,
732 C<&>, C<E<lt>>, and C<E<gt>>.
733
734 =cut
735
736 sub _escaped_characters {
737 return sub {
738 return $_[0] if $_[0] =~ m/^["'&<>]*$/;
739 $err_str = "must only contains the following characters: \", ', &, <, and >";
740 return;
741 };
742 }
743
744 _make_option(html_escaped_characters => '"&<>', _escaped_characters, markdown => '&<');
745
746 =pod
747
748 =head3 B<html_escaped_code_characters> I<(character_class)>
749
750 This option is similar to the C<html_escaped_characters> but is used in the
751 context of C<E<lt>codeE<gt>> blocks.
752
753 =cut
754
755 _make_option(html_escaped_code_characters => '"&<>', _escaped_characters, markdown => '&<>');
756
757 =pod
758
759 =head3 B<force_final_new_line> I<(boolean, default: false)>
760
761 This option forces the processing of the input markdown to behave as if a final
762 new line was always present. Note that, even without this option, a final new
763 line will almost always be present in the output (and will always be present
764 with it).
765
766 =cut
767
768 _make_option(force_final_new_line => 0, _boolean, (markdown => 1));
769
770 =pod
771
772 =head3 B<preserve_white_lines> I<(boolean, default: true)>
773
774 By default, pmarkdown will try to preserve lines that contains only whitespace
775 when possible. If this option is set to false, such lines are treated as if they
776 contained just the new line character.
777
778 =cut
779
780 _make_option(preserve_white_lines => 1, _boolean, (markdown => 0));
781
782 =pod
783
784 =head3 B<disallowed_html_tags> I<(world list)>
785
786 This option specifies a comma separated list (or, in Perl, an array reference)
787 of name of HTML tags that will be disallowed in the output. If these tags appear
788 they will be deactivated in the output.
789
790 =cut
791
792 _make_option(
793 disallowed_html_tags => [],
794 _word_list,
795 github => [qw(title textarea style xmp iframe noembed noframes script plaintext)]);
796
797 =pod
798
799 =head3 B<default_extended_autolinks_scheme> I<(enum, default: https)>
800
801 Specify which scheme is added to the beginning of extended autolinks when none
802 was present initially.
803
804 =cut
805
806 _make_option(
807 default_extended_autolinks_scheme => 'https',
808 _enum(qw(http https)),
809 github => 'http');
810
811 =pod
812
813 =head2 Other options
814
815 =head3 B<warn_for_unused_input> I<(boolean, default: true)>
816
817 In general, all user input is present in the output (possibly as uninterpreted
818 text if it was not understood). But some valid Markdown construct results in
819 parts of the input being ignored. By default C<pmarkdown> will emit a warning
820 when such a construct is found. This option can disable these warnings.
821
822 =cut
823
824 _make_option(
825 warn_for_unused_input => 1,
826 _boolean);
827
828 =pod
829
830 =head1 SEE ALSO
831
832 L<Markdown::Perl>, L<pmarkdown>
833
834 =cut
835
836 1;