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