本站源代码
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.

1003 lines
37KB

  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 = [];
  407. if (other) cm.push(other.orig);
  408. for (var i = 0; i < cm.length; i++)
  409. scroll.push(cm[i].getScrollInfo().top);
  410. for (var ln = 0; ln < linesToAlign.length; ln++)
  411. alignLines(cm, linesToAlign[ln], aligners);
  412. for (var i = 0; i < cm.length; i++)
  413. cm[i].scrollTo(null, scroll[i]);
  414. }
  415. function alignLines(cm, lines, aligners) {
  416. var maxOffset = 0, offset = [];
  417. for (var i = 0; i < cm.length; i++) if (lines[i] != null) {
  418. var off = cm[i].heightAtLine(lines[i], "local");
  419. offset[i] = off;
  420. maxOffset = Math.max(maxOffset, off);
  421. }
  422. for (var i = 0; i < cm.length; i++) if (lines[i] != null) {
  423. var diff = maxOffset - offset[i];
  424. if (diff > 1)
  425. aligners.push(padAbove(cm[i], lines[i], diff));
  426. }
  427. }
  428. function padAbove(cm, line, size) {
  429. var above = true;
  430. if (line > cm.lastLine()) {
  431. line--;
  432. above = false;
  433. }
  434. var elt = document.createElement("div");
  435. elt.className = "CodeMirror-merge-spacer";
  436. elt.style.height = size + "px"; elt.style.minWidth = "1px";
  437. return cm.addLineWidget(line, elt, {height: size, above: above, mergeSpacer: true, handleMouseEvents: true});
  438. }
  439. function drawConnectorsForChunk(dv, chunk, sTopOrig, sTopEdit, w) {
  440. var flip = dv.type == "left";
  441. var top = dv.orig.heightAtLine(chunk.origFrom, "local", true) - sTopOrig;
  442. if (dv.svg) {
  443. var topLpx = top;
  444. var topRpx = dv.edit.heightAtLine(chunk.editFrom, "local", true) - sTopEdit;
  445. if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }
  446. var botLpx = dv.orig.heightAtLine(chunk.origTo, "local", true) - sTopOrig;
  447. var botRpx = dv.edit.heightAtLine(chunk.editTo, "local", true) - sTopEdit;
  448. if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }
  449. var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx;
  450. var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx;
  451. attrs(dv.svg.appendChild(document.createElementNS(svgNS, "path")),
  452. "d", "M -1 " + topRpx + curveTop + " L " + (w + 2) + " " + botLpx + curveBot + " z",
  453. "class", dv.classes.connect);
  454. }
  455. if (dv.copyButtons) {
  456. var copy = dv.copyButtons.appendChild(elt("div", dv.type == "left" ? "\u21dd" : "\u21dc",
  457. "CodeMirror-merge-copy"));
  458. var editOriginals = dv.mv.options.allowEditingOriginals;
  459. copy.title = dv.edit.phrase(editOriginals ? "Push to left" : "Revert chunk");
  460. copy.chunk = chunk;
  461. copy.style.top = (chunk.origTo > chunk.origFrom ? top : dv.edit.heightAtLine(chunk.editFrom, "local") - sTopEdit) + "px";
  462. if (editOriginals) {
  463. var topReverse = dv.edit.heightAtLine(chunk.editFrom, "local") - sTopEdit;
  464. var copyReverse = dv.copyButtons.appendChild(elt("div", dv.type == "right" ? "\u21dd" : "\u21dc",
  465. "CodeMirror-merge-copy-reverse"));
  466. copyReverse.title = "Push to right";
  467. copyReverse.chunk = {editFrom: chunk.origFrom, editTo: chunk.origTo,
  468. origFrom: chunk.editFrom, origTo: chunk.editTo};
  469. copyReverse.style.top = topReverse + "px";
  470. dv.type == "right" ? copyReverse.style.left = "2px" : copyReverse.style.right = "2px";
  471. }
  472. }
  473. }
  474. function copyChunk(dv, to, from, chunk) {
  475. if (dv.diffOutOfDate) return;
  476. var origStart = chunk.origTo > from.lastLine() ? Pos(chunk.origFrom - 1) : Pos(chunk.origFrom, 0)
  477. var origEnd = Pos(chunk.origTo, 0)
  478. var editStart = chunk.editTo > to.lastLine() ? Pos(chunk.editFrom - 1) : Pos(chunk.editFrom, 0)
  479. var editEnd = Pos(chunk.editTo, 0)
  480. var handler = dv.mv.options.revertChunk
  481. if (handler)
  482. handler(dv.mv, from, origStart, origEnd, to, editStart, editEnd)
  483. else
  484. to.replaceRange(from.getRange(origStart, origEnd), editStart, editEnd)
  485. }
  486. // Merge view, containing 0, 1, or 2 diff views.
  487. var MergeView = CodeMirror.MergeView = function(node, options) {
  488. if (!(this instanceof MergeView)) return new MergeView(node, options);
  489. this.options = options;
  490. var origLeft = options.origLeft, origRight = options.origRight == null ? options.orig : options.origRight;
  491. var hasLeft = origLeft != null, hasRight = origRight != null;
  492. var panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0);
  493. var wrap = [], left = this.left = null, right = this.right = null;
  494. var self = this;
  495. if (hasLeft) {
  496. left = this.left = new DiffView(this, "left");
  497. var leftPane = elt("div", null, "CodeMirror-merge-pane CodeMirror-merge-left");
  498. wrap.push(leftPane);
  499. wrap.push(buildGap(left));
  500. }
  501. var editPane = elt("div", null, "CodeMirror-merge-pane CodeMirror-merge-editor");
  502. wrap.push(editPane);
  503. if (hasRight) {
  504. right = this.right = new DiffView(this, "right");
  505. wrap.push(buildGap(right));
  506. var rightPane = elt("div", null, "CodeMirror-merge-pane CodeMirror-merge-right");
  507. wrap.push(rightPane);
  508. }
  509. (hasRight ? rightPane : editPane).className += " CodeMirror-merge-pane-rightmost";
  510. wrap.push(elt("div", null, null, "height: 0; clear: both;"));
  511. var wrapElt = this.wrap = node.appendChild(elt("div", wrap, "CodeMirror-merge CodeMirror-merge-" + panes + "pane"));
  512. this.edit = CodeMirror(editPane, copyObj(options));
  513. if (left) left.init(leftPane, origLeft, options);
  514. if (right) right.init(rightPane, origRight, options);
  515. if (options.collapseIdentical)
  516. this.editor().operation(function() {
  517. collapseIdenticalStretches(self, options.collapseIdentical);
  518. });
  519. if (options.connect == "align") {
  520. this.aligners = [];
  521. alignChunks(this.left || this.right, true);
  522. }
  523. if (left) left.registerEvents(right)
  524. if (right) right.registerEvents(left)
  525. var onResize = function() {
  526. if (left) makeConnections(left);
  527. if (right) makeConnections(right);
  528. };
  529. CodeMirror.on(window, "resize", onResize);
  530. var resizeInterval = setInterval(function() {
  531. for (var p = wrapElt.parentNode; p && p != document.body; p = p.parentNode) {}
  532. if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, "resize", onResize); }
  533. }, 5000);
  534. };
  535. function buildGap(dv) {
  536. var lock = dv.lockButton = elt("div", null, "CodeMirror-merge-scrolllock");
  537. var lockWrap = elt("div", [lock], "CodeMirror-merge-scrolllock-wrap");
  538. CodeMirror.on(lock, "click", function() { setScrollLock(dv, !dv.lockScroll); });
  539. var gapElts = [lockWrap];
  540. if (dv.mv.options.revertButtons !== false) {
  541. dv.copyButtons = elt("div", null, "CodeMirror-merge-copybuttons-" + dv.type);
  542. CodeMirror.on(dv.copyButtons, "click", function(e) {
  543. var node = e.target || e.srcElement;
  544. if (!node.chunk) return;
  545. if (node.className == "CodeMirror-merge-copy-reverse") {
  546. copyChunk(dv, dv.orig, dv.edit, node.chunk);
  547. return;
  548. }
  549. copyChunk(dv, dv.edit, dv.orig, node.chunk);
  550. });
  551. gapElts.unshift(dv.copyButtons);
  552. }
  553. if (dv.mv.options.connect != "align") {
  554. var svg = document.createElementNS && document.createElementNS(svgNS, "svg");
  555. if (svg && !svg.createSVGRect) svg = null;
  556. dv.svg = svg;
  557. if (svg) gapElts.push(svg);
  558. }
  559. return dv.gap = elt("div", gapElts, "CodeMirror-merge-gap");
  560. }
  561. MergeView.prototype = {
  562. constructor: MergeView,
  563. editor: function() { return this.edit; },
  564. rightOriginal: function() { return this.right && this.right.orig; },
  565. leftOriginal: function() { return this.left && this.left.orig; },
  566. setShowDifferences: function(val) {
  567. if (this.right) this.right.setShowDifferences(val);
  568. if (this.left) this.left.setShowDifferences(val);
  569. },
  570. rightChunks: function() {
  571. if (this.right) { ensureDiff(this.right); return this.right.chunks; }
  572. },
  573. leftChunks: function() {
  574. if (this.left) { ensureDiff(this.left); return this.left.chunks; }
  575. }
  576. };
  577. function asString(obj) {
  578. if (typeof obj == "string") return obj;
  579. else return obj.getValue();
  580. }
  581. // Operations on diffs
  582. var dmp;
  583. function getDiff(a, b, ignoreWhitespace) {
  584. if (!dmp) dmp = new diff_match_patch();
  585. var diff = dmp.diff_main(a, b);
  586. // The library sometimes leaves in empty parts, which confuse the algorithm
  587. for (var i = 0; i < diff.length; ++i) {
  588. var part = diff[i];
  589. if (ignoreWhitespace ? !/[^ \t]/.test(part[1]) : !part[1]) {
  590. diff.splice(i--, 1);
  591. } else if (i && diff[i - 1][0] == part[0]) {
  592. diff.splice(i--, 1);
  593. diff[i][1] += part[1];
  594. }
  595. }
  596. return diff;
  597. }
  598. function getChunks(diff) {
  599. var chunks = [];
  600. if (!diff.length) return chunks;
  601. var startEdit = 0, startOrig = 0;
  602. var edit = Pos(0, 0), orig = Pos(0, 0);
  603. for (var i = 0; i < diff.length; ++i) {
  604. var part = diff[i], tp = part[0];
  605. if (tp == DIFF_EQUAL) {
  606. var startOff = !startOfLineClean(diff, i) || edit.line < startEdit || orig.line < startOrig ? 1 : 0;
  607. var cleanFromEdit = edit.line + startOff, cleanFromOrig = orig.line + startOff;
  608. moveOver(edit, part[1], null, orig);
  609. var endOff = endOfLineClean(diff, i) ? 1 : 0;
  610. var cleanToEdit = edit.line + endOff, cleanToOrig = orig.line + endOff;
  611. if (cleanToEdit > cleanFromEdit) {
  612. if (i) chunks.push({origFrom: startOrig, origTo: cleanFromOrig,
  613. editFrom: startEdit, editTo: cleanFromEdit});
  614. startEdit = cleanToEdit; startOrig = cleanToOrig;
  615. }
  616. } else {
  617. moveOver(tp == DIFF_INSERT ? edit : orig, part[1]);
  618. }
  619. }
  620. if (startEdit <= edit.line || startOrig <= orig.line)
  621. chunks.push({origFrom: startOrig, origTo: orig.line + 1,
  622. editFrom: startEdit, editTo: edit.line + 1});
  623. return chunks;
  624. }
  625. function endOfLineClean(diff, i) {
  626. if (i == diff.length - 1) return true;
  627. var next = diff[i + 1][1];
  628. if ((next.length == 1 && i < diff.length - 2) || next.charCodeAt(0) != 10) return false;
  629. if (i == diff.length - 2) return true;
  630. next = diff[i + 2][1];
  631. return (next.length > 1 || i == diff.length - 3) && next.charCodeAt(0) == 10;
  632. }
  633. function startOfLineClean(diff, i) {
  634. if (i == 0) return true;
  635. var last = diff[i - 1][1];
  636. if (last.charCodeAt(last.length - 1) != 10) return false;
  637. if (i == 1) return true;
  638. last = diff[i - 2][1];
  639. return last.charCodeAt(last.length - 1) == 10;
  640. }
  641. function chunkBoundariesAround(chunks, n, nInEdit) {
  642. var beforeE, afterE, beforeO, afterO;
  643. for (var i = 0; i < chunks.length; i++) {
  644. var chunk = chunks[i];
  645. var fromLocal = nInEdit ? chunk.editFrom : chunk.origFrom;
  646. var toLocal = nInEdit ? chunk.editTo : chunk.origTo;
  647. if (afterE == null) {
  648. if (fromLocal > n) { afterE = chunk.editFrom; afterO = chunk.origFrom; }
  649. else if (toLocal > n) { afterE = chunk.editTo; afterO = chunk.origTo; }
  650. }
  651. if (toLocal <= n) { beforeE = chunk.editTo; beforeO = chunk.origTo; }
  652. else if (fromLocal <= n) { beforeE = chunk.editFrom; beforeO = chunk.origFrom; }
  653. }
  654. return {edit: {before: beforeE, after: afterE}, orig: {before: beforeO, after: afterO}};
  655. }
  656. function collapseSingle(cm, from, to) {
  657. cm.addLineClass(from, "wrap", "CodeMirror-merge-collapsed-line");
  658. var widget = document.createElement("span");
  659. widget.className = "CodeMirror-merge-collapsed-widget";
  660. widget.title = cm.phrase("Identical text collapsed. Click to expand.");
  661. var mark = cm.markText(Pos(from, 0), Pos(to - 1), {
  662. inclusiveLeft: true,
  663. inclusiveRight: true,
  664. replacedWith: widget,
  665. clearOnEnter: true
  666. });
  667. function clear() {
  668. mark.clear();
  669. cm.removeLineClass(from, "wrap", "CodeMirror-merge-collapsed-line");
  670. }
  671. if (mark.explicitlyCleared) clear();
  672. CodeMirror.on(widget, "click", clear);
  673. mark.on("clear", clear);
  674. CodeMirror.on(widget, "click", clear);
  675. return {mark: mark, clear: clear};
  676. }
  677. function collapseStretch(size, editors) {
  678. var marks = [];
  679. function clear() {
  680. for (var i = 0; i < marks.length; i++) marks[i].clear();
  681. }
  682. for (var i = 0; i < editors.length; i++) {
  683. var editor = editors[i];
  684. var mark = collapseSingle(editor.cm, editor.line, editor.line + size);
  685. marks.push(mark);
  686. mark.mark.on("clear", clear);
  687. }
  688. return marks[0].mark;
  689. }
  690. function unclearNearChunks(dv, margin, off, clear) {
  691. for (var i = 0; i < dv.chunks.length; i++) {
  692. var chunk = dv.chunks[i];
  693. for (var l = chunk.editFrom - margin; l < chunk.editTo + margin; l++) {
  694. var pos = l + off;
  695. if (pos >= 0 && pos < clear.length) clear[pos] = false;
  696. }
  697. }
  698. }
  699. function collapseIdenticalStretches(mv, margin) {
  700. if (typeof margin != "number") margin = 2;
  701. var clear = [], edit = mv.editor(), off = edit.firstLine();
  702. for (var l = off, e = edit.lastLine(); l <= e; l++) clear.push(true);
  703. if (mv.left) unclearNearChunks(mv.left, margin, off, clear);
  704. if (mv.right) unclearNearChunks(mv.right, margin, off, clear);
  705. for (var i = 0; i < clear.length; i++) {
  706. if (clear[i]) {
  707. var line = i + off;
  708. for (var size = 1; i < clear.length - 1 && clear[i + 1]; i++, size++) {}
  709. if (size > margin) {
  710. var editors = [{line: line, cm: edit}];
  711. if (mv.left) editors.push({line: getMatchingOrigLine(line, mv.left.chunks), cm: mv.left.orig});
  712. if (mv.right) editors.push({line: getMatchingOrigLine(line, mv.right.chunks), cm: mv.right.orig});
  713. var mark = collapseStretch(size, editors);
  714. if (mv.options.onCollapse) mv.options.onCollapse(mv, line, size, mark);
  715. }
  716. }
  717. }
  718. }
  719. // General utilities
  720. function elt(tag, content, className, style) {
  721. var e = document.createElement(tag);
  722. if (className) e.className = className;
  723. if (style) e.style.cssText = style;
  724. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  725. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  726. return e;
  727. }
  728. function clear(node) {
  729. for (var count = node.childNodes.length; count > 0; --count)
  730. node.removeChild(node.firstChild);
  731. }
  732. function attrs(elt) {
  733. for (var i = 1; i < arguments.length; i += 2)
  734. elt.setAttribute(arguments[i], arguments[i+1]);
  735. }
  736. function copyObj(obj, target) {
  737. if (!target) target = {};
  738. for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
  739. return target;
  740. }
  741. function moveOver(pos, str, copy, other) {
  742. var out = copy ? Pos(pos.line, pos.ch) : pos, at = 0;
  743. for (;;) {
  744. var nl = str.indexOf("\n", at);
  745. if (nl == -1) break;
  746. ++out.line;
  747. if (other) ++other.line;
  748. at = nl + 1;
  749. }
  750. out.ch = (at ? 0 : out.ch) + (str.length - at);
  751. if (other) other.ch = (at ? 0 : other.ch) + (str.length - at);
  752. return out;
  753. }
  754. // Tracks collapsed markers and line widgets, in order to be able to
  755. // accurately align the content of two editors.
  756. var F_WIDGET = 1, F_WIDGET_BELOW = 2, F_MARKER = 4
  757. function TrackAlignable(cm) {
  758. this.cm = cm
  759. this.alignable = []
  760. this.height = cm.doc.height
  761. var self = this
  762. cm.on("markerAdded", function(_, marker) {
  763. if (!marker.collapsed) return
  764. var found = marker.find(1)
  765. if (found != null) self.set(found.line, F_MARKER)
  766. })
  767. cm.on("markerCleared", function(_, marker, _min, max) {
  768. if (max != null && marker.collapsed)
  769. self.check(max, F_MARKER, self.hasMarker)
  770. })
  771. cm.on("markerChanged", this.signal.bind(this))
  772. cm.on("lineWidgetAdded", function(_, widget, lineNo) {
  773. if (widget.mergeSpacer) return
  774. if (widget.above) self.set(lineNo - 1, F_WIDGET_BELOW)
  775. else self.set(lineNo, F_WIDGET)
  776. })
  777. cm.on("lineWidgetCleared", function(_, widget, lineNo) {
  778. if (widget.mergeSpacer) return
  779. if (widget.above) self.check(lineNo - 1, F_WIDGET_BELOW, self.hasWidgetBelow)
  780. else self.check(lineNo, F_WIDGET, self.hasWidget)
  781. })
  782. cm.on("lineWidgetChanged", this.signal.bind(this))
  783. cm.on("change", function(_, change) {
  784. var start = change.from.line, nBefore = change.to.line - change.from.line
  785. var nAfter = change.text.length - 1, end = start + nAfter
  786. if (nBefore || nAfter) self.map(start, nBefore, nAfter)
  787. self.check(end, F_MARKER, self.hasMarker)
  788. if (nBefore || nAfter) self.check(change.from.line, F_MARKER, self.hasMarker)
  789. })
  790. cm.on("viewportChange", function() {
  791. if (self.cm.doc.height != self.height) self.signal()
  792. })
  793. }
  794. TrackAlignable.prototype = {
  795. signal: function() {
  796. CodeMirror.signal(this, "realign")
  797. this.height = this.cm.doc.height
  798. },
  799. set: function(n, flags) {
  800. var pos = -1
  801. for (; pos < this.alignable.length; pos += 2) {
  802. var diff = this.alignable[pos] - n
  803. if (diff == 0) {
  804. if ((this.alignable[pos + 1] & flags) == flags) return
  805. this.alignable[pos + 1] |= flags
  806. this.signal()
  807. return
  808. }
  809. if (diff > 0) break
  810. }
  811. this.signal()
  812. this.alignable.splice(pos, 0, n, flags)
  813. },
  814. find: function(n) {
  815. for (var i = 0; i < this.alignable.length; i += 2)
  816. if (this.alignable[i] == n) return i
  817. return -1
  818. },
  819. check: function(n, flag, pred) {
  820. var found = this.find(n)
  821. if (found == -1 || !(this.alignable[found + 1] & flag)) return
  822. if (!pred.call(this, n)) {
  823. this.signal()
  824. var flags = this.alignable[found + 1] & ~flag
  825. if (flags) this.alignable[found + 1] = flags
  826. else this.alignable.splice(found, 2)
  827. }
  828. },
  829. hasMarker: function(n) {
  830. var handle = this.cm.getLineHandle(n)
  831. if (handle.markedSpans) for (var i = 0; i < handle.markedSpans.length; i++)
  832. if (handle.markedSpans[i].marker.collapsed && handle.markedSpans[i].to != null)
  833. return true
  834. return false
  835. },
  836. hasWidget: function(n) {
  837. var handle = this.cm.getLineHandle(n)
  838. if (handle.widgets) for (var i = 0; i < handle.widgets.length; i++)
  839. if (!handle.widgets[i].above && !handle.widgets[i].mergeSpacer) return true
  840. return false
  841. },
  842. hasWidgetBelow: function(n) {
  843. if (n == this.cm.lastLine()) return false
  844. var handle = this.cm.getLineHandle(n + 1)
  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. map: function(from, nBefore, nAfter) {
  850. var diff = nAfter - nBefore, to = from + nBefore, widgetFrom = -1, widgetTo = -1
  851. for (var i = 0; i < this.alignable.length; i += 2) {
  852. var n = this.alignable[i]
  853. if (n == from && (this.alignable[i + 1] & F_WIDGET_BELOW)) widgetFrom = i
  854. if (n == to && (this.alignable[i + 1] & F_WIDGET_BELOW)) widgetTo = i
  855. if (n <= from) continue
  856. else if (n < to) this.alignable.splice(i--, 2)
  857. else this.alignable[i] += diff
  858. }
  859. if (widgetFrom > -1) {
  860. var flags = this.alignable[widgetFrom + 1]
  861. if (flags == F_WIDGET_BELOW) this.alignable.splice(widgetFrom, 2)
  862. else this.alignable[widgetFrom + 1] = flags & ~F_WIDGET_BELOW
  863. }
  864. if (widgetTo > -1 && nAfter)
  865. this.set(from + nAfter, F_WIDGET_BELOW)
  866. }
  867. }
  868. function posMin(a, b) { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; }
  869. function posMax(a, b) { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; }
  870. function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
  871. function findPrevDiff(chunks, start, isOrig) {
  872. for (var i = chunks.length - 1; i >= 0; i--) {
  873. var chunk = chunks[i];
  874. var to = (isOrig ? chunk.origTo : chunk.editTo) - 1;
  875. if (to < start) return to;
  876. }
  877. }
  878. function findNextDiff(chunks, start, isOrig) {
  879. for (var i = 0; i < chunks.length; i++) {
  880. var chunk = chunks[i];
  881. var from = (isOrig ? chunk.origFrom : chunk.editFrom);
  882. if (from > start) return from;
  883. }
  884. }
  885. function goNearbyDiff(cm, dir) {
  886. var found = null, views = cm.state.diffViews, line = cm.getCursor().line;
  887. if (views) for (var i = 0; i < views.length; i++) {
  888. var dv = views[i], isOrig = cm == dv.orig;
  889. ensureDiff(dv);
  890. var pos = dir < 0 ? findPrevDiff(dv.chunks, line, isOrig) : findNextDiff(dv.chunks, line, isOrig);
  891. if (pos != null && (found == null || (dir < 0 ? pos > found : pos < found)))
  892. found = pos;
  893. }
  894. if (found != null)
  895. cm.setCursor(found, 0);
  896. else
  897. return CodeMirror.Pass;
  898. }
  899. CodeMirror.commands.goNextDiff = function(cm) {
  900. return goNearbyDiff(cm, 1);
  901. };
  902. CodeMirror.commands.goPrevDiff = function(cm) {
  903. return goNearbyDiff(cm, -1);
  904. };
  905. });
上海开阖软件有限公司 沪ICP备12045867号-1