]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/difflib.php
Use __construct
[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 __construct($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 __construct($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 __construct($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 __construct($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      * Computes diff between sequences of strings.
512      *
513      * @param $from_lines array An array of strings.
514      *        (Typically these are lines from a file.)
515      * @param $to_lines array An array of strings.
516      */
517     function __construct($from_lines, $to_lines)
518     {
519         $eng = new _DiffEngine;
520         $this->edits = $eng->diff($from_lines, $to_lines);
521         //$this->_check($from_lines, $to_lines);
522     }
523
524     /**
525      * Compute reversed Diff.
526      *
527      * SYNOPSIS:
528      *
529      *  $diff = new Diff($lines1, $lines2);
530      *  $rev = $diff->reverse();
531      * @return object A Diff object representing the inverse of the
532      *                original diff.
533      */
534     function reverse()
535     {
536         $rev = $this;
537         $rev->edits = array();
538         foreach ($this->edits as $edit) {
539             $rev->edits[] = $edit->reverse();
540         }
541         return $rev;
542     }
543
544     /**
545      * Check for empty diff.
546      *
547      * @return bool True iff two sequences were identical.
548      */
549     function isEmpty()
550     {
551         foreach ($this->edits as $edit) {
552             if ($edit->type != 'copy')
553                 return false;
554         }
555         return true;
556     }
557
558     /**
559      * Compute the length of the Longest Common Subsequence (LCS).
560      *
561      * This is mostly for diagnostic purposed.
562      *
563      * @return int The length of the LCS.
564      */
565     function lcs()
566     {
567         $lcs = 0;
568         foreach ($this->edits as $edit) {
569             if ($edit->type == 'copy')
570                 $lcs += sizeof($edit->orig);
571         }
572         return $lcs;
573     }
574
575     /**
576      * Get the original set of lines.
577      *
578      * This reconstructs the $from_lines parameter passed to the
579      * constructor.
580      *
581      * @return array The original sequence of strings.
582      */
583     function orig()
584     {
585         $lines = array();
586
587         foreach ($this->edits as $edit) {
588             if ($edit->orig)
589                 array_splice($lines, sizeof($lines), 0, $edit->orig);
590         }
591         return $lines;
592     }
593
594     /**
595      * Get the final set of lines.
596      *
597      * This reconstructs the $to_lines parameter passed to the
598      * constructor.
599      *
600      * @return array The sequence of strings.
601      */
602     function _final()
603     {
604         $lines = array();
605
606         foreach ($this->edits as $edit) {
607             if ($edit->final)
608                 array_splice($lines, sizeof($lines), 0, $edit->final);
609         }
610         return $lines;
611     }
612
613     /**
614      * Check a Diff for validity.
615      *
616      * This is here only for debugging purposes.
617      */
618     function _check($from_lines, $to_lines)
619     {
620         if (serialize($from_lines) != serialize($this->orig()))
621             trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
622         if (serialize($to_lines) != serialize($this->_final()))
623             trigger_error("Reconstructed final doesn't match", E_USER_ERROR);
624
625         $rev = $this->reverse();
626         if (serialize($to_lines) != serialize($rev->orig()))
627             trigger_error("Reversed original doesn't match", E_USER_ERROR);
628         if (serialize($from_lines) != serialize($rev->_final()))
629             trigger_error("Reversed final doesn't match", E_USER_ERROR);
630
631         $prevtype = 'none';
632         foreach ($this->edits as $edit) {
633             if ($prevtype == $edit->type)
634                 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
635             $prevtype = $edit->type;
636         }
637
638         $lcs = $this->lcs();
639         trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
640     }
641 }
642
643 /**
644  * FIXME: bad name.
645  */
646 class MappedDiff
647     extends Diff
648 {
649     /**
650      * Computes diff between sequences of strings.
651      *
652      * This can be used to compute things like
653      * case-insensitve diffs, or diffs which ignore
654      * changes in white-space.
655      *
656      * @param $from_lines array An array of strings.
657      *  (Typically these are lines from a file.)
658      *
659      * @param $to_lines array An array of strings.
660      *
661      * @param $mapped_from_lines array This array should
662      *  have the same size number of elements as $from_lines.
663      *  The elements in $mapped_from_lines and
664      *  $mapped_to_lines are what is actually compared
665      *  when computing the diff.
666      *
667      * @param $mapped_to_lines array This array should
668      *  have the same number of elements as $to_lines.
669      */
670     function __construct($from_lines, $to_lines,
671                          $mapped_from_lines, $mapped_to_lines)
672     {
673         assert(sizeof($from_lines) == sizeof($mapped_from_lines));
674         assert(sizeof($to_lines) == sizeof($mapped_to_lines));
675
676         $this->Diff($mapped_from_lines, $mapped_to_lines);
677
678         $xi = $yi = 0;
679         // Optimizing loop invariants:
680         // http://phplens.com/lens/php-book/optimizing-debugging-php.php
681         for ($i = 0, $max = sizeof($this->edits); $i < $max; $i++) {
682             $orig = &$this->edits[$i]->orig;
683             if (is_array($orig)) {
684                 $orig = array_slice($from_lines, $xi, sizeof($orig));
685                 $xi += sizeof($orig);
686             }
687
688             $final = &$this->edits[$i]->final;
689             if (is_array($final)) {
690                 $final = array_slice($to_lines, $yi, sizeof($final));
691                 $yi += sizeof($final);
692             }
693         }
694     }
695 }
696
697 /**
698  * A class to format Diffs
699  *
700  * This class formats the diff in classic diff format.
701  * It is intended that this class be customized via inheritance,
702  * to obtain fancier outputs.
703  */
704 class DiffFormatter
705 {
706     /**
707      * Number of leading context "lines" to preserve.
708      *
709      * This should be left at zero for this class, but subclasses
710      * may want to set this to other values.
711      */
712     public $leading_context_lines = 0;
713
714     /**
715      * Number of trailing context "lines" to preserve.
716      *
717      * This should be left at zero for this class, but subclasses
718      * may want to set this to other values.
719      */
720     public $trailing_context_lines = 0;
721
722     /**
723      * Format a diff.
724      *
725      * @param $diff object A Diff object.
726      * @return string The formatted output.
727      */
728     function format($diff)
729     {
730
731         $xi = $yi = 1;
732         $block = false;
733         $context = array();
734
735         $nlead = $this->leading_context_lines;
736         $ntrail = $this->trailing_context_lines;
737
738         $this->_start_diff();
739
740         foreach ($diff->edits as $edit) {
741             if ($edit->type == 'copy') {
742                 if (is_array($block)) {
743                     if (sizeof($edit->orig) <= $nlead + $ntrail) {
744                         $block[] = $edit;
745                     } else {
746                         if ($ntrail) {
747                             $context = array_slice($edit->orig, 0, $ntrail);
748                             $block[] = new _DiffOp_Copy($context);
749                         }
750                         $this->_block($x0, $ntrail + $xi - $x0,
751                             $y0, $ntrail + $yi - $y0,
752                             $block);
753                         $block = false;
754                     }
755                 }
756                 $context = $edit->orig;
757             } else {
758                 if (!is_array($block)) {
759                     $context = array_slice($context, max(0, sizeof($context) - $nlead));
760                     $x0 = $xi - sizeof($context);
761                     $y0 = $yi - sizeof($context);
762                     $block = array();
763                     if ($context)
764                         $block[] = new _DiffOp_Copy($context);
765                 }
766                 $block[] = $edit;
767             }
768
769             if ($edit->orig)
770                 $xi += sizeof($edit->orig);
771             if ($edit->final)
772                 $yi += sizeof($edit->final);
773         }
774
775         if (is_array($block))
776             $this->_block($x0, $xi - $x0,
777                 $y0, $yi - $y0,
778                 $block);
779
780         return $this->_end_diff();
781     }
782
783     function _block($xbeg, $xlen, $ybeg, $ylen, &$edits)
784     {
785         $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
786         foreach ($edits as $edit) {
787             if ($edit->type == 'copy')
788                 $this->_context($edit->orig);
789             elseif ($edit->type == 'add')
790                 $this->_added($edit->final); elseif ($edit->type == 'delete')
791                 $this->_deleted($edit->orig); elseif ($edit->type == 'change')
792                 $this->_changed($edit->orig, $edit->final); else
793                 trigger_error("Unknown edit type", E_USER_ERROR);
794         }
795         $this->_end_block();
796     }
797
798     function _start_diff()
799     {
800         ob_start();
801     }
802
803     function _end_diff()
804     {
805         $val = ob_get_contents();
806         ob_end_clean();
807         return $val;
808     }
809
810     function _block_header($xbeg, $xlen, $ybeg, $ylen)
811     {
812         if ($xlen > 1)
813             $xbeg .= "," . ($xbeg + $xlen - 1);
814         if ($ylen > 1)
815             $ybeg .= "," . ($ybeg + $ylen - 1);
816
817         return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
818     }
819
820     function _start_block($header)
821     {
822         echo $header;
823     }
824
825     function _end_block()
826     {
827     }
828
829     function _lines($lines, $prefix = ' ')
830     {
831         foreach ($lines as $line)
832             echo "$prefix $line\n";
833     }
834
835     function _context($lines)
836     {
837         $this->_lines($lines);
838     }
839
840     function _added($lines)
841     {
842         $this->_lines($lines, ">");
843     }
844
845     function _deleted($lines)
846     {
847         $this->_lines($lines, "<");
848     }
849
850     function _changed($orig, $final)
851     {
852         $this->_deleted($orig);
853         echo "---\n";
854         $this->_added($final);
855     }
856 }
857
858 /**
859  * "Unified" diff formatter.
860  *
861  * This class formats the diff in classic "unified diff" format.
862  */
863 class UnifiedDiffFormatter extends DiffFormatter
864 {
865     function __construct($context_lines = 4)
866     {
867         $this->leading_context_lines = $context_lines;
868         $this->trailing_context_lines = $context_lines;
869     }
870
871     function _block_header($xbeg, $xlen, $ybeg, $ylen)
872     {
873         if ($xlen != 1)
874             $xbeg .= "," . $xlen;
875         if ($ylen != 1)
876             $ybeg .= "," . $ylen;
877         return "@@ -$xbeg +$ybeg @@\n";
878     }
879
880     function _added($lines)
881     {
882         $this->_lines($lines, "+");
883     }
884
885     function _deleted($lines)
886     {
887         $this->_lines($lines, "-");
888     }
889
890     function _changed($orig, $final)
891     {
892         $this->_deleted($orig);
893         $this->_added($final);
894     }
895 }
896
897 /**
898  * block conflict diff formatter.
899  *
900  * This class will format a diff identical to Diff3 (i.e. editpage
901  * conflicts), but when there are only two source files. To be used by
902  * future enhancements to reloading / upgrading pgsrc.
903  *
904  * Functional but not finished yet, need to eliminate redundant block
905  * suffixes (i.e. "=======" immediately followed by another prefix)
906  * see class LoadFileConflictPageEditor
907  */
908 class BlockDiffFormatter extends DiffFormatter
909 {
910     function __construct($context_lines = 4)
911     {
912         $this->leading_context_lines = $context_lines;
913         $this->trailing_context_lines = $context_lines;
914     }
915
916     function _lines($lines, $prefix = '')
917     {
918         if (!$prefix == '')
919             echo "$prefix\n";
920         foreach ($lines as $line)
921             echo "$line\n";
922         if (!$prefix == '')
923             echo "$prefix\n";
924     }
925
926     function _added($lines)
927     {
928         $this->_lines($lines, ">>>>>>>");
929     }
930
931     function _deleted($lines)
932     {
933         $this->_lines($lines, "<<<<<<<");
934     }
935
936     function _block_header($xbeg, $xlen, $ybeg, $ylen)
937     {
938         return "";
939     }
940
941     function _changed($orig, $final)
942     {
943         $this->_deleted($orig);
944         $this->_added($final);
945     }
946 }
947
948 // Local Variables:
949 // mode: php
950 // tab-width: 8
951 // c-basic-offset: 4
952 // c-hanging-comment-ender-p: nil
953 // indent-tabs-mode: nil
954 // End: