GPQAPP

Форк
0
1009 строк · 37.2 Кб
1
// CodeMirror, copyright (c) by Marijn Haverbeke and others
2
// Distributed under an MIT license: https://codemirror.net/LICENSE
3

4
// declare global: diff_match_patch, DIFF_INSERT, DIFF_DELETE, DIFF_EQUAL
5

6
(function(mod) {
7
  if (typeof exports == "object" && typeof module == "object") // CommonJS
8
    mod(require("../../lib/codemirror")); // Note non-packaged dependency diff_match_patch
9
  else if (typeof define == "function" && define.amd) // AMD
10
    define(["../../lib/codemirror", "diff_match_patch"], mod);
11
  else // Plain browser env
12
    mod(CodeMirror);
13
})(function(CodeMirror) {
14
  "use strict";
15
  var Pos = CodeMirror.Pos;
16
  var svgNS = "http://www.w3.org/2000/svg";
17

18
  function DiffView(mv, type) {
19
    this.mv = mv;
20
    this.type = type;
21
    this.classes = type == "left"
22
      ? {chunk: "CodeMirror-merge-l-chunk",
23
         start: "CodeMirror-merge-l-chunk-start",
24
         end: "CodeMirror-merge-l-chunk-end",
25
         insert: "CodeMirror-merge-l-inserted",
26
         del: "CodeMirror-merge-l-deleted",
27
         connect: "CodeMirror-merge-l-connect"}
28
      : {chunk: "CodeMirror-merge-r-chunk",
29
         start: "CodeMirror-merge-r-chunk-start",
30
         end: "CodeMirror-merge-r-chunk-end",
31
         insert: "CodeMirror-merge-r-inserted",
32
         del: "CodeMirror-merge-r-deleted",
33
         connect: "CodeMirror-merge-r-connect"};
34
  }
35

36
  DiffView.prototype = {
37
    constructor: DiffView,
38
    init: function(pane, orig, options) {
39
      this.edit = this.mv.edit;
40
      ;(this.edit.state.diffViews || (this.edit.state.diffViews = [])).push(this);
41
      this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: !this.mv.options.allowEditingOriginals}, copyObj(options)));
42
      if (this.mv.options.connect == "align") {
43
        if (!this.edit.state.trackAlignable) this.edit.state.trackAlignable = new TrackAlignable(this.edit)
44
        this.orig.state.trackAlignable = new TrackAlignable(this.orig)
45
      }
46
      this.lockButton.title = this.edit.phrase("Toggle locked scrolling");
47

48
      this.orig.state.diffViews = [this];
49
      var classLocation = options.chunkClassLocation || "background";
50
      if (Object.prototype.toString.call(classLocation) != "[object Array]") classLocation = [classLocation]
51
      this.classes.classLocation = classLocation
52

53
      this.diff = getDiff(asString(orig), asString(options.value), this.mv.options.ignoreWhitespace);
54
      this.chunks = getChunks(this.diff);
55
      this.diffOutOfDate = this.dealigned = false;
56
      this.needsScrollSync = null
57

58
      this.showDifferences = options.showDifferences !== false;
59
    },
60
    registerEvents: function(otherDv) {
61
      this.forceUpdate = registerUpdate(this);
62
      setScrollLock(this, true, false);
63
      registerScroll(this, otherDv);
64
    },
65
    setShowDifferences: function(val) {
66
      val = val !== false;
67
      if (val != this.showDifferences) {
68
        this.showDifferences = val;
69
        this.forceUpdate("full");
70
      }
71
    }
72
  };
73

74
  function ensureDiff(dv) {
75
    if (dv.diffOutOfDate) {
76
      dv.diff = getDiff(dv.orig.getValue(), dv.edit.getValue(), dv.mv.options.ignoreWhitespace);
77
      dv.chunks = getChunks(dv.diff);
78
      dv.diffOutOfDate = false;
79
      CodeMirror.signal(dv.edit, "updateDiff", dv.diff);
80
    }
81
  }
82

83
  var updating = false;
84
  function registerUpdate(dv) {
85
    var edit = {from: 0, to: 0, marked: []};
86
    var orig = {from: 0, to: 0, marked: []};
87
    var debounceChange, updatingFast = false;
88
    function update(mode) {
89
      updating = true;
90
      updatingFast = false;
91
      if (mode == "full") {
92
        if (dv.svg) clear(dv.svg);
93
        if (dv.copyButtons) clear(dv.copyButtons);
94
        clearMarks(dv.edit, edit.marked, dv.classes);
95
        clearMarks(dv.orig, orig.marked, dv.classes);
96
        edit.from = edit.to = orig.from = orig.to = 0;
97
      }
98
      ensureDiff(dv);
99
      if (dv.showDifferences) {
100
        updateMarks(dv.edit, dv.diff, edit, DIFF_INSERT, dv.classes);
101
        updateMarks(dv.orig, dv.diff, orig, DIFF_DELETE, dv.classes);
102
      }
103

104
      if (dv.mv.options.connect == "align")
105
        alignChunks(dv);
106
      makeConnections(dv);
107
      if (dv.needsScrollSync != null) syncScroll(dv, dv.needsScrollSync)
108

109
      updating = false;
110
    }
111
    function setDealign(fast) {
112
      if (updating) return;
113
      dv.dealigned = true;
114
      set(fast);
115
    }
116
    function set(fast) {
117
      if (updating || updatingFast) return;
118
      clearTimeout(debounceChange);
119
      if (fast === true) updatingFast = true;
120
      debounceChange = setTimeout(update, fast === true ? 20 : 250);
121
    }
122
    function change(_cm, change) {
123
      if (!dv.diffOutOfDate) {
124
        dv.diffOutOfDate = true;
125
        edit.from = edit.to = orig.from = orig.to = 0;
126
      }
127
      // Update faster when a line was added/removed
128
      setDealign(change.text.length - 1 != change.to.line - change.from.line);
129
    }
130
    function swapDoc() {
131
      dv.diffOutOfDate = true;
132
      dv.dealigned = true;
133
      update("full");
134
    }
135
    dv.edit.on("change", change);
136
    dv.orig.on("change", change);
137
    dv.edit.on("swapDoc", swapDoc);
138
    dv.orig.on("swapDoc", swapDoc);
139
    if (dv.mv.options.connect == "align") {
140
      CodeMirror.on(dv.edit.state.trackAlignable, "realign", setDealign)
141
      CodeMirror.on(dv.orig.state.trackAlignable, "realign", setDealign)
142
    }
143
    dv.edit.on("viewportChange", function() { set(false); });
144
    dv.orig.on("viewportChange", function() { set(false); });
145
    update();
146
    return update;
147
  }
