LaravelTest
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) {7if (typeof exports == "object" && typeof module == "object") // CommonJS8mod(require("../../lib/codemirror")); // Note non-packaged dependency diff_match_patch9else if (typeof define == "function" && define.amd) // AMD10define(["../../lib/codemirror", "diff_match_patch"], mod);11else // Plain browser env12mod(CodeMirror);13})(function(CodeMirror) {14"use strict";15var Pos = CodeMirror.Pos;16var svgNS = "http://www.w3.org/2000/svg";17
18function DiffView(mv, type) {19this.mv = mv;20this.type = type;21this.classes = type == "left"22? {chunk: "CodeMirror-merge-l-chunk",23start: "CodeMirror-merge-l-chunk-start",24end: "CodeMirror-merge-l-chunk-end",25insert: "CodeMirror-merge-l-inserted",26del: "CodeMirror-merge-l-deleted",27connect: "CodeMirror-merge-l-connect"}28: {chunk: "CodeMirror-merge-r-chunk",29start: "CodeMirror-merge-r-chunk-start",30end: "CodeMirror-merge-r-chunk-end",31insert: "CodeMirror-merge-r-inserted",32del: "CodeMirror-merge-r-deleted",33connect: "CodeMirror-merge-r-connect"};34}35
36DiffView.prototype = {37constructor: DiffView,38init: function(pane, orig, options) {39this.edit = this.mv.edit;40;(this.edit.state.diffViews || (this.edit.state.diffViews = [])).push(this);41this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: !this.mv.options.allowEditingOriginals}, copyObj(options)));42if (this.mv.options.connect == "align") {43if (!this.edit.state.trackAlignable) this.edit.state.trackAlignable = new TrackAlignable(this.edit)44this.orig.state.trackAlignable = new TrackAlignable(this.orig)45}46this.lockButton.title = this.edit.phrase("Toggle locked scrolling");47
48this.orig.state.diffViews = [this];49var classLocation = options.chunkClassLocation || "background";50if (Object.prototype.toString.call(classLocation) != "[object Array]") classLocation = [classLocation]51this.classes.classLocation = classLocation52
53this.diff = getDiff(asString(orig), asString(options.value), this.mv.options.ignoreWhitespace);54this.chunks = getChunks(this.diff);55this.diffOutOfDate = this.dealigned = false;56this.needsScrollSync = null57
58this.showDifferences = options.showDifferences !== false;59},60registerEvents: function(otherDv) {61this.forceUpdate = registerUpdate(this);62setScrollLock(this, true, false);63registerScroll(this, otherDv);64},65setShowDifferences: function(val) {66val = val !== false;67if (val != this.showDifferences) {68this.showDifferences = val;69this.forceUpdate("full");70}71}72};73
74function ensureDiff(dv) {75if (dv.diffOutOfDate) {76dv.diff = getDiff(dv.orig.getValue(), dv.edit.getValue(), dv.mv.options.ignoreWhitespace);77dv.chunks = getChunks(dv.diff);78dv.diffOutOfDate = false;79CodeMirror.signal(dv.edit, "updateDiff", dv.diff);80}81}82
83var updating = false;84function registerUpdate(dv) {85var edit = {from: 0, to: 0, marked: []};86var orig = {from: 0, to: 0, marked: []};87var debounceChange, updatingFast = false;88function update(mode) {89updating = true;90updatingFast = false;91if (mode == "full") {92if (dv.svg) clear(dv.svg);93if (dv.copyButtons) clear(dv.copyButtons);94clearMarks(dv.edit, edit.marked, dv.classes);95clearMarks(dv.orig, orig.marked, dv.classes);96edit.from = edit.to = orig.from = orig.to = 0;97}98ensureDiff(dv);99if (dv.showDifferences) {100updateMarks(dv.edit, dv.diff, edit, DIFF_INSERT, dv.classes);101updateMarks(dv.orig, dv.diff, orig, DIFF_DELETE, dv.classes);102}103
104if (dv.mv.options.connect == "align")105alignChunks(dv);106makeConnections(dv);107if (dv.needsScrollSync != null) syncScroll(dv, dv.needsScrollSync)108
109updating = false;110}111function setDealign(fast) {112if (updating) return;113dv.dealigned = true;114set(fast);115}116function set(fast) {117if (updating || updatingFast) return;118clearTimeout(debounceChange);119if (fast === true) updatingFast = true;120debounceChange = setTimeout(update, fast === true ? 20 : 250);121}122function change(_cm, change) {123if (!dv.diffOutOfDate) {124dv.diffOutOfDate = true;125edit.from = edit.to = orig.from = orig.to = 0;126}127// Update faster when a line was added/removed128setDealign(change.text.length - 1 != change.to.line - change.from.line);129}130function swapDoc() {131dv.diffOutOfDate = true;132dv.dealigned = true;133update("full");134}135dv.edit.on("change", change);136dv.orig.on("change", change);137dv.edit.on("swapDoc", swapDoc);138dv.orig.on("swapDoc", swapDoc);139if (dv.mv.options.connect == "align") {140CodeMirror.on(dv.edit.state.trackAlignable, "realign", setDealign)141CodeMirror.on(dv.orig.state.trackAlignable, "realign", setDealign)142}143dv.edit.on("viewportChange", function() { set(false); });144dv.orig.on("viewportChange", function() { set(false); });145update();146return update;147}148
149function registerScroll(dv, otherDv) {150dv.edit.on("scroll", function() {151syncScroll(dv, true) && makeConnections(dv);152});153dv.orig.on("scroll", function() {154syncScroll(dv, false) && makeConnections(dv);155if (otherDv) syncScroll(otherDv, true) && makeConnections(otherDv);156});157}158
159function syncScroll(dv, toOrig) {160// Change handler will do a refresh after a timeout when diff is out of date161if (dv.diffOutOfDate) {162if (dv.lockScroll && dv.needsScrollSync == null) dv.needsScrollSync = toOrig163return false164}165dv.needsScrollSync = null166if (!dv.lockScroll) return true;167var editor, other, now = +new Date;168if (toOrig) { editor = dv.edit; other = dv.orig; }169else { editor = dv.orig; other = dv.edit; }170// Don't take action if the position of this editor was recently set171// (to prevent feedback loops)172if (editor.state.scrollSetBy == dv && (editor.state.scrollSetAt || 0) + 250 > now) return false;173
174var sInfo = editor.getScrollInfo();175if (dv.mv.options.connect == "align") {176targetPos = sInfo.top;177} else {178var halfScreen = .5 * sInfo.clientHeight, midY = sInfo.top + halfScreen;179var mid = editor.lineAtHeight(midY, "local");180var around = chunkBoundariesAround(dv.chunks, mid, toOrig);181var off = getOffsets(editor, toOrig ? around.edit : around.orig);182var offOther = getOffsets(other, toOrig ? around.orig : around.edit);183var ratio = (midY - off.top) / (off.bot - off.top);184var targetPos = (offOther.top - halfScreen) + ratio * (offOther.bot - offOther.top);185
186var botDist, mix;187// Some careful tweaking to make sure no space is left out of view188// when scrolling to top or bottom.189if (targetPos > sInfo.top && (mix = sInfo.top / halfScreen) < 1) {190targetPos = targetPos * mix + sInfo.top * (1 - mix);191} else if ((botDist = sInfo.height - sInfo.clientHeight - sInfo.top) < halfScreen) {192var otherInfo = other.getScrollInfo();193var botDistOther = otherInfo.height - otherInfo.clientHeight - targetPos;194if (botDistOther > botDist && (mix = botDist / halfScreen) < 1)195targetPos = targetPos * mix + (otherInfo.height - otherInfo.clientHeight - botDist) * (1 - mix);196}197}198
199other.scrollTo(sInfo.left, targetPos);200other.state.scrollSetAt = now;201other.state.scrollSetBy = dv;202return true;203}204
205function getOffsets(editor, around) {206var bot = around.after;207if (bot == null) bot = editor.lastLine() + 1;208return {top: editor.heightAtLine(around.before || 0, "local"),209bot: editor.heightAtLine(bot, "local")};210}211
212function setScrollLock(dv, val, action) {213dv.lockScroll = val;214if (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 content219
220function removeClass(editor, line, classes) {221var locs = classes.classLocation222for (var i = 0; i < locs.length; i++) {223editor.removeLineClass(line, locs[i], classes.chunk);224editor.removeLineClass(line, locs[i], classes.start);225editor.removeLineClass(line, locs[i], classes.end);226}227}228
229function clearMarks(editor, arr, classes) {230for (var i = 0; i < arr.length; ++i) {231var mark = arr[i];232if (mark instanceof CodeMirror.TextMarker)233mark.clear();234else if (mark.parent)235removeClass(editor, mark, classes);236}237arr.length = 0;238}239
240// FIXME maybe add a margin around viewport to prevent too many updates241function updateMarks(editor, diff, state, type, classes) {242var vp = editor.getViewport();243editor.operation(function() {244if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {245clearMarks(editor, state.marked, classes);246markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes);247state.from = vp.from; state.to = vp.to;248} else {249if (vp.from < state.from) {250markChanges(editor, diff, type, state.marked, vp.from, state.from, classes);251state.from = vp.from;252}253if (vp.to > state.to) {254markChanges(editor, diff, type, state.marked, state.to, vp.to, classes);255state.to = vp.to;256}257}258});259}260
261function addClass(editor, lineNr, classes, main, start, end) {262var locs = classes.classLocation, line = editor.getLineHandle(lineNr);263for (var i = 0; i < locs.length; i++) {264if (main) editor.addLineClass(line, locs[i], classes.chunk);265if (start) editor.addLineClass(line, locs[i], classes.start);266if (end) editor.addLineClass(line, locs[i], classes.end);267}268return line;269}270
271function markChanges(editor, diff, type, marks, from, to, classes) {272var pos = Pos(0, 0);273var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1));274var cls = type == DIFF_DELETE ? classes.del : classes.insert;275function markChunk(start, end) {276var bfrom = Math.max(from, start), bto = Math.min(to, end);277for (var i = bfrom; i < bto; ++i)278marks.push(addClass(editor, i, classes, true, i == start, i == end - 1));279// When the chunk is empty, make sure a horizontal line shows up280if (start == end && bfrom == end && bto == end) {281if (bfrom)282marks.push(addClass(editor, bfrom - 1, classes, false, false, true));283else284marks.push(addClass(editor, bfrom, classes, false, true, false));285}286}287
288var chunkStart = 0, pending = false;289for (var i = 0; i < diff.length; ++i) {290var part = diff[i], tp = part[0], str = part[1];291if (tp == DIFF_EQUAL) {292var cleanFrom = pos.line + (startOfLineClean(diff, i) ? 0 : 1);293moveOver(pos, str);294var cleanTo = pos.line + (endOfLineClean(diff, i) ? 1 : 0);295if (cleanTo > cleanFrom) {296if (pending) { markChunk(chunkStart, cleanFrom); pending = false }297chunkStart = cleanTo;298}299} else {300pending = true301if (tp == type) {302var end = moveOver(pos, str, true);303var a = posMax(top, pos), b = posMin(bot, end);304if (!posEq(a, b))305marks.push(editor.markText(a, b, {className: cls}));306pos = end;307}308}309}310if (pending) markChunk(chunkStart, pos.line + 1);311}312
313// Updating the gap between editor and original314
315function makeConnections(dv) {316if (!dv.showDifferences) return;317
318if (dv.svg) {319clear(dv.svg);320var w = dv.gap.offsetWidth;321attrs(dv.svg, "width", w, "height", dv.gap.offsetHeight);322}323if (dv.copyButtons) clear(dv.copyButtons);324
325var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport();326var outerTop = dv.mv.wrap.getBoundingClientRect().top327var sTopEdit = outerTop - dv.edit.getScrollerElement().getBoundingClientRect().top + dv.edit.getScrollInfo().top328var sTopOrig = outerTop - dv.orig.getScrollerElement().getBoundingClientRect().top + dv.orig.getScrollInfo().top;329for (var i = 0; i < dv.chunks.length; i++) {330var ch = dv.chunks[i];331if (ch.editFrom <= vpEdit.to && ch.editTo >= vpEdit.from &&332ch.origFrom <= vpOrig.to && ch.origTo >= vpOrig.from)333drawConnectorsForChunk(dv, ch, sTopOrig, sTopEdit, w);334}335}336
337function getMatchingOrigLine(editLine, chunks) {338var editStart = 0, origStart = 0;339for (var i = 0; i < chunks.length; i++) {340var chunk = chunks[i];341if (chunk.editTo > editLine && chunk.editFrom <= editLine) return null;342if (chunk.editFrom > editLine) break;343editStart = chunk.editTo;344origStart = chunk.origTo;345}346return origStart + (editLine - editStart);347}348
349// Combines information about chunks and widgets/markers to return350// an array of lines, in a single editor, that probably need to be351// aligned with their counterparts in the editor next to it.352function alignableFor(cm, chunks, isOrig) {353var tracker = cm.state.trackAlignable354var start = cm.firstLine(), trackI = 0355var result = []356for (var i = 0;; i++) {357var chunk = chunks[i]358var chunkStart = !chunk ? 1e9 : isOrig ? chunk.origFrom : chunk.editFrom359for (; trackI < tracker.alignable.length; trackI += 2) {360var n = tracker.alignable[trackI] + 1361if (n <= start) continue362if (n <= chunkStart) result.push(n)363else break364}365if (!chunk) break366result.push(start = isOrig ? chunk.origTo : chunk.editTo)367}368return result369}370
371// Given information about alignable lines in two editors, fill in372// the result (an array of three-element arrays) to reflect the373// lines that need to be aligned with each other.374function mergeAlignable(result, origAlignable, chunks, setIndex) {375var rI = 0, origI = 0, chunkI = 0, diff = 0376outer: for (;; rI++) {377var nextR = result[rI], nextO = origAlignable[origI]378if (!nextR && nextO == null) break379
380var rLine = nextR ? nextR[0] : 1e9, oLine = nextO == null ? 1e9 : nextO381while (chunkI < chunks.length) {382var chunk = chunks[chunkI]383if (chunk.origFrom <= oLine && chunk.origTo > oLine) {384origI++385rI--386continue outer;387}388if (chunk.editTo > rLine) {389if (chunk.editFrom <= rLine) continue outer;390break391}392diff += (chunk.origTo - chunk.origFrom) - (chunk.editTo - chunk.editFrom)393chunkI++394}395if (rLine == oLine - diff) {396nextR[setIndex] = oLine397origI++398} else if (rLine < oLine - diff) {399nextR[setIndex] = rLine + diff400} else {401var record = [oLine - diff, null, null]402record[setIndex] = oLine403result.splice(rI, 0, record)404origI++405}406}407}408
409function findAlignedLines(dv, other) {410var alignable = alignableFor(dv.edit, dv.chunks, false), result = []411if (other) for (var i = 0, j = 0; i < other.chunks.length; i++) {412var n = other.chunks[i].editTo413while (j < alignable.length && alignable[j] < n) j++414if (j == alignable.length || alignable[j] != n) alignable.splice(j++, 0, n)415}416for (var i = 0; i < alignable.length; i++)417result.push([alignable[i], null, null])418
419mergeAlignable(result, alignableFor(dv.orig, dv.chunks, true), dv.chunks, 1)420if (other)421mergeAlignable(result, alignableFor(other.orig, other.chunks, true), other.chunks, 2)422
423return result424}425
426function alignChunks(dv, force) {427if (!dv.dealigned && !force) return;428if (!dv.orig.curOp) return dv.orig.operation(function() {429alignChunks(dv, force);430});431
432dv.dealigned = false;433var other = dv.mv.left == dv ? dv.mv.right : dv.mv.left;434if (other) {435ensureDiff(other);436other.dealigned = false;437}438var linesToAlign = findAlignedLines(dv, other);439
440// Clear old aligners441var aligners = dv.mv.aligners;442for (var i = 0; i < aligners.length; i++)443aligners[i].clear();444aligners.length = 0;445
446var cm = [dv.edit, dv.orig], scroll = [], offset = []447if (other) cm.push(other.orig);448for (var i = 0; i < cm.length; i++) {449scroll.push(cm[i].getScrollInfo().top);450offset.push(-cm[i].getScrollerElement().getBoundingClientRect().top)451}452
453if (offset[0] != offset[1] || cm.length == 3 && offset[1] != offset[2])454alignLines(cm, offset, [0, 0, 0], aligners)455for (var ln = 0; ln < linesToAlign.length; ln++)456alignLines(cm, offset, linesToAlign[ln], aligners);457
458for (var i = 0; i < cm.length; i++)459cm[i].scrollTo(null, scroll[i]);460}461
462function alignLines(cm, cmOffset, lines, aligners) {463var maxOffset = -1e8, offset = [];464for (var i = 0; i < cm.length; i++) if (lines[i] != null) {465var off = cm[i].heightAtLine(lines[i], "local") - cmOffset[i];466offset[i] = off;467maxOffset = Math.max(maxOffset, off);468}469for (var i = 0; i < cm.length; i++) if (lines[i] != null) {470var diff = maxOffset - offset[i];471if (diff > 1)472aligners.push(padAbove(cm[i], lines[i], diff));473}474}475
476function padAbove(cm, line, size) {477var above = true;478if (line > cm.lastLine()) {479line--;480above = false;481}482var elt = document.createElement("div");483elt.className = "CodeMirror-merge-spacer";484elt.style.height = size + "px"; elt.style.minWidth = "1px";485return cm.addLineWidget(line, elt, {height: size, above: above, mergeSpacer: true, handleMouseEvents: true});486}487
488function drawConnectorsForChunk(dv, chunk, sTopOrig, sTopEdit, w) {489var flip = dv.type == "left";490var top = dv.orig.heightAtLine(chunk.origFrom, "local", true) - sTopOrig;491if (dv.svg) {492var topLpx = top;493var topRpx = dv.edit.heightAtLine(chunk.editFrom, "local", true) - sTopEdit;494if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }495var botLpx = dv.orig.heightAtLine(chunk.origTo, "local", true) - sTopOrig;496var botRpx = dv.edit.heightAtLine(chunk.editTo, "local", true) - sTopEdit;497if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }498var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx;499var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx;500attrs(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}504if (dv.copyButtons) {505var copy = dv.copyButtons.appendChild(elt("div", dv.type == "left" ? "\u21dd" : "\u21dc",506"CodeMirror-merge-copy"));507var editOriginals = dv.mv.options.allowEditingOriginals;508copy.title = dv.edit.phrase(editOriginals ? "Push to left" : "Revert chunk");509copy.chunk = chunk;510copy.style.top = (chunk.origTo > chunk.origFrom ? top : dv.edit.heightAtLine(chunk.editFrom, "local") - sTopEdit) + "px";511copy.setAttribute("role", "button");512
513if (editOriginals) {514var topReverse = dv.edit.heightAtLine(chunk.editFrom, "local") - sTopEdit;515var copyReverse = dv.copyButtons.appendChild(elt("div", dv.type == "right" ? "\u21dd" : "\u21dc",516"CodeMirror-merge-copy-reverse"));517copyReverse.title = "Push to right";518copyReverse.chunk = {editFrom: chunk.origFrom, editTo: chunk.origTo,519origFrom: chunk.editFrom, origTo: chunk.editTo};520copyReverse.style.top = topReverse + "px";521dv.type == "right" ? copyReverse.style.left = "2px" : copyReverse.style.right = "2px";522copyReverse.setAttribute("role", "button");523}524}525}526
527function copyChunk(dv, to, from, chunk) {528if (dv.diffOutOfDate) return;529var origStart = chunk.origTo > from.lastLine() ? Pos(chunk.origFrom - 1) : Pos(chunk.origFrom, 0)530var origEnd = Pos(chunk.origTo, 0)531var editStart = chunk.editTo > to.lastLine() ? Pos(chunk.editFrom - 1) : Pos(chunk.editFrom, 0)532var editEnd = Pos(chunk.editTo, 0)533var handler = dv.mv.options.revertChunk534if (handler)535handler(dv.mv, from, origStart, origEnd, to, editStart, editEnd)536else537to.replaceRange(from.getRange(origStart, origEnd), editStart, editEnd)538}539
540// Merge view, containing 0, 1, or 2 diff views.541
542var MergeView = CodeMirror.MergeView = function(node, options) {543if (!(this instanceof MergeView)) return new MergeView(node, options);544
545this.options = options;546var origLeft = options.origLeft, origRight = options.origRight == null ? options.orig : options.origRight;547
548var hasLeft = origLeft != null, hasRight = origRight != null;549var panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0);550var wrap = [], left = this.left = null, right = this.right = null;551var self = this;552
553if (hasLeft) {554left = this.left = new DiffView(this, "left");555var leftPane = elt("div", null, "CodeMirror-merge-pane CodeMirror-merge-left");556wrap.push(leftPane);557wrap.push(buildGap(left));558}559
560var editPane = elt("div", null, "CodeMirror-merge-pane CodeMirror-merge-editor");561wrap.push(editPane);562
563if (hasRight) {564right = this.right = new DiffView(this, "right");565wrap.push(buildGap(right));566var rightPane = elt("div", null, "CodeMirror-merge-pane CodeMirror-merge-right");567wrap.push(rightPane);568}569
570(hasRight ? rightPane : editPane).className += " CodeMirror-merge-pane-rightmost";571
572wrap.push(elt("div", null, null, "height: 0; clear: both;"));573
574var wrapElt = this.wrap = node.appendChild(elt("div", wrap, "CodeMirror-merge CodeMirror-merge-" + panes + "pane"));575this.edit = CodeMirror(editPane, copyObj(options));576
577if (left) left.init(leftPane, origLeft, options);578if (right) right.init(rightPane, origRight, options);579if (options.collapseIdentical)580this.editor().operation(function() {581collapseIdenticalStretches(self, options.collapseIdentical);582});583if (options.connect == "align") {584this.aligners = [];585alignChunks(this.left || this.right, true);586}587if (left) left.registerEvents(right)588if (right) right.registerEvents(left)589
590
591var onResize = function() {592if (left) makeConnections(left);593if (right) makeConnections(right);594};595CodeMirror.on(window, "resize", onResize);596var resizeInterval = setInterval(function() {597for (var p = wrapElt.parentNode; p && p != document.body; p = p.parentNode) {}598if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, "resize", onResize); }599}, 5000);600};601
602function buildGap(dv) {603var lock = dv.lockButton = elt("div", null, "CodeMirror-merge-scrolllock");604lock.setAttribute("role", "button");605var lockWrap = elt("div", [lock], "CodeMirror-merge-scrolllock-wrap");606CodeMirror.on(lock, "click", function() { setScrollLock(dv, !dv.lockScroll); });607var gapElts = [lockWrap];608if (dv.mv.options.revertButtons !== false) {609dv.copyButtons = elt("div", null, "CodeMirror-merge-copybuttons-" + dv.type);610CodeMirror.on(dv.copyButtons, "click", function(e) {611var node = e.target || e.srcElement;612if (!node.chunk) return;613if (node.className == "CodeMirror-merge-copy-reverse") {614copyChunk(dv, dv.orig, dv.edit, node.chunk);615return;616}617copyChunk(dv, dv.edit, dv.orig, node.chunk);618});619gapElts.unshift(dv.copyButtons);620}621if (dv.mv.options.connect != "align") {622var svg = document.createElementNS && document.createElementNS(svgNS, "svg");623if (svg && !svg.createSVGRect) svg = null;624dv.svg = svg;625if (svg) gapElts.push(svg);626}627
628return dv.gap = elt("div", gapElts, "CodeMirror-merge-gap");629}630
631MergeView.prototype = {632constructor: MergeView,633editor: function() { return this.edit; },634rightOriginal: function() { return this.right && this.right.orig; },635leftOriginal: function() { return this.left && this.left.orig; },636setShowDifferences: function(val) {637if (this.right) this.right.setShowDifferences(val);638if (this.left) this.left.setShowDifferences(val);639},640rightChunks: function() {641if (this.right) { ensureDiff(this.right); return this.right.chunks; }642},643leftChunks: function() {644if (this.left) { ensureDiff(this.left); return this.left.chunks; }645}646};647
648function asString(obj) {649if (typeof obj == "string") return obj;650else return obj.getValue();651}652
653// Operations on diffs654var dmp;655function getDiff(a, b, ignoreWhitespace) {656if (!dmp) dmp = new diff_match_patch();657
658var diff = dmp.diff_main(a, b);659// The library sometimes leaves in empty parts, which confuse the algorithm660for (var i = 0; i < diff.length; ++i) {661var part = diff[i];662if (ignoreWhitespace ? !/[^ \t]/.test(part[1]) : !part[1]) {663diff.splice(i--, 1);664} else if (i && diff[i - 1][0] == part[0]) {665diff.splice(i--, 1);666diff[i][1] += part[1];667}668}669return diff;670}671
672function getChunks(diff) {673var chunks = [];674if (!diff.length) return chunks;675var startEdit = 0, startOrig = 0;676var edit = Pos(0, 0), orig = Pos(0, 0);677for (var i = 0; i < diff.length; ++i) {678var part = diff[i], tp = part[0];679if (tp == DIFF_EQUAL) {680var startOff = !startOfLineClean(diff, i) || edit.line < startEdit || orig.line < startOrig ? 1 : 0;681var cleanFromEdit = edit.line + startOff, cleanFromOrig = orig.line + startOff;682moveOver(edit, part[1], null, orig);683var endOff = endOfLineClean(diff, i) ? 1 : 0;684var cleanToEdit = edit.line + endOff, cleanToOrig = orig.line + endOff;685if (cleanToEdit > cleanFromEdit) {686if (i) chunks.push({origFrom: startOrig, origTo: cleanFromOrig,687editFrom: startEdit, editTo: cleanFromEdit});688startEdit = cleanToEdit; startOrig = cleanToOrig;689}690} else {691moveOver(tp == DIFF_INSERT ? edit : orig, part[1]);692}693}694if (startEdit <= edit.line || startOrig <= orig.line)695chunks.push({origFrom: startOrig, origTo: orig.line + 1,696editFrom: startEdit, editTo: edit.line + 1});697return chunks;698}699
700function endOfLineClean(diff, i) {701if (i == diff.length - 1) return true;702var next = diff[i + 1][1];703if ((next.length == 1 && i < diff.length - 2) || next.charCodeAt(0) != 10) return false;704if (i == diff.length - 2) return true;705next = diff[i + 2][1];706return (next.length > 1 || i == diff.length - 3) && next.charCodeAt(0) == 10;707}708
709function startOfLineClean(diff, i) {710if (i == 0) return true;711var last = diff[i - 1][1];712if (last.charCodeAt(last.length - 1) != 10) return false;713if (i == 1) return true;714last = diff[i - 2][1];715return last.charCodeAt(last.length - 1) == 10;716}717
718function chunkBoundariesAround(chunks, n, nInEdit) {719var beforeE, afterE, beforeO, afterO;720for (var i = 0; i < chunks.length; i++) {721var chunk = chunks[i];722var fromLocal = nInEdit ? chunk.editFrom : chunk.origFrom;723var toLocal = nInEdit ? chunk.editTo : chunk.origTo;724if (afterE == null) {725if (fromLocal > n) { afterE = chunk.editFrom; afterO = chunk.origFrom; }726else if (toLocal > n) { afterE = chunk.editTo; afterO = chunk.origTo; }727}728if (toLocal <= n) { beforeE = chunk.editTo; beforeO = chunk.origTo; }729else if (fromLocal <= n) { beforeE = chunk.editFrom; beforeO = chunk.origFrom; }730}731return {edit: {before: beforeE, after: afterE}, orig: {before: beforeO, after: afterO}};732}733
734function collapseSingle(cm, from, to) {735cm.addLineClass(from, "wrap", "CodeMirror-merge-collapsed-line");736var widget = document.createElement("span");737widget.className = "CodeMirror-merge-collapsed-widget";738widget.title = cm.phrase("Identical text collapsed. Click to expand.");739var mark = cm.markText(Pos(from, 0), Pos(to - 1), {740inclusiveLeft: true,741inclusiveRight: true,742replacedWith: widget,743clearOnEnter: true744});745function clear() {746mark.clear();747cm.removeLineClass(from, "wrap", "CodeMirror-merge-collapsed-line");748}749if (mark.explicitlyCleared) clear();750CodeMirror.on(widget, "click", clear);751mark.on("clear", clear);752CodeMirror.on(widget, "click", clear);753return {mark: mark, clear: clear};754}755
756function collapseStretch(size, editors) {757var marks = [];758function clear() {759for (var i = 0; i < marks.length; i++) marks[i].clear();760}761for (var i = 0; i < editors.length; i++) {762var editor = editors[i];763var mark = collapseSingle(editor.cm, editor.line, editor.line + size);764marks.push(mark);765mark.mark.on("clear", clear);766}767return marks[0].mark;768}769
770function unclearNearChunks(dv, margin, off, clear) {771for (var i = 0; i < dv.chunks.length; i++) {772var chunk = dv.chunks[i];773for (var l = chunk.editFrom - margin; l < chunk.editTo + margin; l++) {774var pos = l + off;775if (pos >= 0 && pos < clear.length) clear[pos] = false;776}777}778}779
780function collapseIdenticalStretches(mv, margin) {781if (typeof margin != "number") margin = 2;782var clear = [], edit = mv.editor(), off = edit.firstLine();783for (var l = off, e = edit.lastLine(); l <= e; l++) clear.push(true);784if (mv.left) unclearNearChunks(mv.left, margin, off, clear);785if (mv.right) unclearNearChunks(mv.right, margin, off, clear);786
787for (var i = 0; i < clear.length; i++) {788if (clear[i]) {789var line = i + off;790for (var size = 1; i < clear.length - 1 && clear[i + 1]; i++, size++) {}791if (size > margin) {792var editors = [{line: line, cm: edit}];793if (mv.left) editors.push({line: getMatchingOrigLine(line, mv.left.chunks), cm: mv.left.orig});794if (mv.right) editors.push({line: getMatchingOrigLine(line, mv.right.chunks), cm: mv.right.orig});795var mark = collapseStretch(size, editors);796if (mv.options.onCollapse) mv.options.onCollapse(mv, line, size, mark);797}798}799}800}801
802// General utilities803
804function elt(tag, content, className, style) {805var e = document.createElement(tag);806if (className) e.className = className;807if (style) e.style.cssText = style;808if (typeof content == "string") e.appendChild(document.createTextNode(content));809else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);810return e;811}812
813function clear(node) {814for (var count = node.childNodes.length; count > 0; --count)815node.removeChild(node.firstChild);816}817
818function attrs(elt) {819for (var i = 1; i < arguments.length; i += 2)820elt.setAttribute(arguments[i], arguments[i+1]);821}822
823function copyObj(obj, target) {824if (!target) target = {};825for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];826return target;827}828
829function moveOver(pos, str, copy, other) {830var out = copy ? Pos(pos.line, pos.ch) : pos, at = 0;831for (;;) {832var nl = str.indexOf("\n", at);833if (nl == -1) break;834++out.line;835if (other) ++other.line;836at = nl + 1;837}838out.ch = (at ? 0 : out.ch) + (str.length - at);839if (other) other.ch = (at ? 0 : other.ch) + (str.length - at);840return out;841}842
843// Tracks collapsed markers and line widgets, in order to be able to844// accurately align the content of two editors.845
846var F_WIDGET = 1, F_WIDGET_BELOW = 2, F_MARKER = 4847
848function TrackAlignable(cm) {849this.cm = cm850this.alignable = []851this.height = cm.doc.height852var self = this853cm.on("markerAdded", function(_, marker) {854if (!marker.collapsed) return855var found = marker.find(1)856if (found != null) self.set(found.line, F_MARKER)857})858cm.on("markerCleared", function(_, marker, _min, max) {859if (max != null && marker.collapsed)860self.check(max, F_MARKER, self.hasMarker)861})862cm.on("markerChanged", this.signal.bind(this))863cm.on("lineWidgetAdded", function(_, widget, lineNo) {864if (widget.mergeSpacer) return865if (widget.above) self.set(lineNo - 1, F_WIDGET_BELOW)866else self.set(lineNo, F_WIDGET)867})868cm.on("lineWidgetCleared", function(_, widget, lineNo) {869if (widget.mergeSpacer) return870if (widget.above) self.check(lineNo - 1, F_WIDGET_BELOW, self.hasWidgetBelow)871else self.check(lineNo, F_WIDGET, self.hasWidget)872})873cm.on("lineWidgetChanged", this.signal.bind(this))874cm.on("change", function(_, change) {875var start = change.from.line, nBefore = change.to.line - change.from.line876var nAfter = change.text.length - 1, end = start + nAfter877if (nBefore || nAfter) self.map(start, nBefore, nAfter)878self.check(end, F_MARKER, self.hasMarker)879if (nBefore || nAfter) self.check(change.from.line, F_MARKER, self.hasMarker)880})881cm.on("viewportChange", function() {882if (self.cm.doc.height != self.height) self.signal()883})884}885
886TrackAlignable.prototype = {887signal: function() {888CodeMirror.signal(this, "realign")889this.height = this.cm.doc.height890},891
892set: function(n, flags) {893var pos = -1894for (; pos < this.alignable.length; pos += 2) {895var diff = this.alignable[pos] - n896if (diff == 0) {897if ((this.alignable[pos + 1] & flags) == flags) return898this.alignable[pos + 1] |= flags899this.signal()900return901}902if (diff > 0) break903}904this.signal()905this.alignable.splice(pos, 0, n, flags)906},907
908find: function(n) {909for (var i = 0; i < this.alignable.length; i += 2)910if (this.alignable[i] == n) return i911return -1912},913
914check: function(n, flag, pred) {915var found = this.find(n)916if (found == -1 || !(this.alignable[found + 1] & flag)) return917if (!pred.call(this, n)) {918this.signal()919var flags = this.alignable[found + 1] & ~flag920if (flags) this.alignable[found + 1] = flags921else this.alignable.splice(found, 2)922}923},924
925hasMarker: function(n) {926var handle = this.cm.getLineHandle(n)927if (handle.markedSpans) for (var i = 0; i < handle.markedSpans.length; i++)928if (handle.markedSpans[i].marker.collapsed && handle.markedSpans[i].to != null)929return true930return false931},932
933hasWidget: function(n) {934var handle = this.cm.getLineHandle(n)935if (handle.widgets) for (var i = 0; i < handle.widgets.length; i++)936if (!handle.widgets[i].above && !handle.widgets[i].mergeSpacer) return true937return false938},939
940hasWidgetBelow: function(n) {941if (n == this.cm.lastLine()) return false942var handle = this.cm.getLineHandle(n + 1)943if (handle.widgets) for (var i = 0; i < handle.widgets.length; i++)944if (handle.widgets[i].above && !handle.widgets[i].mergeSpacer) return true945return false946},947
948map: function(from, nBefore, nAfter) {949var diff = nAfter - nBefore, to = from + nBefore, widgetFrom = -1, widgetTo = -1950for (var i = 0; i < this.alignable.length; i += 2) {951var n = this.alignable[i]952if (n == from && (this.alignable[i + 1] & F_WIDGET_BELOW)) widgetFrom = i953if (n == to && (this.alignable[i + 1] & F_WIDGET_BELOW)) widgetTo = i954if (n <= from) continue955else if (n < to) this.alignable.splice(i--, 2)956else this.alignable[i] += diff957}958if (widgetFrom > -1) {959var flags = this.alignable[widgetFrom + 1]960if (flags == F_WIDGET_BELOW) this.alignable.splice(widgetFrom, 2)961else this.alignable[widgetFrom + 1] = flags & ~F_WIDGET_BELOW962}963if (widgetTo > -1 && nAfter)964this.set(from + nAfter, F_WIDGET_BELOW)965}966}967
968function posMin(a, b) { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; }969function posMax(a, b) { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; }970function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }971
972function findPrevDiff(chunks, start, isOrig) {973for (var i = chunks.length - 1; i >= 0; i--) {974var chunk = chunks[i];975var to = (isOrig ? chunk.origTo : chunk.editTo) - 1;976if (to < start) return to;977}978}979
980function findNextDiff(chunks, start, isOrig) {981for (var i = 0; i < chunks.length; i++) {982var chunk = chunks[i];983var from = (isOrig ? chunk.origFrom : chunk.editFrom);984if (from > start) return from;985}986}987
988function goNearbyDiff(cm, dir) {989var found = null, views = cm.state.diffViews, line = cm.getCursor().line;990if (views) for (var i = 0; i < views.length; i++) {991var dv = views[i], isOrig = cm == dv.orig;992ensureDiff(dv);993var pos = dir < 0 ? findPrevDiff(dv.chunks, line, isOrig) : findNextDiff(dv.chunks, line, isOrig);994if (pos != null && (found == null || (dir < 0 ? pos > found : pos < found)))995found = pos;996}997if (found != null)998cm.setCursor(found, 0);999else1000return CodeMirror.Pass;1001}1002
1003CodeMirror.commands.goNextDiff = function(cm) {1004return goNearbyDiff(cm, 1);1005};1006CodeMirror.commands.goPrevDiff = function(cm) {1007return goNearbyDiff(cm, -1);1008};1009});1010