]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/smiley.pm
124245b68f9f13979ed84d0ede65b4f177ad40c3
[ikiwiki.git] / 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                 my $epos=$-[1];
47                 my $spos=$-[2];
48
49                 # Smilies are not allowed inside <pre> or <code>.
50                 # For each tag in turn, match forward to find the next <tag>
51                 # or </tag> after the smiley.
52                 my $pos=pos;
53                 foreach my $tag ("pre", "code") {
54                         if (m/.*?<(\/)?\s*$tag\s*>/isg && defined $1) {
55                                 # </tag> found first, so the smiley is
56                                 # inside the tag, so do not expand it.
57                                 next MATCH;
58                         }
59                         # Reset pos back to where it was before this test.
60                         pos=$pos;
61                 }
62
63                 if ($escape) {
64                         # Remove escape.
65                         substr($_, $epos, 1)="";
66                 }
67                 else {
68                         # Replace the smiley with its expanded value.
69                         substr($_, $spos, length($smiley))=
70                                 htmllink($params{page}, $params{destpage},
71                                          $smileys{$smiley}, linktext => $smiley);
72                 }
73         }
74
75         return $_;
76 } # }}}
77
78 1