summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/smiley.pm
blob: 7e0b54499d1edb70a57d42a959e56b0ed513f26f (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. # Smilies are not allowed inside <pre> or <code>.
  35. # For each tag in turn, match forward to find <tag> or
  36. # </tag>. If it's </tag>, then the smiley is inside the
  37. # tag, and is not expanded. If it's <tag>, the smiley is
  38. # outside the block.
  39. my $pos=pos;
  40. foreach my $tag ("pre", "code") {
  41. if (m/.*?<(\/)?\s*$tag\s*>/isg) {
  42. if (defined $1) {
  43. # Inside tag, so do nothing.
  44. # (Smiley hunting will continue after
  45. # the tag.)
  46. next MATCH;
  47. }
  48. else {
  49. # Reset pos back to where it was before
  50. # this test.
  51. pos=$pos;
  52. }
  53. }
  54. }
  55. if ($1) {
  56. # Remove escape.
  57. substr($_, $-[1], 1)="";
  58. }
  59. else {
  60. # Replace the smiley with its expanded value.
  61. substr($_, $-[2], length($2))=
  62. htmllink($params{page}, $params{destpage}, $smileys{$2}, linktext => $2);
  63. }
  64. }
  65. return $_;
  66. } # }}}
  67. 1