148

149
  function registerScroll(dv, otherDv) {
150
    dv.edit.on("scroll", function() {
151
      syncScroll(dv, true) && makeConnections(dv);
152
    });
153
    dv.orig.on("scroll", function() {
154
      syncScroll(dv, false) && makeConnections(dv);
155
      if (otherDv) syncScroll(otherDv, true) && makeConnections(otherDv);
156
    });
157
  }
158

159
  function syncScroll(dv, toOrig) {
160
    // Change handler will do a refresh after a timeout when diff is out of date
161
    if (dv.diffOutOfDate) {
162
      if (dv.lockScroll && dv.needsScrollSync == null) dv.needsScrollSync = toOrig
163
      return false
164
    }
165
    dv.needsScrollSync = null
166
    if (!dv.lockScroll) return true;
167
    var editor, other, now = +new Date;
168
    if (toOrig) { editor = dv.edit; other = dv.orig; }
169
    else { editor = dv.orig; other = dv.edit; }
170
    // Don't take action if the position of this editor was recently set
171
    // (to prevent feedback loops)
172
    if (editor.state.scrollSetBy == dv && (editor.state.scrollSetAt || 0) + 250 > now) return false;
173

174
    var sInfo = editor.getScrollInfo();
175
    if (dv.mv.options.connect == "align") {
176
      targetPos = sInfo.top;
177
    } else {
178
      var halfScreen = .5 * sInfo.clientHeight, midY = sInfo.top + halfScreen;
179
      var mid = editor.lineAtHeight(midY, "local");
180
      var around = chunkBoundariesAround(dv.chunks, mid, toOrig);
181
      var off = getOffsets(editor, toOrig ? around.edit : around.orig);
182
      var offOther = getOffsets(other, toOrig ? around.orig : around.edit);
183
      var ratio = (midY - off.top) / (off.bot - off.top);
184
      var targetPos = (offOther.top - halfScreen) + ratio * (offOther.bot - offOther.top);
185

186
      var botDist, mix;
187
      // Some careful tweaking to make sure no space is left out of view
188
      // when scrolling to top or bottom.
189
      if (targetPos > sInfo.top && (mix = sInfo.top / halfScreen) < 1) {
190
        targetPos = targetPos * mix + sInfo.top * (1 - mix);
191
      } else if ((botDist = sInfo.height - sInfo.clientHeight - sInfo.top) < halfScreen) {
192
        var otherInfo = other.getScrollInfo();
193
        var botDistOther = otherInfo.height - otherInfo.clientHeight - targetPos;
194
        if (botDistOther > botDist && (mix = botDist / halfScreen) < 1)
195
          targetPos = targetPos * mix + (otherInfo.height - otherInfo.clientHeight - botDist) * (1 - mix);
196
      }
197
    }
198

199
    other.scrollTo(sInfo.left, targetPos);
200
    other.state.scrollSetAt = now;
201
    other.state.scrollSetBy = dv;
202
    return true;
203
  }
204

205
  function getOffsets(editor, around) {
206
    var bot = around.after;
207
    if (bot == null) bot = editor.lastLine() + 1;
208
    return {top: editor.heightAtLine(around.before || 0, "local"),
209
            bot: editor.heightAtLine(bot, "local")};
210
  }
211

212
  function setScrollLock(dv, val, action) {
213
    dv.lockScroll = val;
214
    if (val && action != false) syncScroll(dv, DIFF_INSERT) && makeConnections(dv);
215
    (val ? CodeMirror.addClass : CodeMirror.rmClass)(dv.lockButton, "CodeMirror-merge-scrolllock-enabled");
216
  }
217

218
  // Updating the marks for editor content
219

220
  function removeClass(editor, line, classes) {
221
    var locs = classes.classLocation
222
    for (var i = 0; i < locs.length; i++) {
223
      editor.removeLineClass(line, locs[i], classes.chunk);
224
      editor.removeLineClass(line, locs[i], classes.start);
225
      editor.removeLineClass(line, locs[i], classes.end);
226
    }
227
  }
228

229
  function clearMarks(editor, arr, classes) {
230
    for (var i = 0; i < arr.length; ++i) {
231
      var mark = arr[i];
232
      if (mark instanceof CodeMirror.TextMarker)
233
        mark.clear();
234
      else if (mark.parent)
235
        removeClass(editor, mark, classes);
236
    }
237
    arr.length = 0;
238
  }
239

240
  // FIXME maybe add a margin around viewport to prevent too many updates
241
  function updateMarks(editor, diff, state, type, classes) {
242
    var vp = editor.getViewport();
243
    editor.operation(function() {
244
      if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
245
        clearMarks(editor, state.marked, classes);
246
        markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes);
247
        state.from = vp.from; state.to = vp.to;
248
      } else {
249
        if (vp.from < state.from) {
250
          markChanges(editor, diff, type, state.marked, vp.from, state.from, classes);
251
          state.from = vp.from;
252
        }
253
        if (vp.to > state.to) {
254
          markChanges(editor, diff, type, state.marked, state.to, vp.to, classes);
255
          state.to = vp.to;
256
        }
257
      }
258
    });
