6 // A PHP diff engine for phpwiki.
8 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
9 // You may copy this code freely under the conditions of the GPL.
18 trigger_error("pure virtual", E_USER_ERROR);
22 return $this->orig ? sizeof($this->orig) : 0;
26 return $this->final ? sizeof($this->final) : 0;
30 class _DiffOp_Copy extends _DiffOp {
33 function _DiffOp_Copy ($orig, $final = false) {
34 if (!is_array($final))
37 $this->final = $final;
41 return new _DiffOp_Copy($this->final, $this->orig);
45 class _DiffOp_Delete extends _DiffOp {
48 function _DiffOp_Delete ($lines) {
54 return new _DiffOp_Add($this->orig);
58 class _DiffOp_Add extends _DiffOp {
61 function _DiffOp_Add ($lines) {
62 $this->final = $lines;
67 return new _DiffOp_Delete($this->final);
71 class _DiffOp_Change extends _DiffOp {
74 function _DiffOp_Change ($orig, $final) {
76 $this->final = $final;
80 return new _DiffOp_Change($this->final, $this->orig);
86 * Class used internally by Diff to actually compute the diffs.
88 * The algorithm used here is mostly lifted from the perl module
89 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
90 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
92 * More ideas are taken from:
93 * http://www.ics.uci.edu/~eppstein/161/960229.html
95 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
96 * diffutils-2.7, which can be found at:
97 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
99 * Finally, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
102 * @author Geoffrey T. Dairiki
107 function diff ($from_lines, $to_lines) {
108 $n_from = sizeof($from_lines);
109 $n_to = sizeof($to_lines);
111 $this->xchanged = $this->ychanged = array();
112 $this->xv = $this->yv = array();
113 $this->xind = $this->yind = array();
115 unset($this->in_seq);
118 // Skip leading common lines.
119 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
120 if ($from_lines[$skip] != $to_lines[$skip])
122 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
124 // Skip trailing common lines.
125 $xi = $n_from; $yi = $n_to;
126 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
127 if ($from_lines[$xi] != $to_lines[$yi])
129 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
132 // Ignore lines which do not exist in both files.
133 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
134 $xhash[$from_lines[$xi]] = 1;
135 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
136 $line = $to_lines[$yi];
137 if ( ($this->ychanged[$yi] = empty($xhash[$line])) )
143 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
144 $line = $from_lines[$xi];
145 if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
152 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
154 // Merge edits when possible
155 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
156 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
158 // Compute the edit operations.
161 while ($xi < $n_from || $yi < $n_to) {
162 assert($yi < $n_to || $this->xchanged[$xi]);
163 assert($xi < $n_from || $this->ychanged[$yi]);
165 // Skip matching "snake".
167 while ( $xi < $n_from && $yi < $n_to
168 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
169 $copy[] = $from_lines[$xi++];
173 $edits[] = new _DiffOp_Copy($copy);
175 // Find deletes & adds.
177 while ($xi < $n_from && $this->xchanged[$xi])
178 $delete[] = $from_lines[$xi++];
181 while ($yi < $n_to && $this->ychanged[$yi])
182 $add[] = $to_lines[$yi++];
185 $edits[] = new _DiffOp_Change($delete, $add);
187 $edits[] = new _DiffOp_Delete($delete);
189 $edits[] = new _DiffOp_Add($add);
195 /* Divide the Largest Common Subsequence (LCS) of the sequences
196 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
199 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
200 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
201 * sub sequences. The first sub-sequence is contained in [X0, X1),
202 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
203 * that (X0, Y0) == (XOFF, YOFF) and
204 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
206 * This function assumes that the first lines of the specified portions
207 * of the two files do not match, and likewise that the last lines do not
208 * match. The caller must trim matching lines from the beginning and end
209 * of the portions it is going to specify.
211 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
214 if ($xlim - $xoff > $ylim - $yoff) {
215 // Things seems faster (I'm not sure I understand why)
216 // when the shortest sequence in X.
218 list ($xoff, $xlim, $yoff, $ylim)
219 = array( $yoff, $ylim, $xoff, $xlim);
223 for ($i = $ylim - 1; $i >= $yoff; $i--)
224 $ymatches[$this->xv[$i]][] = $i;
226 for ($i = $ylim - 1; $i >= $yoff; $i--)
227 $ymatches[$this->yv[$i]][] = $i;
230 $this->seq[0]= $yoff - 1;
231 $this->in_seq = array();
234 $numer = $xlim - $xoff + $nchunks - 1;
236 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
238 for ($i = 0; $i <= $this->lcs; $i++)
239 $ymids[$i][$chunk-1] = $this->seq[$i];
241 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
242 for ( ; $x < $x1; $x++) {
243 $line = $flip ? $this->yv[$x] : $this->xv[$x];
244 if (empty($ymatches[$line]))
246 $matches = $ymatches[$line];
248 while (list ($junk, $y) = each($matches))
249 if (empty($this->in_seq[$y])) {
250 $k = $this->_lcs_pos($y);
252 $ymids[$k] = $ymids[$k-1];
255 while (list ($junk, $y) = each($matches)) {
256 if ($y > $this->seq[$k-1]) {
257 assert($y < $this->seq[$k]);
258 // Optimization: this is a common case:
259 // next match is just replacing previous match.
260 $this->in_seq[$this->seq[$k]] = false;
262 $this->in_seq[$y] = 1;
264 else if (empty($this->in_seq[$y])) {
265 $k = $this->_lcs_pos($y);
267 $ymids[$k] = $ymids[$k-1];
273 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
274 $ymid = $ymids[$this->lcs];
275 for ($n = 0; $n < $nchunks - 1; $n++) {
276 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
278 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
280 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
282 return array($this->lcs, $seps);
285 function _lcs_pos ($ypos) {
287 if ($end == 0 || $ypos > $this->seq[$end]) {
288 $this->seq[++$this->lcs] = $ypos;
289 $this->in_seq[$ypos] = 1;
294 while ($beg < $end) {
295 $mid = (int)(($beg + $end) / 2);
296 if ( $ypos > $this->seq[$mid] )
302 assert($ypos != $this->seq[$end]);
304 $this->in_seq[$this->seq[$end]] = false;
305 $this->seq[$end] = $ypos;
306 $this->in_seq[$ypos] = 1;
310 /* Find LCS of two sequences.
312 * The results are recorded in the vectors $this->{x,y}changed[], by
313 * storing a 1 in the element for each line that is an insertion
314 * or deletion (ie. is not in the LCS).
316 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
318 * Note that XLIM, YLIM are exclusive bounds.
319 * All line numbers are origin-0 and discarded lines are not counted.
321 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
322 // Slide down the bottom initial diagonal.
323 while ($xoff < $xlim && $yoff < $ylim
324 && $this->xv[$xoff] == $this->yv[$yoff]) {
329 // Slide up the top initial diagonal.
330 while ($xlim > $xoff && $ylim > $yoff
331 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
336 if ($xoff == $xlim || $yoff == $ylim)
339 // This is ad hoc but seems to work well.
340 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
341 //$nchunks = max(2,min(8,(int)$nchunks));
342 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
344 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
348 // X and Y sequences have no common subsequence:
350 while ($yoff < $ylim)
351 $this->ychanged[$this->yind[$yoff++]] = 1;
352 while ($xoff < $xlim)
353 $this->xchanged[$this->xind[$xoff++]] = 1;
356 // Use the partitions to split this problem into subproblems.
359 while ($pt2 = next($seps)) {
360 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
366 /* Adjust inserts/deletes of identical lines to join changes
367 * as much as possible.
369 * We do something when a run of changed lines include a
370 * line at one end and has an excluded, identical line at the other.
371 * We are free to choose which identical line is included.
372 * `compareseq' usually chooses the one at the beginning,
373 * but usually it is cleaner to consider the following identical line
374 * to be the "change".
376 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
378 function _shift_boundaries ($lines, &$changed, $other_changed) {
382 assert('sizeof($lines) == sizeof($changed)');
383 $len = sizeof($lines);
384 $other_len = sizeof($other_changed);
388 * Scan forwards to find beginning of another run of changes.
389 * Also keep track of the corresponding point in the other file.
391 * Throughout this code, $i and $j are adjusted together so that
392 * the first $i elements of $changed and the first $j elements
393 * of $other_changed both contain the same number of zeros
395 * Furthermore, $j is always kept so that $j == $other_len or
396 * $other_changed[$j] == false.
398 while ($j < $other_len && $other_changed[$j])
401 while ($i < $len && ! $changed[$i]) {
402 assert('$j < $other_len && ! $other_changed[$j]');
404 while ($j < $other_len && $other_changed[$j])
413 // Find the end of this run of changes.
414 while (++$i < $len && $changed[$i])
419 * Record the length of this run of changes, so that
420 * we can later determine whether the run has grown.
422 $runlength = $i - $start;
425 * Move the changed region back, so long as the
426 * previous unchanged line matches the last changed one.
427 * This merges with previous changed regions.
429 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
430 $changed[--$start] = 1;
431 $changed[--$i] = false;
432 while ($start > 0 && $changed[$start - 1])
435 while ($other_changed[--$j])
437 assert('$j >= 0 && !$other_changed[$j]');
441 * Set CORRESPONDING to the end of the changed run, at the last
442 * point where it corresponds to a changed run in the other file.
443 * CORRESPONDING == LEN means no such point has been found.
445 $corresponding = $j < $other_len ? $i : $len;
448 * Move the changed region forward, so long as the
449 * first changed line matches the following unchanged one.
450 * This merges with following changed regions.
451 * Do this second, so that if there are no merges,
452 * the changed region is moved forward as far as possible.
454 while ($i < $len && $lines[$start] == $lines[$i]) {
455 $changed[$start++] = false;
457 while ($i < $len && $changed[$i])
460 assert('$j < $other_len && ! $other_changed[$j]');
462 if ($j < $other_len && $other_changed[$j]) {
464 while ($j < $other_len && $other_changed[$j])
468 } while ($runlength != $i - $start);
471 * If possible, move the fully-merged run of changes
472 * back to a corresponding run in the other file.
474 while ($corresponding < $i) {
475 $changed[--$start] = 1;
478 while ($other_changed[--$j])
480 assert('$j >= 0 && !$other_changed[$j]');
487 * Class representing a 'diff' between two sequences of strings.
495 * Computes diff between sequences of strings.
497 * @param $from_lines array An array of strings.
498 * (Typically these are lines from a file.)
499 * @param $to_lines array An array of strings.
501 function Diff($from_lines, $to_lines) {
502 $eng = new _DiffEngine;
503 $this->edits = $eng->diff($from_lines, $to_lines);
504 //$this->_check($from_lines, $to_lines);
508 * Compute reversed Diff.
512 * $diff = new Diff($lines1, $lines2);
513 * $rev = $diff->reverse();
514 * @return object A Diff object representing the inverse of the
517 function reverse () {
519 $rev->edits = array();
520 foreach ($this->edits as $edit) {
521 $rev->edits[] = $edit->reverse();
527 * Check for empty diff.
529 * @return bool True iff two sequences were identical.
531 function isEmpty () {
532 foreach ($this->edits as $edit) {
533 if ($edit->type != 'copy')
540 * Compute the length of the Longest Common Subsequence (LCS).
542 * This is mostly for diagnostic purposed.
544 * @return int The length of the LCS.
548 foreach ($this->edits as $edit) {
549 if ($edit->type == 'copy')
550 $lcs += sizeof($edit->orig);
556 * Get the original set of lines.
558 * This reconstructs the $from_lines parameter passed to the
561 * @return array The original sequence of strings.
566 foreach ($this->edits as $edit) {
568 array_splice($lines, sizeof($lines), 0, $edit->orig);
574 * Get the final set of lines.
576 * This reconstructs the $to_lines parameter passed to the
579 * @return array The sequence of strings.
584 foreach ($this->edits as $edit) {
586 array_splice($lines, sizeof($lines), 0, $edit->final);
592 * Check a Diff for validity.
594 * This is here only for debugging purposes.
596 function _check ($from_lines, $to_lines) {
597 if (serialize($from_lines) != serialize($this->orig()))
598 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
599 if (serialize($to_lines) != serialize($this->_final()))
600 trigger_error("Reconstructed final doesn't match", E_USER_ERROR);
602 $rev = $this->reverse();
603 if (serialize($to_lines) != serialize($rev->orig()))
604 trigger_error("Reversed original doesn't match", E_USER_ERROR);
605 if (serialize($from_lines) != serialize($rev->_final()))
606 trigger_error("Reversed final doesn't match", E_USER_ERROR);
610 foreach ($this->edits as $edit) {
611 if ( $prevtype == $edit->type )
612 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
613 $prevtype = $edit->type;
617 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
633 * Computes diff between sequences of strings.
635 * This can be used to compute things like
636 * case-insensitve diffs, or diffs which ignore
637 * changes in white-space.
639 * @param $from_lines array An array of strings.
640 * (Typically these are lines from a file.)
642 * @param $to_lines array An array of strings.
644 * @param $mapped_from_lines array This array should
645 * have the same size number of elements as $from_lines.
646 * The elements in $mapped_from_lines and
647 * $mapped_to_lines are what is actually compared
648 * when computing the diff.
650 * @param $mapped_to_lines array This array should
651 * have the same number of elements as $to_lines.
653 function MappedDiff($from_lines, $to_lines,
654 $mapped_from_lines, $mapped_to_lines) {
656 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
657 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
659 $this->Diff($mapped_from_lines, $mapped_to_lines);
662 // Optimizing loop invariants:
663 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
664 for ($i = 0, $max = sizeof($this->edits); $i < $max; $i++) {
665 $orig = &$this->edits[$i]->orig;
666 if (is_array($orig)) {
667 $orig = array_slice($from_lines, $xi, sizeof($orig));
668 $xi += sizeof($orig);
671 $final = &$this->edits[$i]->final;
672 if (is_array($final)) {
673 $final = array_slice($to_lines, $yi, sizeof($final));
674 $yi += sizeof($final);
682 * A class to format Diffs
684 * This class formats the diff in classic diff format.
685 * It is intended that this class be customized via inheritance,
686 * to obtain fancier outputs.
691 * Number of leading context "lines" to preserve.
693 * This should be left at zero for this class, but subclasses
694 * may want to set this to other values.
696 var $leading_context_lines = 0;
699 * Number of trailing context "lines" to preserve.
701 * This should be left at zero for this class, but subclasses
702 * may want to set this to other values.
704 var $trailing_context_lines = 0;
709 * @param $diff object A Diff object.
710 * @return string The formatted output.
712 function format($diff) {
718 $nlead = $this->leading_context_lines;
719 $ntrail = $this->trailing_context_lines;
721 $this->_start_diff();
723 foreach ($diff->edits as $edit) {
724 if ($edit->type == 'copy') {
725 if (is_array($block)) {
726 if (sizeof($edit->orig) <= $nlead + $ntrail) {
731 $context = array_slice($edit->orig, 0, $ntrail);
732 $block[] = new _DiffOp_Copy($context);
734 $this->_block($x0, $ntrail + $xi - $x0,
735 $y0, $ntrail + $yi - $y0,
740 $context = $edit->orig;
743 if (! is_array($block)) {
744 $context = array_slice($context, max(0, sizeof($context) - $nlead));
745 $x0 = $xi - sizeof($context);
746 $y0 = $yi - sizeof($context);
749 $block[] = new _DiffOp_Copy($context);
755 $xi += sizeof($edit->orig);
757 $yi += sizeof($edit->final);
760 if (is_array($block))
761 $this->_block($x0, $xi - $x0,
765 return $this->_end_diff();
768 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
769 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
770 foreach ($edits as $edit) {
771 if ($edit->type == 'copy')
772 $this->_context($edit->orig);
773 elseif ($edit->type == 'add')
774 $this->_added($edit->final);
775 elseif ($edit->type == 'delete')
776 $this->_deleted($edit->orig);
777 elseif ($edit->type == 'change')
778 $this->_changed($edit->orig, $edit->final);
780 trigger_error("Unknown edit type", E_USER_ERROR);
785 function _start_diff() {
789 function _end_diff() {
790 $val = ob_get_contents();
795 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
797 $xbeg .= "," . ($xbeg + $xlen - 1);
799 $ybeg .= "," . ($ybeg + $ylen - 1);
801 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
804 function _start_block($header) {
808 function _end_block() {
811 function _lines($lines, $prefix = ' ') {
812 foreach ($lines as $line)
813 echo "$prefix $line\n";
816 function _context($lines) {
817 $this->_lines($lines);
820 function _added($lines) {
821 $this->_lines($lines, ">");
823 function _deleted($lines) {
824 $this->_lines($lines, "<");
827 function _changed($orig, $final) {
828 $this->_deleted($orig);
830 $this->_added($final);
835 * "Unified" diff formatter.
837 * This class formats the diff in classic "unified diff" format.
839 class UnifiedDiffFormatter extends DiffFormatter
841 function UnifiedDiffFormatter($context_lines = 4) {
842 $this->leading_context_lines = $context_lines;
843 $this->trailing_context_lines = $context_lines;
846 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
848 $xbeg .= "," . $xlen;
850 $ybeg .= "," . $ylen;
851 return "@@ -$xbeg +$ybeg @@\n";
854 function _added($lines) {
855 $this->_lines($lines, "+");
857 function _deleted($lines) {
858 $this->_lines($lines, "-");
860 function _changed($orig, $final) {
861 $this->_deleted($orig);
862 $this->_added($final);
867 * block conflict diff formatter.
869 * This class will format a diff identical to Diff3 (i.e. editpage
870 * conflicts), but when there are only two source files. To be used by
871 * future enhancements to reloading / upgrading pgsrc.
873 * Functional but not finished yet, need to eliminate redundant block
874 * suffixes (i.e. "=======" immediately followed by another prefix)
875 * see class LoadFileConflictPageEditor
877 class BlockDiffFormatter extends DiffFormatter
879 function BlockDiffFormatter($context_lines = 4) {
880 $this->leading_context_lines = $context_lines;
881 $this->trailing_context_lines = $context_lines;
883 function _lines($lines, $prefix = '') {
886 foreach ($lines as $line)
891 function _added($lines) {
892 $this->_lines($lines, ">>>>>>>");
894 function _deleted($lines) {
895 $this->_lines($lines, "<<<<<<<");
897 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
900 function _changed($orig, $final) {
901 $this->_deleted($orig);
902 $this->_added($final);
910 // c-hanging-comment-ender-p: nil
911 // indent-tabs-mode: nil