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