ide-assi 0.402.0 → 0.404.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,6 +29,7 @@ var require$$4$2 = require('async_hooks');
29
29
  var require$$1$3 = require('console');
30
30
  var require$$1$4 = require('url');
31
31
  var require$$0$e = require('diagnostics_channel');
32
+ var diffMatch_patch = require('diff-match_patch');
32
33
 
33
34
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
34
35
 
@@ -217623,6 +217624,31 @@ function maxLineNumber(lines) {
217623
217624
  last = last * 10 + 9;
217624
217625
  return last;
217625
217626
  }
217627
+ const activeLineGutterMarker = /*@__PURE__*/new class extends GutterMarker {
217628
+ constructor() {
217629
+ super(...arguments);
217630
+ this.elementClass = "cm-activeLineGutter";
217631
+ }
217632
+ };
217633
+ const activeLineGutterHighlighter = /*@__PURE__*/gutterLineClass.compute(["selection"], state => {
217634
+ let marks = [], last = -1;
217635
+ for (let range of state.selection.ranges) {
217636
+ let linePos = state.doc.lineAt(range.head).from;
217637
+ if (linePos > last) {
217638
+ last = linePos;
217639
+ marks.push(activeLineGutterMarker.range(linePos));
217640
+ }
217641
+ }
217642
+ return RangeSet.of(marks);
217643
+ });
217644
+ /**
217645
+ Returns an extension that adds a `cm-activeLineGutter` class to
217646
+ all gutter elements on the [active
217647
+ line](https://codemirror.net/6/docs/ref/#view.highlightActiveLine).
217648
+ */
217649
+ function highlightActiveLineGutter() {
217650
+ return activeLineGutterHighlighter;
217651
+ }
217626
217652
 
