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