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