217627
217653
  /**
217628
217654
  The default maximum length of a `TreeBuffer` node.
@@ -221519,9 +221545,7 @@ function syntaxHighlighting(highlighter, options) {
221519
221545
  ext.push(EditorView.styleModule.of(highlighter.module));
221520
221546
  themeType = highlighter.themeType;
221521
221547
  }
221522
- if (options === null || options === void 0 ? void 0 : options.fallback)
221523
- ext.push(fallbackHighlighter.of(highlighter));
221524
- else if (themeType)
221548
+ if (themeType)
221525
221549
  ext.push(highlighterFacet.computeN([EditorView.darkTheme], state => {
221526
221550
  return state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
221527
221551
  }));
@@ -232546,2265 +232570,43 @@ const lintExtensions = [
232546
232570
  baseTheme
232547
232571
  ];
232548
232572
 
232549
- var diffMatchPatch = {exports: {}};
232550
-
232551
- /**
232552
- * Diff Match and Patch
232553
- * Copyright 2018 The diff-match-patch Authors.
232554
- * https://github.com/google/diff-match-patch
232555
- *
232556
- * Licensed under the Apache License, Version 2.0 (the "License");
232557
- * you may not use this file except in compliance with the License.
232558
- * You may obtain a copy of the License at
232559
- *
232560
- * http://www.apache.org/licenses/LICENSE-2.0
232561
- *
232562
- * Unless required by applicable law or agreed to in writing, software
232563
- * distributed under the License is distributed on an "AS IS" BASIS,
232564
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
232565
- * See the License for the specific language governing permissions and
232566
- * limitations under the License.
232567
- */
232568
-
232569
- var hasRequiredDiffMatchPatch;
232570
-
232571
- function requireDiffMatchPatch () {
232572
- if (hasRequiredDiffMatchPatch) return diffMatchPatch.exports;
232573
- hasRequiredDiffMatchPatch = 1;
232574
- (function (module) {
232575
- /**
232576
- * @fileoverview Computes the difference between two texts to create a patch.
232577
- * Applies the patch onto another text, allowing for errors.
232578
- * @author fraser@google.com (Neil Fraser)
232579
- */
232580
-
232581
- /**
232582
- * Class containing the diff, match and patch methods.
232583
- * @constructor
232584
- */
232585
- var diff_match_patch = function() {
232586
-
232587
- // Defaults.
232588
- // Redefine these in your program to override the defaults.
232589
-
232590
- // Number of seconds to map a diff before giving up (0 for infinity).
232591
- this.Diff_Timeout = 1.0;
232592
- // Cost of an empty edit operation in terms of edit characters.
232593
- this.Diff_EditCost = 4;
232594
- // At what point is no match declared (0.0 = perfection, 1.0 = very loose).
232595
- this.Match_Threshold = 0.5;
232596
- // How far to search for a match (0 = exact location, 1000+ = broad match).
232597
- // A match this many characters away from the expected location will add
232598
- // 1.0 to the score (0.0 is a perfect match).
232599
- this.Match_Distance = 1000;
232600
- // When deleting a large block of text (over ~64 characters), how close do
232601
- // the contents have to be to match the expected contents. (0.0 = perfection,
232602
- // 1.0 = very loose). Note that Match_Threshold controls how closely the
232603
- // end points of a delete need to match.
232604
- this.Patch_DeleteThreshold = 0.5;
232605
- // Chunk size for context length.
232606
- this.Patch_Margin = 4;
232607
-
232608
- // The number of bits in an int.
232609
- this.Match_MaxBits = 32;
232610
- };
232611
-
232612
-
232613
- // DIFF FUNCTIONS
232614
-
232615
-
232616
- /**
232617
- * The data structure representing a diff is an array of tuples:
232618
- * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
232619
- * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
232620
- */
232621
- var DIFF_DELETE = -1;
232622
- var DIFF_INSERT = 1;
232623
- var DIFF_EQUAL = 0;
232624
-
232625
- /**
232626
- * Class representing one diff tuple.
232627
- * ~Attempts to look like a two-element array (which is what this used to be).~
232628
- * Constructor returns an actual two-element array, to allow destructing @JackuB
232629
- * See https://github.com/JackuB/diff-match-patch/issues/14 for details
232630
- * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL.
232631
- * @param {string} text Text to be deleted, inserted, or retained.
232632
- * @constructor
232633
- */
232634
- diff_match_patch.Diff = function(op, text) {
232635
- return [op, text];
232636
- };
232637
-
232638
- /**
232639
- * Find the differences between two texts. Simplifies the problem by stripping
232640
- * any common prefix or suffix off the texts before diffing.
232641
- * @param {string} text1 Old string to be diffed.
232642
- * @param {string} text2 New string to be diffed.
232643
- * @param {boolean=} opt_checklines Optional speedup flag. If present and false,
232644
- * then don't run a line-level diff first to identify the changed areas.
232645
- * Defaults to true, which does a faster, slightly less optimal diff.
232646
- * @param {number=} opt_deadline Optional time when the diff should be complete
232647
- * by. Used internally for recursive calls. Users should set DiffTimeout
232648
- * instead.
232649
- * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
232650
- */
232651
- diff_match_patch.prototype.diff_main = function(text1, text2, opt_checklines,
232652
- opt_deadline) {
232653
- // Set a deadline by which time the diff must be complete.
232654
- if (typeof opt_deadline == 'undefined') {
232655
- if (this.Diff_Timeout <= 0) {
232656
- opt_deadline = Number.MAX_VALUE;
232657
- } else {
232658
- opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000;
232659
- }
232660
- }
232661
- var deadline = opt_deadline;
232662
-
232663
- // Check for null inputs.
232664
- if (text1 == null || text2 == null) {
232665
- throw new Error('Null input. (diff_main)');
232666
- }
232667
-
232668
- // Check for equality (speedup).
232669
- if (text1 == text2) {
232670
- if (text1) {
232671
- return [new diff_match_patch.Diff(DIFF_EQUAL, text1)];
232672
- }
232673
- return [];
232674
- }
232675
-
232676
- if (typeof opt_checklines == 'undefined') {
232677
- opt_checklines = true;
232678
- }
232679
- var checklines = opt_checklines;
232680
-
232681
- // Trim off common prefix (speedup).
232682
- var commonlength = this.diff_commonPrefix(text1, text2);
232683
- var commonprefix = text1.substring(0, commonlength);
232684
- text1 = text1.substring(commonlength);
232685
- text2 = text2.substring(commonlength);
232686
-
232687
- // Trim off common suffix (speedup).
232688
- commonlength = this.diff_commonSuffix(text1, text2);
232689
- var commonsuffix = text1.substring(text1.length - commonlength);
232690
- text1 = text1.substring(0, text1.length - commonlength);
232691
- text2 = text2.substring(0, text2.length - commonlength);
232692
-
232693
- // Compute the diff on the middle block.
232694
- var diffs = this.diff_compute_(text1, text2, checklines, deadline);
232695
-
232696
- // Restore the prefix and suffix.
232697
- if (commonprefix) {
232698
- diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, commonprefix));
232699
- }
232700
- if (commonsuffix) {
232701
- diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, commonsuffix));
232702
- }
232703
- this.diff_cleanupMerge(diffs);
232704
- return diffs;
232705
- };
232706
-
232707
-
232708
- /**
232709
- * Find the differences between two texts. Assumes that the texts do not
232710
- * have any common prefix or suffix.
232711
- * @param {string} text1 Old string to be diffed.
232712
- * @param {string} text2 New string to be diffed.
232713
- * @param {boolean} checklines Speedup flag. If false, then don't run a
232714
- * line-level diff first to identify the changed areas.
232715
- * If true, then run a faster, slightly less optimal diff.
232716
- * @param {number} deadline Time when the diff should be complete by.
232717
- * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
232718
- * @private
232719
- */
232720
- diff_match_patch.prototype.diff_compute_ = function(text1, text2, checklines,
232721
- deadline) {
232722
- var diffs;
232723
-
232724
- if (!text1) {
232725
- // Just add some text (speedup).
232726
- return [new diff_match_patch.Diff(DIFF_INSERT, text2)];
232727
- }
232728
-
232729
- if (!text2) {
232730
- // Just delete some text (speedup).
232731
- return [new diff_match_patch.Diff(DIFF_DELETE, text1)];
232732
- }
232733
-
232734
- var longtext = text1.length > text2.length ? text1 : text2;
232735
- var shorttext = text1.length > text2.length ? text2 : text1;
232736
- var i = longtext.indexOf(shorttext);
232737
- if (i != -1) {
232738
- // Shorter text is inside the longer text (speedup).
232739
- diffs = [new diff_match_patch.Diff(DIFF_INSERT, longtext.substring(0, i)),
232740
- new diff_match_patch.Diff(DIFF_EQUAL, shorttext),
232741
- new diff_match_patch.Diff(DIFF_INSERT,
232742
- longtext.substring(i + shorttext.length))];
232743
- // Swap insertions for deletions if diff is reversed.
232744
- if (text1.length > text2.length) {
232745
- diffs[0][0] = diffs[2][0] = DIFF_DELETE;
232746
- }
232747
- return diffs;
232748
- }
232749
-
232750
- if (shorttext.length == 1) {
232751
- // Single character string.
232752
- // After the previous speedup, the character can't be an equality.
232753
- return [new diff_match_patch.Diff(DIFF_DELETE, text1),
232754
- new diff_match_patch.Diff(DIFF_INSERT, text2)];
232755
- }
232756
-
232757
- // Check to see if the problem can be split in two.
232758
- var hm = this.diff_halfMatch_(text1, text2);
232759
- if (hm) {
232760
- // A half-match was found, sort out the return data.
232761
- var text1_a = hm[0];
232762
- var text1_b = hm[1];
232763
- var text2_a = hm[2];
232764
- var text2_b = hm[3];
232765
- var mid_common = hm[4];
232766
- // Send both pairs off for separate processing.
232767
- var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline);
232768
- var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline);
232769
- // Merge the results.
232770
- return diffs_a.concat([new diff_match_patch.Diff(DIFF_EQUAL, mid_common)],
232771
- diffs_b);
232772
- }
232773
-
232774
- if (checklines && text1.length > 100 && text2.length > 100) {
232775
- return this.diff_lineMode_(text1, text2, deadline);
232776
- }
232777
-
232778
- return this.diff_bisect_(text1, text2, deadline);
232779
- };
232780
-
232781
-
232782
- /**
232783
- * Do a quick line-level diff on both strings, then rediff the parts for
232784
- * greater accuracy.
232785
- * This speedup can produce non-minimal diffs.
232786
- * @param {string} text1 Old string to be diffed.
232787
- * @param {string} text2 New string to be diffed.
232788
- * @param {number} deadline Time when the diff should be complete by.
232789
- * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
232790
- * @private
232791
- */
232792
- diff_match_patch.prototype.diff_lineMode_ = function(text1, text2, deadline) {
232793
- // Scan the text on a line-by-line basis first.
232794
- var a = this.diff_linesToChars_(text1, text2);
232795
- text1 = a.chars1;
232796
- text2 = a.chars2;
232797
- var linearray = a.lineArray;
232798
-
232799
- var diffs = this.diff_main(text1, text2, false, deadline);
232800
-
232801
- // Convert the diff back to original text.
232802
- this.diff_charsToLines_(diffs, linearray);
232803
- // Eliminate freak matches (e.g. blank lines)
232804
- this.diff_cleanupSemantic(diffs);
232805
-
232806
- // Rediff any replacement blocks, this time character-by-character.
232807
- // Add a dummy entry at the end.
232808
- diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, ''));
232809
- var pointer = 0;
232810
- var count_delete = 0;
232811
- var count_insert = 0;
232812
- var text_delete = '';
232813
- var text_insert = '';
232814
- while (pointer < diffs.length) {
232815
- switch (diffs[pointer][0]) {
232816
- case DIFF_INSERT:
232817
- count_insert++;
232818
- text_insert += diffs[pointer][1];
232819
- break;
232820
- case DIFF_DELETE:
232821
- count_delete++;
232822
- text_delete += diffs[pointer][1];
232823
- break;
232824
- case DIFF_EQUAL:
232825
- // Upon reaching an equality, check for prior redundancies.
232826
- if (count_delete >= 1 && count_insert >= 1) {
232827
- // Delete the offending records and add the merged ones.
232828
- diffs.splice(pointer - count_delete - count_insert,
232829
- count_delete + count_insert);
232830
- pointer = pointer - count_delete - count_insert;
232831
- var subDiff =
232832
- this.diff_main(text_delete, text_insert, false, deadline);
232833
- for (var j = subDiff.length - 1; j >= 0; j--) {
232834
- diffs.splice(pointer, 0, subDiff[j]);
232835
- }
232836
- pointer = pointer + subDiff.length;
232837
- }
232838
- count_insert = 0;
232839
- count_delete = 0;
232840
- text_delete = '';
232841
- text_insert = '';
232842
- break;
232843
- }
232844
- pointer++;
232845
- }
232846
- diffs.pop(); // Remove the dummy entry at the end.
232847
-
232848
- return diffs;
232849
- };
232850
-
232851
-
232852
- /**
232853
- * Find the 'middle snake' of a diff, split the problem in two
232854
- * and return the recursively constructed diff.
232855
- * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
232856
- * @param {string} text1 Old string to be diffed.
232857
- * @param {string} text2 New string to be diffed.
232858
- * @param {number} deadline Time at which to bail if not yet complete.
232859
- * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
232860
- * @private
232861
- */
232862
- diff_match_patch.prototype.diff_bisect_ = function(text1, text2, deadline) {
232863
- // Cache the text lengths to prevent multiple calls.
232864
- var text1_length = text1.length;
232865
- var text2_length = text2.length;
232866
- var max_d = Math.ceil((text1_length + text2_length) / 2);
232867
- var v_offset = max_d;
232868
- var v_length = 2 * max_d;
232869
- var v1 = new Array(v_length);
232870
- var v2 = new Array(v_length);
232871
- // Setting all elements to -1 is faster in Chrome & Firefox than mixing
232872
- // integers and undefined.
232873
- for (var x = 0; x < v_length; x++) {
232874
- v1[x] = -1;
232875
- v2[x] = -1;
232876
- }
232877
- v1[v_offset + 1] = 0;
232878
- v2[v_offset + 1] = 0;
232879
- var delta = text1_length - text2_length;
232880
- // If the total number of characters is odd, then the front path will collide
232881
- // with the reverse path.
232882
- var front = (delta % 2 != 0);
232883
- // Offsets for start and end of k loop.
232884
- // Prevents mapping of space beyond the grid.
232885
- var k1start = 0;
232886
- var k1end = 0;
232887
- var k2start = 0;
232888
- var k2end = 0;
232889
- for (var d = 0; d < max_d; d++) {
232890
- // Bail out if deadline is reached.
232891
- if ((new Date()).getTime() > deadline) {
232892
- break;
232893
- }
232894
-
232895
- // Walk the front path one step.
232896
- for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
232897
- var k1_offset = v_offset + k1;
232898
- var x1;
232899
- if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) {
232900
- x1 = v1[k1_offset + 1];
232901
- } else {
232902
- x1 = v1[k1_offset - 1] + 1;
232903
- }
232904
- var y1 = x1 - k1;
232905
- while (x1 < text1_length && y1 < text2_length &&
232906
- text1.charAt(x1) == text2.charAt(y1)) {
232907
- x1++;
232908
- y1++;
232909
- }
232910
- v1[k1_offset] = x1;
232911
- if (x1 > text1_length) {
232912
- // Ran off the right of the graph.
232913
- k1end += 2;
232914
- } else if (y1 > text2_length) {
232915
- // Ran off the bottom of the graph.
232916
- k1start += 2;
232917
- } else if (front) {
232918
- var k2_offset = v_offset + delta - k1;
232919
- if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {
232920
- // Mirror x2 onto top-left coordinate system.
232921
- var x2 = text1_length - v2[k2_offset];
232922
- if (x1 >= x2) {
232923
- // Overlap detected.
232924
- return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);
232925
- }
232926
- }
232927
- }
232928
- }
232929
-
232930
- // Walk the reverse path one step.
232931
- for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
232932
- var k2_offset = v_offset + k2;
232933
- var x2;
232934
- if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) {
232935
- x2 = v2[k2_offset + 1];
232936
- } else {
232937
- x2 = v2[k2_offset - 1] + 1;
232938
- }
232939
- var y2 = x2 - k2;
232940
- while (x2 < text1_length && y2 < text2_length &&
232941
- text1.charAt(text1_length - x2 - 1) ==
232942
- text2.charAt(text2_length - y2 - 1)) {
232943
- x2++;
232944
- y2++;
232945
- }
232946
- v2[k2_offset] = x2;
232947
- if (x2 > text1_length) {
232948
- // Ran off the left of the graph.
232949
- k2end += 2;
232950
- } else if (y2 > text2_length) {
232951
- // Ran off the top of the graph.
232952
- k2start += 2;
232953
- } else if (!front) {
232954
- var k1_offset = v_offset + delta - k2;
232955
- if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {
232956
- var x1 = v1[k1_offset];
232957
- var y1 = v_offset + x1 - k1_offset;
232958
- // Mirror x2 onto top-left coordinate system.
232959
- x2 = text1_length - x2;
232960
- if (x1 >= x2) {
232961
- // Overlap detected.
232962
- return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);
232963
- }
232964
- }
232965
- }
232966
- }
232967
- }
232968
- // Diff took too long and hit the deadline or
232969
- // number of diffs equals number of characters, no commonality at all.
232970
- return [new diff_match_patch.Diff(DIFF_DELETE, text1),
232971
- new diff_match_patch.Diff(DIFF_INSERT, text2)];
232972
- };
232973
-
232974
-
232975
- /**
232976
- * Given the location of the 'middle snake', split the diff in two parts
232977
- * and recurse.
232978
- * @param {string} text1 Old string to be diffed.
232979
- * @param {string} text2 New string to be diffed.
232980
- * @param {number} x Index of split point in text1.
232981
- * @param {number} y Index of split point in text2.
232982
- * @param {number} deadline Time at which to bail if not yet complete.
232983
- * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
232984
- * @private
232985
- */
232986
- diff_match_patch.prototype.diff_bisectSplit_ = function(text1, text2, x, y,
232987
- deadline) {
232988
- var text1a = text1.substring(0, x);
232989
- var text2a = text2.substring(0, y);
232990
- var text1b = text1.substring(x);
232991
- var text2b = text2.substring(y);
232992
-
232993
- // Compute both diffs serially.
232994
- var diffs = this.diff_main(text1a, text2a, false, deadline);
232995
- var diffsb = this.diff_main(text1b, text2b, false, deadline);
232996
-
232997
- return diffs.concat(diffsb);
232998
- };
232999
-
233000
-
233001
- /**
233002
- * Split two texts into an array of strings. Reduce the texts to a string of
233003
- * hashes where each Unicode character represents one line.
233004
- * @param {string} text1 First string.
233005
- * @param {string} text2 Second string.
233006
- * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
233007
- * An object containing the encoded text1, the encoded text2 and
233008
- * the array of unique strings.
233009
- * The zeroth element of the array of unique strings is intentionally blank.
233010
- * @private
233011
- */
233012
- diff_match_patch.prototype.diff_linesToChars_ = function(text1, text2) {
233013
- var lineArray = []; // e.g. lineArray[4] == 'Hello\n'
233014
- var lineHash = {}; // e.g. lineHash['Hello\n'] == 4
233015
-
233016
- // '\x00' is a valid character, but various debuggers don't like it.
233017
- // So we'll insert a junk entry to avoid generating a null character.
233018
- lineArray[0] = '';
233019
-
233020
- /**
233021
- * Split a text into an array of strings. Reduce the texts to a string of
233022
- * hashes where each Unicode character represents one line.
233023
- * Modifies linearray and linehash through being a closure.
233024
- * @param {string} text String to encode.
233025
- * @return {string} Encoded string.
233026
- * @private
233027
- */
233028
- function diff_linesToCharsMunge_(text) {
233029
- var chars = '';
233030
- // Walk the text, pulling out a substring for each line.
233031
- // text.split('\n') would would temporarily double our memory footprint.
233032
- // Modifying text would create many large strings to garbage collect.
233033
- var lineStart = 0;
233034
- var lineEnd = -1;
233035
- // Keeping our own length variable is faster than looking it up.
233036
- var lineArrayLength = lineArray.length;
233037
- while (lineEnd < text.length - 1) {
233038
- lineEnd = text.indexOf('\n', lineStart);
233039
- if (lineEnd == -1) {
233040
- lineEnd = text.length - 1;
233041
- }
233042
- var line = text.substring(lineStart, lineEnd + 1);
233043
-
233044
- if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :
233045
- (lineHash[line] !== undefined)) {
233046
- chars += String.fromCharCode(lineHash[line]);
233047
- } else {
233048
- if (lineArrayLength == maxLines) {
233049
- // Bail out at 65535 because
233050
- // String.fromCharCode(65536) == String.fromCharCode(0)
233051
- line = text.substring(lineStart);
233052
- lineEnd = text.length;
233053
- }
233054
- chars += String.fromCharCode(lineArrayLength);
233055
- lineHash[line] = lineArrayLength;
233056
- lineArray[lineArrayLength++] = line;
233057
- }
233058
- lineStart = lineEnd + 1;
233059
- }
233060
- return chars;
233061
- }
233062
- // Allocate 2/3rds of the space for text1, the rest for text2.
233063
- var maxLines = 40000;
233064
- var chars1 = diff_linesToCharsMunge_(text1);
233065
- maxLines = 65535;
233066
- var chars2 = diff_linesToCharsMunge_(text2);
233067
- return {chars1: chars1, chars2: chars2, lineArray: lineArray};
233068
- };
233069
-
233070
-
233071
- /**
233072
- * Rehydrate the text in a diff from a string of line hashes to real lines of
233073
- * text.
233074
- * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
233075
- * @param {!Array.<string>} lineArray Array of unique strings.
233076
- * @private
233077
- */
233078
- diff_match_patch.prototype.diff_charsToLines_ = function(diffs, lineArray) {
233079
- for (var i = 0; i < diffs.length; i++) {
233080
- var chars = diffs[i][1];
233081
- var text = [];
233082
- for (var j = 0; j < chars.length; j++) {
233083
- text[j] = lineArray[chars.charCodeAt(j)];
233084
- }
233085
- diffs[i][1] = text.join('');
233086
- }
233087
- };
233088
-
233089
-
233090
- /**
233091
- * Determine the common prefix of two strings.
233092
- * @param {string} text1 First string.
233093
- * @param {string} text2 Second string.
233094
- * @return {number} The number of characters common to the start of each
233095
- * string.
233096
- */
233097
- diff_match_patch.prototype.diff_commonPrefix = function(text1, text2) {
233098
- // Quick check for common null cases.
233099
- if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) {
233100
- return 0;
233101
- }
233102
- // Binary search.
233103
- // Performance analysis: https://neil.fraser.name/news/2007/10/09/
233104
- var pointermin = 0;
233105
- var pointermax = Math.min(text1.length, text2.length);
233106
- var pointermid = pointermax;
233107
- var pointerstart = 0;
233108
- while (pointermin < pointermid) {
233109
- if (text1.substring(pointerstart, pointermid) ==
233110
- text2.substring(pointerstart, pointermid)) {
233111
- pointermin = pointermid;
233112
- pointerstart = pointermin;
233113
- } else {
233114
- pointermax = pointermid;
233115
- }
233116
- pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
233117
- }
233118
- return pointermid;
233119
- };
233120
-
233121
-
233122
- /**
233123
- * Determine the common suffix of two strings.
233124
- * @param {string} text1 First string.
233125
- * @param {string} text2 Second string.
233126
- * @return {number} The number of characters common to the end of each string.
233127
- */
233128
- diff_match_patch.prototype.diff_commonSuffix = function(text1, text2) {
233129
- // Quick check for common null cases.
233130
- if (!text1 || !text2 ||
233131
- text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) {
233132
- return 0;
233133
- }
233134
- // Binary search.
233135
- // Performance analysis: https://neil.fraser.name/news/2007/10/09/
233136
- var pointermin = 0;
233137
- var pointermax = Math.min(text1.length, text2.length);
233138
- var pointermid = pointermax;
233139
- var pointerend = 0;
233140
- while (pointermin < pointermid) {
233141
- if (text1.substring(text1.length - pointermid, text1.length - pointerend) ==
233142
- text2.substring(text2.length - pointermid, text2.length - pointerend)) {
233143
- pointermin = pointermid;
233144
- pointerend = pointermin;
233145
- } else {
233146
- pointermax = pointermid;
233147
- }
233148
- pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
233149
- }
233150
- return pointermid;
233151
- };
233152
-
233153
-
233154
- /**
233155
- * Determine if the suffix of one string is the prefix of another.
233156
- * @param {string} text1 First string.
233157
- * @param {string} text2 Second string.
233158
- * @return {number} The number of characters common to the end of the first
233159
- * string and the start of the second string.
233160
- * @private
233161
- */
233162
- diff_match_patch.prototype.diff_commonOverlap_ = function(text1, text2) {
233163
- // Cache the text lengths to prevent multiple calls.
233164
- var text1_length = text1.length;
233165
- var text2_length = text2.length;
233166
- // Eliminate the null case.
233167
- if (text1_length == 0 || text2_length == 0) {
233168
- return 0;
233169
- }
233170
- // Truncate the longer string.
233171
- if (text1_length > text2_length) {
233172
- text1 = text1.substring(text1_length - text2_length);
233173
- } else if (text1_length < text2_length) {
233174
- text2 = text2.substring(0, text1_length);
233175
- }
233176
- var text_length = Math.min(text1_length, text2_length);
233177
- // Quick check for the worst case.
233178
- if (text1 == text2) {
233179
- return text_length;
233180
- }
233181
-
233182
- // Start by looking for a single character match
233183
- // and increase length until no match is found.
233184
- // Performance analysis: https://neil.fraser.name/news/2010/11/04/
233185
- var best = 0;
233186
- var length = 1;
233187
- while (true) {
233188
- var pattern = text1.substring(text_length - length);
233189
- var found = text2.indexOf(pattern);
233190
- if (found == -1) {
233191
- return best;
233192
- }
233193
- length += found;
233194
- if (found == 0 || text1.substring(text_length - length) ==
233195
- text2.substring(0, length)) {
233196
- best = length;
233197
- length++;
233198
- }
233199
- }
233200
- };
233201
-
233202
-
233203
- /**
233204
- * Do the two texts share a substring which is at least half the length of the
233205
- * longer text?
233206
- * This speedup can produce non-minimal diffs.
233207
- * @param {string} text1 First string.
233208
- * @param {string} text2 Second string.
233209
- * @return {Array.<string>} Five element Array, containing the prefix of
233210
- * text1, the suffix of text1, the prefix of text2, the suffix of
233211
- * text2 and the common middle. Or null if there was no match.
233212
- * @private
233213
- */
233214
- diff_match_patch.prototype.diff_halfMatch_ = function(text1, text2) {
233215
- if (this.Diff_Timeout <= 0) {
233216
- // Don't risk returning a non-optimal diff if we have unlimited time.
233217
- return null;
233218
- }
233219
- var longtext = text1.length > text2.length ? text1 : text2;
233220
- var shorttext = text1.length > text2.length ? text2 : text1;
233221
- if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
233222
- return null; // Pointless.
233223
- }
233224
- var dmp = this; // 'this' becomes 'window' in a closure.
233225
-
233226
- /**
233227
- * Does a substring of shorttext exist within longtext such that the substring
233228
- * is at least half the length of longtext?
233229
- * Closure, but does not reference any external variables.
233230
- * @param {string} longtext Longer string.
233231
- * @param {string} shorttext Shorter string.
233232
- * @param {number} i Start index of quarter length substring within longtext.
233233
- * @return {Array.<string>} Five element Array, containing the prefix of
233234
- * longtext, the suffix of longtext, the prefix of shorttext, the suffix
233235
- * of shorttext and the common middle. Or null if there was no match.
233236
- * @private
233237
- */
233238
- function diff_halfMatchI_(longtext, shorttext, i) {
233239
- // Start with a 1/4 length substring at position i as a seed.
233240
- var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
233241
- var j = -1;
233242
- var best_common = '';
233243
- var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;
233244
- while ((j = shorttext.indexOf(seed, j + 1)) != -1) {
233245
- var prefixLength = dmp.diff_commonPrefix(longtext.substring(i),
233246
- shorttext.substring(j));
233247
- var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i),
233248
- shorttext.substring(0, j));
233249
- if (best_common.length < suffixLength + prefixLength) {
233250
- best_common = shorttext.substring(j - suffixLength, j) +
233251
- shorttext.substring(j, j + prefixLength);
233252
- best_longtext_a = longtext.substring(0, i - suffixLength);
233253
- best_longtext_b = longtext.substring(i + prefixLength);
233254
- best_shorttext_a = shorttext.substring(0, j - suffixLength);
233255
- best_shorttext_b = shorttext.substring(j + prefixLength);
233256
- }
233257
- }
233258
- if (best_common.length * 2 >= longtext.length) {
233259
- return [best_longtext_a, best_longtext_b,
233260
- best_shorttext_a, best_shorttext_b, best_common];
233261
- } else {
233262
- return null;
233263
- }
233264
- }
233265
-
233266
- // First check if the second quarter is the seed for a half-match.
233267
- var hm1 = diff_halfMatchI_(longtext, shorttext,
233268
- Math.ceil(longtext.length / 4));
233269
- // Check again based on the third quarter.
233270
- var hm2 = diff_halfMatchI_(longtext, shorttext,
233271
- Math.ceil(longtext.length / 2));
233272
- var hm;
233273
- if (!hm1 && !hm2) {
233274
- return null;
233275
- } else if (!hm2) {
233276
- hm = hm1;
233277
- } else if (!hm1) {
233278
- hm = hm2;
233279
- } else {
233280
- // Both matched. Select the longest.
233281
- hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
233282
- }
233283
-
233284
- // A half-match was found, sort out the return data.
233285
- var text1_a, text1_b, text2_a, text2_b;
233286
- if (text1.length > text2.length) {
233287
- text1_a = hm[0];
233288
- text1_b = hm[1];
233289
- text2_a = hm[2];
233290
- text2_b = hm[3];
233291
- } else {
233292
- text2_a = hm[0];
233293
- text2_b = hm[1];
233294
- text1_a = hm[2];
233295
- text1_b = hm[3];
233296
- }
233297
- var mid_common = hm[4];
233298
- return [text1_a, text1_b, text2_a, text2_b, mid_common];
233299
- };
233300
-
233301
-
233302
- /**
233303
- * Reduce the number of edits by eliminating semantically trivial equalities.
233304
- * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
233305
- */
233306
- diff_match_patch.prototype.diff_cleanupSemantic = function(diffs) {
233307
- var changes = false;
233308
- var equalities = []; // Stack of indices where equalities are found.
233309
- var equalitiesLength = 0; // Keeping our own length var is faster in JS.
233310
- /** @type {?string} */
233311
- var lastEquality = null;
233312
- // Always equal to diffs[equalities[equalitiesLength - 1]][1]
233313
- var pointer = 0; // Index of current position.
233314
- // Number of characters that changed prior to the equality.
233315
- var length_insertions1 = 0;
233316
- var length_deletions1 = 0;
233317
- // Number of characters that changed after the equality.
233318
- var length_insertions2 = 0;
233319
- var length_deletions2 = 0;
233320
- while (pointer < diffs.length) {
233321
- if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.
233322
- equalities[equalitiesLength++] = pointer;
233323
- length_insertions1 = length_insertions2;
233324
- length_deletions1 = length_deletions2;
233325
- length_insertions2 = 0;
233326
- length_deletions2 = 0;
233327
- lastEquality = diffs[pointer][1];
233328
- } else { // An insertion or deletion.
233329
- if (diffs[pointer][0] == DIFF_INSERT) {
233330
- length_insertions2 += diffs[pointer][1].length;
233331
- } else {
233332
- length_deletions2 += diffs[pointer][1].length;
233333
- }
233334
- // Eliminate an equality that is smaller or equal to the edits on both
233335
- // sides of it.
233336
- if (lastEquality && (lastEquality.length <=
233337
- Math.max(length_insertions1, length_deletions1)) &&
233338
- (lastEquality.length <= Math.max(length_insertions2,
233339
- length_deletions2))) {
233340
- // Duplicate record.
233341
- diffs.splice(equalities[equalitiesLength - 1], 0,
233342
- new diff_match_patch.Diff(DIFF_DELETE, lastEquality));
233343
- // Change second copy to insert.
233344
- diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
233345
- // Throw away the equality we just deleted.
233346
- equalitiesLength--;
233347
- // Throw away the previous equality (it needs to be reevaluated).
233348
- equalitiesLength--;
233349
- pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
233350
- length_insertions1 = 0; // Reset the counters.
233351
- length_deletions1 = 0;
233352
- length_insertions2 = 0;
233353
- length_deletions2 = 0;
233354
- lastEquality = null;
233355
- changes = true;
233356
- }
233357
- }
233358
- pointer++;
233359
- }
233360
-
233361
- // Normalize the diff.
233362
- if (changes) {
233363
- this.diff_cleanupMerge(diffs);
233364
- }
233365
- this.diff_cleanupSemanticLossless(diffs);
233366
-
233367
- // Find any overlaps between deletions and insertions.
233368
- // e.g: <del>abcxxx</del><ins>xxxdef</ins>
233369
- // -> <del>abc</del>xxx<ins>def</ins>
233370
- // e.g: <del>xxxabc</del><ins>defxxx</ins>
233371
- // -> <ins>def</ins>xxx<del>abc</del>
233372
- // Only extract an overlap if it is as big as the edit ahead or behind it.
233373
- pointer = 1;
233374
- while (pointer < diffs.length) {
233375
- if (diffs[pointer - 1][0] == DIFF_DELETE &&
233376
- diffs[pointer][0] == DIFF_INSERT) {
233377
- var deletion = diffs[pointer - 1][1];
233378
- var insertion = diffs[pointer][1];
233379
- var overlap_length1 = this.diff_commonOverlap_(deletion, insertion);
233380
- var overlap_length2 = this.diff_commonOverlap_(insertion, deletion);
233381
- if (overlap_length1 >= overlap_length2) {
233382
- if (overlap_length1 >= deletion.length / 2 ||
233383
- overlap_length1 >= insertion.length / 2) {
233384
- // Overlap found. Insert an equality and trim the surrounding edits.
233385
- diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_EQUAL,
233386
- insertion.substring(0, overlap_length1)));
233387
- diffs[pointer - 1][1] =
233388
- deletion.substring(0, deletion.length - overlap_length1);
233389
- diffs[pointer + 1][1] = insertion.substring(overlap_length1);
233390
- pointer++;
233391
- }
233392
- } else {
233393
- if (overlap_length2 >= deletion.length / 2 ||
233394
- overlap_length2 >= insertion.length / 2) {
233395
- // Reverse overlap found.
233396
- // Insert an equality and swap and trim the surrounding edits.
233397
- diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_EQUAL,
233398
- deletion.substring(0, overlap_length2)));
233399
- diffs[pointer - 1][0] = DIFF_INSERT;
233400
- diffs[pointer - 1][1] =
233401
- insertion.substring(0, insertion.length - overlap_length2);
233402
- diffs[pointer + 1][0] = DIFF_DELETE;
233403
- diffs[pointer + 1][1] =
233404
- deletion.substring(overlap_length2);
233405
- pointer++;
233406
- }
233407
- }
233408
- pointer++;
233409
- }
233410
- pointer++;
233411
- }
233412
- };
233413
-
233414
-
233415
- /**
233416
- * Look for single edits surrounded on both sides by equalities
233417
- * which can be shifted sideways to align the edit to a word boundary.
233418
- * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
233419
- * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
233420
- */
233421
- diff_match_patch.prototype.diff_cleanupSemanticLossless = function(diffs) {
233422
- /**
233423
- * Given two strings, compute a score representing whether the internal
233424
- * boundary falls on logical boundaries.
233425
- * Scores range from 6 (best) to 0 (worst).
233426
- * Closure, but does not reference any external variables.
233427
- * @param {string} one First string.
233428
- * @param {string} two Second string.
233429
- * @return {number} The score.
233430
- * @private
233431
- */
233432
- function diff_cleanupSemanticScore_(one, two) {
233433
- if (!one || !two) {
233434
- // Edges are the best.
233435
- return 6;
233436
- }
233437
-
233438
- // Each port of this function behaves slightly differently due to
233439
- // subtle differences in each language's definition of things like
233440
- // 'whitespace'. Since this function's purpose is largely cosmetic,
233441
- // the choice has been made to use each language's native features
233442
- // rather than force total conformity.
233443
- var char1 = one.charAt(one.length - 1);
233444
- var char2 = two.charAt(0);
233445
- var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_);
233446
- var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_);
233447
- var whitespace1 = nonAlphaNumeric1 &&
233448
- char1.match(diff_match_patch.whitespaceRegex_);
233449
- var whitespace2 = nonAlphaNumeric2 &&
233450
- char2.match(diff_match_patch.whitespaceRegex_);
233451
- var lineBreak1 = whitespace1 &&
233452
- char1.match(diff_match_patch.linebreakRegex_);
233453
- var lineBreak2 = whitespace2 &&
233454
- char2.match(diff_match_patch.linebreakRegex_);
233455
- var blankLine1 = lineBreak1 &&
233456
- one.match(diff_match_patch.blanklineEndRegex_);
233457
- var blankLine2 = lineBreak2 &&
233458
- two.match(diff_match_patch.blanklineStartRegex_);
233459
-
233460
- if (blankLine1 || blankLine2) {
233461
- // Five points for blank lines.
233462
- return 5;
233463
- } else if (lineBreak1 || lineBreak2) {
233464
- // Four points for line breaks.
233465
- return 4;
233466
- } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {
233467
- // Three points for end of sentences.
233468
- return 3;
233469
- } else if (whitespace1 || whitespace2) {
233470
- // Two points for whitespace.
233471
- return 2;
233472
- } else if (nonAlphaNumeric1 || nonAlphaNumeric2) {
233473
- // One point for non-alphanumeric.
233474
- return 1;
233475
- }
233476
- return 0;
233477
- }
233478
-
233479
- var pointer = 1;
233480
- // Intentionally ignore the first and last element (don't need checking).
233481
- while (pointer < diffs.length - 1) {
233482
- if (diffs[pointer - 1][0] == DIFF_EQUAL &&
233483
- diffs[pointer + 1][0] == DIFF_EQUAL) {
233484
- // This is a single edit surrounded by equalities.
233485
- var equality1 = diffs[pointer - 1][1];
233486
- var edit = diffs[pointer][1];
233487
- var equality2 = diffs[pointer + 1][1];
233488
-
233489
- // First, shift the edit as far left as possible.
233490
- var commonOffset = this.diff_commonSuffix(equality1, edit);
233491
- if (commonOffset) {
233492
- var commonString = edit.substring(edit.length - commonOffset);
233493
- equality1 = equality1.substring(0, equality1.length - commonOffset);
233494
- edit = commonString + edit.substring(0, edit.length - commonOffset);
233495
- equality2 = commonString + equality2;
233496
- }
233497
-
233498
- // Second, step character by character right, looking for the best fit.
233499
- var bestEquality1 = equality1;
233500
- var bestEdit = edit;
233501
- var bestEquality2 = equality2;
233502
- var bestScore = diff_cleanupSemanticScore_(equality1, edit) +
233503
- diff_cleanupSemanticScore_(edit, equality2);
233504
- while (edit.charAt(0) === equality2.charAt(0)) {
233505
- equality1 += edit.charAt(0);
233506
- edit = edit.substring(1) + equality2.charAt(0);
233507
- equality2 = equality2.substring(1);
233508
- var score = diff_cleanupSemanticScore_(equality1, edit) +
233509
- diff_cleanupSemanticScore_(edit, equality2);
233510
- // The >= encourages trailing rather than leading whitespace on edits.
233511
- if (score >= bestScore) {
233512
- bestScore = score;
233513
- bestEquality1 = equality1;
233514
- bestEdit = edit;
233515
- bestEquality2 = equality2;
233516
- }
233517
- }
233518
-
233519
- if (diffs[pointer - 1][1] != bestEquality1) {
233520
- // We have an improvement, save it back to the diff.
233521
- if (bestEquality1) {
233522
- diffs[pointer - 1][1] = bestEquality1;
233523
- } else {
233524
- diffs.splice(pointer - 1, 1);
233525
- pointer--;
233526
- }
233527
- diffs[pointer][1] = bestEdit;
233528
- if (bestEquality2) {
233529
- diffs[pointer + 1][1] = bestEquality2;
233530
- } else {
233531
- diffs.splice(pointer + 1, 1);
233532
- pointer--;
233533
- }
233534
- }
233535
- }
233536
- pointer++;
233537
- }
233538
- };
233539
-
233540
- // Define some regex patterns for matching boundaries.
233541
- diff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/;
233542
- diff_match_patch.whitespaceRegex_ = /\s/;
233543
- diff_match_patch.linebreakRegex_ = /[\r\n]/;
233544
- diff_match_patch.blanklineEndRegex_ = /\n\r?\n$/;
233545
- diff_match_patch.blanklineStartRegex_ = /^\r?\n\r?\n/;
233546
-
233547
- /**
233548
- * Reduce the number of edits by eliminating operationally trivial equalities.
233549
- * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
233550
- */
233551
- diff_match_patch.prototype.diff_cleanupEfficiency = function(diffs) {
233552
- var changes = false;
233553
- var equalities = []; // Stack of indices where equalities are found.
233554
- var equalitiesLength = 0; // Keeping our own length var is faster in JS.
233555
- /** @type {?string} */
233556
- var lastEquality = null;
233557
- // Always equal to diffs[equalities[equalitiesLength - 1]][1]
233558
- var pointer = 0; // Index of current position.
233559
- // Is there an insertion operation before the last equality.
233560
- var pre_ins = false;
233561
- // Is there a deletion operation before the last equality.
233562
- var pre_del = false;
233563
- // Is there an insertion operation after the last equality.
233564
- var post_ins = false;
233565
- // Is there a deletion operation after the last equality.
233566
- var post_del = false;
233567
- while (pointer < diffs.length) {
233568
- if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.
233569
- if (diffs[pointer][1].length < this.Diff_EditCost &&
233570
- (post_ins || post_del)) {
233571
- // Candidate found.
233572
- equalities[equalitiesLength++] = pointer;
233573
- pre_ins = post_ins;
233574
- pre_del = post_del;
233575
- lastEquality = diffs[pointer][1];
233576
- } else {
233577
- // Not a candidate, and can never become one.
233578
- equalitiesLength = 0;
233579
- lastEquality = null;
233580
- }
233581
- post_ins = post_del = false;
233582
- } else { // An insertion or deletion.
233583
- if (diffs[pointer][0] == DIFF_DELETE) {
233584
- post_del = true;
233585
- } else {
233586
- post_ins = true;
233587
- }
233588
- /*
233589
- * Five types to be split:
233590
- * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
233591
- * <ins>A</ins>X<ins>C</ins><del>D</del>
233592
- * <ins>A</ins><del>B</del>X<ins>C</ins>
233593
- * <ins>A</del>X<ins>C</ins><del>D</del>
233594
- * <ins>A</ins><del>B</del>X<del>C</del>
233595
- */
233596
- if (lastEquality && ((pre_ins && pre_del && post_ins && post_del) ||
233597
- ((lastEquality.length < this.Diff_EditCost / 2) &&
233598
- (pre_ins + pre_del + post_ins + post_del) == 3))) {
233599
- // Duplicate record.
233600
- diffs.splice(equalities[equalitiesLength - 1], 0,
233601
- new diff_match_patch.Diff(DIFF_DELETE, lastEquality));
233602
- // Change second copy to insert.
233603
- diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
233604
- equalitiesLength--; // Throw away the equality we just deleted;
233605
- lastEquality = null;
233606
- if (pre_ins && pre_del) {
233607
- // No changes made which could affect previous entry, keep going.
233608
- post_ins = post_del = true;
233609
- equalitiesLength = 0;
233610
- } else {
233611
- equalitiesLength--; // Throw away the previous equality.
233612
- pointer = equalitiesLength > 0 ?
233613
- equalities[equalitiesLength - 1] : -1;
233614
- post_ins = post_del = false;
233615
- }
233616
- changes = true;
233617
- }
233618
- }
233619
- pointer++;
233620
- }
233621
-
233622
- if (changes) {
233623
- this.diff_cleanupMerge(diffs);
233624
- }
233625
- };
233626
-
233627
-
233628
- /**
233629
- * Reorder and merge like edit sections. Merge equalities.
233630
- * Any edit section can move as long as it doesn't cross an equality.
233631
- * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
233632
- */
233633
- diff_match_patch.prototype.diff_cleanupMerge = function(diffs) {
233634
- // Add a dummy entry at the end.
233635
- diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, ''));
233636
- var pointer = 0;
233637
- var count_delete = 0;
233638
- var count_insert = 0;
233639
- var text_delete = '';
233640
- var text_insert = '';
233641
- var commonlength;
233642
- while (pointer < diffs.length) {
233643
- switch (diffs[pointer][0]) {
233644
- case DIFF_INSERT:
233645
- count_insert++;
233646
- text_insert += diffs[pointer][1];
233647
- pointer++;
233648
- break;
233649
- case DIFF_DELETE:
233650
- count_delete++;
233651
- text_delete += diffs[pointer][1];
233652
- pointer++;
233653
- break;
233654
- case DIFF_EQUAL:
233655
- // Upon reaching an equality, check for prior redundancies.
233656
- if (count_delete + count_insert > 1) {
233657
- if (count_delete !== 0 && count_insert !== 0) {
233658
- // Factor out any common prefixies.
233659
- commonlength = this.diff_commonPrefix(text_insert, text_delete);
233660
- if (commonlength !== 0) {
233661
- if ((pointer - count_delete - count_insert) > 0 &&
233662
- diffs[pointer - count_delete - count_insert - 1][0] ==
233663
- DIFF_EQUAL) {
233664
- diffs[pointer - count_delete - count_insert - 1][1] +=
233665
- text_insert.substring(0, commonlength);
233666
- } else {
233667
- diffs.splice(0, 0, new diff_match_patch.Diff(DIFF_EQUAL,
233668
- text_insert.substring(0, commonlength)));
233669
- pointer++;
233670
- }
233671
- text_insert = text_insert.substring(commonlength);
233672
- text_delete = text_delete.substring(commonlength);
233673
- }
233674
- // Factor out any common suffixies.
233675
- commonlength = this.diff_commonSuffix(text_insert, text_delete);
233676
- if (commonlength !== 0) {
233677
- diffs[pointer][1] = text_insert.substring(text_insert.length -
233678
- commonlength) + diffs[pointer][1];
233679
- text_insert = text_insert.substring(0, text_insert.length -
233680
- commonlength);
233681
- text_delete = text_delete.substring(0, text_delete.length -
233682
- commonlength);
233683
- }
233684
- }
233685
- // Delete the offending records and add the merged ones.
233686
- pointer -= count_delete + count_insert;
233687
- diffs.splice(pointer, count_delete + count_insert);
233688
- if (text_delete.length) {
233689
- diffs.splice(pointer, 0,
233690
- new diff_match_patch.Diff(DIFF_DELETE, text_delete));
233691
- pointer++;
233692
- }
233693
- if (text_insert.length) {
233694
- diffs.splice(pointer, 0,
233695
- new diff_match_patch.Diff(DIFF_INSERT, text_insert));
233696
- pointer++;
233697
- }
233698
- pointer++;
233699
- } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) {
233700
- // Merge this equality with the previous one.
233701
- diffs[pointer - 1][1] += diffs[pointer][1];
233702
- diffs.splice(pointer, 1);
233703
- } else {
233704
- pointer++;
233705
- }
233706
- count_insert = 0;
233707
- count_delete = 0;
233708
- text_delete = '';
233709
- text_insert = '';
233710
- break;
233711
- }
233712
- }
233713
- if (diffs[diffs.length - 1][1] === '') {
233714
- diffs.pop(); // Remove the dummy entry at the end.
233715
- }
233716
-
233717
- // Second pass: look for single edits surrounded on both sides by equalities
233718
- // which can be shifted sideways to eliminate an equality.
233719
- // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
233720
- var changes = false;
233721
- pointer = 1;
233722
- // Intentionally ignore the first and last element (don't need checking).
233723
- while (pointer < diffs.length - 1) {
233724
- if (diffs[pointer - 1][0] == DIFF_EQUAL &&
233725
- diffs[pointer + 1][0] == DIFF_EQUAL) {
233726
- // This is a single edit surrounded by equalities.
233727
- if (diffs[pointer][1].substring(diffs[pointer][1].length -
233728
- diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) {
233729
- // Shift the edit over the previous equality.
233730
- diffs[pointer][1] = diffs[pointer - 1][1] +
233731
- diffs[pointer][1].substring(0, diffs[pointer][1].length -
233732
- diffs[pointer - 1][1].length);
233733
- diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
233734
- diffs.splice(pointer - 1, 1);
233735
- changes = true;
233736
- } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==
233737
- diffs[pointer + 1][1]) {
233738
- // Shift the edit over the next equality.
233739
- diffs[pointer - 1][1] += diffs[pointer + 1][1];
233740
- diffs[pointer][1] =
233741
- diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
233742
- diffs[pointer + 1][1];
233743
- diffs.splice(pointer + 1, 1);
233744
- changes = true;
233745
- }
233746
- }
233747
- pointer++;
233748
- }
233749
- // If shifts were made, the diff needs reordering and another shift sweep.
233750
- if (changes) {
233751
- this.diff_cleanupMerge(diffs);
233752
- }
233753
- };
233754
-
233755
-
233756
- /**
233757
- * loc is a location in text1, compute and return the equivalent location in
233758
- * text2.
233759
- * e.g. 'The cat' vs 'The big cat', 1->1, 5->8
233760
- * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
233761
- * @param {number} loc Location within text1.
233762
- * @return {number} Location within text2.
233763
- */
233764
- diff_match_patch.prototype.diff_xIndex = function(diffs, loc) {
233765
- var chars1 = 0;
233766
- var chars2 = 0;
233767
- var last_chars1 = 0;
233768
- var last_chars2 = 0;
233769
- var x;
233770
- for (x = 0; x < diffs.length; x++) {
233771
- if (diffs[x][0] !== DIFF_INSERT) { // Equality or deletion.
233772
- chars1 += diffs[x][1].length;
233773
- }
233774
- if (diffs[x][0] !== DIFF_DELETE) { // Equality or insertion.
233775
- chars2 += diffs[x][1].length;
233776
- }
233777
- if (chars1 > loc) { // Overshot the location.
233778
- break;
233779
- }
233780
- last_chars1 = chars1;
233781
- last_chars2 = chars2;
233782
- }
233783
- // Was the location was deleted?
233784
- if (diffs.length != x && diffs[x][0] === DIFF_DELETE) {
233785
- return last_chars2;
233786
- }
233787
- // Add the remaining character length.
233788
- return last_chars2 + (loc - last_chars1);
233789
- };
233790
-
233791
-
233792
- /**
233793
- * Convert a diff array into a pretty HTML report.
233794
- * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
233795
- * @return {string} HTML representation.
233796
- */
233797
- diff_match_patch.prototype.diff_prettyHtml = function(diffs) {
233798
- var html = [];
233799
- var pattern_amp = /&/g;
233800
- var pattern_lt = /</g;
233801
- var pattern_gt = />/g;
233802
- var pattern_para = /\n/g;
233803
- for (var x = 0; x < diffs.length; x++) {
233804
- var op = diffs[x][0]; // Operation (insert, delete, equal)
233805
- var data = diffs[x][1]; // Text of change.
233806
- var text = data.replace(pattern_amp, '&amp;').replace(pattern_lt, '&lt;')
233807
- .replace(pattern_gt, '&gt;').replace(pattern_para, '&para;<br>');
233808
- switch (op) {
233809
- case DIFF_INSERT:
233810
- html[x] = '<ins style="background:#e6ffe6;">' + text + '</ins>';
233811
- break;
233812
- case DIFF_DELETE:
233813
- html[x] = '<del style="background:#ffe6e6;">' + text + '</del>';
233814
- break;
233815
- case DIFF_EQUAL:
233816
- html[x] = '<span>' + text + '</span>';
233817
- break;
233818
- }
233819
- }
233820
- return html.join('');
233821
- };
233822
-
233823
-
233824
- /**
233825
- * Compute and return the source text (all equalities and deletions).
233826
- * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
233827
- * @return {string} Source text.
233828
- */
233829
- diff_match_patch.prototype.diff_text1 = function(diffs) {
233830
- var text = [];
233831
- for (var x = 0; x < diffs.length; x++) {
233832
- if (diffs[x][0] !== DIFF_INSERT) {
233833
- text[x] = diffs[x][1];
233834
- }
233835
- }
233836
- return text.join('');
233837
- };
233838
-
233839
-
233840
- /**
233841
- * Compute and return the destination text (all equalities and insertions).
233842
- * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
233843
- * @return {string} Destination text.
233844
- */
233845
- diff_match_patch.prototype.diff_text2 = function(diffs) {
233846
- var text = [];
233847
- for (var x = 0; x < diffs.length; x++) {
233848
- if (diffs[x][0] !== DIFF_DELETE) {
233849
- text[x] = diffs[x][1];
233850
- }
233851
- }
233852
- return text.join('');
233853
- };
233854
-
233855
-
233856
- /**
233857
- * Compute the Levenshtein distance; the number of inserted, deleted or
233858
- * substituted characters.
233859
- * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
233860
- * @return {number} Number of changes.
233861
- */
233862
- diff_match_patch.prototype.diff_levenshtein = function(diffs) {
233863
- var levenshtein = 0;
233864
- var insertions = 0;
233865
- var deletions = 0;
233866
- for (var x = 0; x < diffs.length; x++) {
233867
- var op = diffs[x][0];
233868
- var data = diffs[x][1];
233869
- switch (op) {
233870
- case DIFF_INSERT:
233871
- insertions += data.length;
233872
- break;
233873
- case DIFF_DELETE:
233874
- deletions += data.length;
233875
- break;
233876
- case DIFF_EQUAL:
233877
- // A deletion and an insertion is one substitution.
233878
- levenshtein += Math.max(insertions, deletions);
233879
- insertions = 0;
233880
- deletions = 0;
233881
- break;
233882
- }
233883
- }
233884
- levenshtein += Math.max(insertions, deletions);
233885
- return levenshtein;
233886
- };
233887
-
233888
-
233889
- /**
233890
- * Crush the diff into an encoded string which describes the operations
233891
- * required to transform text1 into text2.
233892
- * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
233893
- * Operations are tab-separated. Inserted text is escaped using %xx notation.
233894
- * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
233895
- * @return {string} Delta text.
233896
- */
233897
- diff_match_patch.prototype.diff_toDelta = function(diffs) {
233898
- var text = [];
233899
- for (var x = 0; x < diffs.length; x++) {
233900
- switch (diffs[x][0]) {
233901
- case DIFF_INSERT:
233902
- text[x] = '+' + encodeURI(diffs[x][1]);
233903
- break;
233904
- case DIFF_DELETE:
233905
- text[x] = '-' + diffs[x][1].length;
233906
- break;
233907
- case DIFF_EQUAL:
233908
- text[x] = '=' + diffs[x][1].length;
233909
- break;
233910
- }
233911
- }
233912
- return text.join('\t').replace(/%20/g, ' ');
233913
- };
233914
-
233915
-
233916
- /**
233917
- * Given the original text1, and an encoded string which describes the
233918
- * operations required to transform text1 into text2, compute the full diff.
233919
- * @param {string} text1 Source string for the diff.
233920
- * @param {string} delta Delta text.
233921
- * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
233922
- * @throws {!Error} If invalid input.
233923
- */
233924
- diff_match_patch.prototype.diff_fromDelta = function(text1, delta) {
233925
- var diffs = [];
233926
- var diffsLength = 0; // Keeping our own length var is faster in JS.
233927
- var pointer = 0; // Cursor in text1
233928
- var tokens = delta.split(/\t/g);
233929
- for (var x = 0; x < tokens.length; x++) {
233930
- // Each token begins with a one character parameter which specifies the
233931
- // operation of this token (delete, insert, equality).
233932
- var param = tokens[x].substring(1);
233933
- switch (tokens[x].charAt(0)) {
233934
- case '+':
233935
- try {
233936
- diffs[diffsLength++] =
233937
- new diff_match_patch.Diff(DIFF_INSERT, decodeURI(param));
233938
- } catch (ex) {
233939
- // Malformed URI sequence.
233940
- throw new Error('Illegal escape in diff_fromDelta: ' + param);
233941
- }
233942
- break;
233943
- case '-':
233944
- // Fall through.
233945
- case '=':
233946
- var n = parseInt(param, 10);
233947
- if (isNaN(n) || n < 0) {
233948
- throw new Error('Invalid number in diff_fromDelta: ' + param);
233949
- }
233950
- var text = text1.substring(pointer, pointer += n);
233951
- if (tokens[x].charAt(0) == '=') {
233952
- diffs[diffsLength++] = new diff_match_patch.Diff(DIFF_EQUAL, text);
233953
- } else {
233954
- diffs[diffsLength++] = new diff_match_patch.Diff(DIFF_DELETE, text);
233955
- }
233956
- break;
233957
- default:
233958
- // Blank tokens are ok (from a trailing \t).
233959
- // Anything else is an error.
233960
- if (tokens[x]) {
233961
- throw new Error('Invalid diff operation in diff_fromDelta: ' +
233962
- tokens[x]);
233963
- }
233964
- }
233965
- }
233966
- if (pointer != text1.length) {
233967
- throw new Error('Delta length (' + pointer +
233968
- ') does not equal source text length (' + text1.length + ').');
233969
- }
233970
- return diffs;
233971
- };
233972
-
233973
-
233974
- // MATCH FUNCTIONS
233975
-
233976
-
233977
- /**
233978
- * Locate the best instance of 'pattern' in 'text' near 'loc'.
233979
- * @param {string} text The text to search.
233980
- * @param {string} pattern The pattern to search for.
233981
- * @param {number} loc The location to search around.
233982
- * @return {number} Best match index or -1.
233983
- */
233984
- diff_match_patch.prototype.match_main = function(text, pattern, loc) {
233985
- // Check for null inputs.
233986
- if (text == null || pattern == null || loc == null) {
233987
- throw new Error('Null input. (match_main)');
233988
- }
233989
-
233990
- loc = Math.max(0, Math.min(loc, text.length));
233991
- if (text == pattern) {
233992
- // Shortcut (potentially not guaranteed by the algorithm)
233993
- return 0;
233994
- } else if (!text.length) {
233995
- // Nothing to match.
233996
- return -1;
233997
- } else if (text.substring(loc, loc + pattern.length) == pattern) {
233998
- // Perfect match at the perfect spot! (Includes case of null pattern)
233999
- return loc;
234000
- } else {
234001
- // Do a fuzzy compare.
234002
- return this.match_bitap_(text, pattern, loc);
234003
- }
234004
- };
234005
-
234006
-
234007
- /**
234008
- * Locate the best instance of 'pattern' in 'text' near 'loc' using the
234009
- * Bitap algorithm.
234010
- * @param {string} text The text to search.
234011
- * @param {string} pattern The pattern to search for.
234012
- * @param {number} loc The location to search around.
234013
- * @return {number} Best match index or -1.
234014
- * @private
234015
- */
234016
- diff_match_patch.prototype.match_bitap_ = function(text, pattern, loc) {
234017
- if (pattern.length > this.Match_MaxBits) {
234018
- throw new Error('Pattern too long for this browser.');
234019
- }
234020
-
234021
- // Initialise the alphabet.
234022
- var s = this.match_alphabet_(pattern);
234023
-
234024
- var dmp = this; // 'this' becomes 'window' in a closure.
234025
-
234026
- /**
234027
- * Compute and return the score for a match with e errors and x location.
234028
- * Accesses loc and pattern through being a closure.
234029
- * @param {number} e Number of errors in match.
234030
- * @param {number} x Location of match.
234031
- * @return {number} Overall score for match (0.0 = good, 1.0 = bad).
234032
- * @private
234033
- */
234034
- function match_bitapScore_(e, x) {
234035
- var accuracy = e / pattern.length;
234036
- var proximity = Math.abs(loc - x);
234037
- if (!dmp.Match_Distance) {
234038
- // Dodge divide by zero error.
234039
- return proximity ? 1.0 : accuracy;
234040
- }
234041
- return accuracy + (proximity / dmp.Match_Distance);
234042
- }
234043
-
234044
- // Highest score beyond which we give up.
234045
- var score_threshold = this.Match_Threshold;
234046
- // Is there a nearby exact match? (speedup)
234047
- var best_loc = text.indexOf(pattern, loc);
234048
- if (best_loc != -1) {
234049
- score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold);
234050
- // What about in the other direction? (speedup)
234051
- best_loc = text.lastIndexOf(pattern, loc + pattern.length);
234052
- if (best_loc != -1) {
234053
- score_threshold =
234054
- Math.min(match_bitapScore_(0, best_loc), score_threshold);
234055
- }
234056
- }
234057
-
234058
- // Initialise the bit arrays.
234059
- var matchmask = 1 << (pattern.length - 1);
234060
- best_loc = -1;
234061
-
234062
- var bin_min, bin_mid;
234063
- var bin_max = pattern.length + text.length;
234064
- var last_rd;
234065
- for (var d = 0; d < pattern.length; d++) {
234066
- // Scan for the best match; each iteration allows for one more error.
234067
- // Run a binary search to determine how far from 'loc' we can stray at this
234068
- // error level.
234069
- bin_min = 0;
234070
- bin_mid = bin_max;
234071
- while (bin_min < bin_mid) {
234072
- if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) {
234073
- bin_min = bin_mid;
234074
- } else {
234075
- bin_max = bin_mid;
234076
- }
234077
- bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min);
234078
- }
234079
- // Use the result from this iteration as the maximum for the next.
234080
- bin_max = bin_mid;
234081
- var start = Math.max(1, loc - bin_mid + 1);
234082
- var finish = Math.min(loc + bin_mid, text.length) + pattern.length;
234083
-
234084
- var rd = Array(finish + 2);
234085
- rd[finish + 1] = (1 << d) - 1;
234086
- for (var j = finish; j >= start; j--) {
234087
- // The alphabet (s) is a sparse hash, so the following line generates
234088
- // warnings.
234089
- var charMatch = s[text.charAt(j - 1)];
234090
- if (d === 0) { // First pass: exact match.
234091
- rd[j] = ((rd[j + 1] << 1) | 1) & charMatch;
234092
- } else { // Subsequent passes: fuzzy match.
234093
- rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) |
234094
- (((last_rd[j + 1] | last_rd[j]) << 1) | 1) |
234095
- last_rd[j + 1];
234096
- }
234097
- if (rd[j] & matchmask) {
234098
- var score = match_bitapScore_(d, j - 1);
234099
- // This match will almost certainly be better than any existing match.
234100
- // But check anyway.
234101
- if (score <= score_threshold) {
234102
- // Told you so.
234103
- score_threshold = score;
234104
- best_loc = j - 1;
234105
- if (best_loc > loc) {
234106
- // When passing loc, don't exceed our current distance from loc.
234107
- start = Math.max(1, 2 * loc - best_loc);
234108
- } else {
234109
- // Already passed loc, downhill from here on in.
234110
- break;
234111
- }
234112
- }
234113
- }
234114
- }
234115
- // No hope for a (better) match at greater error levels.
234116
- if (match_bitapScore_(d + 1, loc) > score_threshold) {
234117
- break;
234118
- }
234119
- last_rd = rd;
234120
- }
234121
- return best_loc;
234122
- };
234123
-
234124
-
234125
- /**
234126
- * Initialise the alphabet for the Bitap algorithm.
234127
- * @param {string} pattern The text to encode.
234128
- * @return {!Object} Hash of character locations.
234129
- * @private
234130
- */
234131
- diff_match_patch.prototype.match_alphabet_ = function(pattern) {
234132
- var s = {};
234133
- for (var i = 0; i < pattern.length; i++) {
234134
- s[pattern.charAt(i)] = 0;
234135
- }
234136
- for (var i = 0; i < pattern.length; i++) {
234137
- s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1);
234138
- }
234139
- return s;
234140
- };
234141
-
234142
-
234143
- // PATCH FUNCTIONS
234144
-
234145
-
234146
- /**
234147
- * Increase the context until it is unique,
234148
- * but don't let the pattern expand beyond Match_MaxBits.
234149
- * @param {!diff_match_patch.patch_obj} patch The patch to grow.
234150
- * @param {string} text Source text.
234151
- * @private
234152
- */
234153
- diff_match_patch.prototype.patch_addContext_ = function(patch, text) {
234154
- if (text.length == 0) {
234155
- return;
234156
- }
234157
- if (patch.start2 === null) {
234158
- throw Error('patch not initialized');
234159
- }
234160
- var pattern = text.substring(patch.start2, patch.start2 + patch.length1);
234161
- var padding = 0;
234162
-
234163
- // Look for the first and last matches of pattern in text. If two different
234164
- // matches are found, increase the pattern length.
234165
- while (text.indexOf(pattern) != text.lastIndexOf(pattern) &&
234166
- pattern.length < this.Match_MaxBits - this.Patch_Margin -
234167
- this.Patch_Margin) {
234168
- padding += this.Patch_Margin;
234169
- pattern = text.substring(patch.start2 - padding,
234170
- patch.start2 + patch.length1 + padding);
234171
- }
234172
- // Add one chunk for good luck.
234173
- padding += this.Patch_Margin;
234174
-
234175
- // Add the prefix.
234176
- var prefix = text.substring(patch.start2 - padding, patch.start2);
234177
- if (prefix) {
234178
- patch.diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, prefix));
234179
- }
234180
- // Add the suffix.
234181
- var suffix = text.substring(patch.start2 + patch.length1,
234182
- patch.start2 + patch.length1 + padding);
234183
- if (suffix) {
234184
- patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, suffix));
234185
- }
234186
-
234187
- // Roll back the start points.
234188
- patch.start1 -= prefix.length;
234189
- patch.start2 -= prefix.length;
234190
- // Extend the lengths.
234191
- patch.length1 += prefix.length + suffix.length;
234192
- patch.length2 += prefix.length + suffix.length;
234193
- };
234194
-
234195
-
234196
- /**
234197
- * Compute a list of patches to turn text1 into text2.
234198
- * Use diffs if provided, otherwise compute it ourselves.
234199
- * There are four ways to call this function, depending on what data is
234200
- * available to the caller:
234201
- * Method 1:
234202
- * a = text1, b = text2
234203
- * Method 2:
234204
- * a = diffs
234205
- * Method 3 (optimal):
234206
- * a = text1, b = diffs
234207
- * Method 4 (deprecated, use method 3):
234208
- * a = text1, b = text2, c = diffs
234209
- *
234210
- * @param {string|!Array.<!diff_match_patch.Diff>} a text1 (methods 1,3,4) or
234211
- * Array of diff tuples for text1 to text2 (method 2).
234212
- * @param {string|!Array.<!diff_match_patch.Diff>=} opt_b text2 (methods 1,4) or
234213
- * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
234214
- * @param {string|!Array.<!diff_match_patch.Diff>=} opt_c Array of diff tuples
234215
- * for text1 to text2 (method 4) or undefined (methods 1,2,3).
234216
- * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
234217
- */
234218
- diff_match_patch.prototype.patch_make = function(a, opt_b, opt_c) {
234219
- var text1, diffs;
234220
- if (typeof a == 'string' && typeof opt_b == 'string' &&
234221
- typeof opt_c == 'undefined') {
234222
- // Method 1: text1, text2
234223
- // Compute diffs from text1 and text2.
234224
- text1 = /** @type {string} */(a);
234225
- diffs = this.diff_main(text1, /** @type {string} */(opt_b), true);
234226
- if (diffs.length > 2) {
234227
- this.diff_cleanupSemantic(diffs);
234228
- this.diff_cleanupEfficiency(diffs);
234229
- }
234230
- } else if (a && typeof a == 'object' && typeof opt_b == 'undefined' &&
234231
- typeof opt_c == 'undefined') {
234232
- // Method 2: diffs
234233
- // Compute text1 from diffs.
234234
- diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(a);
234235
- text1 = this.diff_text1(diffs);
234236
- } else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' &&
234237
- typeof opt_c == 'undefined') {
234238
- // Method 3: text1, diffs
234239
- text1 = /** @type {string} */(a);
234240
- diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_b);
234241
- } else if (typeof a == 'string' && typeof opt_b == 'string' &&
234242
- opt_c && typeof opt_c == 'object') {
234243
- // Method 4: text1, text2, diffs
234244
- // text2 is not used.
234245
- text1 = /** @type {string} */(a);
234246
- diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_c);
234247
- } else {
234248
- throw new Error('Unknown call format to patch_make.');
234249
- }
234250
-
234251
- if (diffs.length === 0) {
234252
- return []; // Get rid of the null case.
234253
- }
234254
- var patches = [];
234255
- var patch = new diff_match_patch.patch_obj();
234256
- var patchDiffLength = 0; // Keeping our own length var is faster in JS.
234257
- var char_count1 = 0; // Number of characters into the text1 string.
234258
- var char_count2 = 0; // Number of characters into the text2 string.
234259
- // Start with text1 (prepatch_text) and apply the diffs until we arrive at
234260
- // text2 (postpatch_text). We recreate the patches one by one to determine
234261
- // context info.
234262
- var prepatch_text = text1;
234263
- var postpatch_text = text1;
234264
- for (var x = 0; x < diffs.length; x++) {
234265
- var diff_type = diffs[x][0];
234266
- var diff_text = diffs[x][1];
234267
-
234268
- if (!patchDiffLength && diff_type !== DIFF_EQUAL) {
234269
- // A new patch starts here.
234270
- patch.start1 = char_count1;
234271
- patch.start2 = char_count2;
234272
- }
234273
-
234274
- switch (diff_type) {
234275
- case DIFF_INSERT:
234276
- patch.diffs[patchDiffLength++] = diffs[x];
234277
- patch.length2 += diff_text.length;
234278
- postpatch_text = postpatch_text.substring(0, char_count2) + diff_text +
234279
- postpatch_text.substring(char_count2);
234280
- break;
234281
- case DIFF_DELETE:
234282
- patch.length1 += diff_text.length;
234283
- patch.diffs[patchDiffLength++] = diffs[x];
234284
- postpatch_text = postpatch_text.substring(0, char_count2) +
234285
- postpatch_text.substring(char_count2 +
234286
- diff_text.length);
234287
- break;
234288
- case DIFF_EQUAL:
234289
- if (diff_text.length <= 2 * this.Patch_Margin &&
234290
- patchDiffLength && diffs.length != x + 1) {
234291
- // Small equality inside a patch.
234292
- patch.diffs[patchDiffLength++] = diffs[x];
234293
- patch.length1 += diff_text.length;
234294
- patch.length2 += diff_text.length;
234295
- } else if (diff_text.length >= 2 * this.Patch_Margin) {
234296
- // Time for a new patch.
234297
- if (patchDiffLength) {
234298
- this.patch_addContext_(patch, prepatch_text);
234299
- patches.push(patch);
234300
- patch = new diff_match_patch.patch_obj();
234301
- patchDiffLength = 0;
234302
- // Unlike Unidiff, our patch lists have a rolling context.
234303
- // https://github.com/google/diff-match-patch/wiki/Unidiff
234304
- // Update prepatch text & pos to reflect the application of the
234305
- // just completed patch.
234306
- prepatch_text = postpatch_text;
234307
- char_count1 = char_count2;
234308
- }
234309
- }
234310
- break;
234311
- }
234312
-
234313
- // Update the current character count.
234314
- if (diff_type !== DIFF_INSERT) {
234315
- char_count1 += diff_text.length;
234316
- }
234317
- if (diff_type !== DIFF_DELETE) {
234318
- char_count2 += diff_text.length;
234319
- }
234320
- }
234321
- // Pick up the leftover patch if not empty.
234322
- if (patchDiffLength) {
234323
- this.patch_addContext_(patch, prepatch_text);
234324
- patches.push(patch);
234325
- }
234326
-
234327
- return patches;
234328
- };
234329
-
234330
-
234331
- /**
234332
- * Given an array of patches, return another array that is identical.
234333
- * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
234334
- * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
234335
- */
234336
- diff_match_patch.prototype.patch_deepCopy = function(patches) {
234337
- // Making deep copies is hard in JavaScript.
234338
- var patchesCopy = [];
234339
- for (var x = 0; x < patches.length; x++) {
234340
- var patch = patches[x];
234341
- var patchCopy = new diff_match_patch.patch_obj();
234342
- patchCopy.diffs = [];
234343
- for (var y = 0; y < patch.diffs.length; y++) {
234344
- patchCopy.diffs[y] =
234345
- new diff_match_patch.Diff(patch.diffs[y][0], patch.diffs[y][1]);
234346
- }
234347
- patchCopy.start1 = patch.start1;
234348
- patchCopy.start2 = patch.start2;
234349
- patchCopy.length1 = patch.length1;
234350
- patchCopy.length2 = patch.length2;
234351
- patchesCopy[x] = patchCopy;
234352
- }
234353
- return patchesCopy;
234354
- };
234355
-
234356
-
234357
- /**
234358
- * Merge a set of patches onto the text. Return a patched text, as well
234359
- * as a list of true/false values indicating which patches were applied.
234360
- * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
234361
- * @param {string} text Old text.
234362
- * @return {!Array.<string|!Array.<boolean>>} Two element Array, containing the
234363
- * new text and an array of boolean values.
234364
- */
234365
- diff_match_patch.prototype.patch_apply = function(patches, text) {
234366
- if (patches.length == 0) {
234367
- return [text, []];
234368
- }
234369
-
234370
- // Deep copy the patches so that no changes are made to originals.
234371
- patches = this.patch_deepCopy(patches);
234372
-
234373
- var nullPadding = this.patch_addPadding(patches);
234374
- text = nullPadding + text + nullPadding;
234375
-
234376
- this.patch_splitMax(patches);
234377
- // delta keeps track of the offset between the expected and actual location
234378
- // of the previous patch. If there are patches expected at positions 10 and
234379
- // 20, but the first patch was found at 12, delta is 2 and the second patch
234380
- // has an effective expected position of 22.
234381
- var delta = 0;
234382
- var results = [];
234383
- for (var x = 0; x < patches.length; x++) {
234384
- var expected_loc = patches[x].start2 + delta;
234385
- var text1 = this.diff_text1(patches[x].diffs);
234386
- var start_loc;
234387
- var end_loc = -1;
234388
- if (text1.length > this.Match_MaxBits) {
234389
- // patch_splitMax will only provide an oversized pattern in the case of
234390
- // a monster delete.
234391
- start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits),
234392
- expected_loc);
234393
- if (start_loc != -1) {
234394
- end_loc = this.match_main(text,
234395
- text1.substring(text1.length - this.Match_MaxBits),
234396
- expected_loc + text1.length - this.Match_MaxBits);
234397
- if (end_loc == -1 || start_loc >= end_loc) {
234398
- // Can't find valid trailing context. Drop this patch.
234399
- start_loc = -1;
234400
- }
234401
- }
234402
- } else {
234403
- start_loc = this.match_main(text, text1, expected_loc);
234404
- }
234405
- if (start_loc == -1) {
234406
- // No match found. :(
234407
- results[x] = false;
234408
- // Subtract the delta for this failed patch from subsequent patches.
234409
- delta -= patches[x].length2 - patches[x].length1;
234410
- } else {
234411
- // Found a match. :)
234412
- results[x] = true;
234413
- delta = start_loc - expected_loc;
234414
- var text2;
234415
- if (end_loc == -1) {
234416
- text2 = text.substring(start_loc, start_loc + text1.length);
234417
- } else {
234418
- text2 = text.substring(start_loc, end_loc + this.Match_MaxBits);
234419
- }
234420
- if (text1 == text2) {
234421
- // Perfect match, just shove the replacement text in.
234422
- text = text.substring(0, start_loc) +
234423
- this.diff_text2(patches[x].diffs) +
234424
- text.substring(start_loc + text1.length);
234425
- } else {
234426
- // Imperfect match. Run a diff to get a framework of equivalent
234427
- // indices.
234428
- var diffs = this.diff_main(text1, text2, false);
234429
- if (text1.length > this.Match_MaxBits &&
234430
- this.diff_levenshtein(diffs) / text1.length >
234431
- this.Patch_DeleteThreshold) {
234432
- // The end points match, but the content is unacceptably bad.
234433
- results[x] = false;
234434
- } else {
234435
- this.diff_cleanupSemanticLossless(diffs);
234436
- var index1 = 0;
234437
- var index2;
234438
- for (var y = 0; y < patches[x].diffs.length; y++) {
234439
- var mod = patches[x].diffs[y];
234440
- if (mod[0] !== DIFF_EQUAL) {
234441
- index2 = this.diff_xIndex(diffs, index1);
234442
- }
234443
- if (mod[0] === DIFF_INSERT) { // Insertion
234444
- text = text.substring(0, start_loc + index2) + mod[1] +
234445
- text.substring(start_loc + index2);
234446
- } else if (mod[0] === DIFF_DELETE) { // Deletion
234447
- text = text.substring(0, start_loc + index2) +
234448
- text.substring(start_loc + this.diff_xIndex(diffs,
234449
- index1 + mod[1].length));
234450
- }
234451
- if (mod[0] !== DIFF_DELETE) {
234452
- index1 += mod[1].length;
234453
- }
234454
- }
234455
- }
234456
- }
234457
- }
234458
- }
234459
- // Strip the padding off.
234460
- text = text.substring(nullPadding.length, text.length - nullPadding.length);
234461
- return [text, results];
234462
- };
234463
-
234464
-
234465
- /**
234466
- * Add some padding on text start and end so that edges can match something.
234467
- * Intended to be called only from within patch_apply.
234468
- * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
234469
- * @return {string} The padding string added to each side.
234470
- */
234471
- diff_match_patch.prototype.patch_addPadding = function(patches) {
234472
- var paddingLength = this.Patch_Margin;
234473
- var nullPadding = '';
234474
- for (var x = 1; x <= paddingLength; x++) {
234475
- nullPadding += String.fromCharCode(x);
234476
- }
234477
-
234478
- // Bump all the patches forward.
234479
- for (var x = 0; x < patches.length; x++) {
234480
- patches[x].start1 += paddingLength;
234481
- patches[x].start2 += paddingLength;
234482
- }
234483
-
234484
- // Add some padding on start of first diff.
234485
- var patch = patches[0];
234486
- var diffs = patch.diffs;
234487
- if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) {
234488
- // Add nullPadding equality.
234489
- diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, nullPadding));
234490
- patch.start1 -= paddingLength; // Should be 0.
234491
- patch.start2 -= paddingLength; // Should be 0.
234492
- patch.length1 += paddingLength;
234493
- patch.length2 += paddingLength;
234494
- } else if (paddingLength > diffs[0][1].length) {
234495
- // Grow first equality.
234496
- var extraLength = paddingLength - diffs[0][1].length;
234497
- diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1];
234498
- patch.start1 -= extraLength;
234499
- patch.start2 -= extraLength;
234500
- patch.length1 += extraLength;
234501
- patch.length2 += extraLength;
234502
- }
234503
-
234504
- // Add some padding on end of last diff.
234505
- patch = patches[patches.length - 1];
234506
- diffs = patch.diffs;
234507
- if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) {
234508
- // Add nullPadding equality.
234509
- diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, nullPadding));
234510
- patch.length1 += paddingLength;
234511
- patch.length2 += paddingLength;
234512
- } else if (paddingLength > diffs[diffs.length - 1][1].length) {
234513
- // Grow last equality.
234514
- var extraLength = paddingLength - diffs[diffs.length - 1][1].length;
234515
- diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength);
234516
- patch.length1 += extraLength;
234517
- patch.length2 += extraLength;
234518
- }
234519
-
234520
- return nullPadding;
234521
- };
234522
-
234523
-
234524
- /**
234525
- * Look through the patches and break up any which are longer than the maximum
234526
- * limit of the match algorithm.
234527
- * Intended to be called only from within patch_apply.
234528
- * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
234529
- */
234530
- diff_match_patch.prototype.patch_splitMax = function(patches) {
234531
- var patch_size = this.Match_MaxBits;
234532
- for (var x = 0; x < patches.length; x++) {
234533
- if (patches[x].length1 <= patch_size) {
234534
- continue;
234535
- }
234536
- var bigpatch = patches[x];
234537
- // Remove the big old patch.
234538
- patches.splice(x--, 1);
234539
- var start1 = bigpatch.start1;
234540
- var start2 = bigpatch.start2;
234541
- var precontext = '';
234542
- while (bigpatch.diffs.length !== 0) {
234543
- // Create one of several smaller patches.
234544
- var patch = new diff_match_patch.patch_obj();
234545
- var empty = true;
234546
- patch.start1 = start1 - precontext.length;
234547
- patch.start2 = start2 - precontext.length;
234548
- if (precontext !== '') {
234549
- patch.length1 = patch.length2 = precontext.length;
234550
- patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, precontext));
234551
- }
234552
- while (bigpatch.diffs.length !== 0 &&
234553
- patch.length1 < patch_size - this.Patch_Margin) {
234554
- var diff_type = bigpatch.diffs[0][0];
234555
- var diff_text = bigpatch.diffs[0][1];
234556
- if (diff_type === DIFF_INSERT) {
234557
- // Insertions are harmless.
234558
- patch.length2 += diff_text.length;
234559
- start2 += diff_text.length;
234560
- patch.diffs.push(bigpatch.diffs.shift());
234561
- empty = false;
234562
- } else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 &&
234563
- patch.diffs[0][0] == DIFF_EQUAL &&
234564
- diff_text.length > 2 * patch_size) {
234565
- // This is a large deletion. Let it pass in one chunk.
234566
- patch.length1 += diff_text.length;
234567
- start1 += diff_text.length;
234568
- empty = false;
234569
- patch.diffs.push(new diff_match_patch.Diff(diff_type, diff_text));
234570
- bigpatch.diffs.shift();
234571
- } else {
234572
- // Deletion or equality. Only take as much as we can stomach.
234573
- diff_text = diff_text.substring(0,
234574
- patch_size - patch.length1 - this.Patch_Margin);
234575
- patch.length1 += diff_text.length;
234576
- start1 += diff_text.length;
234577
- if (diff_type === DIFF_EQUAL) {
234578
- patch.length2 += diff_text.length;
234579
- start2 += diff_text.length;
234580
- } else {
234581
- empty = false;
234582
- }
234583
- patch.diffs.push(new diff_match_patch.Diff(diff_type, diff_text));
234584
- if (diff_text == bigpatch.diffs[0][1]) {
234585
- bigpatch.diffs.shift();
234586
- } else {
234587
- bigpatch.diffs[0][1] =
234588
- bigpatch.diffs[0][1].substring(diff_text.length);
234589
- }
234590
- }
234591
- }
234592
- // Compute the head context for the next patch.
234593
- precontext = this.diff_text2(patch.diffs);
234594
- precontext =
234595
- precontext.substring(precontext.length - this.Patch_Margin);
234596
- // Append the end context for this patch.
234597
- var postcontext = this.diff_text1(bigpatch.diffs)
234598
- .substring(0, this.Patch_Margin);
234599
- if (postcontext !== '') {
234600
- patch.length1 += postcontext.length;
234601
- patch.length2 += postcontext.length;
234602
- if (patch.diffs.length !== 0 &&
234603
- patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) {
234604
- patch.diffs[patch.diffs.length - 1][1] += postcontext;
234605
- } else {
234606
- patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, postcontext));
234607
- }
234608
- }
234609
- if (!empty) {
234610
- patches.splice(++x, 0, patch);
234611
- }
234612
- }
234613
- }
234614
- };
234615
-
234616
-
234617
- /**
234618
- * Take a list of patches and return a textual representation.
234619
- * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
234620
- * @return {string} Text representation of patches.
234621
- */
234622
- diff_match_patch.prototype.patch_toText = function(patches) {
234623
- var text = [];
234624
- for (var x = 0; x < patches.length; x++) {
234625
- text[x] = patches[x];
234626
- }
234627
- return text.join('');
234628
- };
234629
-
234630
-
234631
- /**
234632
- * Parse a textual representation of patches and return a list of Patch objects.
234633
- * @param {string} textline Text representation of patches.
234634
- * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
234635
- * @throws {!Error} If invalid input.
234636
- */
234637
- diff_match_patch.prototype.patch_fromText = function(textline) {
234638
- var patches = [];
234639
- if (!textline) {
234640
- return patches;
234641
- }
234642
- var text = textline.split('\n');
234643
- var textPointer = 0;
234644
- var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;
234645
- while (textPointer < text.length) {
234646
- var m = text[textPointer].match(patchHeader);
234647
- if (!m) {
234648
- throw new Error('Invalid patch string: ' + text[textPointer]);
234649
- }
234650
- var patch = new diff_match_patch.patch_obj();
234651
- patches.push(patch);
234652
- patch.start1 = parseInt(m[1], 10);
234653
- if (m[2] === '') {
234654
- patch.start1--;
234655
- patch.length1 = 1;
234656
- } else if (m[2] == '0') {
234657
- patch.length1 = 0;
234658
- } else {
234659
- patch.start1--;
234660
- patch.length1 = parseInt(m[2], 10);
234661
- }
234662
-
234663
- patch.start2 = parseInt(m[3], 10);
234664
- if (m[4] === '') {
234665
- patch.start2--;
234666
- patch.length2 = 1;
234667
- } else if (m[4] == '0') {
234668
- patch.length2 = 0;
234669
- } else {
234670
- patch.start2--;
234671
- patch.length2 = parseInt(m[4], 10);
234672
- }
234673
- textPointer++;
234674
-
234675
- while (textPointer < text.length) {
234676
- var sign = text[textPointer].charAt(0);
234677
- try {
234678
- var line = decodeURI(text[textPointer].substring(1));
234679
- } catch (ex) {
234680
- // Malformed URI sequence.
234681
- throw new Error('Illegal escape in patch_fromText: ' + line);
234682
- }
234683
- if (sign == '-') {
234684
- // Deletion.
234685
- patch.diffs.push(new diff_match_patch.Diff(DIFF_DELETE, line));
234686
- } else if (sign == '+') {
234687
- // Insertion.
234688
- patch.diffs.push(new diff_match_patch.Diff(DIFF_INSERT, line));
234689
- } else if (sign == ' ') {
234690
- // Minor equality.
234691
- patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, line));
234692
- } else if (sign == '@') {
234693
- // Start of next patch.
234694
- break;
234695
- } else if (sign === '') ; else {
234696
- // WTF?
234697
- throw new Error('Invalid patch mode "' + sign + '" in: ' + line);
234698
- }
234699
- textPointer++;
234700
- }
234701
- }
234702
- return patches;
234703
- };
234704
-
234705
-
234706
- /**
234707
- * Class representing one patch operation.
234708
- * @constructor
234709
- */
234710
- diff_match_patch.patch_obj = function() {
234711
- /** @type {!Array.<!diff_match_patch.Diff>} */
234712
- this.diffs = [];
234713
- /** @type {?number} */
234714
- this.start1 = null;
234715
- /** @type {?number} */
234716
- this.start2 = null;
234717
- /** @type {number} */
234718
- this.length1 = 0;
234719
- /** @type {number} */
234720
- this.length2 = 0;
234721
- };
234722
-
234723
-
234724
- /**
234725
- * Emulate GNU diff's format.
234726
- * Header: @@ -382,8 +481,9 @@
234727
- * Indices are printed as 1-based, not 0-based.
234728
- * @return {string} The GNU diff string.
234729
- */
234730
- diff_match_patch.patch_obj.prototype.toString = function() {
234731
- var coords1, coords2;
234732
- if (this.length1 === 0) {
234733
- coords1 = this.start1 + ',0';
234734
- } else if (this.length1 == 1) {
234735
- coords1 = this.start1 + 1;
234736
- } else {
234737
- coords1 = (this.start1 + 1) + ',' + this.length1;
234738
- }
234739
- if (this.length2 === 0) {
234740
- coords2 = this.start2 + ',0';
234741
- } else if (this.length2 == 1) {
234742
- coords2 = this.start2 + 1;
234743
- } else {
234744
- coords2 = (this.start2 + 1) + ',' + this.length2;
234745
- }
234746
- var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\n'];
234747
- var op;
234748
- // Escape the body of the patch with %xx notation.
234749
- for (var x = 0; x < this.diffs.length; x++) {
234750
- switch (this.diffs[x][0]) {
234751
- case DIFF_INSERT:
234752
- op = '+';
234753
- break;
234754
- case DIFF_DELETE:
234755
- op = '-';
234756
- break;
234757
- case DIFF_EQUAL:
234758
- op = ' ';
234759
- break;
234760
- }
234761
- text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\n';
234762
- }
234763
- return text.join('').replace(/%20/g, ' ');
234764
- };
234765
-
234766
-
234767
- // The following export code was added by @ForbesLindesay
234768
- module.exports = diff_match_patch;
234769
- module.exports['diff_match_patch'] = diff_match_patch;
234770
- module.exports['DIFF_DELETE'] = DIFF_DELETE;
234771
- module.exports['DIFF_INSERT'] = DIFF_INSERT;
234772
- module.exports['DIFF_EQUAL'] = DIFF_EQUAL;
234773
- } (diffMatchPatch));
234774
- return diffMatchPatch.exports;
234775
- }
234776
-
234777
- var diffMatchPatchExports = requireDiffMatchPatch();
232573
+ // --- Diff 데코레이션을 위한 StateEffect 정의 ---
232574
+ const setAsisDecorationsEffect = StateEffect.define();
232575
+ const setTobeDecorationsEffect = StateEffect.define();
234778
232576
 
