]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/difflib.php
More infiltration of new object-based HTML generation.
[SourceForge/phpwiki.git] / lib / difflib.php
1 <?php
2 rcs_id('$Id: difflib.php,v 1.5 2002-01-21 06:55:47 dairiki Exp $');
3 // difflib.php
4 //
5 // A PHP diff engine for phpwiki.
6 //
7 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
8 // You may copy this code freely under the conditions of the GPL.
9 //
10
11 // FIXME: possibly remove assert()'s for production version?
12
13 // PHP3 does not have assert()
14 define('USE_ASSERTS', function_exists('assert'));
15
16 class _DiffOp {
17     var $type;
18     var $orig;
19     var $final;
20     
21     function reverse() {
22         trigger_error("pure virtual", E_USER_ERROR);
23     }
24
25     function norig() {
26         return $this->orig ? sizeof($this->orig) : 0;
27     }
28
29     function nfinal() {
30         return $this->final ? sizeof($this->final) : 0;
31     }
32 }
33
34 class _DiffOp_Copy extends _DiffOp {
35     var $type = 'copy';
36     
37     function _DiffOp_Copy ($orig, $final = false) {
38         if (!is_array($final))
39             $final = $orig;
40         $this->orig = $orig;
41         $this->final = $final;
42     }
43
44     function reverse() {
45         return new _DiffOp_Copy($this->final, $this->orig);
46     }
47 }
48
49 class _DiffOp_Delete extends _DiffOp {
50     var $type = 'delete';
51     
52     function _DiffOp_Delete ($lines) {
53         $this->orig = $lines;
54         $this->final = false;
55     }
56
57     function reverse() {
58         return new _DiffOp_Add($this->orig);
59     }
60 }
61
62 class _DiffOp_Add extends _DiffOp {
63     var $type = 'add';
64     
65     function _DiffOp_Add ($lines) {
66         $this->final = $lines;
67         $this->orig = false;
68     }
69
70     function reverse() {
71         return new _DiffOp_Delete($this->final);
72     }
73 }
74
75 class _DiffOp_Change extends _DiffOp {
76     var $type = 'change';
77     
78     function _DiffOp_Change ($orig, $final) {
79         $this->orig = $orig;
80         $this->final = $final;
81     }
82
83     function reverse() {
84         return new _DiffOp_Change($this->final, $this->orig);
85     }
86 }
87         
88       
89 /**
90  * Class used internally by Diff to actually compute the diffs.
91  *
92  * The algorithm used here is mostly lifted from the perl module
93  * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
94  *   http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
95  *
96  * More ideas are taken from:
97  *   http://www.ics.uci.edu/~eppstein/161/960229.html
98  *
99  * Some ideas are (and a bit of code) are from from analyze.c, from GNU
100  * diffutils-2.7, which can be found at:
101  *   ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
102  *
103  * Finally, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
104  * are my own.
105  *
106  * @author Geoffrey T. Dairiki
107  * @access private
108  */
109 class _DiffEngine
110 {
111     function diff ($from_lines, $to_lines) {
112         $n_from = sizeof($from_lines);
113         $n_to = sizeof($to_lines);
114
115         $this->xchanged = $this->ychanged = array();
116         $this->xv = $this->yv = array();
117         $this->xind = $this->yind = array();
118         unset($this->seq);
119         unset($this->in_seq);
120         unset($this->lcs);
121          
122         // Skip leading common lines.
123         for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
124             if ($from_lines[$skip] != $to_lines[$skip])
125                 break;
126             $this->xchanged[$skip] = $this->ychanged[$skip] = false;
127         }
128         // Skip trailing common lines.
129         $xi = $n_from; $yi = $n_to;
130         for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
131             if ($from_lines[$xi] != $to_lines[$yi])
132                 break;
133             $this->xchanged[$xi] = $this->ychanged[$yi] = false;
134         }
135         
136         // Ignore lines which do not exist in both files.
137         for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
138             $xhash[$from_lines[$xi]] = 1;
139         for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
140             $line = $to_lines[$yi];
141             if ( ($this->ychanged[$yi] = empty($xhash[$line])) )
142                 continue;
143             $yhash[$line] = 1;
144             $this->yv[] = $line;
145             $this->yind[] = $yi;
146         }
147         for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
148             $line = $from_lines[$xi];
149             if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
150                 continue;
151             $this->xv[] = $line;
152             $this->xind[] = $xi;
153         }
154
155         // Find the LCS.
156         $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
157
158         // Merge edits when possible
159         $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
160         $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
161
162         // Compute the edit operations.
163         $edits = array();
164         $xi = $yi = 0;
165         while ($xi < $n_from || $yi < $n_to) {
166             USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
167             USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
168
169             // Skip matching "snake".
170             $copy = array();
171             while ( $xi < $n_from && $yi < $n_to
172                     && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
173                 $copy[] = $from_lines[$xi++];
174                 ++$yi;
175             }
176             if ($copy)
177                 $edits[] = new _DiffOp_Copy($copy);
178
179             // Find deletes & adds.
180             $delete = array();
181             while ($xi < $n_from && $this->xchanged[$xi])
182                 $delete[] = $from_lines[$xi++];
183
184             $add = array();
185             while ($yi < $n_to && $this->ychanged[$yi])
186                 $add[] = $to_lines[$yi++];
187             
188             if ($delete && $add)
189                 $edits[] = new _DiffOp_Change($delete, $add);
190             elseif ($delete)
191                 $edits[] = new _DiffOp_Delete($delete);
192             elseif ($add)
193                 $edits[] = new _DiffOp_Add($add);
194         }
195         return $edits;
196     }
197     
198
199     /* Divide the Largest Common Subsequence (LCS) of the sequences
200      * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
201      * sized segments.
202      *
203      * Returns (LCS, PTS).  LCS is the length of the LCS. PTS is an
204      * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
205      * sub sequences.  The first sub-sequence is contained in [X0, X1),
206      * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on.  Note
207      * that (X0, Y0) == (XOFF, YOFF) and
208      * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
209      *
210      * This function assumes that the first lines of the specified portions
211      * of the two files do not match, and likewise that the last lines do not
212      * match.  The caller must trim matching lines from the beginning and end
213      * of the portions it is going to specify.
214      */
215     function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
216         $flip = false;
217         
218         if ($xlim - $xoff > $ylim - $yoff) {
219             // Things seems faster (I'm not sure I understand why)
220             // when the shortest sequence in X.
221             $flip = true;
222             list ($xoff, $xlim, $yoff, $ylim)
223                 = array( $yoff, $ylim, $xoff, $xlim);
224         }
225
226         if ($flip)
227             for ($i = $ylim - 1; $i >= $yoff; $i--)
228                 $ymatches[$this->xv[$i]][] = $i;
229         else
230             for ($i = $ylim - 1; $i >= $yoff; $i--)
231                 $ymatches[$this->yv[$i]][] = $i;
232
233         $this->lcs = 0;
234         $this->seq[0]= $yoff - 1;
235         $this->in_seq = array();
236         $ymids[0] = array();
237     
238         $numer = $xlim - $xoff + $nchunks - 1;
239         $x = $xoff;
240         for ($chunk = 0; $chunk < $nchunks; $chunk++) {
241             if ($chunk > 0)
242                 for ($i = 0; $i <= $this->lcs; $i++)
243                     $ymids[$i][$chunk-1] = $this->seq[$i];
244
245             $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
246             for ( ; $x < $x1; $x++) {
247                 $line = $flip ? $this->yv[$x] : $this->xv[$x];
248                 if (empty($ymatches[$line]))
249                     continue;
250                 $matches = $ymatches[$line];
251                 reset($matches);
252                 while (list ($junk, $y) = each($matches))
253                     if (empty($this->in_seq[$y])) {
254                         $k = $this->_lcs_pos($y);
255                         USE_ASSERTS && assert($k > 0);
256                         $ymids[$k] = $ymids[$k-1];
257                         break;
258                     }
259                 while (list ($junk, $y) = each($matches)) {
260                     if ($y > $this->seq[$k-1]) {
261                         USE_ASSERTS && assert($y < $this->seq[$k]);
262                         // Optimization: this is a common case:
263                         //  next match is just replacing previous match.
264                         $this->in_seq[$this->seq[$k]] = false;
265                         $this->seq[$k] = $y;
266                         $this->in_seq[$y] = 1;
267                     }
268                     else if (empty($this->in_seq[$y])) {
269                         $k = $this->_lcs_pos($y);
270                         USE_ASSERTS && assert($k > 0);
271                         $ymids[$k] = $ymids[$k-1];
272                     }
273                 }
274             }
275         }
276
277         $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
278         $ymid = $ymids[$this->lcs];
279         for ($n = 0; $n < $nchunks - 1; $n++) {
280             $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
281             $y1 = $ymid[$n] + 1;
282             $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
283         }
284         $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
285
286         return array($this->lcs, $seps);
287     }
288
289     function _lcs_pos ($ypos) {
290         $end = $this->lcs;
291         if ($end == 0 || $ypos > $this->seq[$end]) {
292             $this->seq[++$this->lcs] = $ypos;
293             $this->in_seq[$ypos] = 1;
294             return $this->lcs;
295         }
296
297         $beg = 1;
298         while ($beg < $end) {
299             $mid = (int)(($beg + $end) / 2);
300             if ( $ypos > $this->seq[$mid] )
301                 $beg = $mid + 1;
302             else
303                 $end = $mid;
304         }
305
306         USE_ASSERTS && assert($ypos != $this->seq[$end]);
307
308         $this->in_seq[$this->seq[$end]] = false;
309         $this->seq[$end] = $ypos;
310         $this->in_seq[$ypos] = 1;
311         return $end;
312     }
313
314     /* Find LCS of two sequences.
315      *
316      * The results are recorded in the vectors $this->{x,y}changed[], by
317      * storing a 1 in the element for each line that is an insertion
318      * or deletion (ie. is not in the LCS).
319      *
320      * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
321      *
322      * Note that XLIM, YLIM are exclusive bounds.
323      * All line numbers are origin-0 and discarded lines are not counted.
324      */
325     function _compareseq ($xoff, $xlim, $yoff, $ylim) {
326         // Slide down the bottom initial diagonal.
327         while ($xoff < $xlim && $yoff < $ylim
328                && $this->xv[$xoff] == $this->yv[$yoff]) {
329             ++$xoff;
330             ++$yoff;
331         }
332
333         // Slide up the top initial diagonal.
334         while ($xlim > $xoff && $ylim > $yoff
335                && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
336             --$xlim;
337             --$ylim;
338         }
339
340         if ($xoff == $xlim || $yoff == $ylim)
341             $lcs = 0;
342         else {
343             // This is ad hoc but seems to work well.
344             //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
345             //$nchunks = max(2,min(8,(int)$nchunks));
346             $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
347             list ($lcs, $seps)
348                 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
349         }
350
351         if ($lcs == 0) {
352             // X and Y sequences have no common subsequence:
353             // mark all changed.
354             while ($yoff < $ylim)
355                 $this->ychanged[$this->yind[$yoff++]] = 1;
356             while ($xoff < $xlim)
357                 $this->xchanged[$this->xind[$xoff++]] = 1;
358         }
359         else {
360             // Use the partitions to split this problem into subproblems.
361             reset($seps);
362             $pt1 = $seps[0];
363             while ($pt2 = next($seps)) {
364                 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
365                 $pt1 = $pt2;
366             }
367         }
368     }
369
370     /* Adjust inserts/deletes of identical lines to join changes
371      * as much as possible.
372      *
373      * We do something when a run of changed lines include a
374      * line at one end and has an excluded, identical line at the other.
375      * We are free to choose which identical line is included.
376      * `compareseq' usually chooses the one at the beginning,
377      * but usually it is cleaner to consider the following identical line
378      * to be the "change".
379      *
380      * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
381      */
382     function _shift_boundaries ($lines, &$changed, $other_changed) {
383         $i = 0;
384         $j = 0;
385
386         USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
387         $len = sizeof($lines);
388         $other_len = sizeof($other_changed);
389
390         while (1) {
391             /*
392              * Scan forwards to find beginning of another run of changes.
393              * Also keep track of the corresponding point in the other file.
394              *
395              * Throughout this code, $i and $j are adjusted together so that
396              * the first $i elements of $changed and the first $j elements
397              * of $other_changed both contain the same number of zeros
398              * (unchanged lines).
399              * Furthermore, $j is always kept so that $j == $other_len or
400              * $other_changed[$j] == false.
401              */
402             while ($j < $other_len && $other_changed[$j])
403                 $j++;
404             
405             while ($i < $len && ! $changed[$i]) {
406                 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
407                 $i++; $j++;
408                 while ($j < $other_len && $other_changed[$j])
409                     $j++;
410             }
411             
412             if ($i == $len)
413                 break;
414
415             $start = $i;
416
417             // Find the end of this run of changes.
418             while (++$i < $len && $changed[$i])
419                 continue;
420
421             do {
422                 /*
423                  * Record the length of this run of changes, so that
424                  * we can later determine whether the run has grown.
425                  */
426                 $runlength = $i - $start;
427
428                 /*
429                  * Move the changed region back, so long as the
430                  * previous unchanged line matches the last changed one.
431                  * This merges with previous changed regions.
432                  */
433                 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
434                     $changed[--$start] = 1;
435                     $changed[--$i] = false;
436                     while ($start > 0 && $changed[$start - 1])
437                         $start--;
438                     USE_ASSERTS && assert('$j > 0');
439                     while ($other_changed[--$j])
440                         continue;
441                     USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
442                 }
443
444                 /*
445                  * Set CORRESPONDING to the end of the changed run, at the last
446                  * point where it corresponds to a changed run in the other file.
447                  * CORRESPONDING == LEN means no such point has been found.
448                  */
449                 $corresponding = $j < $other_len ? $i : $len;
450
451                 /*
452                  * Move the changed region forward, so long as the
453                  * first changed line matches the following unchanged one.
454                  * This merges with following changed regions.
455                  * Do this second, so that if there are no merges,
456                  * the changed region is moved forward as far as possible.
457                  */
458                 while ($i < $len && $lines[$start] == $lines[$i]) {
459                     $changed[$start++] = false;
460                     $changed[$i++] = 1;
461                     while ($i < $len && $changed[$i])
462                         $i++;
463
464                     USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
465                     $j++;
466                     if ($j < $other_len && $other_changed[$j]) {
467                         $corresponding = $i;
468                         while ($j < $other_len && $other_changed[$j])
469                             $j++;
470                     }
471                 }
472             } while ($runlength != $i - $start);
473
474             /*
475              * If possible, move the fully-merged run of changes
476              * back to a corresponding run in the other file.
477              */
478             while ($corresponding < $i) {
479                 $changed[--$start] = 1;
480                 $changed[--$i] = 0;
481                 USE_ASSERTS && assert('$j > 0');
482                 while ($other_changed[--$j])
483                     continue;
484                 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
485             }
486         }
487     }
488 }
489
490 /**
491  * Class representing a 'diff' between two sequences of strings.
492  */
493 class Diff 
494 {
495     var $edits;
496
497     /**
498      * Constructor.
499      * Computes diff between sequences of strings.
500      *
501      * @param $from_lines array An array of strings.
502      *        (Typically these are lines from a file.)
503      * @param $to_lines array An array of strings.
504      */
505     function Diff($from_lines, $to_lines) {
506         $eng = new _DiffEngine;
507         $this->edits = $eng->diff($from_lines, $to_lines);
508         //$this->_check($from_lines, $to_lines);
509     }
510
511     /**
512      * Compute reversed Diff.
513      *
514      * SYNOPSIS:
515      *
516      *  $diff = new Diff($lines1, $lines2);
517      *  $rev = $diff->reverse();
518      * @return object A Diff object representing the inverse of the
519      *                original diff.
520      */
521     function reverse () {
522         $rev = $this;
523         $rev->edits = array();
524         foreach ($this->edits as $edit) {
525             $rev->edits[] = $edit->reverse();
526         }
527         return $rev;
528     }
529
530     /**
531      * Check for empty diff.
532      *
533      * @return bool True iff two sequences were identical.
534      */
535     function isEmpty () {
536         foreach ($this->edits as $edit) {
537             if ($edit->type != 'copy')
538                 return false;
539         }
540         return true;
541     }
542   
543     /**
544      * Compute the length of the Longest Common Subsequence (LCS).
545      *
546      * This is mostly for diagnostic purposed.
547      *
548      * @return int The length of the LCS.
549      */
550     function lcs () {
551         $lcs = 0;
552         foreach ($this->edits as $edit) {
553             if ($edit->type == 'copy')
554                 $lcs += sizeof($edit->orig);
555         }
556         return $lcs;
557     }
558
559     /**
560      * Get the original set of lines.
561      *
562      * This reconstructs the $from_lines parameter passed to the
563      * constructor.
564      *
565      * @return array The original sequence of strings.
566      */
567     function orig() {
568         $lines = array();
569         
570         foreach ($this->edits as $edit) {
571             if ($edit->orig)
572                 array_splice($lines, sizeof($lines), 0, $edit->orig);
573         }
574         return $lines;
575     }
576
577     /**
578      * Get the final set of lines.
579      *
580      * This reconstructs the $to_lines parameter passed to the
581      * constructor.
582      *
583      * @return array The sequence of strings.
584      */
585     function final() {
586         $lines = array();
587         
588         foreach ($this->edits as $edit) {
589             if ($edit->final)
590                 array_splice($lines, sizeof($lines), 0, $edit->final);
591         }
592         return $lines;
593     }
594
595     /**
596      * Check a Diff for validity. 
597      *
598      * This is here only for debugging purposes.
599      */
600     function _check ($from_lines, $to_lines) {
601         if (serialize($from_lines) != serialize($this->orig()))
602             trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
603         if (serialize($to_lines) != serialize($this->final()))
604             trigger_error("Reconstructed final doesn't match", E_USER_ERROR);
605
606         $rev = $this->reverse();
607         if (serialize($to_lines) != serialize($rev->orig()))
608             trigger_error("Reversed original doesn't match", E_USER_ERROR);
609         if (serialize($from_lines) != serialize($rev->final()))
610             trigger_error("Reversed final doesn't match", E_USER_ERROR);
611
612
613         $prevtype = 'none';
614         foreach ($this->edits as $edit) {
615             if ( $prevtype == $edit->type )
616                 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
617             $prevtype = $edit->type;
618         }
619
620         $lcs = $this->lcs();
621         trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
622     }
623 }
624
625             
626
627             
628 /**
629  * FIXME: bad name.
630  */
631 class MappedDiff
632 extends Diff
633 {
634     /**
635      * Constructor.
636      *
637      * Computes diff between sequences of strings.
638      *
639      * This can be used to compute things like
640      * case-insensitve diffs, or diffs which ignore
641      * changes in white-space.
642      *
643      * @param $from_lines array An array of strings.
644      *  (Typically these are lines from a file.)
645      *
646      * @param $to_lines array An array of strings.
647      *
648      * @param $mapped_from_lines array This array should
649      *  have the same size number of elements as $from_lines.
650      *  The elements in $mapped_from_lines and
651      *  $mapped_to_lines are what is actually compared
652      *  when computing the diff.
653      *
654      * @param $mapped_to_lines array This array should
655      *  have the same number of elements as $to_lines.
656      */
657     function MappedDiff($from_lines, $to_lines,
658                         $mapped_from_lines, $mapped_to_lines) {
659
660         assert(sizeof($from_lines) == sizeof($mapped_from_lines));
661         assert(sizeof($to_lines) == sizeof($mapped_to_lines));
662         
663         $this->Diff($mapped_from_lines, $mapped_to_lines);
664
665         $xi = $yi = 0;
666         for ($i = 0; $i < sizeof($this->edits); $i++) {
667             $orig = &$this->edits[$i]->orig;
668             if (is_array($orig)) {
669                 $orig = array_slice($from_lines, $xi, sizeof($orig));
670                 $xi += sizeof($orig);
671             }
672             
673             $final = &$this->edits[$i]->final;
674             if (is_array($final)) {
675                 $final = array_slice($to_lines, $yi, sizeof($final));
676                 $yi += sizeof($final);
677             }
678         }
679     }
680 }
681
682
683 /**
684  * A class to format Diffs
685  *
686  * This class formats the diff in classic diff format.
687  * It is intended that this class be customized via inheritance,
688  * to obtain fancier outputs.
689  */
690 class DiffFormatter
691 {
692     /**
693      * Number of leading context "lines" to preserve.
694      *
695      * This should be left at zero for this class, but subclasses
696      * may want to set this to other values.
697      */
698     var $leading_context_lines = 0;
699
700     /**
701      * Number of trailing context "lines" to preserve.
702      *
703      * This should be left at zero for this class, but subclasses
704      * may want to set this to other values.
705      */
706     var $trailing_context_lines = 0;
707
708     /**
709      * Format a diff.
710      *
711      * @param $diff object A Diff object.
712      * @return string The formatted output.
713      */
714     function format($diff) {
715
716         $xi = $yi = 1;
717         $block = false;
718         $context = array();
719
720         $nlead = $this->leading_context_lines;
721         $ntrail = $this->trailing_context_lines;
722
723         $this->_start_diff();
724
725         foreach ($diff->edits as $edit) {
726             if ($edit->type == 'copy') {
727                 if (is_array($block)) {
728                     if (sizeof($edit->orig) <= $nlead + $ntrail) {
729                         $block[] = $edit;
730                     }
731                     else{
732                         if ($ntrail) {
733                             $context = array_slice($edit->orig, 0, $ntrail);
734                             $block[] = new _DiffOp_Copy($context);
735                         }
736                         $this->_block($x0, $ntrail + $xi - $x0,
737                                       $y0, $ntrail + $yi - $y0,
738                                       $block);
739                         $block = false;
740                     }
741                 }
742                 $context = $edit->orig;
743             }
744             else {
745                 if (! is_array($block)) {
746                     $context = array_slice($context, sizeof($context) - $nlead);
747                     $x0 = $xi - sizeof($context);
748                     $y0 = $yi - sizeof($context);
749                     $block = array();
750                     if ($context)
751                         $block[] = new _DiffOp_Copy($context);
752                 }
753                 $block[] = $edit;
754             }
755
756             if ($edit->orig)
757                 $xi += sizeof($edit->orig);
758             if ($edit->final)
759                 $yi += sizeof($edit->final);
760         }
761
762         if (is_array($block))
763             $this->_block($x0, $xi - $x0,
764                           $y0, $yi - $y0,
765                           $block);
766
767         return $this->_end_diff();
768     }
769
770     function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
771         $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
772         foreach ($edits as $edit) {
773             if ($edit->type == 'copy')
774                 $this->_context($edit->orig);
775             elseif ($edit->type == 'add')
776                 $this->_added($edit->final);
777             elseif ($edit->type == 'delete')
778                 $this->_deleted($edit->orig);
779             elseif ($edit->type == 'change')
780                 $this->_changed($edit->orig, $edit->final);
781             else
782                 trigger_error("Unknown edit type", E_USER_ERROR);
783         }
784         $this->_end_block();
785     }
786
787     function _start_diff() {
788         ob_start();
789     }
790
791     function _end_diff() {
792         $val = ob_get_contents();
793         ob_end_clean();
794         return $val;
795     }
796
797     function _block_header($xbeg, $xlen, $ybeg, $ylen) {
798         if ($xlen > 1)
799             $xbeg .= "," . ($xbeg + $xlen - 1);
800         if ($ylen > 1)
801             $ybeg .= "," . ($ybeg + $ylen - 1);
802
803         return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
804     }
805     
806     function _start_block($header) {
807         echo $header;
808     }
809     
810     function _end_block() {
811     }
812
813     function _lines($lines, $prefix = ' ') {
814         foreach ($lines as $line)
815             echo "$prefix $line\n";
816     }
817     
818     function _context($lines) {
819         $this->_lines($lines);
820     }
821
822     function _added($lines) {
823         $this->_lines($lines, ">");
824     }
825     function _deleted($lines) {
826         $this->_lines($lines, "<");
827     }
828
829     function _changed($orig, $final) {
830         $this->_deleted($orig);
831         echo "---\n";
832         $this->_added($final);
833     }
834 }
835
836 /**
837  * "Unified" diff formatter.
838  *
839  * This class formats the diff in classic "unified diff" format.
840  */
841 class UnifiedDiffFormatter extends DiffFormatter
842 {
843     function UnifiedDiffFormatter($context_lines = 4) {
844         $this->leading_context_lines = $context_lines;
845         $this->trailing_context_lines = $context_lines;
846     }
847     
848     function _block_header($xbeg, $xlen, $ybeg, $ylen) {
849         if ($xlen != 1)
850             $xbeg .= "," . $xlen;
851         if ($ylen != 1)
852             $ybeg .= "," . $ylen;
853         return "@@ -$xbeg +$ybeg @@";
854     }
855
856     function _added($lines) {
857         $this->_lines($lines, "+");
858     }
859     function _deleted($lines) {
860         $this->_lines($lines, "-");
861     }
862     function _changed($orig, $final) {
863         $this->_deleted($orig);
864         $this->_added($final);
865     }
866 }
867
868 // Local Variables:
869 // mode: php
870 // tab-width: 8
871 // c-basic-offset: 4
872 // c-hanging-comment-ender-p: nil
873 // indent-tabs-mode: nil
874 // End:   
875 ?>