259
  }
260

261
  function addClass(editor, lineNr, classes, main, start, end) {
262
    var locs = classes.classLocation, line = editor.getLineHandle(lineNr);
263
    for (var i = 0; i < locs.length; i++) {
264
      if (main) editor.addLineClass(line, locs[i], classes.chunk);
265
      if (start) editor.addLineClass(line, locs[i], classes.start);
266
      if (end) editor.addLineClass(line, locs[i], classes.end);
267
    }
268
    return line;
269
  }
270

271
  function markChanges(editor, diff, type, marks, from, to, classes) {
272
    var pos = Pos(0, 0);
273
    var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1));
274
    var cls = type == DIFF_DELETE ? classes.del : classes.insert;
275
    function markChunk(start, end) {
276
      var bfrom = Math.max(from, start), bto = Math.min(to, end);
277
      for (var i = bfrom; i < bto; ++i)
278
        marks.push(addClass(editor, i, classes, true, i == start, i == end - 1));
279
      // When the chunk is empty, make sure a horizontal line shows up
280
      if (start == end && bfrom == end && bto == end) {
281
        if (bfrom)
282
          marks.push(addClass(editor, bfrom - 1, classes, false, false, true));
283
        else
284
          marks.push(addClass(editor, bfrom, classes, false, true, false));
285
      }
286
    }
287

288
    var chunkStart = 0, pending = false;
289
    for (var i = 0; i < diff.length; ++i) {
290
      var part = diff[i], tp = part[0], str = part[1];
291
      if (tp == DIFF_EQUAL) {
292
        var cleanFrom = pos.line + (startOfLineClean(diff, i) ? 0 : 1);
293
        moveOver(pos, str);
294
        var cleanTo = pos.line + (endOfLineClean(diff, i) ? 1 : 0);
295
        if (cleanTo > cleanFrom) {
296
          if (pending) { markChunk(chunkStart, cleanFrom); pending = false }
297
          chunkStart = cleanTo;
298
        }
299
      } else {
300
        pending = true
301
        if (tp == type) {
302
          var end = moveOver(pos, str, true);
303
          var a = posMax(top, pos), b = posMin(bot, end);
304
          if (!posEq(a, b))
305
            marks.push(editor.markText(a, b, {className: cls}));
306
          pos = end;
307
        }
308
      }
309
    }
310
    if (pending) markChunk(chunkStart, pos.line + 1);
311
  }
312

313
  // Updating the gap between editor and original
314

315
  function makeConnections(dv) {
316
    if (!dv.showDifferences) return;
317

318
    if (dv.svg) {
319
      clear(dv.svg);
320
      var w = dv.gap.offsetWidth;
321
      attrs(dv.svg, "width", w, "height", dv.gap.offsetHeight);
322
    }
323
    if (dv.copyButtons) clear(dv.copyButtons);
324

325
    var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport();
326
    var outerTop = dv.mv.wrap.getBoundingClientRect().top
327
    var sTopEdit = outerTop - dv.edit.getScrollerElement().getBoundingClientRect().top + dv.edit.getScrollInfo().top
328
    var sTopOrig = outerTop - dv.orig.getScrollerElement().getBoundingClientRect().top + dv.orig.getScrollInfo().top;
329
    for (var i = 0; i < dv.chunks.length; i++) {
330
      var ch = dv.chunks[i];
331
      if (ch.editFrom <= vpEdit.to && ch.editTo >= vpEdit.from &&
332
          ch.origFrom <= vpOrig.to && ch.origTo >= vpOrig.from)
333
        drawConnectorsForChunk(dv, ch, sTopOrig, sTopEdit, w);
334
    }
335
  }
336

337
  function getMatchingOrigLine(editLine, chunks) {
338
    var editStart = 0, origStart = 0;
339
    for (var i = 0; i < chunks.length; i++) {
340
      var chunk = chunks[i];
341
      if (chunk.editTo > editLine && chunk.editFrom <= editLine) return null;
342
      if (chunk.editFrom > editLine) break;
343
      editStart = chunk.editTo;
344
      origStart = chunk.origTo;
345
    }
346
    return origStart + (editLine - editStart);
347
  }
348

349
  // Combines information about chunks and widgets/markers to return
350
  // an array of lines, in a single editor, that probably need to be
351
  // aligned with their counterparts in the editor next to it.
352
  function alignableFor(cm, chunks, isOrig) {
353
    var tracker = cm.state.trackAlignable
354
    var start = cm.firstLine(), trackI = 0
355
    var result = []
356
    for (var i = 0;; i++) {
357
      var chunk = chunks[i]
358
      var chunkStart = !chunk ? 1e9 : isOrig ? chunk.origFrom : chunk.editFrom
359
      for (; trackI < tracker.alignable.length; trackI += 2) {
360
        var n = tracker.alignable[trackI] + 1
361
        if (n <= start) continue
362
        if (n <= chunkStart) result.push(n)
363
        else break
364
      }
365
      if (!chunk) break
366
      result.push(start = isOrig ? chunk.origTo : chunk.editTo)
367
    }
368
    return result
369
  }
370

371
  // Given information about alignable lines in two editors, fill in
372
  // the result (an array of three-element arrays) to reflect the
373
  // lines that need to be aligned with each other.
