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