234779
- // Diff 데코레이션을 위한 StateField 정의 (변동 없음)
232577
+ // --- Diff 데코레이션을 위한 StateField 정의 ---
234780
232578
  const asisDiffDecorations = StateField.define({
234781
- create() { return Decoration.none; },
232579
+ create() {
232580
+ return Decoration.none;
232581
+ },
234782
232582
  update(decorations, tr) {
234783
- return tr.effects.reduce((currentDecos, effect) => {
232583
+ decorations = decorations.map(tr.changes);
232584
+ for (let effect of tr.effects) {
234784
232585
  if (effect.is(setAsisDecorationsEffect)) {
234785
232586
  return effect.value;
234786
232587
  }
234787
- return currentDecos;
234788
- }, decorations);
232588
+ }
232589
+ return decorations;
234789
232590
  },
234790
232591
  provide: f => EditorView.decorations.from(f)
234791
232592
  });
234792
232593
 
234793
232594
  const tobeDiffDecorations = StateField.define({
234794
- create() { return Decoration.none; },
232595
+ create() {
232596
+ return Decoration.none;
232597
+ },
234795
232598
  update(decorations, tr) {
234796
- return tr.effects.reduce((currentDecos, effect) => {
232599
+ decorations = decorations.map(tr.changes);
232600
+ for (let effect of tr.effects) {
234797
232601
  if (effect.is(setTobeDecorationsEffect)) {
234798
232602
  return effect.value;
234799
232603
  }
234800
- return currentDecos;
234801
- }, decorations);
232604
+ }
232605
+ return decorations;
234802
232606
  },
234803
232607
  provide: f => EditorView.decorations.from(f)
234804
232608
  });