374
  function mergeAlignable(result, origAlignable, chunks, setIndex) {
375
    var rI = 0, origI = 0, chunkI = 0, diff = 0
376
    outer: for (;; rI++) {
377
      var nextR = result[rI], nextO = origAlignable[origI]
378
      if (!nextR && nextO == null) break
379

380
      var rLine = nextR ? nextR[0] : 1e9, oLine = nextO == null ? 1e9 : nextO
381
      while (chunkI < chunks.length) {
382
        var chunk = chunks[chunkI]
383
        if (chunk.origFrom <= oLine && chunk.origTo > oLine) {
384
          origI++
385
          rI--
386
          continue outer;
387
        }
388
        if (chunk.editTo > rLine) {
389
          if (chunk.editFrom <= rLine) continue outer;
390
          break
391
        }
392
        diff += (chunk.origTo - chunk.origFrom) - (chunk.editTo - chunk.editFrom)
393
        chunkI++
394
      }
395
      if (rLine == oLine - diff) {
396
        nextR[setIndex] = oLine
397
        origI++
398
      } else if (rLine < oLine - diff) {
399
        nextR[setIndex] = rLine + diff
400
      } else {
401
        var record = [oLine - diff, null, null]
402
        record[setIndex] = oLine
403
        result.splice(rI, 0, record)
404
        origI++
405
      }
406
    }
407
  }
408

409
  function findAlignedLines(dv, other) {
410
    var alignable = alignableFor(dv.edit, dv.chunks, false), result = []
411
    if (other) for (var i = 0, j = 0; i < other.chunks.length; i++) {
412
      var n = other.chunks[i].editTo
413
      while (j < alignable.length && alignable[j] < n) j++
414
      if (j == alignable.length || alignable[j] != n) alignable.splice(j++, 0, n)
415
    }
416
    for (var i = 0; i < alignable.length; i++)
417
      result.push([alignable[i], null, null])
418

419
    mergeAlignable(result, alignableFor(dv.orig, dv.chunks, true), dv.chunks, 1)
420
    if (other)
421
      mergeAlignable(result, alignableFor(other.orig, other.chunks, true), other.chunks, 2)
422

423
    return result
424
  }
425

426
  function alignChunks(dv, force) {
427
    if (!dv.dealigned && !force) return;
428
    if (!dv.orig.curOp) return dv.orig.operation(function() {
429
      alignChunks(dv, force);
430
    });
431

432
    dv.dealigned = false;
433
    var other = dv.mv.left == dv ? dv.mv.right : dv.mv.left;
434
    if (other) {
435
      ensureDiff(other);
436
      other.dealigned = false;
437
    }
438
    var linesToAlign = findAlignedLines(dv, other);
439

440
    // Clear old aligners
441
    var aligners = dv.mv.aligners;
442
    for (var i = 0; i < aligners.length; i++)
443
      aligners[i].clear();
444
    aligners.length = 0;
445

446
    var cm = [dv.edit, dv.orig], scroll = [], offset = []
447
    if (other) cm.push(other.orig);
448
    for (var i = 0; i < cm.length; i++) {
449
      scroll.push(cm[i].getScrollInfo().top);
450
      offset.push(-cm[i].getScrollerElement().getBoundingClientRect().top)
451
    }
452

453
    if (offset[0] != offset[1] || cm.length == 3 && offset[1] != offset[2])
454
      alignLines(cm, offset, [0, 0, 0], aligners)
455
    for (var ln = 0; ln < linesToAlign.length; ln++)
456
      alignLines(cm, offset, linesToAlign[ln], aligners);
457

458
    for (var i = 0; i < cm.length; i++)
459
      cm[i].scrollTo(null, scroll[i]);
460
  }
461

462
  function alignLines(cm, cmOffset, lines, aligners) {
463
    var maxOffset = -1e8, offset = [];
464
    for (var i = 0; i < cm.length; i++) if (lines[i] != null) {
465
      var off = cm[i].heightAtLine(lines[i], "local") - cmOffset[i];
466
      offset[i] = off;
467
      maxOffset = Math.max(maxOffset, off);
468
    }
469
    for (var i = 0; i < cm.length; i++) if (lines[i] != null) {
470
      var diff = maxOffset - offset[i];
471
      if (diff > 1)
472
        aligners.push(padAbove(cm[i], lines[i], diff));
473
    }
474
  }
475

476
  function padAbove(cm, line, size) {
477
    var above = true;
478
    if (line > cm.lastLine()) {
479
      line--;
480
      above = false;
481
    }
482
    var elt = document.createElement("div");
483
    elt.className = "CodeMirror-merge-spacer";
484
    elt.style.height = size + "px"; elt.style.minWidth = "1px";
485
    return cm.addLineWidget(line, elt, {height: size, above: above, mergeSpacer: true, handleMouseEvents: true});
486
  }
487

488
  function drawConnectorsForChunk(dv, chunk, sTopOrig, sTopEdit, w) {
489
    var flip = dv.type == "left";
490
    var top = dv.orig.heightAtLine(chunk.origFrom, "local", true) - sTopOrig;
491
    if (dv.svg) {
492
      var topLpx = top;
493
      var topRpx = dv.edit.heightAtLine(chunk.editFrom, "local", true) - sTopEdit;
494
      if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }
495
      var botLpx = dv.orig.heightAtLine(chunk.origTo, "local", true) - sTopOrig;
496
      var botRpx = dv.edit.heightAtLine(chunk.editTo, "local", true) - sTopEdit;
497
      if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }
498
      var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx;
499
      var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx;
500
      attrs(dv.svg.appendChild(document.createElementNS(svgNS, "path")),
501
            "d", "M -1 " + topRpx + curveTop + " L " + (w + 2) + " " + botLpx + curveBot + " z",
502
            "class", dv.classes.connect);
503
    }
