3 * A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
5 * Additions by Axel Boldt for MediaWiki
7 * @copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
8 * @license You may copy this code freely under the conditions of the GPL.
10 define('USE_ASSERTS', function_exists('assert'));
18 trigger_error("pure virtual", E_USER_ERROR);
22 return $this->orig ? count($this->orig) : 0;
26 return $this->closing ? count($this->closing) : 0;
30 class _DiffOp_Copy extends _DiffOp {
33 function __construct($orig, $closing = false) {
34 if (!is_array($closing))
37 $this->closing = $closing;
41 return new _DiffOp_Copy($this->closing, $this->orig);
45 class _DiffOp_Delete extends _DiffOp {
48 function __construct($lines) {
50 $this->closing = false;
54 return new _DiffOp_Add($this->orig);
58 class _DiffOp_Add extends _DiffOp {
61 function __construct($lines) {
62 $this->closing = $lines;
67 return new _DiffOp_Delete($this->closing);
71 class _DiffOp_Change extends _DiffOp {
74 function __construct($orig, $closing) {
76 $this->closing = $closing;
80 return new _DiffOp_Change($this->closing, $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 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
102 * @author Geoffrey T. Dairiki
107 function diff($from_lines, $to_lines) {
108 $n_from = count($from_lines);
109 $n_to = count($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.
127 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
128 if ($from_lines[$xi] != $to_lines[$yi])
130 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
133 // Ignore lines which do not exist in both files.
134 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
135 $xhash[$from_lines[$xi]] = 1;
136 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
137 $line = $to_lines[$yi];
138 if (($this->ychanged[$yi] = empty($xhash[$line])))
144 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
145 $line = $from_lines[$xi];
146 if (($this->xchanged[$xi] = empty($yhash[$line])))
153 $this->_compareseq(0, count($this->xv), 0, count($this->yv));
155 // Merge edits when possible
156 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
157 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
159 // Compute the edit operations.
162 while ($xi < $n_from || $yi < $n_to) {
163 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
164 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
166 // Skip matching "snake".
168 while ($xi < $n_from && $yi < $n_to && !$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);
196 * Divide the Largest Common Subsequence (LCS) of the sequences
197 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
200 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
201 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
202 * sub sequences. The first sub-sequence is contained in [X0, X1),
203 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
204 * that (X0, Y0) == (XOFF, YOFF) and
205 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
207 * This function assumes that the first lines of the specified portions
208 * of the two files do not match, and likewise that the last lines do not
209 * match. The caller must trim matching lines from the beginning and end
210 * of the portions it is going to specify.
212 function _diag($xoff, $xlim, $yoff, $ylim, $nchunks) {
215 if ($xlim - $xoff > $ylim - $yoff) {
216 // Things seems faster (I'm not sure I understand why)
217 // when the shortest sequence in X.
219 list ($xoff, $xlim, $yoff, $ylim) = 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);
251 USE_ASSERTS && assert($k > 0);
252 $ymids[$k] = $ymids[$k-1];
255 while (list ($junk, $y) = each($matches)) {
256 if ($y > $this->seq[$k-1]) {
257 USE_ASSERTS && 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);
266 USE_ASSERTS && assert($k > 0);
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 USE_ASSERTS && assert($ypos != $this->seq[$end]);
304 $this->in_seq[$this->seq[$end]] = false;
305 $this->seq[$end] = $ypos;
306 $this->in_seq[$ypos] = 1;
311 * Find LCS of two sequences.
313 * The results are recorded in the vectors $this->{x,y}changed[], by
314 * storing a 1 in the element for each line that is an insertion
315 * or deletion (ie. is not in the LCS).
317 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
319 * Note that XLIM, YLIM are exclusive bounds.
320 * All line numbers are origin-0 and discarded lines are not counted.
322 function _compareseq($xoff, $xlim, $yoff, $ylim) {
323 // Slide down the bottom initial diagonal.
324 while ($xoff < $xlim && $yoff < $ylim && $this->xv[$xoff] == $this->yv[$yoff]) {
329 // Slide up the top initial diagonal.
330 while ($xlim > $xoff && $ylim > $yoff && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
335 if ($xoff == $xlim || $yoff == $ylim)
338 // This is ad hoc but seems to work well.
339 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
340 //$nchunks = max(2,min(8,(int)$nchunks));
341 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
343 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
347 // X and Y sequences have no common subsequence:
349 while ($yoff < $ylim)
350 $this->ychanged[$this->yind[$yoff++]] = 1;
351 while ($xoff < $xlim)
352 $this->xchanged[$this->xind[$xoff++]] = 1;
355 // Use the partitions to split this problem into subproblems.
358 while ($pt2 = next($seps)) {
359 $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 USE_ASSERTS && assert('count($lines) == count($changed)');
383 $len = count($lines);
384 $other_len = count($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 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
405 while ($j < $other_len && $other_changed[$j])
414 // Find the end of this run of changes.
415 while (++$i < $len && $changed[$i])
420 * Record the length of this run of changes, so that
421 * we can later determine whether the run has grown.
423 $runlength = $i - $start;
426 * Move the changed region back, so long as the
427 * previous unchanged line matches the last changed one.
428 * This merges with previous changed regions.
430 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
431 $changed[--$start] = 1;
432 $changed[--$i] = false;
433 while ($start > 0 && $changed[$start - 1])
435 USE_ASSERTS && assert('$j > 0');
436 while ($other_changed[--$j])
438 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
442 * Set CORRESPONDING to the end of the changed run, at the last
443 * point where it corresponds to a changed run in the other file.
444 * CORRESPONDING == LEN means no such point has been found.
446 $corresponding = $j < $other_len ? $i : $len;
449 * Move the changed region forward, so long as the
450 * first changed line matches the following unchanged one.
451 * This merges with following changed regions.
452 * Do this second, so that if there are no merges,
453 * the changed region is moved forward as far as possible.
455 while ($i < $len && $lines[$start] == $lines[$i]) {
456 $changed[$start++] = false;
458 while ($i < $len && $changed[$i])
461 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
463 if ($j < $other_len && $other_changed[$j]) {
465 while ($j < $other_len && $other_changed[$j])
469 } while ($runlength != $i - $start);
472 * If possible, move the fully-merged run of changes
473 * back to a corresponding run in the other file.
475 while ($corresponding < $i) {
476 $changed[--$start] = 1;
478 USE_ASSERTS && assert('$j > 0');
479 while ($other_changed[--$j])
481 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
488 * Class representing a 'diff' between two sequences of strings.
496 * Computes diff between sequences of strings.
498 * @param $from_lines array An array of strings.
499 * (Typically these are lines from a file.)
500 * @param $to_lines array An array of strings.
502 function __construct($from_lines, $to_lines) {
503 $eng = new _DiffEngine;
504 $this->edits = $eng->diff($from_lines, $to_lines);
505 //$this->_check($from_lines, $to_lines);
509 * Compute reversed Diff.
513 * $diff = new Diff($lines1, $lines2);
514 * $rev = $diff->reverse();
515 * @return object A Diff object representing the inverse of the
520 $rev->edits = array();
521 foreach ($this->edits as $edit) {
522 $rev->edits[] = $edit->reverse();
528 * Check for empty diff.
530 * @return bool True iff two sequences were identical.
533 foreach ($this->edits as $edit) {
534 if ($edit->type != 'copy')
541 * Compute the length of the Longest Common Subsequence (LCS).
543 * This is mostly for diagnostic purposed.
545 * @return int The length of the LCS.
549 foreach ($this->edits as $edit) {
550 if ($edit->type == 'copy')
551 $lcs += count($edit->orig);
557 * Get the original set of lines.
559 * This reconstructs the $from_lines parameter passed to the
562 * @return array The original sequence of strings.
567 foreach ($this->edits as $edit) {
569 array_splice($lines, count($lines), 0, $edit->orig);
575 * Get the closing set of lines.
577 * This reconstructs the $to_lines parameter passed to the
580 * @return array The sequence of strings.
585 foreach ($this->edits as $edit) {
587 array_splice($lines, count($lines), 0, $edit->closing);
593 * Check a Diff for validity.
595 * This is here only for debugging purposes.
597 function _check($from_lines, $to_lines) {
598 if (serialize($from_lines) != serialize($this->orig()))
599 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
600 if (serialize($to_lines) != serialize($this->closing()))
601 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
603 $rev = $this->reverse();
604 if (serialize($to_lines) != serialize($rev->orig()))
605 trigger_error("Reversed original doesn't match", E_USER_ERROR);
606 if (serialize($from_lines) != serialize($rev->closing()))
607 trigger_error("Reversed closing 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);
624 class MappedDiff extends Diff {
628 * Computes diff between sequences of strings.
630 * This can be used to compute things like
631 * case-insensitve diffs, or diffs which ignore
632 * changes in white-space.
634 * @param $from_lines array An array of strings.
635 * (Typically these are lines from a file.)
637 * @param $to_lines array An array of strings.
639 * @param $mapped_from_lines array This array should
640 * have the same size number of elements as $from_lines.
641 * The elements in $mapped_from_lines and
642 * $mapped_to_lines are what is actually compared
643 * when computing the diff.
645 * @param $mapped_to_lines array This array should
646 * have the same number of elements as $to_lines.
648 function __construct($from_lines, $to_lines, $mapped_from_lines, $mapped_to_lines) {
650 assert(count($from_lines) == count($mapped_from_lines));
651 assert(count($to_lines) == count($mapped_to_lines));
653 parent::__construct($mapped_from_lines, $mapped_to_lines);
656 $ecnt = count($this->edits);
657 for ($i = 0; $i < $ecnt; $i++) {
658 $orig = &$this->edits[$i]->orig;
659 if (is_array($orig)) {
660 $orig = array_slice($from_lines, $xi, count($orig));
664 $closing = &$this->edits[$i]->closing;
665 if (is_array($closing)) {
666 $closing = array_slice($to_lines, $yi, count($closing));
667 $yi += count($closing);
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.
680 class DiffFormatter {
682 * Number of leading context "lines" to preserve.
684 * This should be left at zero for this class, but subclasses
685 * may want to set this to other values.
687 var $leading_context_lines = 0;
690 * Number of trailing context "lines" to preserve.
692 * This should be left at zero for this class, but subclasses
693 * may want to set this to other values.
695 var $trailing_context_lines = 0;
700 * @param $diff object A Diff object.
701 * @return string The formatted output.
703 function format($diff) {
709 $nlead = $this->leading_context_lines;
710 $ntrail = $this->trailing_context_lines;
712 $this->_start_diff();
714 foreach ($diff->edits as $edit) {
715 if ($edit->type == 'copy') {
716 if (is_array($block)) {
717 if (count($edit->orig) <= $nlead + $ntrail) {
722 $context = array_slice($edit->orig, 0, $ntrail);
723 $block[] = new _DiffOp_Copy($context);
725 $this->_block($x0, $ntrail + $xi - $x0, $y0, $ntrail + $yi - $y0, $block);
729 $context = $edit->orig;
732 if (! is_array($block)) {
733 $context = array_slice($context, count($context) - $nlead);
734 $x0 = $xi - count($context);
735 $y0 = $yi - count($context);
738 $block[] = new _DiffOp_Copy($context);
744 $xi += count($edit->orig);
746 $yi += count($edit->closing);
749 if (is_array($block))
750 $this->_block($x0, $xi - $x0, $y0, $yi - $y0, $block);
752 return $this->_end_diff();
755 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
756 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
757 foreach ($edits as $edit) {
758 if ($edit->type == 'copy')
759 $this->_context($edit->orig);
760 elseif ($edit->type == 'add')
761 $this->_added($edit->closing);
762 elseif ($edit->type == 'delete')
763 $this->_deleted($edit->orig);
764 elseif ($edit->type == 'change')
765 $this->_changed($edit->orig, $edit->closing);
767 trigger_error("Unknown edit type", E_USER_ERROR);
772 function _start_diff() {
776 function _end_diff() {
777 $val = ob_get_contents();
782 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
784 $xbeg .= "," . ($xbeg + $xlen - 1);
786 $ybeg .= "," . ($ybeg + $ylen - 1);
788 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
791 function _start_block($header) {
795 function _end_block() {
798 function _lines($lines, $prefix = ' ') {
799 foreach ($lines as $line)
800 echo "$prefix $line\n";
803 function _context($lines) {
804 $this->_lines($lines);
807 function _added($lines) {
808 $this->_lines($lines, ">");
810 function _deleted($lines) {
811 $this->_lines($lines, "<");
814 function _changed($orig, $closing) {
815 $this->_deleted($orig);
817 $this->_added($closing);
822 * Utilityclass for styling HTML formatted diffs
824 * Depends on global var $DIFF_INLINESTYLES, if true some minimal predefined
825 * inline styles are used. Useful for HTML mails and RSS feeds
827 * @author Andreas Gohr <andi@splitbrain.org>
831 * Holds the style names and basic CSS
833 static public $styles = array(
834 'diff-addedline' => 'background-color: #ddffdd;',
835 'diff-deletedline' => 'background-color: #ffdddd;',
836 'diff-context' => 'background-color: #f5f5f5;',
837 'diff-mark' => 'color: #ff0000;',
841 * Return a class or style parameter
843 static function css($classname){
844 global $DIFF_INLINESTYLES;
846 if($DIFF_INLINESTYLES){
847 if(!isset(self::$styles[$classname])) return '';
848 return 'style="'.self::$styles[$classname].'"';
850 return 'class="'.$classname.'"';
856 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
860 define('NBSP', "\xC2\xA0"); // utf-8 non-breaking space.
862 class _HWLDF_WordAccumulator {
864 function __construct() {
865 $this->_lines = array();
871 function _flushGroup($new_tag) {
872 if ($this->_group !== '') {
873 if ($this->_tag == 'mark')
874 $this->_line .= '<strong '.HTMLDiff::css('diff-mark').'>'.$this->_group.'</strong>';
875 elseif ($this->_tag == 'add')
876 $this->_line .= '<span '.HTMLDiff::css('diff-addedline').'>'.$this->_group.'</span>';
877 elseif ($this->_tag == 'del')
878 $this->_line .= '<span '.HTMLDiff::css('diff-deletedline').'><del>'.$this->_group.'</del></span>';
880 $this->_line .= $this->_group;
883 $this->_tag = $new_tag;
886 function _flushLine($new_tag) {
887 $this->_flushGroup($new_tag);
888 if ($this->_line != '')
889 $this->_lines[] = $this->_line;
893 function addWords($words, $tag = '') {
894 if ($tag != $this->_tag)
895 $this->_flushGroup($tag);
897 foreach ($words as $word) {
898 // new-line should only come as first char of word.
901 if ($word[0] == "\n") {
902 $this->_group .= NBSP;
903 $this->_flushLine($tag);
904 $word = substr($word, 1);
906 assert(!strstr($word, "\n"));
907 $this->_group .= $word;
911 function getLines() {
912 $this->_flushLine('~done');
913 return $this->_lines;
917 class WordLevelDiff extends MappedDiff {
919 function __construct($orig_lines, $closing_lines) {
920 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
921 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
923 parent::__construct($orig_words, $closing_words, $orig_stripped, $closing_stripped);
926 function _split($lines) {
927 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xsu',
928 implode("\n", $lines), $m)) {
929 return array(array(''), array(''));
931 return array($m[0], $m[1]);
935 $orig = new _HWLDF_WordAccumulator;
937 foreach ($this->edits as $edit) {
938 if ($edit->type == 'copy')
939 $orig->addWords($edit->orig);
941 $orig->addWords($edit->orig, 'mark');
943 return $orig->getLines();
947 $closing = new _HWLDF_WordAccumulator;
949 foreach ($this->edits as $edit) {
950 if ($edit->type == 'copy')
951 $closing->addWords($edit->closing);
952 elseif ($edit->closing)
953 $closing->addWords($edit->closing, 'mark');
955 return $closing->getLines();
959 class InlineWordLevelDiff extends MappedDiff {
961 function __construct($orig_lines, $closing_lines) {
962 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
963 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
965 parent::__construct($orig_words, $closing_words, $orig_stripped, $closing_stripped);
968 function _split($lines) {
969 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xsu',
970 implode("\n", $lines), $m)) {
971 return array(array(''), array(''));
973 return array($m[0], $m[1]);
977 $orig = new _HWLDF_WordAccumulator;
978 foreach ($this->edits as $edit) {
979 if ($edit->type == 'copy')
980 $orig->addWords($edit->closing);
981 elseif ($edit->type == 'change'){
982 $orig->addWords($edit->orig, 'del');
983 $orig->addWords($edit->closing, 'add');
984 } elseif ($edit->type == 'delete')
985 $orig->addWords($edit->orig, 'del');
986 elseif ($edit->type == 'add')
987 $orig->addWords($edit->closing, 'add');
989 $orig->addWords($edit->orig, 'del');
991 return $orig->getLines();
996 * "Unified" diff formatter.
998 * This class formats the diff in classic "unified diff" format.
1000 class UnifiedDiffFormatter extends DiffFormatter {
1002 function __construct($context_lines = 4) {
1003 $this->leading_context_lines = $context_lines;
1004 $this->trailing_context_lines = $context_lines;
1007 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1009 $xbeg .= "," . $xlen;
1011 $ybeg .= "," . $ylen;
1012 return "@@ -$xbeg +$ybeg @@\n";
1015 function _added($lines) {
1016 $this->_lines($lines, "+");
1018 function _deleted($lines) {
1019 $this->_lines($lines, "-");
1021 function _changed($orig, $final) {
1022 $this->_deleted($orig);
1023 $this->_added($final);
1028 * Wikipedia Table style diff formatter.
1031 class TableDiffFormatter extends DiffFormatter {
1033 function __construct() {
1034 $this->leading_context_lines = 2;
1035 $this->trailing_context_lines = 2;
1038 function format($diff) {
1039 // Preserve whitespaces by converting some to non-breaking spaces.
1040 // Do not convert all of them to allow word-wrap.
1041 $val = parent::format($diff);
1042 $val = str_replace(' ','  ', $val);
1043 $val = preg_replace('/ (?=<)|(?<=[ >]) /', ' ', $val);
1047 function _pre($text){
1048 $text = htmlspecialchars($text);
1052 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1054 $l1 = $lang['line'].' '.$xbeg;
1055 $l2 = $lang['line'].' '.$ybeg;
1056 $r = '<tr><td '.HTMLDiff::css('diff-blockheader').' colspan="2">'.$l1.":</td>\n".
1057 '<td '.HTMLDiff::css('diff-blockheader').' colspan="2">'.$l2.":</td>\n".
1062 function _start_block($header) {
1066 function _end_block() {
1069 function _lines($lines, $prefix=' ', $color="white") {
1072 function addedLine($line) {
1073 return '<td>+</td><td '.HTMLDiff::css('diff-addedline').'>' . $line.'</td>';
1076 function deletedLine($line) {
1077 return '<td>-</td><td '.HTMLDiff::css('diff-deletedline').'>' . $line.'</td>';
1080 function emptyLine() {
1081 return '<td colspan="2"> </td>';
1084 function contextLine($line) {
1085 return '<td> </td><td '.HTMLDiff::css('diff-context').'>'.$line.'</td>';
1088 function _added($lines) {
1089 foreach ($lines as $line) {
1090 print('<tr>' . $this->emptyLine() . $this->addedLine($line) . "</tr>\n");
1094 function _deleted($lines) {
1095 foreach ($lines as $line) {
1096 print('<tr>' . $this->deletedLine($line) . $this->emptyLine() . "</tr>\n");
1100 function _context($lines) {
1101 foreach ($lines as $line) {
1102 print('<tr>' . $this->contextLine($line) . $this->contextLine($line) . "</tr>\n");
1106 function _changed($orig, $closing) {
1107 $diff = new WordLevelDiff($orig, $closing);
1108 $del = $diff->orig();
1109 $add = $diff->closing();
1111 while ($line = array_shift($del)) {
1112 $aline = array_shift($add);
1113 print('<tr>' . $this->deletedLine($line) . $this->addedLine($aline) . "</tr>\n");
1115 $this->_added($add); # If any leftovers
1120 * Inline style diff formatter.
1123 class InlineDiffFormatter extends DiffFormatter {
1126 function __construct() {
1127 $this->leading_context_lines = 2;
1128 $this->trailing_context_lines = 2;
1131 function format($diff) {
1132 // Preserve whitespaces by converting some to non-breaking spaces.
1133 // Do not convert all of them to allow word-wrap.
1134 $val = parent::format($diff);
1135 $val = str_replace(' ','  ', $val);
1136 $val = preg_replace('/ (?=<)|(?<=[ >]) /', ' ', $val);
1140 function _pre($text){
1141 $text = htmlspecialchars($text);
1145 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1148 $xbeg .= "," . $xlen;
1150 $ybeg .= "," . $ylen;
1151 $r = '<tr><td colspan="'.$this->colspan.'" '.HTMLDiff::css('diff-blockheader').'>@@ '.$lang['line']." -$xbeg +$ybeg @@";
1152 $r .= ' <span '.HTMLDiff::css('diff-deletedline').'><del>'.$lang['deleted'].'</del></span>';
1153 $r .= ' <span '.HTMLDiff::css('diff-addedline').'>'.$lang['created'].'</span>';
1154 $r .= "</td></tr>\n";
1158 function _start_block($header) {
1159 print($header."\n");
1162 function _end_block() {
1165 function _lines($lines, $prefix=' ', $color="white") {
1168 function _added($lines) {
1169 foreach ($lines as $line) {
1170 print('<tr><td colspan="'.$this->colspan.'" '.HTMLDiff::css('diff-addedline').'>'. $line . "</td></tr>\n");
1174 function _deleted($lines) {
1175 foreach ($lines as $line) {
1176 print('<tr><td colspan="'.$this->colspan.'" '.HTMLDiff::css('diff-deletedline').'><del>' . $line . "</del></td></tr>\n");
1180 function _context($lines) {
1181 foreach ($lines as $line) {
1182 print('<tr><td colspan="'.$this->colspan.'" '.HTMLDiff::css('diff-context').'>'.$line."</td></tr>\n");
1186 function _changed($orig, $closing) {
1187 $diff = new InlineWordLevelDiff($orig, $closing);
1188 $add = $diff->inline();
1190 foreach ($add as $line)
1191 print('<tr><td colspan="'.$this->colspan.'">'.$line."</td></tr>\n");
1196 //Setup VIM: ex: et ts=4 :