web commit by http://svend.myopenid.com/: Added note about backslash.
[ikiwiki] / IkiWiki / Plugin / editdiff.pm
1 #!/usr/bin/perl
2 # This plugin adds a "Diff" button to the page edit form.
3 package IkiWiki::Plugin::editdiff;
4
5 use warnings;
6 use strict;
7 use IkiWiki 2.00;
8 use HTML::Entities;
9 use IPC::Open2;
10
11 sub import { #{{{
12         hook(type => "formbuilder_setup", id => "editdiff",
13                 call => \&formbuilder_setup);
14 } #}}}
15
16 sub diff ($$) { #{{{
17         my $orig=shift;
18         my $content=shift;
19
20         my $sigpipe=0;
21         $SIG{PIPE} = sub { $sigpipe=1; };
22
23         my $pid = open2(*DIFFOUT, *DIFFIN, 'diff', '-u', $orig, '-');
24         binmode($_, ':utf8') foreach (*DIFFIN, *DIFFOUT);
25
26         print DIFFIN $content;
27         close DIFFIN;
28         my $ret;
29         while (<DIFFOUT>) {
30                 if (defined $ret) {
31                         $ret.=$_;
32                 }
33                 elsif (/^\@\@/) {
34                         $ret=$_;
35                 }
36         }
37         close DIFFOUT;
38         waitpid $pid, 0;
39
40         $SIG{PIPE}="default";
41         return "couldn't run diff\n" if $sigpipe;
42
43         return "<pre>".encode_entities($ret)."</pre>";
44 } #}}}
45
46 sub formbuilder_setup { #{{{
47         my %params=@_;
48         my $form=$params{form};
49         my $page=$form->field("page");
50
51         return if $form->title ne "editpage"
52                   || $form->field("do") ne "edit";
53
54         $page = IkiWiki::titlepage(IkiWiki::possibly_foolish_untaint($page));
55         return unless exists $pagesources{$page};
56
57         push @{$params{buttons}}, "Diff";
58
59         if ($form->submitted eq "Diff") {
60                 my $content=$form->field('editcontent');
61                 $content=~s/\r\n/\n/g;
62                 $content=~s/\r/\n/g;
63
64                 my $diff = diff(srcfile($pagesources{$page}), $content);
65                 $form->tmpl_param("page_preview", $diff);
66         }
67 } #}}}
68
69 1