summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/smiley.pm
blob: fcf3048b28f34c26f7512c9407f37326fcd305b2 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki::Plugin::smiley;
  3. use warnings;
  4. use strict;
  5. use IkiWiki 2.00;
  6. my %smileys;
  7. my $smiley_regexp;
  8. sub import { #{{{
  9. add_underlay("smiley");
  10. hook(type => "filter", id => "smiley", call => \&filter);
  11. } # }}}
  12. sub build_regexp () { #{{{
  13. my $list=readfile(srcfile("smileys.mdwn"));
  14. while ($list =~ m/^\s*\*\s+\\([^\s]+)\s+\[\[([^]]+)\]\]/mg) {
  15. $smileys{$1}=$2;
  16. }
  17. if (! %smileys) {
  18. debug(gettext("failed to parse any smileys"));
  19. $smiley_regexp='';
  20. return;
  21. }
  22. # sort and reverse so that substrings come after longer strings
  23. # that contain them, in most cases.
  24. $smiley_regexp='('.join('|', map { quotemeta }
  25. reverse sort keys %smileys).')';
  26. #debug($smiley_regexp);
  27. } #}}}
  28. sub filter (@) { #{{{
  29. my %params=@_;
  30. build_regexp() unless defined $smiley_regexp;
  31. $_=$params{content};
  32. return $_ unless length $smiley_regexp;
  33. MATCH: while (m{(?:^|(?<=\s))(\\?)$smiley_regexp(?:(?=\s)|$)}g) {
  34. my $escape=$1;
  35. my $smiley=$2;
  36. # Smilies are not allowed inside <pre> or <code>.
  37. # For each tag in turn, match forward to find the next <tag>
  38. # or </tag> after the smiley.
  39. my $pos=pos;
  40. foreach my $tag ("pre", "code") {
  41. if (m/.*?<(\/)?\s*$tag\s*>/isg && defined $1) {
  42. # </tag> found first, so the smiley is
  43. # inside the tag, so do not expand it.
  44. next MATCH;
  45. }
  46. # Reset pos back to where it was before this test.
  47. pos=$pos;
  48. }
  49. if ($escape) {
  50. # Remove escape.
  51. substr($_, $-[1], 1)="";
  52. }
  53. else {
  54. # Replace the smiley with its expanded value.
  55. substr($_, $-[2], length($smiley))=
  56. htmllink($params{page}, $params{destpage},
  57. $smileys{$smiley}, linktext => $smiley);
  58. }
  59. }
  60. return $_;
  61. } # }}}
  62. 1