504
    if (dv.copyButtons) {
505
      var copy = dv.copyButtons.appendChild(elt("div", dv.type == "left" ? "\u21dd" : "\u21dc",
506
                                                "CodeMirror-merge-copy"));
507
      var editOriginals = dv.mv.options.allowEditingOriginals;
508
      copy.title = dv.edit.phrase(editOriginals ? "Push to left" : "Revert chunk");
509
      copy.chunk = chunk;
510
      copy.style.top = (chunk.origTo > chunk.origFrom ? top : dv.edit.heightAtLine(chunk.editFrom, "local") - sTopEdit) + "px";
511
      copy.setAttribute("role", "button");
512

513
      if (editOriginals) {
514
        var topReverse = dv.edit.heightAtLine(chunk.editFrom, "local") - sTopEdit;
515
        var copyReverse = dv.copyButtons.appendChild(elt("div", dv.type == "right" ? "\u21dd" : "\u21dc",
516
                                                         "CodeMirror-merge-copy-reverse"));
517
        copyReverse.title = "Push to right";
518
        copyReverse.chunk = {editFrom: chunk.origFrom, editTo: chunk.origTo,
519
                             origFrom: chunk.editFrom, origTo: chunk.editTo};
520
        copyReverse.style.top = topReverse + "px";
521
        dv.type == "right" ? copyReverse.style.left = "2px" : copyReverse.style.right = "2px";
522
        copyReverse.setAttribute("role", "button");
523
      }
524
    }
525
  }
526

527
  function copyChunk(dv, to, from, chunk) {
528
    if (dv.diffOutOfDate) return;
529
    var origStart = chunk.origTo > from.lastLine() ? Pos(chunk.origFrom - 1) : Pos(chunk.origFrom, 0)
530
    var origEnd = Pos(chunk.origTo, 0)
531
    var editStart = chunk.editTo > to.lastLine() ? Pos(chunk.editFrom - 1) : Pos(chunk.editFrom, 0)
532
    var editEnd = Pos(chunk.editTo, 0)
533
    var handler = dv.mv.options.revertChunk
534
    if (handler)
535
      handler(dv.mv, from, origStart, origEnd, to, editStart, editEnd)
536
    else
537
      to.replaceRange(from.getRange(origStart, origEnd), editStart, editEnd)
538
  }
539

540
  // Merge view, containing 0, 1, or 2 diff views.
541

542
  var MergeView = CodeMirror.MergeView = function(node, options) {
543
    if (!(this instanceof MergeView)) return new MergeView(node, options);
544

545
    this.options = options;
546
    var origLeft = options.origLeft, origRight = options.origRight == null ? options.orig : options.origRight;
547

548
    var hasLeft = origLeft != null, hasRight = origRight != null;
549
    var panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0);
550
    var wrap = [], left = this.left = null, right = this.right = null;
551
    var self = this;
552

553
    if (hasLeft) {
554
      left = this.left = new DiffView(this, "left");
555
      var leftPane = elt("div", null, "CodeMirror-merge-pane CodeMirror-merge-left");
556
      wrap.push(leftPane);
557
      wrap.push(buildGap(left));
558
    }
559

560
    var editPane = elt("div", null, "CodeMirror-merge-pane CodeMirror-merge-editor");
561
    wrap.push(editPane);
562

563
    if (hasRight) {
564
      right = this.right = new DiffView(this, "right");
565
      wrap.push(buildGap(right));
566
      var rightPane = elt("div", null, "CodeMirror-merge-pane CodeMirror-merge-right");
567
      wrap.push(rightPane);
568
    }
569

570
    (hasRight ? rightPane : editPane).className += " CodeMirror-merge-pane-rightmost";
571

572
    wrap.push(elt("div", null, null, "height: 0; clear: both;"));
573

574
    var wrapElt = this.wrap = node.appendChild(elt("div", wrap, "CodeMirror-merge CodeMirror-merge-" + panes + "pane"));
575
    this.edit = CodeMirror(editPane, copyObj(options));
576

577
    if (left) left.init(leftPane, origLeft, options);
578
    if (right) right.init(rightPane, origRight, options);
579
    if (options.collapseIdentical)
580
      this.editor().operation(function() {
581
        collapseIdenticalStretches(self, options.collapseIdentical);
582
      });
583
    if (options.connect == "align") {
584
      this.aligners = [];
585
      alignChunks(this.left || this.right, true);
586
    }
587
    if (left) left.registerEvents(right)
588
    if (right) right.registerEvents(left)
589

590

591
    var onResize = function() {
592
      if (left) makeConnections(left);
593
      if (right) makeConnections(right);
594
    };
595
    CodeMirror.on(window, "resize", onResize);
596
    var resizeInterval = setInterval(function() {
597
      for (var p = wrapElt.parentNode; p && p != document.body; p = p.parentNode) {}
598
      if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, "resize", onResize); }
599
    }, 5000);
600
  };
601

602
  function buildGap(dv) {
603
    var lock = dv.lockButton = elt("div", null, "CodeMirror-merge-scrolllock");
604
    lock.setAttribute("role", "button");
605
    var lockWrap = elt("div", [lock], "CodeMirror-merge-scrolllock-wrap");
606
    CodeMirror.on(lock, "click", function() { setScrollLock(dv, !dv.lockScroll); });
607
    var gapElts = [lockWrap];
608
    if (dv.mv.options.revertButtons !== false) {
609
      dv.copyButtons = elt("div", null, "CodeMirror-merge-copybuttons-" + dv.type);
610
      CodeMirror.on(dv.copyButtons, "click", function(e) {
611
        var node = e.target || e.srcElement;
612
        if (!node.chunk) return;
613
        if (node.className == "CodeMirror-merge-copy-reverse") {
614
          copyChunk(dv, dv.orig, dv.edit, node.chunk);
615
          return;
616
        }
617
        copyChunk(dv, dv.edit, dv.orig, node.chunk);
618
      });
619
      gapElts.unshift(dv.copyButtons);
620
    }
621
    if (dv.mv.options.connect != "align") {
622
      var svg = document.createElementNS && document.createElementNS(svgNS, "svg");
623
      if (svg && !svg.createSVGRect) svg = null;
624
      dv.svg = svg;
625
      if (svg) gapElts.push(svg);
626
    }
627

628
    return dv.gap = elt("div", gapElts, "CodeMirror-merge-gap");
629
  }
