BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
110 lines · 8.5 KB · download this file
package BlowfishCMS;
# Code colouring, done on the server so pages need no script: a text drawn
# with its keywords, strings, comments, numbers and the like as
# <span class="tok-X"> (site.css colours them from the theme). Used by
# Markdown's fenced code with a language (```perl) and by the Repositories
# add-on for a repository's files (with numbered lines). Moved from that
# add-on in 0.40.
#
# Each language is a list of [class, pattern] rules tried in order at each
# point of the text, then words (keywords get class k) and single
# characters. Classes: k keyword, s string, c comment, n number, v variable,
# t tag, a attribute or key, ins and del (a diff's lines). Patterns use no
# capturing groups (the rule that matched is found by its group number).
# Texts over 256 KB, or in no known language, are left plain.
use v5.36;
use utf8;
my $DQ=qr/"(?:[^"\\]|\\.)*"/s;my $SQ=qr/'(?:[^'\\]|\\.)*'/s;my $BQ=qr/`(?:[^`\\]|\\.)*`/s;
my $DQ1=qr/"(?:[^"\\\n]|\\.)*"/;my $SQ1=qr/'(?:[^'\\\n]|\\.)*'/;
my $NUM=qr/\b(?:0[xX][\da-fA-F_]+|\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?)\b/;
my $SLASH=[c=>qr{//[^\n]*}];my $BLOCK=[c=>qr{/\*.*?(?:\*/|\z)}s];
my %LANG=(
perl=>{rules=>[[v=>qr/\$#?\{\^?\w+\}|\$#?[A-Za-z_][\w:]*|[\@%][A-Za-z_][\w:]*|\$[^\w\s{(]/],[c=>qr/^=[a-zA-Z].*?(?:^=cut\b[^\n]*|\z)/ms],[c=>qr/#[^\n]*/],[s=>$DQ],[s=>$SQ],[n=>$NUM]],
keywords=>[qw(my our local sub return if elsif else unless while until for foreach last next redo package use no require do eval die warn print say and or not xor eq ne lt gt le ge cmp undef defined ref scalar shift push pop unshift splice keys values each delete exists grep map sort reverse join split open close binmode chomp substr length lc uc sprintf printf wantarray BEGIN END __END__ __DATA__ qw qq qr)]},
sh=>{rules=>[[c=>qr/(?<![^\s;|&(])#[^\n]*/],[v=>qr/\$(?:\{[^}\n]*\}|\w+|[#?@*!\$0-9-])/],[s=>$DQ],[s=>$SQ],[n=>$NUM]],
keywords=>[qw(if then else elif fi for in do done while until case esac function return local export readonly set unset shift exit break continue trap eval exec test echo printf read cd)]},
python=>{rules=>[[c=>qr/#[^\n]*/],[s=>qr/(?:[rRbBfFuU]{1,2})?(?:"""(?:[^\\]|\\.)*?"""|'''(?:[^\\]|\\.)*?''')/s],[s=>qr/(?:[rRbBfFuU]{1,2})?(?:$DQ1|$SQ1)/],[v=>qr/@[\w.]+/],[n=>$NUM]],
keywords=>[qw(def class return if elif else for while in not and or is None True False import from as with try except finally raise pass break continue lambda yield global nonlocal assert del async await self)]},
js=>{rules=>[$SLASH,$BLOCK,[s=>$DQ1],[s=>$SQ1],[s=>$BQ],[n=>$NUM]],
keywords=>[qw(const let var function return if else for while do switch case break continue new this class extends super import export from default try catch finally throw typeof instanceof in of async await yield null undefined true false void delete static get set interface type enum implements)]},
c=>{rules=>[$SLASH,$BLOCK,[k=>qr/^[ \t]*#[ \t]*\w+/m],[s=>$DQ1],[s=>$SQ1],[n=>$NUM]],
keywords=>[qw(int char void return if else for while do switch case break continue struct typedef static const unsigned signed long short double float sizeof enum union extern goto fn let mut pub impl use mod match package func var type import true false nil null new class public private protected interface go defer range chan map self Self where trait)]},
css=>{rules=>[$BLOCK,[s=>$DQ1],[s=>$SQ1],[k=>qr/@[\w-]+/],[a=>qr/[\w-]+(?=\s*:[^:{]*[;}])/],[n=>qr/#[\da-fA-F]{3,8}\b|-?\b\d*\.?\d+(?:px|em|rem|%|vh|vw|vmin|vmax|s|ms|fr|deg|ch|ex)?\b/]],keywords=>[qw(important)]},
html=>{rules=>[[c=>qr/<!--.*?(?:-->|\z)/s],[k=>qr/<![A-Za-z][^>]*>|<\?.*?\?>/s],[tag=>qr/<\/?[A-Za-z][^>]*>/s],[n=>qr/&#?\w+;/]]},
json=>{rules=>[[a=>qr/$DQ1(?=\s*:)/],[s=>$DQ1],[n=>qr/-?$NUM/]],keywords=>[qw(true false null)]},
yaml=>{rules=>[[c=>qr/(?<![^\s])#[^\n]*/],[a=>qr/^[ \t-]*[\w.\/-]+(?=[ \t]*:(?:[ \t]|$))/m],[s=>$DQ1],[s=>$SQ1],[n=>$NUM]],keywords=>[qw(true false null yes no on off)]},
ini=>{rules=>[[c=>qr/^[ \t]*[#;][^\n]*/m],[k=>qr/^[ \t]*\[[^\]\n]*\]/m],[a=>qr/^[ \t]*[\w.-]+(?=[ \t]*=)/m],[s=>$DQ1],[s=>$SQ1],[n=>$NUM]],keywords=>[qw(true false)]},
make=>{rules=>[[c=>qr/#[^\n]*/],[a=>qr/^[\w.\/%-]+(?=[ \t]*::?(?!=))/m],[v=>qr/\$\([^)\n]*\)|\$\{[^}\n]*\}|\$[@<^*?]/],[s=>$DQ1],[s=>$SQ1]],
keywords=>[qw(ifeq ifneq ifdef ifndef else endif include define endef export override)]},
roff=>{rules=>[[c=>qr/^\.\\".*$|\\".*$/m],[k=>qr/^\.[A-Za-z]{1,3}\b/m],[v=>qr/\\(?:f[BIRP]|\(..|\*\(..|\*.|[-e&|^])/]]},
markdown=>{rules=>[[s=>qr/^```.*?(?:^```[^\n]*|\z)/ms],[k=>qr/^#{1,6}[ \t].*$/m],[s=>qr/`[^`\n]+`/],[a=>qr/!?\[[^\]\n]*\]\([^)\n]*\)/],[v=>qr/\*\*[^*\n]+\*\*|__[^_\n]+__/]]},
diff=>{rules=>[[k=>qr/^(?:@@|diff |index |\+\+\+|---).*$/m],[ins=>qr/^\+.*$/m],[del=>qr/^-.*$/m]]},
);
# A file's extension, or a fence's word (```javascript), to its language.
my %EXT=(pm=>'perl',pl=>'perl',t=>'perl',cgi=>'perl',psgi=>'perl',perl=>'perl',sh=>'sh',bash=>'sh',ksh=>'sh',zsh=>'sh',shell=>'sh',console=>'sh',
py=>'python',python=>'python',js=>'js',mjs=>'js',cjs=>'js',ts=>'js',tsx=>'js',jsx=>'js',javascript=>'js',typescript=>'js',
c=>'c',h=>'c',cc=>'c',cpp=>'c',hpp=>'c',go=>'c',rs=>'c',rust=>'c',java=>'c',kt=>'c',kotlin=>'c',swift=>'c',cs=>'c',csharp=>'c',
css=>'css',html=>'html',htm=>'html',xml=>'html',svg=>'html',xsl=>'html',json=>'json',yml=>'yaml',yaml=>'yaml',
ini=>'ini',conf=>'ini',cfg=>'ini',toml=>'ini',properties=>'ini',mk=>'make',make=>'make',makefile=>'make',md=>'markdown',markdown=>'markdown',diff=>'diff',patch=>'diff',
map {($_=>'roff')} 1..9,'roff','man');
# The language a fence names (```Perl, ```js), or ''.
sub code_language_named ($word) { return $EXT{lc($word//'')}//'' }
# The language of a file: by its name, or a script's first line (#!/bin/sh).
sub code_language ($name,$text) {
return 'make' if $name =~ /\A(?:GNU)?[Mm]akefile\z/;
return 'sh' if $name =~ /\A\.(?:bashrc|profile|kshrc)\z/;
my ($ext)=$name =~ /\.([A-Za-z0-9]+)\z/;
return $EXT{lc $ext} if defined $ext && $EXT{lc $ext};
# #!/bin/sh, #!/usr/bin/perl -w, #!/usr/bin/env python3: the program's own name.
if ($text =~ m{\A#![ \t]*(?:\S*/)?([a-z]+)\S*(?:[ \t]+([a-z]+))?}) {my $p=($1 eq 'env' ? $2 : $1)//'';return $p =~ /\A(?:perl)\z/ ? 'perl' : $p =~ /\A(?:sh|bash|ksh|zsh|dash)\z/ ? 'sh' : $p =~ /\Apython/ ? 'python' : $p eq 'node' ? 'js' : ''}
return '';
}
my %compiled;
# The text as HTML, escaped, with its tokens in spans. %o: lines => 1 puts
# each line in <span class="line" id="L1">…</span> (a file's page, where
# #L12 jumps to line 12); without it, the lines are as they were.
sub code_highlight ($lang,$text,%o) {
my $L=$LANG{$lang//''};
my @tok;
if ($L && length($text)<=256*1024) {
my @classes=map {$_->[0]} @{$L->{rules}};
my $re=$compiled{$lang}//=do {my $alt=join '|',map {"($_->[1])"} @{$L->{rules}};qr/\G(?:$alt)/};
my %kw=map {($_=>1)} @{$L->{keywords}//[]};
pos($text)=0;
while (pos($text)<length $text) {
if ($text =~ /$re/gc && $+[0]>$-[0]) {
my ($i)=grep {defined $-[$_+1]} 0..$#classes;
my $piece=substr($text,$-[0],$+[0]-$-[0]);
if ($classes[$i] eq 'tag') {push @tok,code_tag_tokens($piece)} else {push @tok,[$classes[$i],$piece]}
}
elsif ($text =~ /\G([A-Za-z_][\w-]*[\w]|[A-Za-z_])/gc) {push @tok,[$kw{$1} ? 'k' : '',$1]}
elsif ($text =~ /\G(\s+|[^\w\s]|\d+)/gc) {push @tok,['',$1]}
else {push @tok,['',substr($text,pos($text))];last}
}
} else {@tok=(['',$text])}
# Into lines: a token over several lines (a comment block) is cut at each end of line.
my @lines=('');
for my $t (@tok) {
my ($class,$s)=@$t;my @parts=split /\n/,$s,-1;
for my $i (0..$#parts) {
push @lines,'' if $i;
next unless length $parts[$i];
$lines[-1].=length $class ? '<span class="tok-'.$class.'">'.h($parts[$i]).'</span>' : h($parts[$i]);
}
}
pop @lines if @lines>1 && $lines[-1] eq '';
return join("\n",@lines)."\n" unless $o{lines};
return join '',map {'<span class="line" id="L'.($_+1).'">'.$lines[$_]."</span>\n"} 0..$#lines;
}
# Inside an HTML or XML tag: its name, each attribute's name and its value.
sub code_tag_tokens ($tag) {
my @t;
$tag =~ m{\A(</?)([^\s/>]+)}g;push @t,['t',$1.$2];
while ($tag =~ m{\G(?:(\s+)|([^\s=/>"']+)|(=)|("[^"]*"|'[^']*')|(/?>)|(.))}gcs) {
push @t,defined $1 ? ['',$1] : defined $2 ? ['a',$2] : defined $3 ? ['',$3] : defined $4 ? ['s',$4] : defined $5 ? ['t',$5] : ['',$6];
}
return @t;
}
1;