summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/color.pm
blob: 9bb2359ce6f45f9ba452ad400aa48fc2c204584e (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 3.00;
  8. sub import {
  9. hook(type => "preprocess", id => "color", call => \&preprocess);
  10. hook(type => "format", id => "color", call => \&format);
  11. hook(type => "getsetup", id => "color", call => \&getsetup);
  12. }
  13. sub getsetup () {
  14. return
  15. plugin => {
  16. safe => 1,
  17. rebuild => undef,
  18. section => "widget",
  19. },
  20. }
  21. sub preserve_style ($$$) {
  22. my $foreground = shift;
  23. my $background = shift;
  24. my $text = shift;
  25. $foreground = defined $foreground ? lc($foreground) : '';
  26. $background = defined $background ? lc($background) : '';
  27. $text = '' unless (defined $text);
  28. # Validate colors. Only color name or color code are valid.
  29. $foreground = '' unless ($foreground &&
  30. ($foreground =~ /^[a-z]+$/ || $foreground =~ /^#[0-9a-f]{3,6}$/));
  31. $background = '' unless ($background &&
  32. ($background =~ /^[a-z]+$/ || $background =~ /^#[0-9a-f]{3,6}$/));
  33. my $preserved = '';
  34. $preserved .= '<span class="color">';
  35. $preserved .= 'color: '.$foreground if ($foreground);
  36. $preserved .= '; ' if ($foreground && $background);
  37. $preserved .= 'background-color: '.$background if ($background);
  38. $preserved .= '</span>';
  39. $preserved .= '<span class="colorend">'.$text.'</span>';
  40. return $preserved;
  41. }
  42. sub replace_preserved_style ($) {
  43. my $content = shift;
  44. $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;
  45. $content =~ s!<span class="colorend">!!g;
  46. return $content;
  47. }
  48. sub preprocess (@) {
  49. my %params = @_;
  50. return preserve_style($params{foreground}, $params{background},
  51. # Preprocess the text to expand any preprocessor directives
  52. # embedded inside it.
  53. IkiWiki::preprocess($params{page}, $params{destpage},
  54. $params{text}));
  55. }
  56. sub format (@) {
  57. my %params = @_;
  58. $params{content} = replace_preserved_style($params{content});
  59. return $params{content};
  60. }
  61. 1