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.

merge.js 37KB

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