]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/color.pm
color: Use markup for the preserved CSS, not character data
[git.ikiwiki.info.git] / IkiWiki / Plugin / color.pm
1 #!/usr/bin/perl
2 # Ikiwiki text colouring plugin
3 # Paweł‚ Tęcza <ptecza@net.icm.edu.pl>
4 package IkiWiki::Plugin::color;
6 use warnings;
7 use strict;
8 use IkiWiki 3.00;
10 sub import {
11         hook(type => "preprocess", id => "color", call => \&preprocess);
12         hook(type => "format",     id => "color", call => \&format);
13         hook(type => "getsetup",   id => "color", call => \&getsetup);
14 }
16 sub getsetup () {
17         return
18                 plugin => {
19                         safe => 1,
20                         rebuild => undef,
21                         section => "widget",
22                 },
23 }
25 sub preserve_style ($$$) {
26         my $foreground = shift;
27         my $background = shift;
28         my $text       = shift;
30         $foreground = defined $foreground ? lc($foreground) : '';
31         $background = defined $background ? lc($background) : '';
32         $text       = '' unless (defined $text);
34         # Validate colors. Only color name or color code are valid.
35         $foreground = '' unless ($foreground &&
36                                 ($foreground =~ /^[a-z]+$/ || $foreground =~ /^#[0-9a-f]{3,6}$/));
37         $background = '' unless ($background &&
38                                 ($background =~ /^[a-z]+$/ || $background =~ /^#[0-9a-f]{3,6}$/));
40         my $preserved = '';
41         $preserved .= '<span class="color"><span value="';
42         $preserved .= 'color: '.$foreground if ($foreground);
43         $preserved .= '; ' if ($foreground && $background);
44         $preserved .= 'background-color: '.$background if ($background);
45         $preserved .= '"></span>'.$text.'</span>';
46         
47         return $preserved;
49 }
51 sub replace_preserved_style ($) {
52         my $content = shift;
54         $content =~ s!<span class="color">\s*<span value="((color: ([a-z]+|\#[0-9a-f]{3,6})?)?((; )?(background-color: ([a-z]+|\#[0-9a-f]{3,6})?)?)?)">\s*</span>!<span class="color" style="$1">!g;
56         return $content;
57 }
59 sub preprocess (@) {
60         my %params = @_;
62         return preserve_style($params{foreground}, $params{background},
63                 # Preprocess the text to expand any preprocessor directives
64                 # embedded inside it.
65                 IkiWiki::preprocess($params{page}, $params{destpage},
66                         $params{text}));
67 }
69 sub format (@) {
70         my %params = @_;
72         $params{content} = replace_preserved_style($params{content});
73         return $params{content};        
74 }
76 1