630

631
  MergeView.prototype = {
632
    constructor: MergeView,
633
    editor: function() { return this.edit; },
634
    rightOriginal: function() { return this.right && this.right.orig; },
635
    leftOriginal: function() { return this.left && this.left.orig; },
636
    setShowDifferences: function(val) {
637
      if (this.right) this.right.setShowDifferences(val);
638
      if (this.left) this.left.setShowDifferences(val);
639
    },
640
    rightChunks: function() {
641
      if (this.right) { ensureDiff(this.right); return this.right.chunks; }
642
    },
643
    leftChunks: function() {
644
      if (this.left) { ensureDiff(this.left); return this.left.chunks; }
645
    }
646
  };
647

648
  function asString(obj) {
649
    if (typeof obj == "string") return obj;
650
    else return obj.getValue();
651
  }
652

653
  // Operations on diffs
654
  var dmp;
655
  function getDiff(a, b, ignoreWhitespace) {
656
    if (!dmp) dmp = new diff_match_patch();
657

658
    var diff = dmp.diff_main(a, b);
659
    // The library sometimes leaves in empty parts, which confuse the algorithm
660
    for (var i = 0; i < diff.length; ++i) {
661
      var part = diff[i];
662
      if (ignoreWhitespace ? !/[^ \t]/.test(part[1]) : !part[1]) {
663
        diff.splice(i--, 1);
664
      } else if (i && diff[i - 1][0] == part[0]) {
665
        diff.splice(i--, 1);
666
        diff[i][1] += part[1];
667
      }
668
    }
669
    return diff;
670
  }
671

672
  function getChunks(diff) {
673
    var chunks = [];
674
    if (!diff.length) return chunks;
675
    var startEdit = 0, startOrig = 0;
676
    var edit = Pos(0, 0), orig = Pos(0, 0);
677
    for (var i = 0; i < diff.length; ++i) {
678
      var part = diff[i], tp = part[0];
679
      if (tp == DIFF_EQUAL) {
680
        var startOff = !startOfLineClean(diff, i) || edit.line < startEdit || orig.line < startOrig ? 1 : 0;
681
        var cleanFromEdit = edit.line + startOff, cleanFromOrig = orig.line + startOff;
682
        moveOver(edit, part[1], null, orig);
683
        var endOff = endOfLineClean(diff, i) ? 1 : 0;
684
        var cleanToEdit = edit.line + endOff, cleanToOrig = orig.line + endOff;
685
        if (cleanToEdit > cleanFromEdit) {
686
          if (i) chunks.push({origFrom: startOrig, origTo: cleanFromOrig,
687
                              editFrom: startEdit, editTo: cleanFromEdit});
688
          startEdit = cleanToEdit; startOrig = cleanToOrig;
689
        }
690
      } else {
691
        moveOver(tp == DIFF_INSERT ? edit : orig, part[1]);
692
      }
693
    }
694
    if (startEdit <= edit.line || startOrig <= orig.line)
695
      chunks.push({origFrom: startOrig, origTo: orig.line + 1,
696
                   editFrom: startEdit, editTo: edit.line + 1});
697
    return chunks;
698
  }
699

700
  function endOfLineClean(diff, i) {
701
    if (i == diff.length - 1) return true;
702
    var next = diff[i + 1][1];
703
    if ((next.length == 1 && i < diff.length - 2) || next.charCodeAt(0) != 10) return false;
704
    if (i == diff.length - 2) return true;
705
    next = diff[i + 2][1];
706
    return (next.length > 1 || i == diff.length - 3) && next.charCodeAt(0) == 10;
707
  }
708

709
  function startOfLineClean(diff, i) {
710
    if (i == 0) return true;
711
    var last = diff[i - 1][1];
712
    if (last.charCodeAt(last.length - 1) != 10) return false;
713
    if (i == 1) return true;
714
    last = diff[i - 2][1];
715
    return last.charCodeAt(last.length - 1) == 10;
716
  }
717

718
  function chunkBoundariesAround(chunks, n, nInEdit) {
719
    var beforeE, afterE, beforeO, afterO;
720
    for (var i = 0; i < chunks.length; i++) {
721
      var chunk = chunks[i];
722
      var fromLocal = nInEdit ? chunk.editFrom : chunk.origFrom;
723
      var toLocal = nInEdit ? chunk.editTo : chunk.origTo;
724
      if (afterE == null) {
725
        if (fromLocal > n) { afterE = chunk.editFrom; afterO = chunk.origFrom; }
726
        else if (toLocal > n) { afterE = chunk.editTo; afterO = chunk.origTo; }
727
      }
728
      if (toLocal <= n) { beforeE = chunk.editTo; beforeO = chunk.origTo; }
729
      else if (fromLocal <= n) { beforeE = chunk.editFrom; beforeO = chunk.origFrom; }
730
    }
731
    return {edit: {before: beforeE, after: afterE}, orig: {before: beforeO, after: afterO}};
732
  }
733

