1
0

merge.js 24 KB

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