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);
85 * Class used internally by Diff to actually compute the diffs.
87 * The algorithm used here is mostly lifted from the perl module
88 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
89 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
91 * More ideas are taken from:
92 * http://www.ics.uci.edu/~eppstein/161/960229.html
94 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
95 * diffutils-2.7, which can be found at:
96 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
98 * Finally, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
101 * @author Geoffrey T. Dairiki
106 function diff ($from_lines, $to_lines) {
107 $n_from = sizeof($from_lines);
108 $n_to = sizeof($to_lines);
110 $this->xchanged = $this->ychanged = array();
111 $this->xv = $this->yv = array();
112 $this->xind = $this->yind = array();
114 unset($this->in_seq);
117 // Skip leading common lines.
118 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
119 if ($from_lines[$skip] != $to_lines[$skip])
121 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
123 // Skip trailing common lines.
124 $xi = $n_from; $yi = $n_to;
125 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
126 if ($from_lines[$xi] != $to_lines[$yi])
128 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
131 // Ignore lines which do not exist in both files.
132 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
133 $xhash[$from_lines[$xi]] = 1;
134 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
135 $line = $to_lines[$yi];
136 if ( ($this->ychanged[$yi] = empty($xhash[$line])) )
142 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
143 $line = $from_lines[$xi];
144 if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
151 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
153 // Merge edits when possible
154 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
155 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
157 // Compute the edit operations.
160 while ($xi < $n_from || $yi < $n_to) {
161 assert($yi < $n_to || $this->xchanged[$xi]);
162 assert($xi < $n_from || $this->ychanged[$yi]);
164 // Skip matching "snake".
166 while ( $xi < $n_from && $yi < $n_to
167 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
168 $copy[] = $from_lines[$xi++];
172 $edits[] = new _DiffOp_Copy($copy);
174 // Find deletes & adds.
176 while ($xi < $n_from && $this->xchanged[$xi])
177 $delete[] = $from_lines[$xi++];
180 while ($yi < $n_to && $this->ychanged[$yi])
181 $add[] = $to_lines[$yi++];
184 $edits[] = new _DiffOp_Change($delete, $add);
186 $edits[] = new _DiffOp_Delete($delete);
188 $edits[] = new _DiffOp_Add($add);
193 /* Divide the Largest Common Subsequence (LCS) of the sequences
194 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
197 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
198 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
199 * sub sequences. The first sub-sequence is contained in [X0, X1),
200 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
201 * that (X0, Y0) == (XOFF, YOFF) and
202 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
204 * This function assumes that the first lines of the specified portions
205 * of the two files do not match, and likewise that the last lines do not
206 * match. The caller must trim matching lines from the beginning and end
207 * of the portions it is going to specify.
209 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
212 if ($xlim - $xoff > $ylim - $yoff) {
213 // Things seems faster (I'm not sure I understand why)
214 // when the shortest sequence in X.
216 list ($xoff, $xlim, $yoff, $ylim)
217 = array( $yoff, $ylim, $xoff, $xlim);
221 for ($i = $ylim - 1; $i >= $yoff; $i--)
222 $ymatches[$this->xv[$i]][] = $i;
224 for ($i = $ylim - 1; $i >= $yoff; $i--)
225 $ymatches[$this->yv[$i]][] = $i;
228 $this->seq[0]= $yoff - 1;
229 $this->in_seq = array();
232 $numer = $xlim - $xoff + $nchunks - 1;
234 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
236 for ($i = 0; $i <= $this->lcs; $i++)
237 $ymids[$i][$chunk-1] = $this->seq[$i];
239 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
240 for ( ; $x < $x1; $x++) {
241 $line = $flip ? $this->yv[$x] : $this->xv[$x];
242 if (empty($ymatches[$line]))
244 $matches = $ymatches[$line];
246 while (list ($junk, $y) = each($matches))
247 if (empty($this->in_seq[$y])) {
248 $k = $this->_lcs_pos($y);
250 $ymids[$k] = $ymids[$k-1];
253 while (list ($junk, $y) = each($matches)) {
254 if ($y > $this->seq[$k-1]) {
255 assert($y < $this->seq[$k]);
256 // Optimization: this is a common case:
257 // next match is just replacing previous match.
258 $this->in_seq[$this->seq[$k]] = false;
260 $this->in_seq[$y] = 1;
262 else if (empty($this->in_seq[$y])) {
263 $k = $this->_lcs_pos($y);
265 $ymids[$k] = $ymids[$k-1];
271 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
272 $ymid = $ymids[$this->lcs];
273 for ($n = 0; $n < $nchunks - 1; $n++) {
274 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
276 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
278 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
280 return array($this->lcs, $seps);
283 function _lcs_pos ($ypos) {
285 if ($end == 0 || $ypos > $this->seq[$end]) {
286 $this->seq[++$this->lcs] = $ypos;
287 $this->in_seq[$ypos] = 1;
292 while ($beg < $end) {
293 $mid = (int)(($beg + $end) / 2);
294 if ( $ypos > $this->seq[$mid] )
300 assert($ypos != $this->seq[$end]);
302 $this->in_seq[$this->seq[$end]] = false;
303 $this->seq[$end] = $ypos;
304 $this->in_seq[$ypos] = 1;
308 /* Find LCS of two sequences.
310 * The results are recorded in the vectors $this->{x,y}changed[], by
311 * storing a 1 in the element for each line that is an insertion
312 * or deletion (ie. is not in the LCS).
314 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
316 * Note that XLIM, YLIM are exclusive bounds.
317 * All line numbers are origin-0 and discarded lines are not counted.
319 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
320 // Slide down the bottom initial diagonal.
321 while ($xoff < $xlim && $yoff < $ylim
322 && $this->xv[$xoff] == $this->yv[$yoff]) {
327 // Slide up the top initial diagonal.
328 while ($xlim > $xoff && $ylim > $yoff
329 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
334 if ($xoff == $xlim || $yoff == $ylim)
337 // This is ad hoc but seems to work well.
338 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
339 //$nchunks = max(2,min(8,(int)$nchunks));
340 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
342 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
346 // X and Y sequences have no common subsequence:
348 while ($yoff < $ylim)
349 $this->ychanged[$this->yind[$yoff++]] = 1;
350 while ($xoff < $xlim)
351 $this->xchanged[$this->xind[$xoff++]] = 1;
354 // Use the partitions to split this problem into subproblems.
357 while ($pt2 = next($seps)) {
358 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
364 /* Adjust inserts/deletes of identical lines to join changes
365 * as much as possible.
367 * We do something when a run of changed lines include a
368 * line at one end and has an excluded, identical line at the other.
369 * We are free to choose which identical line is included.
370 * `compareseq' usually chooses the one at the beginning,
371 * but usually it is cleaner to consider the following identical line
372 * to be the "change".
374 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
376 function _shift_boundaries ($lines, &$changed, $other_changed) {
380 assert('sizeof($lines) == sizeof($changed)');
381 $len = sizeof($lines);
382 $other_len = sizeof($other_changed);
386 * Scan forwards to find beginning of another run of changes.
387 * Also keep track of the corresponding point in the other file.
389 * Throughout this code, $i and $j are adjusted together so that
390 * the first $i elements of $changed and the first $j elements
391 * of $other_changed both contain the same number of zeros
393 * Furthermore, $j is always kept so that $j == $other_len or
394 * $other_changed[$j] == false.
396 while ($j < $other_len && $other_changed[$j])
399 while ($i < $len && ! $changed[$i]) {
400 assert('$j < $other_len && ! $other_changed[$j]');
402 while ($j < $other_len && $other_changed[$j])
411 // Find the end of this run of changes.
412 while (++$i < $len && $changed[$i])
417 * Record the length of this run of changes, so that
418 * we can later determine whether the run has grown.
420 $runlength = $i - $start;
423 * Move the changed region back, so long as the
424 * previous unchanged line matches the last changed one.
425 * This merges with previous changed regions.
427 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
428 $changed[--$start] = 1;
429 $changed[--$i] = false;
430 while ($start > 0 && $changed[$start - 1])
433 while ($other_changed[--$j])
435 assert('$j >= 0 && !$other_changed[$j]');
439 * Set CORRESPONDING to the end of the changed run, at the last
440 * point where it corresponds to a changed run in the other file.
441 * CORRESPONDING == LEN means no such point has been found.
443 $corresponding = $j < $other_len ? $i : $len;
446 * Move the changed region forward, so long as the
447 * first changed line matches the following unchanged one.
448 * This merges with following changed regions.
449 * Do this second, so that if there are no merges,
450 * the changed region is moved forward as far as possible.
452 while ($i < $len && $lines[$start] == $lines[$i]) {
453 $changed[$start++] = false;
455 while ($i < $len && $changed[$i])
458 assert('$j < $other_len && ! $other_changed[$j]');
460 if ($j < $other_len && $other_changed[$j]) {
462 while ($j < $other_len && $other_changed[$j])
466 } while ($runlength != $i - $start);
469 * If possible, move the fully-merged run of changes
470 * back to a corresponding run in the other file.
472 while ($corresponding < $i) {
473 $changed[--$start] = 1;
476 while ($other_changed[--$j])
478 assert('$j >= 0 && !$other_changed[$j]');
485 * Class representing a 'diff' between two sequences of strings.
493 * Computes diff between sequences of strings.
495 * @param $from_lines array An array of strings.
496 * (Typically these are lines from a file.)
497 * @param $to_lines array An array of strings.
499 function Diff($from_lines, $to_lines) {
500 $eng = new _DiffEngine;
501 $this->edits = $eng->diff($from_lines, $to_lines);
502 //$this->_check($from_lines, $to_lines);
506 * Compute reversed Diff.
510 * $diff = new Diff($lines1, $lines2);
511 * $rev = $diff->reverse();
512 * @return object A Diff object representing the inverse of the
515 function reverse () {
517 $rev->edits = array();
518 foreach ($this->edits as $edit) {
519 $rev->edits[] = $edit->reverse();
525 * Check for empty diff.
527 * @return bool True iff two sequences were identical.
529 function isEmpty () {
530 foreach ($this->edits as $edit) {
531 if ($edit->type != 'copy')
538 * Compute the length of the Longest Common Subsequence (LCS).
540 * This is mostly for diagnostic purposed.
542 * @return int The length of the LCS.
546 foreach ($this->edits as $edit) {
547 if ($edit->type == 'copy')
548 $lcs += sizeof($edit->orig);
554 * Get the original set of lines.
556 * This reconstructs the $from_lines parameter passed to the
559 * @return array The original sequence of strings.
564 foreach ($this->edits as $edit) {
566 array_splice($lines, sizeof($lines), 0, $edit->orig);
572 * Get the final set of lines.
574 * This reconstructs the $to_lines parameter passed to the
577 * @return array The sequence of strings.
582 foreach ($this->edits as $edit) {
584 array_splice($lines, sizeof($lines), 0, $edit->final);
590 * Check a Diff for validity.
592 * This is here only for debugging purposes.
594 function _check ($from_lines, $to_lines) {
595 if (serialize($from_lines) != serialize($this->orig()))
596 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
597 if (serialize($to_lines) != serialize($this->_final()))
598 trigger_error("Reconstructed final doesn't match", E_USER_ERROR);
600 $rev = $this->reverse();
601 if (serialize($to_lines) != serialize($rev->orig()))
602 trigger_error("Reversed original doesn't match", E_USER_ERROR);
603 if (serialize($from_lines) != serialize($rev->_final()))
604 trigger_error("Reversed final doesn't match", E_USER_ERROR);
607 foreach ($this->edits as $edit) {
608 if ( $prevtype == $edit->type )
609 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
610 $prevtype = $edit->type;
614 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
627 * Computes diff between sequences of strings.
629 * This can be used to compute things like
630 * case-insensitve diffs, or diffs which ignore
631 * changes in white-space.
633 * @param $from_lines array An array of strings.
634 * (Typically these are lines from a file.)
636 * @param $to_lines array An array of strings.
638 * @param $mapped_from_lines array This array should
639 * have the same size number of elements as $from_lines.
640 * The elements in $mapped_from_lines and
641 * $mapped_to_lines are what is actually compared
642 * when computing the diff.
644 * @param $mapped_to_lines array This array should
645 * have the same number of elements as $to_lines.
647 function MappedDiff($from_lines, $to_lines,
648 $mapped_from_lines, $mapped_to_lines) {
650 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
651 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
653 $this->Diff($mapped_from_lines, $mapped_to_lines);
656 // Optimizing loop invariants:
657 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
658 for ($i = 0, $max = sizeof($this->edits); $i < $max; $i++) {
659 $orig = &$this->edits[$i]->orig;
660 if (is_array($orig)) {
661 $orig = array_slice($from_lines, $xi, sizeof($orig));
662 $xi += sizeof($orig);
665 $final = &$this->edits[$i]->final;
666 if (is_array($final)) {
667 $final = array_slice($to_lines, $yi, sizeof($final));
668 $yi += sizeof($final);
675 * A class to format Diffs
677 * This class formats the diff in classic diff format.
678 * It is intended that this class be customized via inheritance,
679 * to obtain fancier outputs.
684 * Number of leading context "lines" to preserve.
686 * This should be left at zero for this class, but subclasses
687 * may want to set this to other values.
689 var $leading_context_lines = 0;
692 * Number of trailing context "lines" to preserve.
694 * This should be left at zero for this class, but subclasses
695 * may want to set this to other values.
697 var $trailing_context_lines = 0;
702 * @param $diff object A Diff object.
703 * @return string The formatted output.
705 function format($diff) {
711 $nlead = $this->leading_context_lines;
712 $ntrail = $this->trailing_context_lines;
714 $this->_start_diff();
716 foreach ($diff->edits as $edit) {
717 if ($edit->type == 'copy') {
718 if (is_array($block)) {
719 if (sizeof($edit->orig) <= $nlead + $ntrail) {
724 $context = array_slice($edit->orig, 0, $ntrail);
725 $block[] = new _DiffOp_Copy($context);
727 $this->_block($x0, $ntrail + $xi - $x0,
728 $y0, $ntrail + $yi - $y0,
733 $context = $edit->orig;
736 if (! is_array($block)) {
737 $context = array_slice($context, max(0, sizeof($context) - $nlead));
738 $x0 = $xi - sizeof($context);
739 $y0 = $yi - sizeof($context);
742 $block[] = new _DiffOp_Copy($context);
748 $xi += sizeof($edit->orig);
750 $yi += sizeof($edit->final);
753 if (is_array($block))
754 $this->_block($x0, $xi - $x0,
758 return $this->_end_diff();
761 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
762 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
763 foreach ($edits as $edit) {
764 if ($edit->type == 'copy')
765 $this->_context($edit->orig);
766 elseif ($edit->type == 'add')
767 $this->_added($edit->final);
768 elseif ($edit->type == 'delete')
769 $this->_deleted($edit->orig);
770 elseif ($edit->type == 'change')
771 $this->_changed($edit->orig, $edit->final);
773 trigger_error("Unknown edit type", E_USER_ERROR);
778 function _start_diff() {
782 function _end_diff() {
783 $val = ob_get_contents();
788 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
790 $xbeg .= "," . ($xbeg + $xlen - 1);
792 $ybeg .= "," . ($ybeg + $ylen - 1);
794 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
797 function _start_block($header) {
801 function _end_block() {
804 function _lines($lines, $prefix = ' ') {
805 foreach ($lines as $line)
806 echo "$prefix $line\n";
809 function _context($lines) {
810 $this->_lines($lines);
813 function _added($lines) {
814 $this->_lines($lines, ">");
816 function _deleted($lines) {
817 $this->_lines($lines, "<");
820 function _changed($orig, $final) {
821 $this->_deleted($orig);
823 $this->_added($final);
828 * "Unified" diff formatter.
830 * This class formats the diff in classic "unified diff" format.
832 class UnifiedDiffFormatter extends DiffFormatter
834 function UnifiedDiffFormatter($context_lines = 4) {
835 $this->leading_context_lines = $context_lines;
836 $this->trailing_context_lines = $context_lines;
839 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
841 $xbeg .= "," . $xlen;
843 $ybeg .= "," . $ylen;
844 return "@@ -$xbeg +$ybeg @@\n";
847 function _added($lines) {
848 $this->_lines($lines, "+");
850 function _deleted($lines) {
851 $this->_lines($lines, "-");
853 function _changed($orig, $final) {
854 $this->_deleted($orig);
855 $this->_added($final);
860 * block conflict diff formatter.
862 * This class will format a diff identical to Diff3 (i.e. editpage
863 * conflicts), but when there are only two source files. To be used by
864 * future enhancements to reloading / upgrading pgsrc.
866 * Functional but not finished yet, need to eliminate redundant block
867 * suffixes (i.e. "=======" immediately followed by another prefix)
868 * see class LoadFileConflictPageEditor
870 class BlockDiffFormatter extends DiffFormatter
872 function BlockDiffFormatter($context_lines = 4) {
873 $this->leading_context_lines = $context_lines;
874 $this->trailing_context_lines = $context_lines;
876 function _lines($lines, $prefix = '') {
879 foreach ($lines as $line)
884 function _added($lines) {
885 $this->_lines($lines, ">>>>>>>");
887 function _deleted($lines) {
888 $this->_lines($lines, "<<<<<<<");
890 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
893 function _changed($orig, $final) {
894 $this->_deleted($orig);
895 $this->_added($final);
903 // c-hanging-comment-ender-p: nil
904 // indent-tabs-mode: nil