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