2 rcs_id('$Id: difflib.php,v 1.1 2001-12-13 05:10:04 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 trigger_error("pure virtual", E_USER_ERROR);
30 class _DiffOp_Copy extends _DiffOp {
33 function _DiffOp_Copy ($lines) {
35 $this->final = &$this->orig;
43 class _DiffOp_Delete extends _DiffOp {
46 function _DiffOp_Delete ($lines) {
52 return new _DiffOp_Add($this->orig);
56 class _DiffOp_Add extends _DiffOp {
59 function _DiffOp_Add ($lines) {
60 $this->final = $lines;
65 return new _DiffOp_Delete($this->final);
69 class _DiffOp_Change extends _DiffOp {
72 function _DiffOp_Change ($orig, $final) {
74 $this->final = $final;
78 return new _DiffOp_Change($this->final, $this->orig);
84 * Class used internally by Diff to actually compute the diffs.
86 * The algorithm used here is mostly lifted from the perl module
87 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
88 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
90 * More ideas are taken from:
91 * http://www.ics.uci.edu/~eppstein/161/960229.html
93 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
94 * diffutils-2.7, which can be found at:
95 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
97 * Finally, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
102 var $xv = array(), $yv = array();
104 function diff ($from_lines, $to_lines) {
105 $n_from = sizeof($from_lines);
106 $n_to = sizeof($to_lines);
109 // Skip leading common lines.
110 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
111 if ($from_lines[$skip] != $to_lines[$skip])
113 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
115 // Skip trailing common lines.
116 $xi = $n_from; $yi = $n_to;
117 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
118 if ($from_lines[$xi] != $to_lines[$yi])
120 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
123 // Ignore lines which do not exist in both files.
124 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
125 $xhash[$from_lines[$xi]] = 1;
126 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
127 $line = $to_lines[$yi];
128 if ( ($this->ychanged[$yi] = empty($xhash[$line])) )
134 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
135 $line = $from_lines[$xi];
136 if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
143 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
145 // Merge edits when possible
146 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
147 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
149 // Compute the edit operations.
152 while ($xi < $n_from || $yi < $n_to) {
153 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
154 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
156 // Skip matching "snake".
158 while ( $xi < $n_from && $yi < $n_to
159 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
160 $copy[] = $from_lines[$xi++];
164 $edits[] = new _DiffOp_Copy($copy);
166 // Find deletes & adds.
168 while ($xi < $n_from && $this->xchanged[$xi])
169 $delete[] = $from_lines[$xi++];
172 while ($yi < $n_to && $this->ychanged[$yi])
173 $add[] = $to_lines[$yi++];
176 $edits[] = new _DiffOp_Change($delete, $add);
178 $edits[] = new _DiffOp_Delete($delete);
180 $edits[] = new _DiffOp_Add($add);
186 /* Divide the Largest Common Subsequence (LCS) of the sequences
187 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
190 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
191 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
192 * sub sequences. The first sub-sequence is contained in [X0, X1),
193 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
194 * that (X0, Y0) == (XOFF, YOFF) and
195 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
197 * This function assumes that the first lines of the specified portions
198 * of the two files do not match, and likewise that the last lines do not
199 * match. The caller must trim matching lines from the beginning and end
200 * of the portions it is going to specify.
202 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
205 if ($xlim - $xoff > $ylim - $yoff) {
206 // Things seems faster (I'm not sure I understand why)
207 // when the shortest sequence in X.
209 list ($xoff, $xlim, $yoff, $ylim)
210 = array( $yoff, $ylim, $xoff, $xlim);
214 for ($i = $ylim - 1; $i >= $yoff; $i--)
215 $ymatches[$this->xv[$i]][] = $i;
217 for ($i = $ylim - 1; $i >= $yoff; $i--)
218 $ymatches[$this->yv[$i]][] = $i;
221 $this->seq[0]= $yoff - 1;
222 $this->in_seq = array();
225 $numer = $xlim - $xoff + $nchunks - 1;
227 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
229 for ($i = 0; $i <= $this->lcs; $i++)
230 $ymids[$i][$chunk-1] = $this->seq[$i];
232 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
233 for ( ; $x < $x1; $x++) {
234 $line = $flip ? $this->yv[$x] : $this->xv[$x];
235 if (empty($ymatches[$line]))
237 $matches = $ymatches[$line];
239 while (list ($junk, $y) = each($matches))
240 if (empty($this->in_seq[$y])) {
241 $k = $this->_lcs_pos($y);
242 USE_ASSERTS && assert($k > 0);
243 $ymids[$k] = $ymids[$k-1];
246 while (list ($junk, $y) = each($matches)) {
247 if ($y > $this->seq[$k-1]) {
248 USE_ASSERTS && assert($y < $this->seq[$k]);
249 // Optimization: this is a common case:
250 // next match is just replacing previous match.
251 $this->in_seq[$this->seq[$k]] = false;
253 $this->in_seq[$y] = 1;
255 else if (empty($this->in_seq[$y])) {
256 $k = $this->_lcs_pos($y);
257 USE_ASSERTS && assert($k > 0);
258 $ymids[$k] = $ymids[$k-1];
264 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
265 $ymid = $ymids[$this->lcs];
266 for ($n = 0; $n < $nchunks - 1; $n++) {
267 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
269 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
271 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
273 return array($this->lcs, $seps);
276 function _lcs_pos ($ypos) {
278 if ($end == 0 || $ypos > $this->seq[$end]) {
279 $this->seq[++$this->lcs] = $ypos;
280 $this->in_seq[$ypos] = 1;
285 while ($beg < $end) {
286 $mid = (int)(($beg + $end) / 2);
287 if ( $ypos > $this->seq[$mid] )
293 USE_ASSERTS && assert($ypos != $this->seq[$end]);
295 $this->in_seq[$this->seq[$end]] = false;
296 $this->seq[$end] = $ypos;
297 $this->in_seq[$ypos] = 1;
301 /* Find LCS of two sequences.
303 * The results are recorded in the vectors $this->{x,y}changed[], by
304 * storing a 1 in the element for each line that is an insertion
305 * or deletion (ie. is not in the LCS).
307 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
309 * Note that XLIM, YLIM are exclusive bounds.
310 * All line numbers are origin-0 and discarded lines are not counted.
312 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
313 // Slide down the bottom initial diagonal.
314 while ($xoff < $xlim && $yoff < $ylim
315 && $this->xv[$xoff] == $this->yv[$yoff]) {
320 // Slide up the top initial diagonal.
321 while ($xlim > $xoff && $ylim > $yoff
322 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
327 if ($xoff == $xlim || $yoff == $ylim)
330 // This is ad hoc but seems to work well.
331 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
332 //$nchunks = max(2,min(8,(int)$nchunks));
333 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
335 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
339 // X and Y sequences have no common subsequence:
341 while ($yoff < $ylim)
342 $this->ychanged[$this->yind[$yoff++]] = 1;
343 while ($xoff < $xlim)
344 $this->xchanged[$this->xind[$xoff++]] = 1;
347 // Use the partitions to split this problem into subproblems.
350 while ($pt2 = next($seps)) {
351 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
357 /* Adjust inserts/deletes of identical lines to join changes
358 * as much as possible.
360 * We do something when a run of changed lines include a
361 * line at one end and has an excluded, identical line at the other.
362 * We are free to choose which identical line is included.
363 * `compareseq' usually chooses the one at the beginning,
364 * but usually it is cleaner to consider the following identical line
365 * to be the "change".
367 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
369 function _shift_boundaries ($lines, &$changed, $other_changed) {
373 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
374 $len = sizeof($lines);
375 $other_len = sizeof($other_changed);
379 * Scan forwards to find beginning of another run of changes.
380 * Also keep track of the corresponding point in the other file.
382 * Throughout this code, $i and $j are adjusted together so that
383 * the first $i elements of $changed and the first $j elements
384 * of $other_changed both contain the same number of zeros
386 * Furthermore, $j is always kept so that $j == $other_len or
387 * $other_changed[$j] == false.
389 while ($j < $other_len && $other_changed[$j])
392 while ($i < $len && ! $changed[$i]) {
393 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
395 while ($j < $other_len && $other_changed[$j])
404 // Find the end of this run of changes.
405 while (++$i < $len && $changed[$i])
410 * Record the length of this run of changes, so that
411 * we can later determine whether the run has grown.
413 $runlength = $i - $start;
416 * Move the changed region back, so long as the
417 * previous unchanged line matches the last changed one.
418 * This merges with previous changed regions.
420 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
421 $changed[--$start] = 1;
422 $changed[--$i] = false;
423 while ($start > 0 && $changed[$start - 1])
425 USE_ASSERTS && assert('$j > 0');
426 while ($other_changed[--$j])
428 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
432 * Set CORRESPONDING to the end of the changed run, at the last
433 * point where it corresponds to a changed run in the other file.
434 * CORRESPONDING == LEN means no such point has been found.
436 $corresponding = $j < $other_len ? $i : $len;
439 * Move the changed region forward, so long as the
440 * first changed line matches the following unchanged one.
441 * This merges with following changed regions.
442 * Do this second, so that if there are no merges,
443 * the changed region is moved forward as far as possible.
445 while ($i < $len && $lines[$start] == $lines[$i]) {
446 $changed[$start++] = false;
448 while ($i < $len && $changed[$i])
451 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
453 if ($j < $other_len && $other_changed[$j]) {
455 while ($j < $other_len && $other_changed[$j])
459 } while ($runlength != $i - $start);
462 * If possible, move the fully-merged run of changes
463 * back to a corresponding run in the other file.
465 while ($corresponding < $i) {
466 $changed[--$start] = 1;
468 USE_ASSERTS && assert('$j > 0');
469 while ($other_changed[--$j])
471 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
478 * Class representing a diff between two files.
485 * Compute diff between lists of strings.
487 function Diff($from_lines, $to_lines) {
488 $eng = new _DiffEngine;
489 $this->edits = $eng->diff($from_lines, $to_lines);
490 //$this->_check($from_lines, $to_lines);
494 * Compute reversed Diff.
498 * $diff = new Diff($lines1, $lines2);
499 * $rev = $diff->reverse();
501 * // reconstruct $lines1 from $lines2:
502 * $out = $rev->apply($lines2);
504 function reverse () {
506 $rev->edits = array();
507 foreach ($this->edits as $edit) {
508 $rev->edits[] = $edit->reverse();
514 * Return true if two files were equal.
516 function isEmpty () {
517 foreach ($this->edits as $edit) {
518 if ($edit->type != 'copy')
525 * Compute the length of the Longest Common Subsequence (LCS).
527 * This is mostly for diagnostic purposed.
531 foreach ($this->edits as $edit) {
532 if ($edit->type == 'copy')
533 $lcs += sizeof($edit->orig);
539 * Get the original set of lines.
544 foreach ($this->edits as $edit) {
546 array_splice($lines, sizeof($lines), 0, $edit->orig);
552 * Get the final set of lines.
557 foreach ($this->edits as $edit) {
559 array_splice($lines, sizeof($lines), 0, $edit->final);
565 * Check a Diff for validity.
567 * This is here only for debugging purposes.
569 function _check ($from_lines, $to_lines) {
570 if (serialize($from_lines) != serialize($this->orig()))
571 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
572 if (serialize($to_lines) != serialize($this->final()))
573 trigger_error("Reconstructed final doesn't match", E_USER_ERROR);
575 $rev = $this->reverse();
576 if (serialize($to_lines) != serialize($rev->orig()))
577 trigger_error("Reversed original doesn't match", E_USER_ERROR);
578 if (serialize($from_lines) != serialize($rev->final()))
579 trigger_error("Reversed final doesn't match", E_USER_ERROR);
583 foreach ($this->edits as $edit) {
584 if ( $prevtype == $edit->type )
585 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
586 $prevtype = $edit->type;
590 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
596 var $leading_context_lines = 0;
597 var $trailing_context_lines = 0;
599 function format($diff) {
605 $nlead = $this->leading_context_lines;
606 $ntrail = $this->trailing_context_lines;
609 $this->_start_diff();
611 foreach ($diff->edits as $edit) {
612 if ($edit->type == 'copy') {
613 if (is_array($block)) {
614 if (sizeof($edit->orig) <= $nlead + $ntrail) {
619 $context = array_slice($edit->orig, 0, $ntrail);
620 $block[] = new _DiffOp_Copy($context);
622 $this->_block($x0, $ntrail + $xi - $x0,
623 $y0, $ntrail + $yi - $y0,
628 $context = $edit->orig;
631 if (! is_array($block)) {
632 $context = array_slice($context, sizeof($context) - $nlead);
633 $x0 = $xi - sizeof($context);
634 $y0 = $yi - sizeof($context);
637 $block[] = new _DiffOp_Copy($context);
643 $xi += sizeof($edit->orig);
645 $yi += sizeof($edit->final);
648 if (is_array($block))
649 $this->_block($x0, $xi - $x0,
655 $val = ob_get_contents();
660 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
661 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
662 foreach ($edits as $edit) {
663 if ($edit->type == 'copy')
664 $this->_context($edit->orig);
665 elseif ($edit->type == 'add')
666 $this->_added($edit->final);
667 elseif ($edit->type == 'delete')
668 $this->_deleted($edit->orig);
669 elseif ($edit->type == 'change')
670 $this->_changed($edit->orig, $edit->final);
672 trigger_error("Unknown edit type", E_USER_ERROR);
677 function _start_diff() {
680 function _end_diff() {
683 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
685 $xbeg .= "," . ($xbeg + $xlen - 1);
687 $ybeg .= "," . ($ybeg + $ylen - 1);
689 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
692 function _start_block($header) {
696 function _end_block() {
699 function _lines($lines, $prefix = ' ') {
700 foreach ($lines as $line)
701 echo "$prefix $line\n";
704 function _context($lines) {
705 $this->_lines($lines);
708 function _added($lines) {
709 $this->_lines($lines, ">");
711 function _deleted($lines) {
712 $this->_lines($lines, "<");
715 function _changed($orig, $final) {
716 $this->_deleted($orig);
718 $this->_added($final);
722 class UnifiedDiffFormatter extends DiffFormatter
724 function UnifiedDiffFormatter($context_lines = 4) {
725 $this->leading_context_lines = $context_lines;
726 $this->trailing_context_lines = $context_lines;
729 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
731 $xbeg .= "," . $xlen;
733 $ybeg .= "," . $ylen;
734 return "@@ -$xbeg +$ybeg @@";
737 function _added($lines) {
738 $this->_lines($lines, "+");
740 function _deleted($lines) {
741 $this->_lines($lines, "-");
743 function _changed($orig, $final) {
744 $this->_deleted($orig);
745 $this->_added($final);
753 // c-hanging-comment-ender-p: nil
754 // indent-tabs-mode: nil