2 rcs_id('$Id: difflib.php,v 1.5 2002-01-21 06:55:47 dairiki Exp $');
5 // A PHP diff engine for phpwiki.
7 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
8 // You may copy this code freely under the conditions of the GPL.
11 // FIXME: possibly remove assert()'s for production version?
13 // PHP3 does not have assert()
14 define('USE_ASSERTS', function_exists('assert'));
22 trigger_error("pure virtual", E_USER_ERROR);
26 return $this->orig ? sizeof($this->orig) : 0;
30 return $this->final ? sizeof($this->final) : 0;
34 class _DiffOp_Copy extends _DiffOp {
37 function _DiffOp_Copy ($orig, $final = false) {
38 if (!is_array($final))
41 $this->final = $final;
45 return new _DiffOp_Copy($this->final, $this->orig);
49 class _DiffOp_Delete extends _DiffOp {
52 function _DiffOp_Delete ($lines) {
58 return new _DiffOp_Add($this->orig);
62 class _DiffOp_Add extends _DiffOp {
65 function _DiffOp_Add ($lines) {
66 $this->final = $lines;
71 return new _DiffOp_Delete($this->final);
75 class _DiffOp_Change extends _DiffOp {
78 function _DiffOp_Change ($orig, $final) {
80 $this->final = $final;
84 return new _DiffOp_Change($this->final, $this->orig);
90 * Class used internally by Diff to actually compute the diffs.
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
96 * More ideas are taken from:
97 * http://www.ics.uci.edu/~eppstein/161/960229.html
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
103 * Finally, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
106 * @author Geoffrey T. Dairiki
111 function diff ($from_lines, $to_lines) {
112 $n_from = sizeof($from_lines);
113 $n_to = sizeof($to_lines);
115 $this->xchanged = $this->ychanged = array();
116 $this->xv = $this->yv = array();
117 $this->xind = $this->yind = array();
119 unset($this->in_seq);
122 // Skip leading common lines.
123 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
124 if ($from_lines[$skip] != $to_lines[$skip])
126 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
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])
133 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
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])) )
147 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
148 $line = $from_lines[$xi];
149 if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
156 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
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);
162 // Compute the edit operations.
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]);
169 // Skip matching "snake".
171 while ( $xi < $n_from && $yi < $n_to
172 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
173 $copy[] = $from_lines[$xi++];
177 $edits[] = new _DiffOp_Copy($copy);
179 // Find deletes & adds.
181 while ($xi < $n_from && $this->xchanged[$xi])
182 $delete[] = $from_lines[$xi++];
185 while ($yi < $n_to && $this->ychanged[$yi])
186 $add[] = $to_lines[$yi++];
189 $edits[] = new _DiffOp_Change($delete, $add);
191 $edits[] = new _DiffOp_Delete($delete);
193 $edits[] = new _DiffOp_Add($add);
199 /* Divide the Largest Common Subsequence (LCS) of the sequences
200 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
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).
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.
215 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
218 if ($xlim - $xoff > $ylim - $yoff) {
219 // Things seems faster (I'm not sure I understand why)
220 // when the shortest sequence in X.
222 list ($xoff, $xlim, $yoff, $ylim)
223 = array( $yoff, $ylim, $xoff, $xlim);
227 for ($i = $ylim - 1; $i >= $yoff; $i--)
228 $ymatches[$this->xv[$i]][] = $i;
230 for ($i = $ylim - 1; $i >= $yoff; $i--)
231 $ymatches[$this->yv[$i]][] = $i;
234 $this->seq[0]= $yoff - 1;
235 $this->in_seq = array();
238 $numer = $xlim - $xoff + $nchunks - 1;
240 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
242 for ($i = 0; $i <= $this->lcs; $i++)
243 $ymids[$i][$chunk-1] = $this->seq[$i];
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]))
250 $matches = $ymatches[$line];
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];
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;
266 $this->in_seq[$y] = 1;
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];
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);
282 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
284 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
286 return array($this->lcs, $seps);
289 function _lcs_pos ($ypos) {
291 if ($end == 0 || $ypos > $this->seq[$end]) {
292 $this->seq[++$this->lcs] = $ypos;
293 $this->in_seq[$ypos] = 1;
298 while ($beg < $end) {
299 $mid = (int)(($beg + $end) / 2);
300 if ( $ypos > $this->seq[$mid] )
306 USE_ASSERTS && assert($ypos != $this->seq[$end]);
308 $this->in_seq[$this->seq[$end]] = false;
309 $this->seq[$end] = $ypos;
310 $this->in_seq[$ypos] = 1;
314 /* Find LCS of two sequences.
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).
320 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
322 * Note that XLIM, YLIM are exclusive bounds.
323 * All line numbers are origin-0 and discarded lines are not counted.
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]) {
333 // Slide up the top initial diagonal.
334 while ($xlim > $xoff && $ylim > $yoff
335 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
340 if ($xoff == $xlim || $yoff == $ylim)
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;
348 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
352 // X and Y sequences have no common subsequence:
354 while ($yoff < $ylim)
355 $this->ychanged[$this->yind[$yoff++]] = 1;
356 while ($xoff < $xlim)
357 $this->xchanged[$this->xind[$xoff++]] = 1;
360 // Use the partitions to split this problem into subproblems.
363 while ($pt2 = next($seps)) {
364 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
370 /* Adjust inserts/deletes of identical lines to join changes
371 * as much as possible.
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".
380 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
382 function _shift_boundaries ($lines, &$changed, $other_changed) {
386 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
387 $len = sizeof($lines);
388 $other_len = sizeof($other_changed);
392 * Scan forwards to find beginning of another run of changes.
393 * Also keep track of the corresponding point in the other file.
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
399 * Furthermore, $j is always kept so that $j == $other_len or
400 * $other_changed[$j] == false.
402 while ($j < $other_len && $other_changed[$j])
405 while ($i < $len && ! $changed[$i]) {
406 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
408 while ($j < $other_len && $other_changed[$j])
417 // Find the end of this run of changes.
418 while (++$i < $len && $changed[$i])
423 * Record the length of this run of changes, so that
424 * we can later determine whether the run has grown.
426 $runlength = $i - $start;
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.
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])
438 USE_ASSERTS && assert('$j > 0');
439 while ($other_changed[--$j])
441 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
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.
449 $corresponding = $j < $other_len ? $i : $len;
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.
458 while ($i < $len && $lines[$start] == $lines[$i]) {
459 $changed[$start++] = false;
461 while ($i < $len && $changed[$i])
464 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
466 if ($j < $other_len && $other_changed[$j]) {
468 while ($j < $other_len && $other_changed[$j])
472 } while ($runlength != $i - $start);
475 * If possible, move the fully-merged run of changes
476 * back to a corresponding run in the other file.
478 while ($corresponding < $i) {
479 $changed[--$start] = 1;
481 USE_ASSERTS && assert('$j > 0');
482 while ($other_changed[--$j])
484 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
491 * Class representing a 'diff' between two sequences of strings.
499 * Computes diff between sequences of strings.
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.
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);
512 * Compute reversed Diff.
516 * $diff = new Diff($lines1, $lines2);
517 * $rev = $diff->reverse();
518 * @return object A Diff object representing the inverse of the
521 function reverse () {
523 $rev->edits = array();
524 foreach ($this->edits as $edit) {
525 $rev->edits[] = $edit->reverse();
531 * Check for empty diff.
533 * @return bool True iff two sequences were identical.
535 function isEmpty () {
536 foreach ($this->edits as $edit) {
537 if ($edit->type != 'copy')
544 * Compute the length of the Longest Common Subsequence (LCS).
546 * This is mostly for diagnostic purposed.
548 * @return int The length of the LCS.
552 foreach ($this->edits as $edit) {
553 if ($edit->type == 'copy')
554 $lcs += sizeof($edit->orig);
560 * Get the original set of lines.
562 * This reconstructs the $from_lines parameter passed to the
565 * @return array The original sequence of strings.
570 foreach ($this->edits as $edit) {
572 array_splice($lines, sizeof($lines), 0, $edit->orig);
578 * Get the final set of lines.
580 * This reconstructs the $to_lines parameter passed to the
583 * @return array The sequence of strings.
588 foreach ($this->edits as $edit) {
590 array_splice($lines, sizeof($lines), 0, $edit->final);
596 * Check a Diff for validity.
598 * This is here only for debugging purposes.
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);
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);
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;
621 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
637 * Computes diff between sequences of strings.
639 * This can be used to compute things like
640 * case-insensitve diffs, or diffs which ignore
641 * changes in white-space.
643 * @param $from_lines array An array of strings.
644 * (Typically these are lines from a file.)
646 * @param $to_lines array An array of strings.
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.
654 * @param $mapped_to_lines array This array should
655 * have the same number of elements as $to_lines.
657 function MappedDiff($from_lines, $to_lines,
658 $mapped_from_lines, $mapped_to_lines) {
660 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
661 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
663 $this->Diff($mapped_from_lines, $mapped_to_lines);
666 for ($i = 0; $i < sizeof($this->edits); $i++) {
667 $orig = &$this->edits[$i]->orig;
668 if (is_array($orig)) {
669 $orig = array_slice($from_lines, $xi, sizeof($orig));
670 $xi += sizeof($orig);
673 $final = &$this->edits[$i]->final;
674 if (is_array($final)) {
675 $final = array_slice($to_lines, $yi, sizeof($final));
676 $yi += sizeof($final);
684 * A class to format Diffs
686 * This class formats the diff in classic diff format.
687 * It is intended that this class be customized via inheritance,
688 * to obtain fancier outputs.
693 * Number of leading context "lines" to preserve.
695 * This should be left at zero for this class, but subclasses
696 * may want to set this to other values.
698 var $leading_context_lines = 0;
701 * Number of trailing context "lines" to preserve.
703 * This should be left at zero for this class, but subclasses
704 * may want to set this to other values.
706 var $trailing_context_lines = 0;
711 * @param $diff object A Diff object.
712 * @return string The formatted output.
714 function format($diff) {
720 $nlead = $this->leading_context_lines;
721 $ntrail = $this->trailing_context_lines;
723 $this->_start_diff();
725 foreach ($diff->edits as $edit) {
726 if ($edit->type == 'copy') {
727 if (is_array($block)) {
728 if (sizeof($edit->orig) <= $nlead + $ntrail) {
733 $context = array_slice($edit->orig, 0, $ntrail);
734 $block[] = new _DiffOp_Copy($context);
736 $this->_block($x0, $ntrail + $xi - $x0,
737 $y0, $ntrail + $yi - $y0,
742 $context = $edit->orig;
745 if (! is_array($block)) {
746 $context = array_slice($context, sizeof($context) - $nlead);
747 $x0 = $xi - sizeof($context);
748 $y0 = $yi - sizeof($context);
751 $block[] = new _DiffOp_Copy($context);
757 $xi += sizeof($edit->orig);
759 $yi += sizeof($edit->final);
762 if (is_array($block))
763 $this->_block($x0, $xi - $x0,
767 return $this->_end_diff();
770 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
771 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
772 foreach ($edits as $edit) {
773 if ($edit->type == 'copy')
774 $this->_context($edit->orig);
775 elseif ($edit->type == 'add')
776 $this->_added($edit->final);
777 elseif ($edit->type == 'delete')
778 $this->_deleted($edit->orig);
779 elseif ($edit->type == 'change')
780 $this->_changed($edit->orig, $edit->final);
782 trigger_error("Unknown edit type", E_USER_ERROR);
787 function _start_diff() {
791 function _end_diff() {
792 $val = ob_get_contents();
797 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
799 $xbeg .= "," . ($xbeg + $xlen - 1);
801 $ybeg .= "," . ($ybeg + $ylen - 1);
803 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
806 function _start_block($header) {
810 function _end_block() {
813 function _lines($lines, $prefix = ' ') {
814 foreach ($lines as $line)
815 echo "$prefix $line\n";
818 function _context($lines) {
819 $this->_lines($lines);
822 function _added($lines) {
823 $this->_lines($lines, ">");
825 function _deleted($lines) {
826 $this->_lines($lines, "<");
829 function _changed($orig, $final) {
830 $this->_deleted($orig);
832 $this->_added($final);
837 * "Unified" diff formatter.
839 * This class formats the diff in classic "unified diff" format.
841 class UnifiedDiffFormatter extends DiffFormatter
843 function UnifiedDiffFormatter($context_lines = 4) {
844 $this->leading_context_lines = $context_lines;
845 $this->trailing_context_lines = $context_lines;
848 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
850 $xbeg .= "," . $xlen;
852 $ybeg .= "," . $ylen;
853 return "@@ -$xbeg +$ybeg @@";
856 function _added($lines) {
857 $this->_lines($lines, "+");
859 function _deleted($lines) {
860 $this->_lines($lines, "-");
862 function _changed($orig, $final) {
863 $this->_deleted($orig);
864 $this->_added($final);
872 // c-hanging-comment-ender-p: nil
873 // indent-tabs-mode: nil