234805
232609
 
234806
- const setAsisDecorationsEffect = StateEffect.define();
234807
- const setTobeDecorationsEffect = StateEffect.define();
234808
232610
 
234809
232611
  class IdeDiff extends HTMLElement {
234810
232612
 
@@ -234828,9 +232630,13 @@ class IdeDiff extends HTMLElement {
234828
232630
  connectedCallback() {
234829
232631
  this.shadowRoot.innerHTML = `
234830
232632
  <style>
234831
- /* ninegrid CSS 및 필요한 기본 스타일 (변동 없음) */
232633
+ /* ninegrid CSS 및 필요한 기본 스타일 */
234832
232634
  @import "https://cdn.jsdelivr.net/npm/ninegrid@${ninegrid.version}/dist/css/ideDiff.css";
234833
232635
  ${ninegrid.getCustomPath(this, "ideDiff.css")}
232636
+
232637
+ /* Diff 데코레이션 CSS 직접 추가 (없으면 ideDiff.css에 추가) */
232638
+ .cm-inserted-line-bg { background-color: #e6ffed; border-left: 3px solid #66bb6a; }
232639
+ .cm-deleted-line-bg { background-color: #ffebe9; border-left: 3px solid #ef5350; }
234834
232640
  </style>
234835
232641
 
234836
232642
  <div class="wrapper">
@@ -234845,6 +232651,21 @@ class IdeDiff extends HTMLElement {
234845
232651
  });
234846
232652
  }
234847
232653
 
232654
+ disconnectedCallback() {
232655
+ if (this._asisScrollHandler) {
232656
+ this.#asisEditorView.scrollDOM.removeEventListener('scroll', this._asisScrollHandler);
232657
+ this.#tobeEditorView.scrollDOM.removeEventListener('scroll', this._tobeScrollHandler);
232658
+ this._asisScrollHandler = null;
232659
+ this._tobeScrollHandler = null;
232660
+ }
232661
+ if (this.#asisEditorView) {
232662
+ this.#asisEditorView.destroy();
232663
+ }
232664
+ if (this.#tobeEditorView) {
232665
+ this.#tobeEditorView.destroy();
232666
+ }
232667
+ }
232668
+
234848
232669
  #initCodeMirror = () => {
234849
232670
  this.#asisEditorEl = this.shadowRoot.querySelector('.panel.asis');
234850
232671
  this.#tobeEditorEl = this.shadowRoot.querySelector('.panel.tobe');
@@ -234861,9 +232682,10 @@ class IdeDiff extends HTMLElement {
234861
232682
  drawSelection(),
234862
232683
  dropCursor(),
234863
232684
  EditorState.allowMultipleSelections.of(true),
234864
- indentOnInput(),
232685
+ indentOnInput(), // 함수 호출
234865
232686
  bracketMatching(),
234866
232687
  highlightActiveLine(),
232688
+ highlightActiveLineGutter(),
234867
232689
  highlightSelectionMatches(),
234868
232690
  keymap.of([
234869
232691
  ...defaultKeymap,
@@ -234871,11 +232693,11 @@ class IdeDiff extends HTMLElement {
234871
232693
  ...historyKeymap,
234872
232694
  ...lintKeymap,
234873
232695
  ...completionKeymap,
234874
- indentWithTab,
234875
- selectAll
232696
+ indentWithTab(), // 함수 호출
232697
+ selectAll() // 함수 호출
234876
232698
  ]),
234877
- syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
234878
- autocompletion(),
232699
+ syntaxHighlighting(defaultHighlightStyle), // { fallback: true } 제거
232700
+ autocompletion(), // 함수 호출
234879
232701
  ];
234880
232702
 
234881
232703
  // ASIS 에디터 뷰 초기화
@@ -234884,11 +232706,9 @@ class IdeDiff extends HTMLElement {
234884
232706
  doc: '',
234885
232707
  extensions: [
234886
232708
  basicExtensions,
234887
- javascript(),
232709
+ this.#languageCompartment.of(javascript()), // 초기 언어 설정
234888
232710
  EditorState.readOnly.of(true),
234889
- this.#languageCompartment.of(javascript()),
234890
- asisDiffDecorations,
234891
- // ⭐️ updateListener는 유지: 뷰가 DOM에 완전히 렌더링될 때까지 기다림
232711
+ asisDiffDecorations, // ASIS Diff 데코레이션 필드
234892
232712
  EditorView.updateListener.of((update) => {
234893
232713
  if (update.view.contentDOM.firstChild && !update.view._initialAsisContentLoaded) {
234894
232714
  update.view._initialAsisContentLoaded = true;
@@ -234906,11 +232726,9 @@ class IdeDiff extends HTMLElement {
234906
232726
  doc: '',
234907
232727
  extensions: [
234908
232728
  basicExtensions,
234909
- javascript(),
232729
+ this.#languageCompartment.of(javascript()), // 초기 언어 설정
234910
232730
  EditorState.readOnly.of(true),
234911
- this.#languageCompartment.of(javascript()),
234912
- tobeDiffDecorations,
234913
- // ⭐️ updateListener는 유지: 뷰가 DOM에 완전히 렌더링될 때까지 기다림
232731
+ tobeDiffDecorations, // TOBE Diff 데코레이션 필드
234914
232732
  EditorView.updateListener.of((update) => {
234915
232733
  if (update.view.contentDOM.firstChild && !update.view._initialTobeContentLoaded) {
234916
232734
  update.view._initialTobeContentLoaded = true;
@@ -234960,100 +232778,57 @@ class IdeDiff extends HTMLElement {
234960
232778
  this.#tobeEditorView.scrollDOM.addEventListener('scroll', this._tobeScrollHandler);
234961
232779
  };
234962
232780
 
234963
- // IdeDiff 클래스 내부
234964
232781
  #applyDiffDecorations = (asisSrc, tobeSrc) => {
234965
- const dmp = new diffMatchPatchExports.diff_match_patch();
232782
+ const dmp = new diffMatch_patch.diff_match_patch();
234966
232783
  const diffs = dmp.diff_main(asisSrc, tobeSrc);
234967
232784
  dmp.diff_cleanupSemantic(diffs);
234968
232785
 
234969
- const asisLineDecos = [];
234970
- const tobeLineDecos = [];
232786
+ const asisLineBuilder = new RangeSetBuilder();
232787
+ const tobeLineBuilder = new RangeSetBuilder();
234971
232788
 
234972
232789
  let asisCursor = 0;
234973
232790
  let tobeCursor = 0;
234974
232791
 
234975
- // 중요: 새로운 문서 내용을 기반으로 임시 Doc 객체를 생성합니다.
234976
- // Doc 객체를 사용하여 lineAt()을 호출합니다.
234977
- const asisDoc = Text.of(asisSrc.split('\n'));
234978
- const tobeDoc = Text.of(tobeSrc.split('\n'));
232792
+ const insertedLineDeco = Decoration.line({ class: "cm-inserted-line-bg" });
232793
+ const deletedLineDeco = Decoration.line({ class: "cm-deleted-line-bg" });
234979
232794
 
234980
232795
  for (const [op, text] of diffs) {
234981
232796
  const len = text.length;
232797
+ const linesInChunk = text.split('\n');
234982
232798
 
234983
232799
  switch (op) {
234984
- case diffMatchPatchExports.diff_match_patch.DIFF_INSERT: // Added text
234985
- let currentTobeLineOffset = tobeCursor;
234986
- const tobeLines = text.split('\n');
234987
- for (let i = 0; i < tobeLines.length; i++) {
234988
- // 줄의 시작 오프셋이 tobeDoc의 길이를 넘지 않는지 확인
234989
- if (currentTobeLineOffset < tobeDoc.length) {
234990
- const line = tobeDoc.lineAt(currentTobeLineOffset);
234991
- tobeLineDecos.push({
234992
- from: line.from,
234993
- to: line.to,
234994
- deco: Decoration.line({ class: "cm-inserted-line-bg" })
234995
- });
234996
- }
234997
- // 다음 줄의 시작 오프셋 계산 (개행 문자 고려)
234998
- currentTobeLineOffset += tobeLines[i].length + (i < tobeLines.length - 1 ? 1 : 0);
234999
- // 마지막 줄이 비어 있고 개행으로 끝나지 않으면 루프 종료 (lineAt 오류 방지)
235000
- if (i === tobeLines.length - 1 && tobeLines[i].length === 0 && text.endsWith('\n') === false) {
232800
+ case diffMatch_patch.diff_match_patch.DIFF_INSERT:
232801
+ for (let i = 0; i < linesInChunk.length; i++) {
232802
+ if (i === linesInChunk.length - 1 && linesInChunk[i] === '' && !text.endsWith('\n')) {
232803
+ tobeCursor += len;
235001
232804
  break;
235002
232805
  }
232806
+ tobeLineBuilder.add(tobeCursor, tobeCursor, insertedLineDeco);
232807
+ tobeCursor += linesInChunk[i].length + (i < linesInChunk.length - 1 ? 1 : 0);
235003
232808
  }
235004
- tobeCursor += len;
235005
232809
  break;
235006
232810
 
235007
- case diffMatchPatchExports.diff_match_patch.DIFF_DELETE: // Deleted text
235008
- let currentAsisLineOffset = asisCursor;
235009
- const asisLines = text.split('\n');
235010
- for (let i = 0; i < asisLines.length; i++) {
235011
- // 줄의 시작 오프셋이 asisDoc의 길이를 넘지 않는지 확인
235012
- if (currentAsisLineOffset < asisDoc.length) {
235013
- const line = asisDoc.lineAt(currentAsisLineOffset);
235014
- asisLineDecos.push({
235015
- from: line.from,
235016
- to: line.to,
235017
- deco: Decoration.line({ class: "cm-deleted-line-bg" })
235018
- });
235019
- }
235020
- // 다음 줄의 시작 오프셋 계산 (개행 문자 고려)
235021
- currentAsisLineOffset += asisLines[i].length + (i < asisLines.length - 1 ? 1 : 0);
235022
- // 마지막 줄이 비어 있고 개행으로 끝나지 않으면 루프 종료 (lineAt 오류 방지)
235023
- if (i === asisLines.length - 1 && asisLines[i].length === 0 && text.endsWith('\n') === false) {
232811
+ case diffMatch_patch.diff_match_patch.DIFF_DELETE:
232812
+ for (let i = 0; i < linesInChunk.length; i++) {
232813
+ if (i === linesInChunk.length - 1 && linesInChunk[i] === '' && !text.endsWith('\n')) {
232814
+ asisCursor += len;
235024
232815
  break;
235025
232816
  }
232817
+ asisLineBuilder.add(asisCursor, asisCursor, deletedLineDeco);
232818
+ asisCursor += linesInChunk[i].length + (i < linesInChunk.length - 1 ? 1 : 0);
235026
232819
  }
235027
- asisCursor += len;
235028
232820
  break;
235029
232821
 
235030
- case diffMatchPatchExports.diff_match_patch.DIFF_EQUAL: // Unchanged text
232822
+ case diffMatch_patch.diff_match_patch.DIFF_EQUAL:
235031
232823
  asisCursor += len;
235032
232824
  tobeCursor += len;
235033
232825
  break;
235034
232826
  }
235035
232827
  }
235036
232828
 
235037
- // 데코레이션 중복 및 겹침 방지를 위해 정렬
235038
- asisLineDecos.sort((a, b) => a.from - b.from);
235039
- tobeLineDecos.sort((a, b) => a.from - b.from);
235040
-
235041
- // 라인 데코레이션 빌더 생성
235042
- const asisLineBuilder = new RangeSetBuilder();
235043
- for (const { from, to, deco } of asisLineDecos) {
235044
- asisLineBuilder.add(from, to, deco);
235045
- }
235046
- const finalAsisDecorations = asisLineBuilder.finish(); // ⭐️ .update({ add: ... }) 부분 제거
235047
-
235048
- const tobeLineBuilder = new RangeSetBuilder();
235049
- for (const { from, to, deco } of tobeLineDecos) {
235050
- tobeLineBuilder.add(from, to, deco);
235051
- }
235052
- const finalTobeDecorations = tobeLineBuilder.finish(); // ⭐️ .update({ add: ... }) 부분 제거
235053
-
235054
232829
  return {
235055
- asisEffect: setAsisDecorationsEffect.of(finalAsisDecorations),
235056
- tobeEffect: setTobeDecorationsEffect.of(finalTobeDecorations)
232830
+ asisDecorations: asisLineBuilder.finish(),
232831
+ tobeDecorations: tobeLineBuilder.finish()
235057
232832
  };
235058
232833
  };
235059
232834
 
@@ -235063,7 +232838,7 @@ class IdeDiff extends HTMLElement {
235063
232838
  return;
235064
232839
  }
235065
232840
 
235066
- this.#isScrollSyncActive = false; // 스크롤 동기화 일시 중지
232841
+ this.#isScrollSyncActive = false;
235067
232842
 
235068
232843
  let langExtension;
235069
232844
  switch(language) {
@@ -235074,12 +232849,6 @@ class IdeDiff extends HTMLElement {
235074
232849
  langExtension = javascript();
235075
232850
  }
235076
232851
 
235077
- // 데코레이션 효과는 미리 계산해 둡니다.
235078
- const { asisEffect, tobeEffect } = this.#applyDiffDecorations(src1, src2);
235079
-
235080
- // 1단계: 텍스트 내용 변경과 언어 확장을 먼저 디스패치합니다.
235081
- // 'to' 값을 현재 문서 길이 전체로 지정하여 정확한 교체를 보장합니다.
235082
-
235083
232852
  this.#asisEditorView.dispatch({
235084
232853
  changes: { from: 0, to: this.#asisEditorView.state.doc.length, insert: src1 },
235085
232854
  effects: [
@@ -235094,53 +232863,23 @@ class IdeDiff extends HTMLElement {
235094
232863
  ]
235095
232864
  });
235096
232865
 
235097
- console.log(asisEffect, tobeEffect);
235098
-
235099
- // ⭐️ 2단계: 텍스트 및 언어 변경이 완전히 적용되고 뷰가 안정화될 시간을 줍니다.
235100
- // 다음 프레임에서 데코레이션 효과만 별도로 디스패치합니다.
235101
232866
  requestAnimationFrame(() => {
232867
+ const { asisDecorations, tobeDecorations } = this.#applyDiffDecorations(src1, src2);
232868
+
235102
232869
  this.#asisEditorView.dispatch({
235103
- effects: [
235104
- StateEffect.reconfigure.of(
235105
- EditorView.decorations.of(
235106
- Decoration.set(
235107
- Decoration.line({ attributes: { style: "font-weight: bold" } }).range(0)
235108
- )
235109
- )
235110
- )
235111
- ]
232870
+ effects: [setAsisDecorationsEffect.of(asisDecorations)]
235112
232871
  });
235113
232872
  this.#tobeEditorView.dispatch({
235114
- //effects: [tobeEffect]
232873
+ effects: [setTobeDecorationsEffect.of(tobeDecorations)]
235115
232874
  });
235116
232875
 
235117
- // ⭐️ 3단계: 데코레이션까지 적용된 후 뷰가 다시 안정화될 시간을 한 번 더 줍니다.
235118
- // 그 다음 프레임에서 스크롤 동기화를 활성화합니다.
235119
232876
  requestAnimationFrame(() => {
235120
232877
  this.#isScrollSyncActive = true;
235121
- // 필요하다면 여기서 초기 스크롤 위치를 0으로 리셋하여 정렬을 보장할 수 있습니다.
235122
- // this.#asisEditorView.scrollDOM.scrollTop = 0;
235123
- // this.#tobeEditorView.scrollDOM.scrollTop = 0;
235124
232878
  });
235125
232879
  });
235126
232880
  };
235127
-
235128
- disconnectedCallback() {
235129
- // 컴포넌트 해제 시 스크롤 리스너 제거
235130
- if (this._asisScrollHandler) {
235131
- this.#asisEditorView.scrollDOM.removeEventListener('scroll', this._asisScrollHandler);
235132
- this.#tobeEditorView.scrollDOM.removeEventListener('scroll', this._tobeScrollHandler);
235133
- this._asisScrollHandler = null;
235134
- this._tobeScrollHandler = null;
235135
- }
235136
- if (this.#asisEditorView) {
235137
- this.#asisEditorView.destroy();
235138
- }
235139
- if (this.#tobeEditorView) {
235140
- this.#tobeEditorView.destroy();
235141
- }
235142
- }
235143
232881
  }
232882
+
235144
232883
  customElements.define("ide-diff", IdeDiff);
235145
232884
 
235146
232885
  //import "./components/ideAssi.js";