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.
17 trigger_error("pure virtual", E_USER_ERROR);
21 return $this->orig ? sizeof($this->orig) : 0;
25 return $this->final ? sizeof($this->final) : 0;
29 class _DiffOp_Copy extends _DiffOp {
32 function _DiffOp_Copy ($orig, $final = false) {
33 if (!is_array($final))
36 $this->final = $final;
40 return new _DiffOp_Copy($this->final, $this->orig);
44 class _DiffOp_Delete extends _DiffOp {
47 function _DiffOp_Delete ($lines) {
53 return new _DiffOp_Add($this->orig);
57 class _DiffOp_Add extends _DiffOp {
60 function _DiffOp_Add ($lines) {
61 $this->final = $lines;
66 return new _DiffOp_Delete($this->final);
70 class _DiffOp_Change extends _DiffOp {
73 function _DiffOp_Change ($orig, $final) {
75 $this->final = $final;
79 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)
100 * @author Geoffrey T. Dairiki
105 function diff ($from_lines, $to_lines) {
106 $n_from = sizeof($from_lines);
107 $n_to = sizeof($to_lines);
109 $this->xchanged = $this->ychanged = array();
110 $this->xv = $this->yv = array();
111 $this->xind = $this->yind = array();
113 unset($this->in_seq);
116 // Skip leading common lines.
117 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
118 if ($from_lines[$skip] != $to_lines[$skip])
120 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
122 // Skip trailing common lines.
123 $xi = $n_from; $yi = $n_to;
124 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
125 if ($from_lines[$xi] != $to_lines[$yi])
127 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
130 // Ignore lines which do not exist in both files.
131 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
132 $xhash[$from_lines[$xi]] = 1;
133 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
134 $line = $to_lines[$yi];
135 if ( ($this->ychanged[$yi] = empty($xhash[$line])) )
141 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
142 $line = $from_lines[$xi];
143 if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
150 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
152 // Merge edits when possible
153 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
154 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
156 // Compute the edit operations.
159 while ($xi < $n_from || $yi < $n_to) {
160 assert($yi < $n_to || $this->xchanged[$xi]);
161 assert($xi < $n_from || $this->ychanged[$yi]);
163 // Skip matching "snake".
165 while ( $xi < $n_from && $yi < $n_to
166 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
167 $copy[] = $from_lines[$xi++];
171 $edits[] = new _DiffOp_Copy($copy);
173 // Find deletes & adds.
175 while ($xi < $n_from && $this->xchanged[$xi])
176 $delete[] = $from_lines[$xi++];
179 while ($yi < $n_to && $this->ychanged[$yi])
180 $add[] = $to_lines[$yi++];
183 $edits[] = new _DiffOp_Change($delete, $add);
185 $edits[] = new _DiffOp_Delete($delete);
187 $edits[] = new _DiffOp_Add($add);
192 /* Divide the Largest Common Subsequence (LCS) of the sequences
193 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
196 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
197 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
198 * sub sequences. The first sub-sequence is contained in [X0, X1),
199 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
200 * that (X0, Y0) == (XOFF, YOFF) and
201 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
203 * This function assumes that the first lines of the specified portions
204 * of the two files do not match, and likewise that the last lines do not
205 * match. The caller must trim matching lines from the beginning and end
206 * of the portions it is going to specify.
208 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
211 if ($xlim - $xoff > $ylim - $yoff) {
212 // Things seems faster (I'm not sure I understand why)
213 // when the shortest sequence in X.
215 list ($xoff, $xlim, $yoff, $ylim)
216 = array( $yoff, $ylim, $xoff, $xlim);
220 for ($i = $ylim - 1; $i >= $yoff; $i--)
221 $ymatches[$this->xv[$i]][] = $i;
223 for ($i = $ylim - 1; $i >= $yoff; $i--)
224 $ymatches[$this->yv[$i]][] = $i;
227 $this->seq[0]= $yoff - 1;
228 $this->in_seq = array();
231 $numer = $xlim - $xoff + $nchunks - 1;
233 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
235 for ($i = 0; $i <= $this->lcs; $i++)
236 $ymids[$i][$chunk-1] = $this->seq[$i];
238 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
239 for ( ; $x < $x1; $x++) {
240 $line = $flip ? $this->yv[$x] : $this->xv[$x];
241 if (empty($ymatches[$line]))
243 $matches = $ymatches[$line];
245 while (list ($junk, $y) = each($matches))
246 if (empty($this->in_seq[$y])) {
247 $k = $this->_lcs_pos($y);
249 $ymids[$k] = $ymids[$k-1];
252 while (list ($junk, $y) = each($matches)) {
253 if ($y > $this->seq[$k-1]) {
254 assert($y < $this->seq[$k]);
255 // Optimization: this is a common case:
256 // next match is just replacing previous match.
257 $this->in_seq[$this->seq[$k]] = false;
259 $this->in_seq[$y] = 1;
261 else if (empty($this->in_seq[$y])) {
262 $k = $this->_lcs_pos($y);
264 $ymids[$k] = $ymids[$k-1];
270 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
271 $ymid = $ymids[$this->lcs];
272 for ($n = 0; $n < $nchunks - 1; $n++) {
273 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
275 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
277 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
279 return array($this->lcs, $seps);
282 function _lcs_pos ($ypos) {
284 if ($end == 0 || $ypos > $this->seq[$end]) {
285 $this->seq[++$this->lcs] = $ypos;
286 $this->in_seq[$ypos] = 1;
291 while ($beg < $end) {
292 $mid = (int)(($beg + $end) / 2);
293 if ( $ypos > $this->seq[$mid] )
299 assert($ypos != $this->seq[$end]);
301 $this->in_seq[$this->seq[$end]] = false;
302 $this->seq[$end] = $ypos;
303 $this->in_seq[$ypos] = 1;
307 /* Find LCS of two sequences.
309 * The results are recorded in the vectors $this->{x,y}changed[], by
310 * storing a 1 in the element for each line that is an insertion
311 * or deletion (ie. is not in the LCS).
313 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
315 * Note that XLIM, YLIM are exclusive bounds.
316 * All line numbers are origin-0 and discarded lines are not counted.
318 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
319 // Slide down the bottom initial diagonal.
320 while ($xoff < $xlim && $yoff < $ylim
321 && $this->xv[$xoff] == $this->yv[$yoff]) {
326 // Slide up the top initial diagonal.
327 while ($xlim > $xoff && $ylim > $yoff
328 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
333 if ($xoff == $xlim || $yoff == $ylim)
336 // This is ad hoc but seems to work well.
337 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
338 //$nchunks = max(2,min(8,(int)$nchunks));
339 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
341 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
345 // X and Y sequences have no common subsequence:
347 while ($yoff < $ylim)
348 $this->ychanged[$this->yind[$yoff++]] = 1;
349 while ($xoff < $xlim)
350 $this->xchanged[$this->xind[$xoff++]] = 1;
353 // Use the partitions to split this problem into subproblems.
356 while ($pt2 = next($seps)) {
357 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
363 /* Adjust inserts/deletes of identical lines to join changes
364 * as much as possible.
366 * We do something when a run of changed lines include a
367 * line at one end and has an excluded, identical line at the other.
368 * We are free to choose which identical line is included.
369 * `compareseq' usually chooses the one at the beginning,
370 * but usually it is cleaner to consider the following identical line
371 * to be the "change".
373 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
375 function _shift_boundaries ($lines, &$changed, $other_changed) {
379 assert('sizeof($lines) == sizeof($changed)');
380 $len = sizeof($lines);
381 $other_len = sizeof($other_changed);
385 * Scan forwards to find beginning of another run of changes.
386 * Also keep track of the corresponding point in the other file.
388 * Throughout this code, $i and $j are adjusted together so that
389 * the first $i elements of $changed and the first $j elements
390 * of $other_changed both contain the same number of zeros
392 * Furthermore, $j is always kept so that $j == $other_len or
393 * $other_changed[$j] == false.
395 while ($j < $other_len && $other_changed[$j])
398 while ($i < $len && ! $changed[$i]) {
399 assert('$j < $other_len && ! $other_changed[$j]');
401 while ($j < $other_len && $other_changed[$j])
410 // Find the end of this run of changes.
411 while (++$i < $len && $changed[$i])
416 * Record the length of this run of changes, so that
417 * we can later determine whether the run has grown.
419 $runlength = $i - $start;
422 * Move the changed region back, so long as the
423 * previous unchanged line matches the last changed one.
424 * This merges with previous changed regions.
426 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
427 $changed[--$start] = 1;
428 $changed[--$i] = false;
429 while ($start > 0 && $changed[$start - 1])
432 while ($other_changed[--$j])
434 assert('$j >= 0 && !$other_changed[$j]');
438 * Set CORRESPONDING to the end of the changed run, at the last
439 * point where it corresponds to a changed run in the other file.
440 * CORRESPONDING == LEN means no such point has been found.
442 $corresponding = $j < $other_len ? $i : $len;
445 * Move the changed region forward, so long as the
446 * first changed line matches the following unchanged one.
447 * This merges with following changed regions.
448 * Do this second, so that if there are no merges,
449 * the changed region is moved forward as far as possible.
451 while ($i < $len && $lines[$start] == $lines[$i]) {
452 $changed[$start++] = false;
454 while ($i < $len && $changed[$i])
457 assert('$j < $other_len && ! $other_changed[$j]');
459 if ($j < $other_len && $other_changed[$j]) {
461 while ($j < $other_len && $other_changed[$j])
465 } while ($runlength != $i - $start);
468 * If possible, move the fully-merged run of changes
469 * back to a corresponding run in the other file.
471 while ($corresponding < $i) {
472 $changed[--$start] = 1;
475 while ($other_changed[--$j])
477 assert('$j >= 0 && !$other_changed[$j]');
484 * Class representing a 'diff' between two sequences of strings.
492 * Computes diff between sequences of strings.
494 * @param $from_lines array An array of strings.
495 * (Typically these are lines from a file.)
496 * @param $to_lines array An array of strings.
498 function Diff($from_lines, $to_lines) {
499 $eng = new _DiffEngine;
500 $this->edits = $eng->diff($from_lines, $to_lines);
501 //$this->_check($from_lines, $to_lines);
505 * Compute reversed Diff.
509 * $diff = new Diff($lines1, $lines2);
510 * $rev = $diff->reverse();
511 * @return object A Diff object representing the inverse of the
514 function reverse () {
516 $rev->edits = array();
517 foreach ($this->edits as $edit) {
518 $rev->edits[] = $edit->reverse();
524 * Check for empty diff.
526 * @return bool True iff two sequences were identical.
528 function isEmpty () {
529 foreach ($this->edits as $edit) {
530 if ($edit->type != 'copy')
537 * Compute the length of the Longest Common Subsequence (LCS).
539 * This is mostly for diagnostic purposed.
541 * @return int The length of the LCS.
545 foreach ($this->edits as $edit) {
546 if ($edit->type == 'copy')
547 $lcs += sizeof($edit->orig);
553 * Get the original set of lines.
555 * This reconstructs the $from_lines parameter passed to the
558 * @return array The original sequence of strings.
563 foreach ($this->edits as $edit) {
565 array_splice($lines, sizeof($lines), 0, $edit->orig);
571 * Get the final set of lines.
573 * This reconstructs the $to_lines parameter passed to the
576 * @return array The sequence of strings.
581 foreach ($this->edits as $edit) {
583 array_splice($lines, sizeof($lines), 0, $edit->final);
589 * Check a Diff for validity.
591 * This is here only for debugging purposes.
593 function _check ($from_lines, $to_lines) {
594 if (serialize($from_lines) != serialize($this->orig()))
595 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
596 if (serialize($to_lines) != serialize($this->_final()))
597 trigger_error("Reconstructed final doesn't match", E_USER_ERROR);
599 $rev = $this->reverse();
600 if (serialize($to_lines) != serialize($rev->orig()))
601 trigger_error("Reversed original doesn't match", E_USER_ERROR);
602 if (serialize($from_lines) != serialize($rev->_final()))
603 trigger_error("Reversed final doesn't match", E_USER_ERROR);
606 foreach ($this->edits as $edit) {
607 if ( $prevtype == $edit->type )
608 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
609 $prevtype = $edit->type;
613 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
626 * Computes diff between sequences of strings.
628 * This can be used to compute things like
629 * case-insensitve diffs, or diffs which ignore
630 * changes in white-space.
632 * @param $from_lines array An array of strings.
633 * (Typically these are lines from a file.)
635 * @param $to_lines array An array of strings.
637 * @param $mapped_from_lines array This array should
638 * have the same size number of elements as $from_lines.
639 * The elements in $mapped_from_lines and
640 * $mapped_to_lines are what is actually compared
641 * when computing the diff.
643 * @param $mapped_to_lines array This array should
644 * have the same number of elements as $to_lines.
646 function MappedDiff($from_lines, $to_lines,
647 $mapped_from_lines, $mapped_to_lines) {
649 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
650 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
652 $this->Diff($mapped_from_lines, $mapped_to_lines);
655 // Optimizing loop invariants:
656 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
657 for ($i = 0, $max = sizeof($this->edits); $i < $max; $i++) {
658 $orig = &$this->edits[$i]->orig;
659 if (is_array($orig)) {
660 $orig = array_slice($from_lines, $xi, sizeof($orig));
661 $xi += sizeof($orig);
664 $final = &$this->edits[$i]->final;
665 if (is_array($final)) {
666 $final = array_slice($to_lines, $yi, sizeof($final));
667 $yi += sizeof($final);
674 * A class to format Diffs
676 * This class formats the diff in classic diff format.
677 * It is intended that this class be customized via inheritance,
678 * to obtain fancier outputs.
683 * Number of leading context "lines" to preserve.
685 * This should be left at zero for this class, but subclasses
686 * may want to set this to other values.
688 var $leading_context_lines = 0;
691 * Number of trailing 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 $trailing_context_lines = 0;
701 * @param $diff object A Diff object.
702 * @return string The formatted output.
704 function format($diff) {
710 $nlead = $this->leading_context_lines;
711 $ntrail = $this->trailing_context_lines;
713 $this->_start_diff();
715 foreach ($diff->edits as $edit) {
716 if ($edit->type == 'copy') {
717 if (is_array($block)) {
718 if (sizeof($edit->orig) <= $nlead + $ntrail) {
723 $context = array_slice($edit->orig, 0, $ntrail);
724 $block[] = new _DiffOp_Copy($context);
726 $this->_block($x0, $ntrail + $xi - $x0,
727 $y0, $ntrail + $yi - $y0,
732 $context = $edit->orig;
735 if (! is_array($block)) {
736 $context = array_slice($context, max(0, sizeof($context) - $nlead));
737 $x0 = $xi - sizeof($context);
738 $y0 = $yi - sizeof($context);
741 $block[] = new _DiffOp_Copy($context);
747 $xi += sizeof($edit->orig);
749 $yi += sizeof($edit->final);
752 if (is_array($block))
753 $this->_block($x0, $xi - $x0,
757 return $this->_end_diff();
760 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
761 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
762 foreach ($edits as $edit) {
763 if ($edit->type == 'copy')
764 $this->_context($edit->orig);
765 elseif ($edit->type == 'add')
766 $this->_added($edit->final);
767 elseif ($edit->type == 'delete')
768 $this->_deleted($edit->orig);
769 elseif ($edit->type == 'change')
770 $this->_changed($edit->orig, $edit->final);
772 trigger_error("Unknown edit type", E_USER_ERROR);
777 function _start_diff() {
781 function _end_diff() {
782 $val = ob_get_contents();
787 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
789 $xbeg .= "," . ($xbeg + $xlen - 1);
791 $ybeg .= "," . ($ybeg + $ylen - 1);
793 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
796 function _start_block($header) {
800 function _end_block() {
803 function _lines($lines, $prefix = ' ') {
804 foreach ($lines as $line)
805 echo "$prefix $line\n";
808 function _context($lines) {
809 $this->_lines($lines);
812 function _added($lines) {
813 $this->_lines($lines, ">");
815 function _deleted($lines) {
816 $this->_lines($lines, "<");
819 function _changed($orig, $final) {
820 $this->_deleted($orig);
822 $this->_added($final);
827 * "Unified" diff formatter.
829 * This class formats the diff in classic "unified diff" format.
831 class UnifiedDiffFormatter extends DiffFormatter
833 function UnifiedDiffFormatter($context_lines = 4) {
834 $this->leading_context_lines = $context_lines;
835 $this->trailing_context_lines = $context_lines;
838 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
840 $xbeg .= "," . $xlen;
842 $ybeg .= "," . $ylen;
843 return "@@ -$xbeg +$ybeg @@\n";
846 function _added($lines) {
847 $this->_lines($lines, "+");
849 function _deleted($lines) {
850 $this->_lines($lines, "-");
852 function _changed($orig, $final) {
853 $this->_deleted($orig);
854 $this->_added($final);
859 * block conflict diff formatter.
861 * This class will format a diff identical to Diff3 (i.e. editpage
862 * conflicts), but when there are only two source files. To be used by
863 * future enhancements to reloading / upgrading pgsrc.
865 * Functional but not finished yet, need to eliminate redundant block
866 * suffixes (i.e. "=======" immediately followed by another prefix)
867 * see class LoadFileConflictPageEditor
869 class BlockDiffFormatter extends DiffFormatter
871 function BlockDiffFormatter($context_lines = 4) {
872 $this->leading_context_lines = $context_lines;
873 $this->trailing_context_lines = $context_lines;
875 function _lines($lines, $prefix = '') {
878 foreach ($lines as $line)
883 function _added($lines) {
884 $this->_lines($lines, ">>>>>>>");
886 function _deleted($lines) {
887 $this->_lines($lines, "<<<<<<<");
889 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
892 function _changed($orig, $final) {
893 $this->_deleted($orig);
894 $this->_added($final);
902 // c-hanging-comment-ender-p: nil
903 // indent-tabs-mode: nil