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