Debian Codegraph @

lib/Markdown/Perl.pm

raw
1 package Markdown::Perl;
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 Hash::Util 'lock_keys';
12 use List::Util 'none';
13 use List::MoreUtils 'pairwise';
14 use Markdown::Perl::BlockParser;
15 use Markdown::Perl::Inlines;
16 use Markdown::Perl::HTML 'html_escape', 'decode_entities', 'parse_attributes';
17 use Readonly;
18 use Scalar::Util 'blessed';
19
20 use parent 'Markdown::Perl::Options';
21
22 our $VERSION = '1.14'; # remember to bump in App::pmarkdown too.
23
24 our @EXPORT_OK = qw(convert set_options set_mode set_hooks);
25 our %EXPORT_TAGS = (all => \@EXPORT_OK);
26
27 sub new {
28 my ($class, @options) = @_;
29
30 my $this = $class->SUPER::new(
31 mode => undef,
32 options => {},
33 local_options => {},
34 hooks => {});
35 $this->SUPER::set_options(options => @options);
36 lock_keys(%{$this});
37
38 return $this;
39 }
40
41 sub set_options {
42 my ($this, @options) = &_get_this_and_args; ## no critic (ProhibitAmpersandSigils)
43 $this->SUPER::set_options(options => @options);
44 return;
45 }
46
47 sub set_mode {
48 my ($this, $mode) = &_get_this_and_args; ## no critic (ProhibitAmpersandSigils)
49 $this->SUPER::set_mode(options => $mode);
50 return;
51 }
52
53 Readonly::Array my @VALID_HOOKS => qw(resolve_link_ref yaml_metadata);
54
55 sub set_hooks {
56 my ($this, %hooks) = &_get_this_and_args; ## no critic (ProhibitAmpersandSigils)
57 while (my ($k, $v) = each %hooks) {
58 if (none { $_ eq $k } @VALID_HOOKS) {
59 croak "Invalid hook name: ${k}";
60 } elsif (!defined $v) {
61 delete $this->{hooks}{$k};
62 } elsif (ref $v ne 'CODE') {
63 carp 'Hook target must be a CODE reference';
64 } else {
65 $this->{hooks}{$k} = $v;
66 }
67 }
68 return;
69 }
70
71 # Returns @_, unless the first argument is not blessed as a Markdown::Perl
72 # object, in which case it returns a default object.
73 my $default_this = Markdown::Perl->new();
74
75 sub _get_this_and_args { ## no critic (RequireArgUnpacking)
76 return unless @_;
77 # We could use `$this isa Markdown::Perl` that does not require to test
78 # blessedness first. However this requires 5.31.6 which is not in Debian
79 # stable as of writing this.
80 if (!blessed($_[0]) || !$_[0]->isa(__PACKAGE__)) {
81 unshift @_, $default_this;
82 }
83 return @_ if defined wantarray;
84 return;
85 }
86
87 # Takes a string and converts it to HTML. Can be called as a free function or as
88 # class method. In the latter case, provided options override those set in the
89 # class constructor.
90 # Both the input and output are unicode strings.
91 sub convert { ## no critic (RequireArgUnpacking)
92 &_get_this_and_args; ## no critic (ProhibitAmpersandSigils)
93 my $this = shift @_;
94 my $md = \(shift @_); # Taking a reference to avoid copying the input. is it useful?
95 $this->SUPER::set_options(local_options => @_);
96
97 # TODO: introduce an HtmlRenderer object that carries the $linkrefs states
98 # around (instead of having to pass it in all the calls).
99 my ($blocks, $linkrefs) = $this->_parse($md);
100 my $out = $this->_emit_html(0, 'root', $linkrefs, @{$blocks});
101 $this->{local_options} = {};
102 return $out;
103 }
104
105 # This is an internal call for now because the structure of the parse tree is
106 # not defined.
107 # Note that while convert() takes care not to copy the md argument, this is not
108 # the case of this method, however, it can receive a scalar ref instead of a
109 # scalar, to avoid the copy.
110 # TODO: create a BlockTree class and document it, then make this be public.
111 sub _parse {
112 my ($this, $md_or_ref) = &_get_this_and_args; ## no critic (ProhibitAmpersandSigils)
113 my $md = ref($md_or_ref) ? $md_or_ref : \$md_or_ref;
114
115 my $parser = Markdown::Perl::BlockParser->new($this, $md);
116 my ($linkrefs, $blocks) = $parser->process();
117 return ($blocks, $linkrefs) if wantarray;
118 return $blocks;
119 }
120
121 sub _render_inlines {
122 my ($this, $linkrefs, @lines) = @_;
123 return Markdown::Perl::Inlines::render($this, $linkrefs, @lines);
124 }
125
126 # TODO: move this to a separate package and split the method in smaller chunks.
127 sub _emit_html { ## no critic (ProhibitExcessComplexity)
128 my ($this, $tight_block, $parent_type, $linkrefs, @blocks) = @_;
129 my $out = '';
130 my $block_index = 0;
131 for my $bl (@blocks) {
132 $block_index++;
133 if ($bl->{type} eq 'break') {
134 $out .= "<hr />\n";
135 } elsif ($bl->{type} eq 'heading') {
136 my $l = $bl->{level};
137 my $c = $bl->{content};
138 $c = $this->_render_inlines($linkrefs, ref $c eq 'ARRAY' ? @{$c} : $c);
139 $c =~ s/^[ \t]+|[ \t]+$//g; # Only the setext headings spec asks for this, but this can’t hurt atx heading where this can’t change anything.
140 $out .= "<h${l}>$c</h${l}>\n";
141 } elsif ($bl->{type} eq 'code') {
142 my $c = $bl->{content};
143 html_escape($c, $this->get_html_escaped_code_characters);
144 my $i = '';
145 if ($this->get_code_blocks_info eq 'language' && $bl->{info}) {
146 my $l = $bl->{info} =~ s/\s.*//r; # The spec does not really cover this behavior so we’re using Perl notion of whitespace here.
147 decode_entities($l);
148 html_escape($l, $this->get_html_escaped_characters);
149 $i = " class=\"language-${l}\"";
150 }
151 $out .= "<pre><code${i}>$c</code></pre>\n";
152 } elsif ($bl->{type} eq 'html') {
153 $out .= $bl->{content};
154 } elsif ($bl->{type} eq 'paragraph') {
155 my $html = '';
156 if ((
157 $this->get_allow_task_list_markers eq 'list'
158 && $parent_type eq 'list'
159 && $block_index == 1)
160 || $this->get_allow_task_list_markers eq 'always'
161 ) {
162 if ($bl->{content}[0] =~ m/ ^ \s* \[ (?<marker> [ xX] ) \] (?<space> \s | $ ) /x) {
163 $html =
164 '<input '
165 .($LAST_PAREN_MATCH{marker} eq ' ' ? '' : 'checked="" ')
166 .'disabled="" type="checkbox">'
167 .($LAST_PAREN_MATCH{space} eq ' ' ? ' ' : "\n");
168 substr $bl->{content}[0], 0, $LAST_MATCH_END[0], '';
169 }
170 }
171 $html .= $this->_render_inlines($linkrefs, @{$bl->{content}});
172 if ($tight_block) {
173 $out .= $html;
174 } elsif ($this->get_render_naked_paragraphs) {
175 $out .= "${html}\n";
176 } else {
177 $out .= "<p>${html}</p>\n";
178 }
179 } elsif ($bl->{type} eq 'quotes') {
180 my $c = $this->_emit_html(0, 'quotes', $linkrefs, @{$bl->{content}});
181 $out .= "<blockquote>\n${c}</blockquote>\n";
182 } elsif ($bl->{type} eq 'list') {
183 my $type = $bl->{style}; # 'ol' or 'ul'
184 my $start = '';
185 my $num = $bl->{start_num};
186 my $loose = $bl->{loose};
187 $start = " start=\"${num}\"" if $type eq 'ol' && $num != 1;
188 $out .= "<${type}${start}>\n<li>"
189 .join("</li>\n<li>",
190 map { $this->_emit_html(!$loose, 'list', $linkrefs, @{$_->{content}}) } @{$bl->{items}})
191 ."</li>\n</${type}>\n";
192 } elsif ($bl->{type} eq 'table') {
193 $out .= '<table><thead><tr>';
194 my @align = map { $_ ? " align=\"${_}\"" : '' } @{$bl->{content}{align}};
195 my @h = map { $this->_render_inlines($linkrefs, $_) } @{$bl->{content}{headers}};
196 $out .= join('', pairwise { "<th${a}>${b}</th>" } @align, @h);
197 $out .= '</tr></thead>';
198 if (@{$bl->{content}{table}}) {
199 $out .= '<tbody>';
200 my $ms = $this->get_table_blocks_have_cells_for_missing_data;
201 for my $l (@{$bl->{content}{table}}) {
202 $out .= '<tr>';
203 my @d = map { defined ? $this->_render_inlines($linkrefs, $_) : $ms ? '' : undef } @{$l};
204 $out .= join('', pairwise { defined $b ? "<td${a}>${b}</td>" : '' } @align, @d);
205 $out .= '</tr>';
206 }
207 $out .= '</tbody>';
208 }
209 $out .= '</table>';
210 } elsif ($bl->{type} eq 'directive') {
211 my $c = $this->_emit_html(0, 'directive', $linkrefs, @{$bl->{content}});
212 my %attr = parse_attributes($bl->{attributes}) if defined $bl->{attributes}; ## no critic (ProhibitConditionalDeclaration)
213 my @attr = ('div');
214 push @attr, 'id="'.$attr{id}.'"' if exists $attr{id};
215 unshift @{$attr{class}}, lc($bl->{name}) if defined $bl->{name};
216 push @attr, 'class="'.join(' ', @{$attr{class}}).'"' if exists $attr{class};
217 push @attr, map { sprintf 'data-%s="%s"', @{$_} } @{$attr{keys}} if exists $attr{keys};
218 my $tag = join(' ', @attr);
219 # TODO: the inline content is ignored for now
220 # TODO we should add a hook to process the directive in custom cases.
221 $out .= "<${tag}>\n${c}</div>\n";
222 if (defined $bl->{inline} && $this->get_warn_for_unused_input()) {
223 carp 'Unused inline content in a directive block: '.$bl->{inline};
224 }
225 if (defined $attr{junk} && $this->get_warn_for_unused_input()) {
226 carp 'Unused attribute content in a directive block: '.$attr{junk};
227 }
228 } else {
229 confess 'Unexpected block type when rendering HTML output: '.$bl->{type};
230 }
231 }
232 # Note: a final new line should always be appended to $out. This is not
233 # guaranteed when the last element is HTML and the input file did not contain
234 # a final new line, unless the option force_final_new_line is set.
235 return $out;
236 }
237
238 1;
239
240 __END__
241
242 =pod
243
244 =encoding utf8
245
246 =head1 NAME
247
248 Markdown::Perl – Very configurable Markdown processor written in pure Perl,
249 supporting the CommonMark spec and many extensions.
250
251 =head1 SYNOPSIS
252
253 This is the library underlying the L<pmarkdown> tool. It can be used in an
254 object-oriented style:
255
256 use Markdown::Perl;
257 my $converter = Markdown::Perl->new([mode => $mode], %options);
258 my $html = $converter->convert($markdown);
259
260 Or the library can be used functionally:
261
262 use Markdown::Perl 'convert';
263 Markdown::Perl::set_options([mode => $mode], %options);
264 my $html = convert($markdown);
265
266 =head1 DESCRIPTION
267
268 =head2 new
269
270 my $pmarkdown = Markdown::Perl->new([mode => $mode], %options);
271
272 Creates a C<Markdown::Perl> object that can be used to convert Markdown data
273 into HTML. Note that you don’t have to create an instance of this class to use
274 this module. The methods of this class can also be used like package functions
275 and they will operate on an implicit default instance of the class.
276
277 See the L<pmarkdown/MODES> page for the documentation of existing modes.
278
279 See the L<Markdown::Perl::Options> documentation for all the existing options.
280
281 For the reference on the default syntax supported by the library, see the GitHub
282 repository of the project:
283 L<https://github.com/mkende/pmarkdown/blob/main/Syntax.md>
284
285 =head2 set_options
286
287 $pmarkdown->set_options(%options);
288 Markdown::Perl::set_options(%option);
289
290 Sets the options of the current object or, for the functional version, the
291 options used by functional calls to convert(). The options set through the
292 functional version do B<not> apply to any objects created through a call to
293 new().
294
295 See the L<Markdown::Perl::Options> documentation for all the existing options.
296
297 =head2 set_mode
298
299 $pmarkdown->set_mode($mode);
300 Markdown::Perl::set_mode($mode);
301
302 Specifies a I<mode> for the current object or, for the functional version, the
303 mode used by functional calls to convert(). A mode is a set of configuration
304 options working together, typically to replicate the semantics of another
305 existing Markdown processor. See the L<pmarkdown/MODES> documentation for a list
306 of available modes.
307
308 When a mode is applied, it sets specific values for some options but any value
309 for these options set through the set_options() will take precedence, even if
310 set_options() is called before set_mode(). The mode set through the functional
311 version does B<not> apply to any objects created through a call to new().
312
313 =head2 convert
314
315 my $html = $pmarkdown->convert($md);
316 my $html = Markdown::Perl::convert($md);
317
318 Converts the given $md string into HTML. The input string must be a decoded
319 Unicode string (or an ASCII string) and the output is similarly a decoded
320 Unicode string.
321
322 =head2 set_hooks
323
324 $pmarkdown->set_hooks(hook_name => sub { ... }, ...);
325 Markdown::Perl::set_hooks(hook_name => sub { ... }, ...);
326
327 Registers hooks to be called during the processing of a Markdown document. Each
328 hook must point to a code reference. You can remove a hook by passing C<undef>
329 as the value associated with a hook.
330
331 There is currently a single hook:
332
333 =over 4
334
335 =item *
336
337 C<resolve_link_ref>: this hook will receive a single string an argument,
338 containing the label of a link reference in case where there was no matching
339 link definition in the document and it must returns either C<undef> or a
340 hash-reference containing a C<target> key, pointing to the link destination and
341 optionally a C<title> key containing the title of the key. The hash-ref can also
342 contain a C<content> key, in which case its value should be a span of HTML which
343 will replace whatever would have been used for the link content.
344
345 =item *
346
347 C<yaml_metadata>: this hook will trigger if there is B<valid> YAML metadata at
348 the beginning of the file. This also requires that the
349 L<parse_file_metadata option|Markdown::Perl::Options/parse_file_metadata> is set
350 to C<yaml> (which is the default in our default mode). The hook will receive a
351 hashref or an arrayref with the content of the YAML document.
352
353 To allow conditional parsing based on some metadata, if the hook dies, the
354 exception will interrupt the processing and be propagated as-is to the initial
355 caller.
356
357 =back
358
359 =head1 AUTHOR
360
361 Mathias Kende <[email protected]>
362
363 =head1 COPYRIGHT AND LICENSE
364
365 Copyright 2024 Mathias Kende
366
367 Permission is hereby granted, free of charge, to any person obtaining a copy of
368 this software and associated documentation files (the "Software"), to deal in
369 the Software without restriction, including without limitation the rights to
370 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
371 the Software, and to permit persons to whom the Software is furnished to do so,
372 subject to the following conditions:
373
374 The above copyright notice and this permission notice shall be included in all
375 copies or substantial portions of the Software.
376
377 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
378 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
379 FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
380 COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
381 IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
382 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
383
384 =head1 SEE ALSO
385
386 =over
387
388 =item L<pmarkdown>
389
390 =item L<Text::Markdown> another pure Perl implementation, implementing the
391 original Markdown syntax from L<http://daringfireball.net/projects/markdown>.
392
393 =item L<CommonMark> a wrapper around the official CommonMark C library.
394
395 =back
396
397 =cut