734
  function collapseSingle(cm, from, to) {
735
    cm.addLineClass(from, "wrap", "CodeMirror-merge-collapsed-line");
736
    var widget = document.createElement("span");
737
    widget.className = "CodeMirror-merge-collapsed-widget";
738
    widget.title = cm.phrase("Identical text collapsed. Click to expand.");
739
    var mark = cm.markText(Pos(from, 0), Pos(to - 1), {
740
      inclusiveLeft: true,
741
      inclusiveRight: true,
742
      replacedWith: widget,
743
      clearOnEnter: true
744
    });
745
    function clear() {
746
      mark.clear();
747
      cm.removeLineClass(from, "wrap", "CodeMirror-merge-collapsed-line");
748
    }
749
    if (mark.explicitlyCleared) clear();
750
    CodeMirror.on(widget, "click", clear);
751
    mark.on("clear", clear);
752
    CodeMirror.on(widget, "click", clear);
753
    return {mark: mark, clear: clear};
754
  }
755

756
  function collapseStretch(size, editors) {
757
    var marks = [];
758
    function clear() {
759
      for (var i = 0; i < marks.length; i++) marks[i].clear();
760
    }
761
    for (var i = 0; i < editors.length; i++) {
762
      var editor = editors[i];
763
      var mark = collapseSingle(editor.cm, editor.line, editor.line + size);
764
      marks.push(mark);
765
      mark.mark.on("clear", clear);
766
    }
767
    return marks[0].mark;
768
  }
769

770
  function unclearNearChunks(dv, margin, off, clear) {
771
    for (var i = 0; i < dv.chunks.length; i++) {
772
      var chunk = dv.chunks[i];
773
      for (var l = chunk.editFrom - margin; l < chunk.editTo + margin; l++) {
774
        var pos = l + off;
775
        if (pos >= 0 && pos < clear.length) clear[pos] = false;
776
      }
777
    }
778
  }
779

780
  function collapseIdenticalStretches(mv, margin) {
781
    if (typeof margin != "number") margin = 2;
782
    var clear = [], edit = mv.editor(), off = edit.firstLine();
783
    for (var l = off, e = edit.lastLine(); l <= e; l++) clear.push(true);
784
    if (mv.left) unclearNearChunks(mv.left, margin, off, clear);
785
    if (mv.right) unclearNearChunks(mv.right, margin, off, clear);
786

787
    for (var i = 0; i < clear.length; i++) {
788
      if (clear[i]) {
789
        var line = i + off;
790
        for (var size = 1; i < clear.length - 1 && clear[i + 1]; i++, size++) {}
791
        if (size > margin) {
792
          var editors = [{line: line, cm: edit}];
793
          if (mv.left) editors.push({line: getMatchingOrigLine(line, mv.left.chunks), cm: mv.left.orig});
794
          if (mv.right) editors.push({line: getMatchingOrigLine(line, mv.right.chunks), cm: mv.right.orig});
795
          var mark = collapseStretch(size, editors);
796
          if (mv.options.onCollapse) mv.options.onCollapse(mv, line, size, mark);
797
        }
798
      }
799
    }
800
  }
801

802
  // General utilities
803

804
  function elt(tag, content, className, style) {
805
    var e = document.createElement(tag);
806
    if (className) e.className = className;
807
    if (style) e.style.cssText = style;
808
    if (typeof content == "string") e.appendChild(document.createTextNode(content));
809
    else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
810
    return e;
811
  }
812

813
  function clear(node) {
814
    for (var count = node.childNodes.length; count > 0; --count)
815
      node.removeChild(node.firstChild);
816
  }
817

818
  function attrs(elt) {
819
    for (var i = 1; i < arguments.length; i += 2)
820
      elt.setAttribute(arguments[i], arguments[i+1]);
821
  }
822

823
  function copyObj(obj, target) {
824
    if (!target) target = {};
825
    for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
826
    return target;
827
  }
828

829
  function moveOver(pos, str, copy, other) {
830
    var out = copy ? Pos(pos.line, pos.ch) : pos, at = 0;
831
    for (;;) {
832
      var nl = str.indexOf("\n", at);
833
      if (nl == -1) break;
834
      ++out.line;
835
      if (other) ++other.line;
836
      at = nl + 1;
837
    }
838
    out.ch = (at ? 0 : out.ch) + (str.length - at);
839
    if (other) other.ch = (at ? 0 : other.ch) + (str.length - at);
840
    return out;
841
  }
842

843
  // Tracks collapsed markers and line widgets, in order to be able to
844
  // accurately align the content of two editors.
845

846
  var F_WIDGET = 1, F_WIDGET_BELOW = 2, F_MARKER = 4
847

848
  function TrackAlignable(cm) {
849
    this.cm = cm
850
    this.alignable = []
851
    this.height = cm.doc.height
852
    var self = this
853
    cm.on("markerAdded", function(_, marker) {
854
      if (!marker.collapsed) return
855
      var found = marker.find(1)
856
      if (found != null) self.set(found.line, F_MARKER)
857
    })
858
    cm.on("markerCleared", function(_, marker, _min, max) {
859
      if (max != null && marker.collapsed)
860
        self.check(max, F_MARKER, self.hasMarker)
861
    })
862
    cm.on("markerChanged", this.signal.bind(this))
863
    cm.on("lineWidgetAdded", function(_, widget, lineNo) {
864
      if (widget.mergeSpacer) return
865
      if (widget.above) self.set(lineNo - 1, F_WIDGET_BELOW)
866
      else self.set(lineNo, F_WIDGET)
867
    })
868
    cm.on("lineWidgetCleared", function(_, widget, lineNo) {
869
      if (widget.mergeSpacer) return
870
      if (widget.above) self.check(lineNo - 1, F_WIDGET_BELOW, self.hasWidgetBelow)
871
      else self.check(lineNo, F_WIDGET, self.hasWidget)
872
    })
873
    cm.on("lineWidgetChanged", this.signal.bind(this))
874
    cm.on("change", function(_, change) {
875
      var start = change.from.line, nBefore = change.to.line - change.from.line
876
      var nAfter = change.text.length - 1, end = start + nAfter
877
      if (nBefore || nAfter) self.map(start, nBefore, nAfter)
878
      self.check(end, F_MARKER, self.hasMarker)
879
      if (nBefore || nAfter) self.check(change.from.line, F_MARKER, self.hasMarker)
880
    })
881
    cm.on("viewportChange", function() {
882
      if (self.cm.doc.height != self.height) self.signal()
883
    })
884
  }
