You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1018 lines
38 KiB

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