repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

344 lines · 21.3 KB · download this file

package BlowfishCMS;
# Markdown: the texts of pages, blocks, articles and add-ons turned into HTML
# (Text::Markdown, then HTML::Scrubber), with BlowfishCMS's extras: boxes and
# callouts (::: note), figures and embeds of the site's own pictures and items,
# buttons, footnotes, tables of contents, coloured code (Code.pm) and bare
# links. Moved from BlowfishCMS.pm in 0.40.3; the functions keep their names.
#
#   render_markdown(TEXT)        the HTML, remembered per worker by its text
#   markdown_html(TEXT)          the HTML, worked out afresh
#   markdown_inline_html(TEXT)   one line's HTML, without a paragraph around it
#   markdown_box_names, markdown_callouts, markdown_figure_mods,
#   markdown_button_classes      what the extras accept (for the editor's help)
use v5.36;
use utf8;
use Digest::SHA qw(sha256_hex);
use Encode qw(encode);
our $db;

# Rendered Markdown is kept per worker by its text, except when it shows a
# picture (whether that picture still exists is checked each time).
my %markdown_kept;
# Markdown to HTML, remembered per worker by the text itself, so a page shown
# again doesn't redo the work. Not remembered when the result contains a
# picture: whether that picture still exists is checked each time.
sub render_markdown ($body) {
    return $markdown_kept{$body} if defined $body && exists $markdown_kept{$body};
    my $html=markdown_html($body);
    # Not kept either when it embeds a library item: whether that's there is checked each time too.
    my $refs=markdown_embed_refs();
    if (defined $body && $html !~ /<img/ && $body !~ m{\]\(/(?:$refs)/[a-f0-9]{32}/}) {%markdown_kept=() if keys %markdown_kept>5000;$markdown_kept{$body}=$html}
    return $html;
}
# The actual Markdown conversion, in four steps:
#   1. the text is HTML-escaped, so anything typed as HTML shows as text;
#   2. markdown_extras adds, line by line, what Text::Markdown doesn't know
#      (fenced code, pipe tables, footnotes, line breaks) and gives back the
#      few characters it needs unescaped (> for quotes, " around titles);
#   3. Text::Markdown converts it, and markdown_after adds the inline extras
#      (strikethrough, bare links, footnote marks, task lists, heading ids);
#   4. HTML::Scrubber removes every tag and attribute that isn't on its list,
#      and checks the values of the ones that are: links only to http(s),
#      mailto, this site or an anchor, pictures only from this site's media
#      (image_path), ids and classes only of the shapes made here.
# Footnotes' ids carry 8 hex digits of the text's sha256, so two texts on one
# page (two blocks) never share one, and the result can still be cached.
sub markdown_html ($body) {
    require Text::Markdown;require HTML::Scrubber;
    my (%notes,@order,%blocks,@embeds);my $key=substr(sha256_hex(encode('UTF-8',$body//'')),0,8);
    # U+F8FE and U+F8FF mark the placeholders below; typed ones are taken out.
    my $html=markdown_render(h($body) =~ tr/\x{F8FE}\x{F8FF}//dr,\%notes,\%blocks);
    $html=markdown_after($html,\%notes,$key,\@order,\@embeds);
    if (@order) {
        $html.='<section class="footnotes"><ol>'.join('',map {'<li id="fn-'.$key.'-'.$_.'">'.markdown_after($notes{$_},{},$key,[])
            .' <a href="#fnref-'.$key.'-'.$_.'" class="fn-back" title="Back to the text">↩</a></li>'} @order).'</ol></section>';
    }
    my $one=sub ($re) {return sub {my $v=$_[3]//'';return $v =~ $re ? $v : ''}};
    # A class attribute passes only when every class in it is one of these.
    my $classes=sub (@ok) {my %ok=map {($_=>1)} @ok;return sub {my $v=$_[3]//'';my @c=split / /,$v;return (@c && !grep {!$ok{$_}} @c) ? $v : ''}};
    my $note_id=$one->(qr/\Afn(?:ref)?-[a-f0-9]{8}-[A-Za-z0-9_-]{1,30}\z/);
    my $align=$one->(qr/\Aalign-(?:left|center|right)\z/);
    my $scrub = HTML::Scrubber->new(allow=>[qw(p br hr h1 h2 h3 h4 h5 h6 strong em del blockquote ul ol li pre code a img table thead tbody tr th td input sup section
            mark sub kbd div details summary figure figcaption dl dt dd)],
        default=>[0,{ '*' => 0 }], rules=>[
        a=>{href=>sub { my $v=$_[3] // ''; return $v =~ m{\A(?:https?://|mailto:|/(?!/)|\#)}i ? $v : '' }, title=>1, id=>$note_id,
            class=>$classes->('fn-back',markdown_button_classes())},
        img=>{src=>sub { image_path($_[3]) ? $_[3] : '' }, alt=>1, title=>1},
        (map {($_=>{id=>sub {my $v=$_[3]//'';return anchor_ok($v) ? $v : ''}})} qw(h1 h2 h3 h4 h5 h6)),
        li=>{id=>$note_id, class=>$one->(qr/\Atask\z/)},
        input=>{type=>$one->(qr/\Acheckbox\z/), checked=>1, disabled=>1},
        th=>{class=>$align}, td=>{class=>$align},
        sup=>{class=>$one->(qr/\Afn-ref\z/)},
        section=>{class=>$one->(qr/\Afootnotes\z/)},
        blockquote=>{class=>$classes->('callout',map {"callout--$_"} markdown_callouts())},
        p=>{class=>$one->(qr/\Acallout__title\z/)},
        div=>{class=>$classes->((map {"md-$_"} markdown_box_names()),(map {"md-columns--$_"} 2..4),'md-col','md-fold__body')},
        details=>{class=>$one->(qr/\Amd-fold\z/)},
        figure=>{class=>$classes->('md-figure',map {"md-figure--$_"} markdown_figure_mods())},
        dl=>{class=>$one->(qr/\Amd-dl\z/)},
        code=>{class=>$one->(qr/\Alang-[a-z]+\z/)},
        span=>{class=>$classes->(map {"tok-$_"} qw(k s c n v t a ins del))},
    ]);
    $html=$scrub->scrub($html);
    # The embedded library items (markdown_after left a placeholder for each):
    # the core's own player or download card, so they need no place on the list.
    $html =~ s{\x{F8FE}(\d+)\x{F8FE}}{$embeds[$1]//''}ge;
    return $html;
}
# The libraries whose items a text can embed, keyed by the first word of an
# item's address (/video/ID/, its page in item_kinds): the library, and how
# its block draws one item. Pictures aren't here: a text shows a picture by
# its address, as a figure. A new library with item pages joins with a line
# here, and the editor's "library" dialog (markdown_library_json) offers it.
sub markdown_embed_kinds {
    state $kinds={
        video=>{kind=>'video',html=>sub ($u) {video_list_html([$u],0)}},
        # A track is its player only: no title, artwork or download.
        track=>{kind=>'music',html=>sub ($u) {track_player_html($u)}},
        file=>{kind=>'file',html=>sub ($u) {file_list_html([$u])}},
    };
    return $kinds;
}
# Those first words as a regex alternation (video|track|file).
sub markdown_embed_refs { return join '|',sort keys %{markdown_embed_kinds()} }
# A library item embedded in a text: ![Caption](/video/ID/), /track/ID/ or
# /file/ID/ (the address of its page) alone on its line: a video or file as the
# Video and Download blocks draw one, a track as its player alone; the caption
# under it; nothing when it isn't there or isn't public, or without a catalogue to look in.
sub markdown_embed ($ref,$id,$caption) {
    my $embed=markdown_embed_kinds()->{$ref} or return '';
    my $item=$db ? (attempt {item_find($embed->{kind},$id)}) : undef;
    return '' unless $item;
    return '<figure class="md-embed md-embed--'.$ref.'">'.$embed->{html}->($item->{row}).(length $caption ? "<figcaption>$caption</figcaption>" : '').'</figure>';
}
# The fixed lists the page tools choose from (every class a theme can style).
# ::: containers: alignment, text size, a box, the theme's tones, columns.
sub markdown_box_names { return qw(center right lead small muted box soft accent dark light columns) }
# > [!TYPE] callouts, as GitHub names them.
sub markdown_callouts { return qw(note tip important warning caution) }
# {.small .left .round} after a picture alone on its line.
sub markdown_figure_mods { return qw(small medium left right center round) }
# {.button .outline .large} after a link: the classes cta_html gives the Button block.
sub markdown_button_classes { return ('cta','form-submit',(map {"cta--$_->[0]"} button_colours()),'cta--small','cta--large','cta--full') }
# Escaped Markdown to HTML, before the inline extras: markdown_extras, then
# Text::Markdown, then the blocks markdown_extras set aside (containers,
# fold-outs, definition lists: HTML Text::Markdown mustn't touch) put back
# where their placeholders (a private-use character round a number) are.
sub markdown_render ($text,$notes,$blocks) {
    my $html=markdown_code_fix(Text::Markdown::markdown(markdown_extras($text,$notes,$blocks)));
    $html =~ s{<p>\x{F8FF}(\d+)\x{F8FF}</p>}{$blocks->{$1}//''}ge;
    return $html;
}
# Inline Markdown (a definition, a fold-out's title): no paragraph around it.
sub markdown_inline_html ($text) {
    my $html=markdown_code_fix(Text::Markdown::markdown($text));
    $html =~ s{\A\s*<p>((?:(?!</?p>).)*)</p>\s*\z}{$1}s;
    return $html =~ s/\A\s+|\s+\z//gr;
}
# Text already escaped is escaped again inside code; undo that once.
sub markdown_code_fix ($html) {
    $html =~ s{<code>(.*?)</code>}{my $c=$1;$c =~ s/&amp;(quot|lt|gt|amp|#39);/&$1;/g;"<code>$c</code>"}gse;
    return $html;
}
# What Text::Markdown doesn't know, written the way GitHub does, done line by
# line on the escaped text (so the tags made here are the only tags):
#   - ``` fenced code becomes the indented code it understands;
#   - | pipe | tables | become tables, each cell inline Markdown, aligned by
#     their separator line (:--- left, :---: centre, ---: right);
#   - [^name]: footnote definitions are taken out into %$notes (with lines
#     indented under them), drawn as Markdown; markdown_after numbers them;
#   - a quote's > marks, and the quotes around a link's or picture's title,
#     are given back unescaped, as Text::Markdown needs them;
#   - a backslash at the end of a line is a line break;
#   - the page tools, drawn here and set aside in %$blocks (markdown_render
#     puts them back): "::: NAMES" … ":::" containers (markdown_box_names;
#     "columns" splits at ||| lines, up to four), "+++ Title" … "+++"
#     fold-outs, and definition lists (a line, then lines starting ": ").
#     Containers and fold-outs nest, and hold any Markdown; one with no
#     closing line is left as text.
# Lines indented as code keep their backslashes and marks as they are.
sub markdown_extras ($text,$notes={},$blocks={}) {
    my @in=split /\n/,$text,-1;my @out;
    # Finished HTML goes in %$blocks; its place is a placeholder paragraph.
    my $set_aside=sub ($html) {my $n=keys %$blocks;$blocks->{$n}=$html;push @out,'',"\x{F8FF}$n\x{F8FF}",''};
    # The lines up to the matching closing line (nested ones counted), taken
    # out of @in; undef, leaving @in alone, when it never closes.
    my $gather=sub ($open,$close) {
        my $depth=1;
        for my $i (0..$#in) {
            if ($in[$i] =~ $close) {next if --$depth;my @inner=splice @in,0,$i+1;pop @inner;return \@inner}
            $depth++ if $in[$i] =~ $open;
        }
        return undef;
    };
    my ($box_open,$box_close)=(qr/\A {0,3}:{3,}[ \t]*[a-z]/,qr/\A {0,3}:{3,}[ \t]*\z/);
    my ($fold_open,$fold_close)=(qr/\A {0,3}\+{3,}[ \t]+\S/,qr/\A {0,3}\+{3,}[ \t]*\z/);
    my %box_ok=map {($_=>1)} markdown_box_names();
    while (@in) {
        my $line=shift @in;
        # ```perl … ```: a block of code, coloured when the fence names a
        # language code_language_named knows (Code.pm), else plain.
        if ($line =~ /\A\s{0,3}(```+|~~~+)[ \t]*([A-Za-z0-9_+#.-]*)/) {
            my ($fence,$word)=($1,$2);my @code;
            while (@in && $in[0] !~ /\A\s{0,3}\Q$fence\E\s*\z/) {push @code,shift @in}
            shift @in;
            my $lang=code_language_named($word);
            my $raw=join("\n",@code) =~ s/&lt;/</gr =~ s/&gt;/>/gr =~ s/&quot;/"/gr =~ s/&#39;/'/gr =~ s/&amp;/&/gr;
            $set_aside->('<pre><code'.(length $lang ? qq{ class="lang-$lang"} : '').'>'.(length $lang ? code_highlight($lang,$raw) : h($raw)."\n").'</code></pre>');
            next;
        }
        if ($line =~ /\A {0,3}:{3,}[ \t]*([a-z][a-z0-9 \t-]*?)[ \t]*\z/) {
            my @names=grep {$box_ok{$_}} split /[ \t]+/,$1;
            if (@names && (my $inner=$gather->($box_open,$box_close))) {
                my $class=join ' ',map {"md-$_"} grep {$_ ne 'columns'} @names;
                if (grep {$_ eq 'columns'} @names) {
                    my @cols=([]);
                    for my $l (@$inner) {if ($l =~ /\A[ \t]*\|\|\|[ \t]*\z/ && @cols<4) {push @cols,[]} else {push @{$cols[-1]},$l}}
                    $set_aside->('<div class="'.join(' ',grep {length} $class,'md-columns','md-columns--'.(@cols<2 ? 2 : scalar @cols)).'">'
                        .join('',map {'<div class="md-col">'.markdown_render(join("\n",@$_),$notes,$blocks).'</div>'} @cols).'</div>');
                } else {$set_aside->('<div class="'.$class.'">'.markdown_render(join("\n",@$inner),$notes,$blocks).'</div>')}
                next;
            }
        }
        if ($line =~ /\A {0,3}\+{3,}[ \t]+(\S.*?)[ \t]*\z/) {
            my $title=$1;
            if (my $inner=$gather->($fold_open,$fold_close)) {
                $set_aside->('<details class="md-fold"><summary>'.markdown_inline_html($title).'</summary><div class="md-fold__body">'.markdown_render(join("\n",@$inner),$notes,$blocks).'</div></details>');
                next;
            }
        }
        # Term, then ": what it means" lines; a blank line and another term carry the list on.
        if ($line =~ /\S/ && $line !~ /\A(?: {4}|\t|\s*(?:[-*+#|]|&gt;|\d+[.)]\s))/ && @in && $in[0] =~ /\A:[ \t]+\S/) {
            my @items;
            while (1) {
                my @defs;push @defs,shift(@in) =~ s/\A:[ \t]+//r while @in && $in[0] =~ /\A:[ \t]+\S/;
                push @items,[$line,\@defs];
                last unless @in>=3 && $in[0] !~ /\S/ && $in[1] =~ /\S/ && $in[2] =~ /\A:[ \t]+\S/;
                shift @in;$line=shift @in;
            }
            $set_aside->('<dl class="md-dl">'.join('',map {'<dt>'.markdown_inline_html($_->[0]).'</dt>'.join('',map {'<dd>'.markdown_inline_html($_).'</dd>'} @{$_->[1]})} @items).'</dl>');
            next;
        }
        my $sep=qr/\A\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)*\|?\s*\z/;
        if ($line =~ /\|/ && $line !~ /\A(?: {4}|\t)/ && @in && $in[0] =~ $sep && $in[0] =~ /\|/) {
            my $rule=shift @in;my @rows;
            push @rows,shift @in while @in && $in[0] =~ /\|/ && $in[0] =~ /\S/;
            my $trim=sub ($l) {$l =~ s/\A\s*\|//;$l =~ s/\|\s*\z//;return $l};
            my @align=map {my $c=s/\A\s+|\s+\z//gr;$c =~ /\A:-+:\z/ ? 'center' : $c =~ /-:\z/ ? 'right' : $c =~ /\A:/ ? 'left' : ''} split /\|/,$trim->($rule);
            my $cells=sub ($l,$tag) {
                my @c=map {my $c=Text::Markdown::markdown(s/\A\s+|\s+\z//gr);$c =~ s{\A\s*<p>|</p>\s*\z}{}g;$c} split /\|/,$trim->($l);
                return join '',map {my $al=$align[$_]//'';"<$tag".(length $al ? qq{ class="align-$al"} : '').">$c[$_]</$tag>"} 0..$#c;
            };
            push @out,'','<table><thead><tr>'.$cells->($line,'th').'</tr></thead><tbody>'
                .join('',map {'<tr>'.$cells->($_,'td').'</tr>'} @rows).'</tbody></table>','';next;
        }
        if ($line =~ /\A {0,3}\[\^([A-Za-z0-9_-]{1,30})\]:[ \t]*(.*)\z/) {
            my ($name,@note)=($1,$2);
            # Its lines indented under it, and blank lines between them, are part of it.
            while (@in && ($in[0] =~ /\A(?: {4}|\t)/ || ($in[0] !~ /\S/ && @in>1 && $in[1] =~ /\A(?: {4}|\t)/))) {push @note,shift(@in) =~ s/\A(?: {4}|\t)//r}
            $notes->{$name}//=do {my $n=markdown_code_fix(Text::Markdown::markdown(join "\n",@note));$n =~ s{\A\s*<p>((?:(?!</?p>).)*)</p>\s*\z}{$1}s;$n =~ s/\A\s+|\s+\z//gr};
            next;
        }
        unless ($line =~ /\A(?: {4}|\t)/) {
            # A callout starts a quotation of its own: Text::Markdown would
            # join it to a quotation just before it, blank line or not, so an
            # empty block goes between them.
            if ($line =~ /\A {0,3}&gt; ?\[![A-Za-z]+\]/ && (grep {/\S/} @out)[-1] =~ /\A {0,3}>/) {$set_aside->('')}
            if ($line =~ /\A( {0,3})((?:&gt; ?)+)/) {my ($pad,$marks)=($1,$2);substr($line,0,length($pad.$marks))=$pad.($marks =~ s/&gt;/>/gr)}
            # [text](address "title"), ![alt](address 'title') and [id]: address "title".
            $line =~ s{(\]\(\s*[^\s()]+)\s+(&quot;|&#39;)((?:(?!\2).)*)\2\s*\)}{$1 "$3")}g;
            $line =~ s{\A(\s{0,3}\[[^\]]+\]:\s*\S+)\s+(&quot;|&#39;)((?:(?!\2).)*)\2\s*\z}{$1 "$3"};
            $line =~ s/(?<!\\)\\\z/  /;
        }
        push @out,$line;
    }
    # Blank lines at the very start go: after exactly one, Text::Markdown
    # takes indented code for a paragraph (a text starting with ``` code).
    return join("\n",@out) =~ s/\A(?:[ \t]*\n)+//r;
}
# The inline extras, done on Text::Markdown's HTML. Only text between tags
# is changed, and never inside code: ~~strikethrough~~, footnote marks
# [^name] (numbered in the order they first appear, into @$order), and bare
# web addresses made links (not inside a link already). Then the block
# extras: "- [ ]" and "- [x]" list items become tick boxes, and a heading
# ending in {#name} gets that id (when it's a usable anchor; otherwise the
# mark stays, so the writer sees it didn't work).
sub markdown_after ($html,$notes,$key,$order,$embeds=[]) {
    # How deep inside code and links the text so far is.
    my ($code,$link)=(0,0);
    my $seen=sub ($tag) {
        my ($close,$name)=$tag =~ m{\A<(/?)([a-zA-Z]+)};
        if (defined $name) {$name=lc $name;my $d=$close ? -1 : 1;$code+=$d if $name eq 'pre' || $name eq 'code';$link+=$d if $name eq 'a'}
        return $tag;
    };
    $html =~ s{(<[^>]*>)|([^<]+)}{defined $1 ? $seen->($1) : $code>0 ? $2 : markdown_text_extras($2,$link>0,$notes,$key,$order)}ge;
    $html =~ s{<li>(\s*(?:<p>)?)\[([ xX])\]\s+}{my ($p,$x)=($1,$2);'<li class="task">'.$p.'<input type="checkbox" disabled'.($x eq ' ' ? '' : ' checked').'> '}ge;
    $html =~ s{<h([1-6])>(.*?)\s*\{#([a-z][a-z0-9-]{0,39})\}\s*</h\1>}{my ($n,$t,$id)=($1,$2,$3);anchor_ok($id) ? qq{<h$n id="$id">$t</h$n>} : "<h$n>$t {#$id}</h$n>"}ge;
    # > [!NOTE] (or TIP, IMPORTANT, WARNING, CAUTION), a title after it if
    # wanted: the quotation becomes a callout box, its first line a title.
    my %callout=map {($_=>1)} markdown_callouts();
    $html =~ s{<blockquote>(\s*)<p>\[!([A-Za-z]+)\][ \t]*([^\n<]*?)[ \t]*(\n\s*|(?=</p>))}{
        my ($sp,$type,$title,$rest)=($1,lc $2,$3,$4);
        $callout{$type} ? qq{<blockquote class="callout callout--$type">$sp<p class="callout__title">}.(length $title ? $title : ucfirst $type).'</p><p>' : $&
    }ge;
    $html =~ s{<p>\s*</p>}{}g;
    # [Words](/address/){.button .outline .large}: a button, as the Button block draws one.
    $html =~ s{<a (href="[^"]*"(?: title="[^"]*")?)>((?:(?!</a>).)*)</a>\{([^{}\n]{1,80})\}}{
        my ($attrs,$words,$mods)=($1,$2,$3);my %m=map {($_=>1)} $mods =~ /\.([a-z]+)/g;
        if ($m{button}) {
            my ($style)=grep {$m{$_}} map {$_->[0]} button_colours();$style//='primary';
            my ($size)=grep {$m{$_}} qw(small large);
            my $class=join ' ','cta',"cta--$style",($style eq 'theme' ? 'form-submit' : ()),($size ? "cta--$size" : ()),($m{full} ? 'cta--full' : ());
            qq{<a class="$class" $attrs>$words</a>};
        } else {"<a $attrs>$words</a>{$mods}"}
    }ge;
    # A library video, track or file alone on its line: a placeholder for
    # markdown_embed's player or card, put in after the scrubber.
    my $refs=markdown_embed_refs();
    $html =~ s{<p><img src="/($refs)/([a-f0-9]{32})/" alt="([^"]*)"[^>]*>(?:\{[^{}\n]{0,80}\})?</p>}{
        my ($ref,$id,$caption)=($1,$2,$3);push @$embeds,markdown_embed($ref,$id,$caption);"\x{F8FE}$#$embeds\x{F8FE}"
    }ge;
    # A picture alone on its line is a figure: its title is the caption, and
    # {.small .left .round} after it sets its size, side and shape.
    my %fig=map {($_=>1)} markdown_figure_mods();
    $html =~ s{<p>(<img [^>]*>)(?:\{([^{}\n]{1,80})\})?</p>}{
        my ($img,$mods)=($1,$2//'');my ($title)=$img =~ /\stitle="([^"]*)"/;
        my @mods=grep {$fig{$_}} $mods =~ /\.([a-z]+)/g;
        '<figure class="'.join(' ','md-figure',map {"md-figure--$_"} @mods).'">'.$img.(length($title//'') ? "<figcaption>$title</figcaption>" : '').'</figure>';
    }ge;
    return $html;
}
# The inline extras for one piece of text (see markdown_after).
sub markdown_text_extras ($s,$in_link,$notes,$key,$order) {
    $s =~ s{~~(?=\S)(.+?)(?<=\S)~~}{<del>$1</del>}g;
    # ==highlighted==, H~2~O, x^2^ and [[Ctrl]] keys.
    $s =~ s{==(?=\S)(.+?)(?<=\S)==}{<mark>$1</mark>}g;
    $s =~ s{~([^~\s<>]{1,20})~}{<sub>$1</sub>}g;
    $s =~ s{\^([^\^\s<>\[\]]{1,20})\^}{<sup>$1</sup>}g;
    $s =~ s{\[\[([^\[\]\n<>]{1,30})\]\]}{<kbd>$1</kbd>}g;
    return $s if $in_link;
    $s =~ s{\[\^([A-Za-z0-9_-]{1,30})\]}{my $name=$1;exists $notes->{$name} ? markdown_note_mark($name,$key,$order) : "[^$name]"}ge;
    $s =~ s{(?<![\w/])(https?://(?:(?!&(?:lt|gt|quot|#39);)[^\s<>])+)}{markdown_autolink($1)}ge;
    return $s;
}
# A footnote's mark: its number, linking down to the note. Its first mark
# has the id the note links back to.
sub markdown_note_mark ($name,$key,$order) {
    my $first=!grep {$_ eq $name} @$order;
    push @$order,$name if $first;
    my ($n)=grep {$order->[$_] eq $name} 0..$#$order;
    return '<sup class="fn-ref"><a href="#fn-'.$key.'-'.$name.'"'.($first ? ' id="fnref-'.$key.'-'.$name.'"' : '').'>'.($n+1).'</a></sup>';
}
# A bare web address as a link. Punctuation after it (a full stop, a comma,
# a closing bracket it didn't open) stays outside.
sub markdown_autolink ($url) {
    my $tail='';
    while (length $url) {
        my $c=substr($url,-1);
        last unless index('.,;:!?*_~',$c)>=0 || ($c eq ')' && ($url =~ tr/(//) < ($url =~ tr/)//));
        $tail=$c.$tail;chop $url;
    }
    return ($url =~ m{\Ahttps?://[^/\s.]} ? qq{<a href="$url">$url</a>} : $url).$tail;
}

1;