]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/color.pm
Whoops, copyright 2009. /usr/bin/perl for the interpreter like other plugins.
[ikiwiki.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;
5
6 use warnings;
7 use strict;
8 use IkiWiki 3.00;
9
10 sub import {
11         hook(type => "preprocess", id => "color", call => \&preprocess);
12         hook(type => "format",     id => "color", call => \&format);
13 }
14
15 sub preserve_style ($$$) {
16         my $foreground = shift;
17         my $background = shift;
18         my $text       = shift;
19
20         $foreground = defined $foreground ? lc($foreground) : '';
21         $background = defined $background ? lc($background) : '';
22         $text       = '' unless (defined $text);
23
24         # Validate colors. Only color name or color code are valid.
25         $foreground = '' unless ($foreground &&
26                                 ($foreground =~ /^[a-z]+$/ || $foreground =~ /^#[0-9a-f]{3,6}$/));
27         $background = '' unless ($background &&
28                                 ($background =~ /^[a-z]+$/ || $background =~ /^#[0-9a-f]{3,6}$/));
29
30         my $preserved = '';
31         $preserved .= '<span class="color">';
32         $preserved .= 'color: '.$foreground if ($foreground);
33         $preserved .= '; ' if ($foreground && $background);
34         $preserved .= 'background-color: '.$background if ($background);
35         $preserved .= '</span>';
36         $preserved .= '<span class="colorend">'.$text.'</span>';
37         
38         return $preserved;
39
40 }
41
42 sub replace_preserved_style ($) {
43         my $content = shift;
44
45         $content =~ s!<span class="color">((color: ([a-z]+|\#[0-9a-f]{3,6})?)?((; )?(background-color: ([a-z]+|\#[0-9a-f]{3,6})?)?)?)</span>!<span class="color" style="$1">!g;
46         $content =~ s!<span class="colorend">!!g;
47
48         return $content;
49 }
50
51 sub preprocess (@) {
52         my %params = @_;
53
54         # Preprocess the text to expand any preprocessor directives
55         # embedded inside it.
56         $params{text} = IkiWiki::preprocess($params{page}, $params{destpage},
57                                 IkiWiki::filter($params{page}, $params{destpage}, $params{text}));
58
59         return preserve_style($params{foreground}, $params{background}, $params{text});
60 }
61
62 sub format (@) {
63         my %params = @_;
64
65         $params{content} = replace_preserved_style($params{content});
66         return $params{content};        
67 }
68
69 1