merge.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // declare global: diff_match_patch, DIFF_INSERT, DIFF_DELETE, DIFF_EQUAL
  4. (function(mod) {
  5. if (typeof exports == "object" && typeof module == "object") // CommonJS
  6. mod(require("../../lib/codemirror"), require("diff_match_patch"));
  7. else if (typeof define == "function" && define.amd) // AMD
  8. define(["../../lib/codemirror", "diff_match_patch"], mod);
  9. else // Plain browser env
  10. mod(CodeMirror, diff_match_patch);
  11. })(function(CodeMirror, diff_match_patch) {
  12. "use strict";
  13. var Pos = CodeMirror.Pos;
  14. var svgNS = "http://www.w3.org/2000/svg";
  15. function DiffView(mv, type) {
  16. this.mv = mv;
  17. this.type = type;
  18. this.classes = type == "left"
  19. ? {chunk: "CodeMirror-merge-l-chunk",
  20. start: "CodeMirror-merge-l-chunk-start",
  21. end: "CodeMirror-merge-l-chunk-end",
  22. insert: "CodeMirror-merge-l-inserted",
  23. del: "CodeMirror-merge-l-deleted",
  24. connect: "CodeMirror-merge-l-connect"}
  25. : {chunk: "CodeMirror-merge-r-chunk",
  26. start: "CodeMirror-merge-r-chunk-start",
  27. end: "CodeMirror-merge-r-chunk-end",
  28. insert: "CodeMirror-merge-r-inserted",
  29. del: "CodeMirror-merge-r-deleted",
  30. connect: "CodeMirror-merge-r-connect"};
  31. }
  32. DiffView.prototype = {
  33. constructor: DiffView,
  34. init: function(pane, orig, options) {
  35. this.edit = this.mv.edit;
  36. this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: !this.mv.options.allowEditingOriginals}, copyObj(options)));
  37. this.diff = getDiff(asString(orig), asString(options.value));
  38. this.chunks = getChunks(this.diff);
  39. this.diffOutOfDate = this.dealigned = false;
  40. this.showDifferences = options.showDifferences !== false;
  41. this.forceUpdate = registerUpdate(this);
  42. setScrollLock(this, true, false);
  43. registerScroll(this);
  44. },
  45. setShowDifferences: function(val) {
  46. val = val !== false;
  47. if (val != this.showDifferences) {
  48. this.showDifferences = val;
  49. this.forceUpdate("full");
  50. }
  51. }
  52. };
  53. function ensureDiff(dv) {
  54. if (dv.diffOutOfDate) {
  55. dv.diff = getDiff(dv.orig.getValue(), dv.edit.getValue());
  56. dv.chunks = getChunks(dv.diff);
  57. dv.diffOutOfDate = false;
  58. CodeMirror.signal(dv.edit, "updateDiff", dv.diff);
  59. }
  60. }
  61. var updating = false;
  62. function registerUpdate(dv) {
  63. var edit = {from: 0, to: 0, marked: []};
  64. var orig = {from: 0, to: 0, marked: []};
  65. var debounceChange, updatingFast = false;
  66. function update(mode) {
  67. updating = true;
  68. updatingFast = false;
  69. if (mode == "full") {
  70. if (dv.svg) clear(dv.svg);
  71. if (dv.copyButtons) clear(dv.copyButtons);
  72. clearMarks(dv.edit, edit.marked, dv.classes);
  73. clearMarks(dv.orig, orig.marked, dv.classes);
  74. edit.from = edit.to = orig.from = orig.to = 0;
  75. }
  76. ensureDiff(dv);
  77. if (dv.showDifferences) {
  78. updateMarks(dv.edit, dv.diff, edit, DIFF_INSERT, dv.classes);
  79. updateMarks(dv.orig, dv.diff, orig, DIFF_DELETE, dv.classes);
  80. }
  81. makeConnections(dv);
  82. if (dv.mv.options.connect == "align")
  83. alignChunks(dv);
  84. updating = false;
  85. }
  86. function setDealign(fast) {
  87. if (updating) return;
  88. dv.dealigned = true;
  89. set(fast);
  90. }
  91. function set(fast) {
  92. if (updating || updatingFast) return;
  93. clearTimeout(debounceChange);
  94. if (fast === true) updatingFast = true;
  95. debounceChange = setTimeout(update, fast === true ? 20 : 250);
  96. }
  97. function change(_cm, change) {
  98. if (!dv.diffOutOfDate) {
  99. dv.diffOutOfDate = true;
  100. edit.from = edit.to = orig.from = orig.to = 0;
  101. }
  102. // Update faster when a line was added/removed
  103. setDealign(change.text.length - 1 != change.to.line - change.from.line);
  104. }
  105. dv.edit.on("change", change);
  106. dv.orig.on("change", change);
  107. dv.edit.on("markerAdded", setDealign);
  108. dv.edit.on("markerCleared", setDealign);
  109. dv.orig.on("markerAdded", setDealign);
  110. dv.orig.on("markerCleared", setDealign);
  111. dv.edit.on("viewportChange", function() { set(false); });
  112. dv.orig.on("viewportChange", function() { set(false); });
  113. update();
  114. return update;
  115. }
  116. function registerScroll(dv) {
  117. dv.edit.on("scroll", function() {
  118. syncScroll(dv, DIFF_INSERT) && makeConnections(dv);
  119. });
  120. dv.orig.on("scroll", function() {
  121. syncScroll(dv, DIFF_DELETE) && makeConnections(dv);
  122. });
  123. }
  124. function syncScroll(dv, type) {
  125. // Change handler will do a refresh after a timeout when diff is out of date
  126. if (dv.diffOutOfDate) return false;
  127. if (!dv.lockScroll) return true;
  128. var editor, other, now = +new Date;
  129. if (type == DIFF_INSERT) { editor = dv.edit; other = dv.orig; }
  130. else { editor = dv.orig; other = dv.edit; }
  131. // Don't take action if the position of this editor was recently set
  132. // (to prevent feedback loops)
  133. if (editor.state.scrollSetBy == dv && (editor.state.scrollSetAt || 0) + 50 > now) return false;
  134. var sInfo = editor.getScrollInfo();
  135. if (dv.mv.options.connect == "align") {
  136. targetPos = sInfo.top;
  137. } else {
  138. var halfScreen = .5 * sInfo.clientHeight, midY = sInfo.top + halfScreen;
  139. var mid = editor.lineAtHeight(midY, "local");
  140. var around = chunkBoundariesAround(dv.chunks, mid, type == DIFF_INSERT);
  141. var off = getOffsets(editor, type == DIFF_INSERT ? around.edit : around.orig);
  142. var offOther = getOffsets(other, type == DIFF_INSERT ? around.orig : around.edit);
  143. var ratio = (midY - off.top) / (off.bot - off.top);
  144. var targetPos = (offOther.top - halfScreen) + ratio * (offOther.bot - offOther.top);
  145. var botDist, mix;
  146. // Some careful tweaking to make sure no space is left out of view
  147. // when scrolling to top or bottom.
  148. if (targetPos > sInfo.top && (mix = sInfo.top / halfScreen) < 1) {
  149. targetPos = targetPos * mix + sInfo.top * (1 - mix);
  150. } else if ((botDist = sInfo.height - sInfo.clientHeight - sInfo.top) < halfScreen) {
  151. var otherInfo = other.getScrollInfo();
  152. var botDistOther = otherInfo.height - otherInfo.clientHeight - targetPos;
  153. if (botDistOther > botDist && (mix = botDist / halfScreen) < 1)
  154. targetPos = targetPos * mix + (otherInfo.height - otherInfo.clientHeight - botDist) * (1 - mix);
  155. }
  156. }
  157. other.scrollTo(sInfo.left, targetPos);
  158. other.state.scrollSetAt = now;
  159. other.state.scrollSetBy = dv;
  160. return true;
  161. }
  162. function getOffsets(editor, around) {
  163. var bot = around.after;
  164. if (bot == null) bot = editor.lastLine() + 1;
  165. return {top: editor.heightAtLine(around.before || 0, "local"),
  166. bot: editor.heightAtLine(bot, "local")};
  167. }
  168. function setScrollLock(dv, val, action) {
  169. dv.lockScroll = val;
  170. if (val && action != false) syncScroll(dv, DIFF_INSERT) && makeConnections(dv);
  171. dv.lockButton.innerHTML = val ? "\u21db\u21da" : "\u21db&nbsp;&nbsp;\u21da";
  172. }
  173. // Updating the marks for editor content
  174. function clearMarks(editor, arr, classes) {
  175. for (var i = 0; i < arr.length; ++i) {
  176. var mark = arr[i];
  177. if (mark instanceof CodeMirror.TextMarker) {
  178. mark.clear();
  179. } else if (mark.parent) {
  180. editor.removeLineClass(mark, "background", classes.chunk);
  181. editor.removeLineClass(mark, "background", classes.start);
  182. editor.removeLineClass(mark, "background", classes.end);
  183. }
  184. }
  185. arr.length = 0;
  186. }
  187. // FIXME maybe add a margin around viewport to prevent too many updates
  188. function updateMarks(editor, diff, state, type, classes) {
  189. var vp = editor.getViewport();
  190. editor.operation(function() {
  191. if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
  192. clearMarks(editor, state.marked, classes);
  193. markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes);
  194. state.from = vp.from; state.to = vp.to;
  195. } else {
  196. if (vp.from < state.from) {
  197. markChanges(editor, diff, type, state.marked, vp.from, state.from, classes);
  198. state.from = vp.from;
  199. }
  200. if (vp.to > state.to) {
  201. markChanges(editor, diff, type, state.marked, state.to, vp.to, classes);
  202. state.to = vp.to;
  203. }
  204. }
  205. });
  206. }
  207. function markChanges(editor, diff, type, marks, from, to, classes) {
  208. var pos = Pos(0, 0);
  209. var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1));
  210. var cls = type == DIFF_DELETE ? classes.del : classes.insert;
  211. function markChunk(start, end) {
  212. var bfrom = Math.max(from, start), bto = Math.min(to, end);
  213. for (var i = bfrom; i < bto; ++i) {
  214. var line = editor.addLineClass(i, "background", classes.chunk);
  215. if (i == start) editor.addLineClass(line, "background", classes.start);
  216. if (i == end - 1) editor.addLineClass(line, "background", classes.end);
  217. marks.push(line);
  218. }
  219. // When the chunk is empty, make sure a horizontal line shows up
  220. if (start == end && bfrom == end && bto == end) {
  221. if (bfrom)
  222. marks.push(editor.addLineClass(bfrom - 1, "background", classes.end));
  223. else
  224. marks.push(editor.addLineClass(bfrom, "background", classes.start));
  225. }
  226. }
  227. var chunkStart = 0;
  228. for (var i = 0; i < diff.length; ++i) {
  229. var part = diff[i], tp = part[0], str = part[1];
  230. if (tp == DIFF_EQUAL) {
  231. var cleanFrom = pos.line + (startOfLineClean(diff, i) ? 0 : 1);
  232. moveOver(pos, str);
  233. var cleanTo = pos.line + (endOfLineClean(diff, i) ? 1 : 0);
  234. if (cleanTo > cleanFrom) {
  235. if (i) markChunk(chunkStart, cleanFrom);
  236. chunkStart = cleanTo;
  237. }
  238. } else {
  239. if (tp == type) {
  240. var end = moveOver(pos, str, true);
  241. var a = posMax(top, pos), b = posMin(bot, end);
  242. if (!posEq(a, b))
  243. marks.push(editor.markText(a, b, {className: cls}));
  244. pos = end;
  245. }
  246. }
  247. }
  248. if (chunkStart <= pos.line) markChunk(chunkStart, pos.line + 1);
  249. }
  250. // Updating the gap between editor and original
  251. function makeConnections(dv) {
  252. if (!dv.showDifferences) return;
  253. if (dv.svg) {
  254. clear(dv.svg);
  255. var w = dv.gap.offsetWidth;
  256. attrs(dv.svg, "width", w, "height", dv.gap.offsetHeight);
  257. }
  258. if (dv.copyButtons) clear(dv.copyButtons);
  259. var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport();
  260. var sTopEdit = dv.edit.getScrollInfo().top, sTopOrig = dv.orig.getScrollInfo().top;
  261. for (var i = 0; i < dv.chunks.length; i++) {
  262. var ch = dv.chunks[i];
  263. if (ch.editFrom <= vpEdit.to && ch.editTo >= vpEdit.from &&
  264. ch.origFrom <= vpOrig.to && ch.origTo >= vpOrig.from)
  265. drawConnectorsForChunk(dv, ch, sTopOrig, sTopEdit, w);
  266. }
  267. }
  268. function getMatchingOrigLine(editLine, chunks) {
  269. var editStart = 0, origStart = 0;
  270. for (var i = 0; i < chunks.length; i++) {
  271. var chunk = chunks[i];
  272. if (chunk.editTo > editLine && chunk.editFrom <= editLine) return null;
  273. if (chunk.editFrom > editLine) break;
  274. editStart = chunk.editTo;
  275. origStart = chunk.origTo;
  276. }
  277. return origStart + (editLine - editStart);
  278. }
  279. function findAlignedLines(dv, other) {
  280. var linesToAlign = [];
  281. for (var i = 0; i < dv.chunks.length; i++) {
  282. var chunk = dv.chunks[i];
  283. linesToAlign.push([chunk.origTo, chunk.editTo, other ? getMatchingOrigLine(chunk.editTo, other.chunks) : null]);
  284. }
  285. if (other) {
  286. for (var i = 0; i < other.chunks.length; i++) {
  287. var chunk = other.chunks[i];
  288. for (var j = 0; j < linesToAlign.length; j++) {
  289. var align = linesToAlign[j];
  290. if (align[1] == chunk.editTo) {
  291. j = -1;
  292. break;
  293. } else if (align[1] > chunk.editTo) {
  294. break;
  295. }
  296. }
  297. if (j > -1)
  298. linesToAlign.splice(j - 1, 0, [getMatchingOrigLine(chunk.editTo, dv.chunks), chunk.editTo, chunk.origTo]);
  299. }
  300. }
  301. return linesToAlign;
  302. }
  303. function alignChunks(dv, force) {
  304. if (!dv.dealigned && !force) return;
  305. if (!dv.orig.curOp) return dv.orig.operation(function() {
  306. alignChunks(dv, force);
  307. });
  308. dv.dealigned = false;
  309. var other = dv.mv.left == dv ? dv.mv.right : dv.mv.left;
  310. if (other) {
  311. ensureDiff(other);
  312. other.dealigned = false;
  313. }
  314. var linesToAlign = findAlignedLines(dv, other);
  315. // Clear old aligners
  316. var aligners = dv.mv.aligners;
  317. for (var i = 0; i < aligners.length; i++)
  318. aligners[i].clear();
  319. aligners.length = 0;
  320. var cm = [dv.orig, dv.edit], scroll = [];
  321. if (other) cm.push(other.orig);
  322. for (var i = 0; i < cm.length; i++)
  323. scroll.push(cm[i].getScrollInfo().top);
  324. for (var ln = 0; ln < linesToAlign.length; ln++)
  325. alignLines(cm, linesToAlign[ln], aligners);
  326. for (var i = 0; i < cm.length; i++)
  327. cm[i].scrollTo(null, scroll[i]);
  328. }
  329. function alignLines(cm, lines, aligners) {
  330. var maxOffset = 0, offset = [];
  331. for (var i = 0; i < cm.length; i++) if (lines[i] != null) {
  332. var off = cm[i].heightAtLine(lines[i], "local");
  333. offset[i] = off;
  334. maxOffset = Math.max(maxOffset, off);
  335. }
  336. for (var i = 0; i < cm.length; i++) if (lines[i] != null) {
  337. var diff = maxOffset - offset[i];
  338. if (diff > 1)
  339. aligners.push(padAbove(cm[i], lines[i], diff));
  340. }
  341. }
  342. function padAbove(cm, line, size) {
  343. var above = true;
  344. if (line > cm.lastLine()) {
  345. line--;
  346. above = false;
  347. }
  348. var elt = document.createElement("div");
  349. elt.className = "CodeMirror-merge-spacer";
  350. elt.style.height = size + "px"; elt.style.minWidth = "1px";
  351. return cm.addLineWidget(line, elt, {height: size, above: above});
  352. }
  353. function drawConnectorsForChunk(dv, chunk, sTopOrig, sTopEdit, w) {
  354. var flip = dv.type == "left";
  355. var top = dv.orig.heightAtLine(chunk.origFrom, "local") - sTopOrig;
  356. if (dv.svg) {
  357. var topLpx = top;
  358. var topRpx = dv.edit.heightAtLine(chunk.editFrom, "local") - sTopEdit;
  359. if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }
  360. var botLpx = dv.orig.heightAtLine(chunk.origTo, "local") - sTopOrig;
  361. var botRpx = dv.edit.heightAtLine(chunk.editTo, "local") - sTopEdit;
  362. if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }
  363. var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx;
  364. var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx;
  365. attrs(dv.svg.appendChild(document.createElementNS(svgNS, "path")),
  366. "d", "M -1 " + topRpx + curveTop + " L " + (w + 2) + " " + botLpx + curveBot + " z",
  367. "class", dv.classes.connect);
  368. }
  369. if (dv.copyButtons) {
  370. var copy = dv.copyButtons.appendChild(elt("div", dv.type == "left" ? "\u21dd" : "\u21dc",
  371. "CodeMirror-merge-copy"));
  372. var editOriginals = dv.mv.options.allowEditingOriginals;
  373. copy.title = editOriginals ? "Push to left" : "Revert chunk";
  374. copy.chunk = chunk;
  375. copy.style.top = top + "px";
  376. if (editOriginals) {
  377. var topReverse = dv.orig.heightAtLine(chunk.editFrom, "local") - sTopEdit;
  378. var copyReverse = dv.copyButtons.appendChild(elt("div", dv.type == "right" ? "\u21dd" : "\u21dc",
  379. "CodeMirror-merge-copy-reverse"));
  380. copyReverse.title = "Push to right";
  381. copyReverse.chunk = {editFrom: chunk.origFrom, editTo: chunk.origTo,
  382. origFrom: chunk.editFrom, origTo: chunk.editTo};
  383. copyReverse.style.top = topReverse + "px";
  384. dv.type == "right" ? copyReverse.style.left = "2px" : copyReverse.style.right = "2px";
  385. }
  386. }
  387. }
  388. function copyChunk(dv, to, from, chunk) {
  389. if (dv.diffOutOfDate) return;
  390. to.replaceRange(from.getRange(Pos(chunk.origFrom, 0), Pos(chunk.origTo, 0)),
  391. Pos(chunk.editFrom, 0), Pos(chunk.editTo, 0));
  392. }
  393. // Merge view, containing 0, 1, or 2 diff views.
  394. var MergeView = CodeMirror.MergeView = function(node, options) {
  395. if (!(this instanceof MergeView)) return new MergeView(node, options);
  396. this.options = options;
  397. var origLeft = options.origLeft, origRight = options.origRight == null ? options.orig : options.origRight;
  398. var hasLeft = origLeft != null, hasRight = origRight != null;
  399. var panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0);
  400. var wrap = [], left = this.left = null, right = this.right = null;
  401. var self = this;
  402. if (hasLeft) {
  403. left = this.left = new DiffView(this, "left");
  404. var leftPane = elt("div", null, "CodeMirror-merge-pane");
  405. wrap.push(leftPane);
  406. wrap.push(buildGap(left));
  407. }
  408. var editPane = elt("div", null, "CodeMirror-merge-pane");
  409. wrap.push(editPane);
  410. if (hasRight) {
  411. right = this.right = new DiffView(this, "right");
  412. wrap.push(buildGap(right));
  413. var rightPane = elt("div", null, "CodeMirror-merge-pane");
  414. wrap.push(rightPane);
  415. }
  416. (hasRight ? rightPane : editPane).className += " CodeMirror-merge-pane-rightmost";
  417. wrap.push(elt("div", null, null, "height: 0; clear: both;"));
  418. var wrapElt = this.wrap = node.appendChild(elt("div", wrap, "CodeMirror-merge CodeMirror-merge-" + panes + "pane"));
  419. this.edit = CodeMirror(editPane, copyObj(options));
  420. if (left) left.init(leftPane, origLeft, options);
  421. if (right) right.init(rightPane, origRight, options);
  422. if (options.collapseIdentical) {
  423. updating = true;
  424. this.editor().operation(function() {
  425. collapseIdenticalStretches(self, options.collapseIdentical);
  426. });
  427. updating = false;
  428. }
  429. if (options.connect == "align") {
  430. this.aligners = [];
  431. alignChunks(this.left || this.right, true);
  432. }
  433. var onResize = function() {
  434. if (left) makeConnections(left);
  435. if (right) makeConnections(right);
  436. };
  437. CodeMirror.on(window, "resize", onResize);
  438. var resizeInterval = setInterval(function() {
  439. for (var p = wrapElt.parentNode; p && p != document.body; p = p.parentNode) {}
  440. if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, "resize", onResize); }
  441. }, 5000);
  442. };
  443. function buildGap(dv) {
  444. var lock = dv.lockButton = elt("div", null, "CodeMirror-merge-scrolllock");
  445. lock.title = "Toggle locked scrolling";
  446. var lockWrap = elt("div", [lock], "CodeMirror-merge-scrolllock-wrap");
  447. CodeMirror.on(lock, "click", function() { setScrollLock(dv, !dv.lockScroll); });
  448. var gapElts = [lockWrap];
  449. if (dv.mv.options.revertButtons !== false) {
  450. dv.copyButtons = elt("div", null, "CodeMirror-merge-copybuttons-" + dv.type);
  451. CodeMirror.on(dv.copyButtons, "click", function(e) {
  452. var node = e.target || e.srcElement;
  453. if (!node.chunk) return;
  454. if (node.className == "CodeMirror-merge-copy-reverse") {
  455. copyChunk(dv, dv.orig, dv.edit, node.chunk);
  456. return;
  457. }
  458. copyChunk(dv, dv.edit, dv.orig, node.chunk);
  459. });
  460. gapElts.unshift(dv.copyButtons);
  461. }
  462. if (dv.mv.options.connect != "align") {
  463. var svg = document.createElementNS && document.createElementNS(svgNS, "svg");
  464. if (svg && !svg.createSVGRect) svg = null;
  465. dv.svg = svg;
  466. if (svg) gapElts.push(svg);
  467. }
  468. return dv.gap = elt("div", gapElts, "CodeMirror-merge-gap");
  469. }
  470. MergeView.prototype = {
  471. constuctor: MergeView,
  472. editor: function() { return this.edit; },
  473. rightOriginal: function() { return this.right && this.right.orig; },
  474. leftOriginal: function() { return this.left && this.left.orig; },
  475. setShowDifferences: function(val) {
  476. if (this.right) this.right.setShowDifferences(val);
  477. if (this.left) this.left.setShowDifferences(val);
  478. },
  479. rightChunks: function() {
  480. if (this.right) { ensureDiff(this.right); return this.right.chunks; }
  481. },
  482. leftChunks: function() {
  483. if (this.left) { ensureDiff(this.left); return this.left.chunks; }
  484. }
  485. };
  486. function asString(obj) {
  487. if (typeof obj == "string") return obj;
  488. else return obj.getValue();
  489. }
  490. // Operations on diffs
  491. var dmp = new diff_match_patch();
  492. function getDiff(a, b) {
  493. var diff = dmp.diff_main(a, b);
  494. dmp.diff_cleanupSemantic(diff);
  495. // The library sometimes leaves in empty parts, which confuse the algorithm
  496. for (var i = 0; i < diff.length; ++i) {
  497. var part = diff[i];
  498. if (!part[1]) {
  499. diff.splice(i--, 1);
  500. } else if (i && diff[i - 1][0] == part[0]) {
  501. diff.splice(i--, 1);
  502. diff[i][1] += part[1];
  503. }
  504. }
  505. return diff;
  506. }
  507. function getChunks(diff) {
  508. var chunks = [];
  509. var startEdit = 0, startOrig = 0;
  510. var edit = Pos(0, 0), orig = Pos(0, 0);
  511. for (var i = 0; i < diff.length; ++i) {
  512. var part = diff[i], tp = part[0];
  513. if (tp == DIFF_EQUAL) {
  514. var startOff = startOfLineClean(diff, i) ? 0 : 1;
  515. var cleanFromEdit = edit.line + startOff, cleanFromOrig = orig.line + startOff;
  516. moveOver(edit, part[1], null, orig);
  517. var endOff = endOfLineClean(diff, i) ? 1 : 0;
  518. var cleanToEdit = edit.line + endOff, cleanToOrig = orig.line + endOff;
  519. if (cleanToEdit > cleanFromEdit) {
  520. if (i) chunks.push({origFrom: startOrig, origTo: cleanFromOrig,
  521. editFrom: startEdit, editTo: cleanFromEdit});
  522. startEdit = cleanToEdit; startOrig = cleanToOrig;
  523. }
  524. } else {
  525. moveOver(tp == DIFF_INSERT ? edit : orig, part[1]);
  526. }
  527. }
  528. if (startEdit <= edit.line || startOrig <= orig.line)
  529. chunks.push({origFrom: startOrig, origTo: orig.line + 1,
  530. editFrom: startEdit, editTo: edit.line + 1});
  531. return chunks;
  532. }
  533. function endOfLineClean(diff, i) {
  534. if (i == diff.length - 1) return true;
  535. var next = diff[i + 1][1];
  536. if (next.length == 1 || next.charCodeAt(0) != 10) return false;
  537. if (i == diff.length - 2) return true;
  538. next = diff[i + 2][1];
  539. return next.length > 1 && next.charCodeAt(0) == 10;
  540. }
  541. function startOfLineClean(diff, i) {
  542. if (i == 0) return true;
  543. var last = diff[i - 1][1];
  544. if (last.charCodeAt(last.length - 1) != 10) return false;
  545. if (i == 1) return true;
  546. last = diff[i - 2][1];
  547. return last.charCodeAt(last.length - 1) == 10;
  548. }
  549. function chunkBoundariesAround(chunks, n, nInEdit) {
  550. var beforeE, afterE, beforeO, afterO;
  551. for (var i = 0; i < chunks.length; i++) {
  552. var chunk = chunks[i];
  553. var fromLocal = nInEdit ? chunk.editFrom : chunk.origFrom;
  554. var toLocal = nInEdit ? chunk.editTo : chunk.origTo;
  555. if (afterE == null) {
  556. if (fromLocal > n) { afterE = chunk.editFrom; afterO = chunk.origFrom; }
  557. else if (toLocal > n) { afterE = chunk.editTo; afterO = chunk.origTo; }
  558. }
  559. if (toLocal <= n) { beforeE = chunk.editTo; beforeO = chunk.origTo; }
  560. else if (fromLocal <= n) { beforeE = chunk.editFrom; beforeO = chunk.origFrom; }
  561. }
  562. return {edit: {before: beforeE, after: afterE}, orig: {before: beforeO, after: afterO}};
  563. }
  564. function collapseSingle(cm, from, to) {
  565. cm.addLineClass(from, "wrap", "CodeMirror-merge-collapsed-line");
  566. var widget = document.createElement("span");
  567. widget.className = "CodeMirror-merge-collapsed-widget";
  568. widget.title = "Identical text collapsed. Click to expand.";
  569. var mark = cm.markText(Pos(from, 0), Pos(to - 1), {
  570. inclusiveLeft: true,
  571. inclusiveRight: true,
  572. replacedWith: widget,
  573. clearOnEnter: true
  574. });
  575. function clear() {
  576. mark.clear();
  577. cm.removeLineClass(from, "wrap", "CodeMirror-merge-collapsed-line");
  578. }
  579. widget.addEventListener("click", clear);
  580. return {mark: mark, clear: clear};
  581. }
  582. function collapseStretch(size, editors) {
  583. var marks = [];
  584. function clear() {
  585. for (var i = 0; i < marks.length; i++) marks[i].clear();
  586. }
  587. for (var i = 0; i < editors.length; i++) {
  588. var editor = editors[i];
  589. var mark = collapseSingle(editor.cm, editor.line, editor.line + size);
  590. marks.push(mark);
  591. mark.mark.on("clear", clear);
  592. }
  593. return marks[0].mark;
  594. }
  595. function unclearNearChunks(dv, margin, off, clear) {
  596. for (var i = 0; i < dv.chunks.length; i++) {
  597. var chunk = dv.chunks[i];
  598. for (var l = chunk.editFrom - margin; l < chunk.editTo + margin; l++) {
  599. var pos = l + off;
  600. if (pos >= 0 && pos < clear.length) clear[pos] = false;
  601. }
  602. }
  603. }
  604. function collapseIdenticalStretches(mv, margin) {
  605. if (typeof margin != "number") margin = 2;
  606. var clear = [], edit = mv.editor(), off = edit.firstLine();
  607. for (var l = off, e = edit.lastLine(); l <= e; l++) clear.push(true);
  608. if (mv.left) unclearNearChunks(mv.left, margin, off, clear);
  609. if (mv.right) unclearNearChunks(mv.right, margin, off, clear);
  610. for (var i = 0; i < clear.length; i++) {
  611. if (clear[i]) {
  612. var line = i + off;
  613. for (var size = 1; i < clear.length - 1 && clear[i + 1]; i++, size++) {}
  614. if (size > margin) {
  615. var editors = [{line: line, cm: edit}];
  616. if (mv.left) editors.push({line: getMatchingOrigLine(line, mv.left.chunks), cm: mv.left.orig});
  617. if (mv.right) editors.push({line: getMatchingOrigLine(line, mv.right.chunks), cm: mv.right.orig});
  618. var mark = collapseStretch(size, editors);
  619. if (mv.options.onCollapse) mv.options.onCollapse(mv, line, size, mark);
  620. }
  621. }
  622. }
  623. }
  624. // General utilities
  625. function elt(tag, content, className, style) {
  626. var e = document.createElement(tag);
  627. if (className) e.className = className;
  628. if (style) e.style.cssText = style;
  629. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  630. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  631. return e;
  632. }
  633. function clear(node) {
  634. for (var count = node.childNodes.length; count > 0; --count)
  635. node.removeChild(node.firstChild);
  636. }
  637. function attrs(elt) {
  638. for (var i = 1; i < arguments.length; i += 2)
  639. elt.setAttribute(arguments[i], arguments[i+1]);
  640. }
  641. function copyObj(obj, target) {
  642. if (!target) target = {};
  643. for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
  644. return target;
  645. }
  646. function moveOver(pos, str, copy, other) {
  647. var out = copy ? Pos(pos.line, pos.ch) : pos, at = 0;
  648. for (;;) {
  649. var nl = str.indexOf("\n", at);
  650. if (nl == -1) break;
  651. ++out.line;
  652. if (other) ++other.line;
  653. at = nl + 1;
  654. }
  655. out.ch = (at ? 0 : out.ch) + (str.length - at);
  656. if (other) other.ch = (at ? 0 : other.ch) + (str.length - at);
  657. return out;
  658. }
  659. function posMin(a, b) { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; }
  660. function posMax(a, b) { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; }
  661. function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
  662. });