summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/color.pm
blob: ac702ff026052e34b780ec380cf3cc048b7443bc (plain)
  1. #!/usr/bin/perl
  2. # Ikiwiki text colouring plugin
  3. # Paweł‚ Tęcza <ptecza@net.icm.edu.pl>
  4. package IkiWiki::Plugin::color;
  5. use warnings;
  6. use strict;
  7. use IkiWiki 2.00;
  8. sub import { #{{{
  9. hook(type => "preprocess", id => "color", call => \&preprocess);
  10. hook(type => "format", id => "color", call => \&format);
  11. } #}}}
  12. sub preserve_style ($$$) { #{{{
  13. my $foreground = shift;
  14. my $background = shift;
  15. my $text = shift;
  16. $foreground = defined $foreground ? lc($foreground) : '';
  17. $background = defined $background ? lc($background) : '';
  18. $text = '' unless (defined $text);
  19. # Validate colors. Only color name or color code are valid.
  20. $foreground = '' unless ($foreground &&
  21. ($foreground =~ /^[a-z]+$/ || $foreground =~ /^#[0-9a-f]{3,6}$/));
  22. $background = '' unless ($background &&
  23. ($background =~ /^[a-z]+$/ || $background =~ /^#[0-9a-f]{3,6}$/));
  24. my $preserved = '';
  25. $preserved .= '<span class="color">';
  26. $preserved .= 'color: '.$foreground if ($foreground);
  27. $preserved .= '; ' if ($foreground && $background);
  28. $preserved .= 'background-color: '.$background if ($background);
  29. $preserved .= '</span>';
  30. $preserved .= '<span class="colorend">'.$text.'</span>';
  31. return $preserved;
  32. } #}}}
  33. sub replace_preserved_style ($) { #{{{
  34. my $content = shift;
  35. $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;
  36. $content =~ s!<span class="colorend">!!g;
  37. return $content;
  38. } #}}}
  39. sub preprocess (@) { #{{{
  40. my %params = @_;
  41. # Preprocess the text to expand any preprocessor directives
  42. # embedded inside it.
  43. $params{text} = IkiWiki::preprocess($params{page}, $params{destpage},
  44. IkiWiki::filter($params{page}, $params{destpage}, $params{text}));
  45. return preserve_style($params{foreground}, $params{background}, $params{text});
  46. } #}}}
  47. sub format (@) { #{{{
  48. my %params = @_;
  49. $params{content} = replace_preserved_style($params{content});
  50. return $params{content};
  51. } #}}}
  52. 1