885

886
  TrackAlignable.prototype = {
887
    signal: function() {
888
      CodeMirror.signal(this, "realign")
889
      this.height = this.cm.doc.height
890
    },
891

892
    set: function(n, flags) {
893
      var pos = -1
894
      for (; pos < this.alignable.length; pos += 2) {
895
        var diff = this.alignable[pos] - n
896
        if (diff == 0) {
897
          if ((this.alignable[pos + 1] & flags) == flags) return
898
          this.alignable[pos + 1] |= flags
899
          this.signal()
900
          return
901
        }
902
        if (diff > 0) break
903
      }
904
      this.signal()
905
      this.alignable.splice(pos, 0, n, flags)
906
    },
907

908
    find: function(n) {
909
      for (var i = 0; i < this.alignable.length; i += 2)
910
        if (this.alignable[i] == n) return i
911
      return -1
912
    },
913

914
    check: function(n, flag, pred) {
915
      var found = this.find(n)
916
      if (found == -1 || !(this.alignable[found + 1] & flag)) return
917
      if (!pred.call(this, n)) {
918
        this.signal()
919
        var flags = this.alignable[found + 1] & ~flag
920
        if (flags) this.alignable[found + 1] = flags
921
        else this.alignable.splice(found, 2)
922
      }
923
    },
924

925
    hasMarker: function(n) {
926
      var handle = this.cm.getLineHandle(n)
927
      if (handle.markedSpans) for (var i = 0; i < handle.markedSpans.length; i++)
928
        if (handle.markedSpans[i].marker.collapsed && handle.markedSpans[i].to != null)
929
          return true
930
      return false
931
    },
932

933
    hasWidget: function(n) {
934
      var handle = this.cm.getLineHandle(n)
935
      if (handle.widgets) for (var i = 0; i < handle.widgets.length; i++)
936
        if (!handle.widgets[i].above && !handle.widgets[i].mergeSpacer) return true
937
      return false
938
    },
939

940
    hasWidgetBelow: function(n) {
941
      if (n == this.cm.lastLine()) return false
942
      var handle = this.cm.getLineHandle(n + 1)
943
      if (handle.widgets) for (var i = 0; i < handle.widgets.length; i++)
944
        if (handle.widgets[i].above && !handle.widgets[i].mergeSpacer) return true
945
      return false
946
    },
947

948
    map: function(from, nBefore, nAfter) {
949
      var diff = nAfter - nBefore, to = from + nBefore, widgetFrom = -1, widgetTo = -1
950
      for (var i = 0; i < this.alignable.length; i += 2) {
951
        var n = this.alignable[i]
952
        if (n == from && (this.alignable[i + 1] & F_WIDGET_BELOW)) widgetFrom = i
953
        if (n == to && (this.alignable[i + 1] & F_WIDGET_BELOW)) widgetTo = i
954
        if (n <= from) continue
955
        else if (n < to) this.alignable.splice(i--, 2)
956
        else this.alignable[i] += diff
957
      }
958
      if (widgetFrom > -1) {
959
        var flags = this.alignable[widgetFrom + 1]
960
        if (flags == F_WIDGET_BELOW) this.alignable.splice(widgetFrom, 2)
961
        else this.alignable[widgetFrom + 1] = flags & ~F_WIDGET_BELOW
962
      }
963
      if (widgetTo > -1 && nAfter)
964
        this.set(from + nAfter, F_WIDGET_BELOW)
965
    }
966
  }
967

968
  function posMin(a, b) { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; }
969
  function posMax(a, b) { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; }
970
  function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
971

972
  function findPrevDiff(chunks, start, isOrig) {
973
    for (var i = chunks.length - 1; i >= 0; i--) {
974
      var chunk = chunks[i];
975
      var to = (isOrig ? chunk.origTo : chunk.editTo) - 1;
976
      if (to < start) return to;
977
    }
978
  }
979

980
  function findNextDiff(chunks, start, isOrig) {
981
    for (var i = 0; i < chunks.length; i++) {
982
      var chunk = chunks[i];
983
      var from = (isOrig ? chunk.origFrom : chunk.editFrom);
984
      if (from > start) return from;
985
    }
986
  }
987

988
  function goNearbyDiff(cm, dir) {
989
    var found = null, views = cm.state.diffViews, line = cm.getCursor().line;
990
    if (views) for (var i = 0; i < views.length; i++) {
991
      var dv = views[i], isOrig = cm == dv.orig;
992
      ensureDiff(dv);
993
      var pos = dir < 0 ? findPrevDiff(dv.chunks, line, isOrig) : findNextDiff(dv.chunks, line, isOrig);
994
      if (pos != null && (found == null || (dir < 0 ? pos > found : pos < found)))
995
        found = pos;
996
    }
997
    if (found != null)
998
      cm.setCursor(found, 0);
999
    else
1000
      return CodeMirror.Pass;
1001
  }
1002

1003
  CodeMirror.commands.goNextDiff = function(cm) {
1004
    return goNearbyDiff(cm, 1);
1005
  };
1006
  CodeMirror.commands.goPrevDiff = function(cm) {
1007
    return goNearbyDiff(cm, -1);
1008
  };
1009
});
1010

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.