undo.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /**
  2. * Storage and control for undo information within a CodeMirror
  3. * editor. 'Why on earth is such a complicated mess required for
  4. * that?', I hear you ask. The goal, in implementing this, was to make
  5. * the complexity of storing and reverting undo information depend
  6. * only on the size of the edited or restored content, not on the size
  7. * of the whole document. This makes it necessary to use a kind of
  8. * 'diff' system, which, when applied to a DOM tree, causes some
  9. * complexity and hackery.
  10. *
  11. * In short, the editor 'touches' BR elements as it parses them, and
  12. * the UndoHistory stores these. When nothing is touched in commitDelay
  13. * milliseconds, the changes are committed: It goes over all touched
  14. * nodes, throws out the ones that did not change since last commit or
  15. * are no longer in the document, and assembles the rest into zero or
  16. * more 'chains' -- arrays of adjacent lines. Links back to these
  17. * chains are added to the BR nodes, while the chain that previously
  18. * spanned these nodes is added to the undo history. Undoing a change
  19. * means taking such a chain off the undo history, restoring its
  20. * content (text is saved per line) and linking it back into the
  21. * document.
  22. */
  23. // A history object needs to know about the DOM container holding the
  24. // document, the maximum amount of undo levels it should store, the
  25. // delay (of no input) after which it commits a set of changes, and,
  26. // unfortunately, the 'parent' window -- a window that is not in
  27. // designMode, and on which setTimeout works in every browser.
  28. function UndoHistory(container, maxDepth, commitDelay, editor) {
  29. this.container = container;
  30. this.maxDepth = maxDepth; this.commitDelay = commitDelay;
  31. this.editor = editor;
  32. // This line object represents the initial, empty editor.
  33. var initial = {text: "", from: null, to: null};
  34. // As the borders between lines are represented by BR elements, the
  35. // start of the first line and the end of the last one are
  36. // represented by null. Since you can not store any properties
  37. // (links to line objects) in null, these properties are used in
  38. // those cases.
  39. this.first = initial; this.last = initial;
  40. // Similarly, a 'historyTouched' property is added to the BR in
  41. // front of lines that have already been touched, and 'firstTouched'
  42. // is used for the first line.
  43. this.firstTouched = false;
  44. // History is the set of committed changes, touched is the set of
  45. // nodes touched since the last commit.
  46. this.history = []; this.redoHistory = []; this.touched = []; this.lostundo = 0;
  47. }
  48. UndoHistory.prototype = {
  49. // Schedule a commit (if no other touches come in for commitDelay
  50. // milliseconds).
  51. scheduleCommit: function() {
  52. var self = this;
  53. parent.clearTimeout(this.commitTimeout);
  54. this.commitTimeout = parent.setTimeout(function(){self.tryCommit();}, this.commitDelay);
  55. },
  56. // Mark a node as touched. Null is a valid argument.
  57. touch: function(node) {
  58. this.setTouched(node);
  59. this.scheduleCommit();
  60. },
  61. // Undo the last change.
  62. undo: function() {
  63. // Make sure pending changes have been committed.
  64. this.commit();
  65. if (this.history.length) {
  66. // Take the top diff from the history, apply it, and store its
  67. // shadow in the redo history.
  68. var item = this.history.pop();
  69. this.redoHistory.push(this.updateTo(item, "applyChain"));
  70. this.notifyEnvironment();
  71. return this.chainNode(item);
  72. }
  73. },
  74. // Redo the last undone change.
  75. redo: function() {
  76. this.commit();
  77. if (this.redoHistory.length) {
  78. // The inverse of undo, basically.
  79. var item = this.redoHistory.pop();
  80. this.addUndoLevel(this.updateTo(item, "applyChain"));
  81. this.notifyEnvironment();
  82. return this.chainNode(item);
  83. }
  84. },
  85. clear: function() {
  86. this.history = [];
  87. this.redoHistory = [];
  88. this.lostundo = 0;
  89. },
  90. // Ask for the size of the un/redo histories.
  91. historySize: function() {
  92. return {undo: this.history.length, redo: this.redoHistory.length, lostundo: this.lostundo};
  93. },
  94. // Push a changeset into the document.
  95. push: function(from, to, lines) {
  96. var chain = [];
  97. for (var i = 0; i < lines.length; i++) {
  98. var end = (i == lines.length - 1) ? to : document.createElement("br");
  99. chain.push({from: from, to: end, text: cleanText(lines[i])});
  100. from = end;
  101. }
  102. this.pushChains([chain], from == null && to == null);
  103. this.notifyEnvironment();
  104. },
  105. pushChains: function(chains, doNotHighlight) {
  106. this.commit(doNotHighlight);
  107. this.addUndoLevel(this.updateTo(chains, "applyChain"));
  108. this.redoHistory = [];
  109. },
  110. // Retrieve a DOM node from a chain (for scrolling to it after undo/redo).
  111. chainNode: function(chains) {
  112. for (var i = 0; i < chains.length; i++) {
  113. var start = chains[i][0], node = start && (start.from || start.to);
  114. if (node) return node;
  115. }
  116. },
  117. // Clear the undo history, make the current document the start
  118. // position.
  119. reset: function() {
  120. this.history = []; this.redoHistory = []; this.lostundo = 0;
  121. },
  122. textAfter: function(br) {
  123. return this.after(br).text;
  124. },
  125. nodeAfter: function(br) {
  126. return this.after(br).to;
  127. },
  128. nodeBefore: function(br) {
  129. return this.before(br).from;
  130. },
  131. // Commit unless there are pending dirty nodes.
  132. tryCommit: function() {
  133. if (!window || !window.parent || !window.UndoHistory) return; // Stop when frame has been unloaded
  134. if (this.editor.highlightDirty()) this.commit(true);
  135. else this.scheduleCommit();
  136. },
  137. // Check whether the touched nodes hold any changes, if so, commit
  138. // them.
  139. commit: function(doNotHighlight) {
  140. parent.clearTimeout(this.commitTimeout);
  141. // Make sure there are no pending dirty nodes.
  142. if (!doNotHighlight) this.editor.highlightDirty(true);
  143. // Build set of chains.
  144. var chains = this.touchedChains(), self = this;
  145. if (chains.length) {
  146. this.addUndoLevel(this.updateTo(chains, "linkChain"));
  147. this.redoHistory = [];
  148. this.notifyEnvironment();
  149. }
  150. },
  151. // [ end of public interface ]
  152. // Update the document with a given set of chains, return its
  153. // shadow. updateFunc should be "applyChain" or "linkChain". In the
  154. // second case, the chains are taken to correspond the the current
  155. // document, and only the state of the line data is updated. In the
  156. // first case, the content of the chains is also pushed iinto the
  157. // document.
  158. updateTo: function(chains, updateFunc) {
  159. var shadows = [], dirty = [];
  160. for (var i = 0; i < chains.length; i++) {
  161. shadows.push(this.shadowChain(chains[i]));
  162. dirty.push(this[updateFunc](chains[i]));
  163. }
  164. if (updateFunc == "applyChain")
  165. this.notifyDirty(dirty);
  166. return shadows;
  167. },
  168. // Notify the editor that some nodes have changed.
  169. notifyDirty: function(nodes) {
  170. forEach(nodes, method(this.editor, "addDirtyNode"))
  171. this.editor.scheduleHighlight();
  172. },
  173. notifyEnvironment: function() {
  174. if (this.onChange) this.onChange(this.editor);
  175. // Used by the line-wrapping line-numbering code.
  176. if (window.frameElement && window.frameElement.CodeMirror.updateNumbers)
  177. window.frameElement.CodeMirror.updateNumbers();
  178. },
  179. // Link a chain into the DOM nodes (or the first/last links for null
  180. // nodes).
  181. linkChain: function(chain) {
  182. for (var i = 0; i < chain.length; i++) {
  183. var line = chain[i];
  184. if (line.from) line.from.historyAfter = line;
  185. else this.first = line;
  186. if (line.to) line.to.historyBefore = line;
  187. else this.last = line;
  188. }
  189. },
  190. // Get the line object after/before a given node.
  191. after: function(node) {
  192. return node ? node.historyAfter : this.first;
  193. },
  194. before: function(node) {
  195. return node ? node.historyBefore : this.last;
  196. },
  197. // Mark a node as touched if it has not already been marked.
  198. setTouched: function(node) {
  199. if (node) {
  200. if (!node.historyTouched) {
  201. this.touched.push(node);
  202. node.historyTouched = true;
  203. }
  204. }
  205. else {
  206. this.firstTouched = true;
  207. }
  208. },
  209. // Store a new set of undo info, throw away info if there is more of
  210. // it than allowed.
  211. addUndoLevel: function(diffs) {
  212. this.history.push(diffs);
  213. if (this.history.length > this.maxDepth) {
  214. this.history.shift();
  215. this.lostundo += 1;
  216. }
  217. },
  218. // Build chains from a set of touched nodes.
  219. touchedChains: function() {
  220. var self = this;
  221. // The temp system is a crummy hack to speed up determining
  222. // whether a (currently touched) node has a line object associated
  223. // with it. nullTemp is used to store the object for the first
  224. // line, other nodes get it stored in their historyTemp property.
  225. var nullTemp = null;
  226. function temp(node) {return node ? node.historyTemp : nullTemp;}
  227. function setTemp(node, line) {
  228. if (node) node.historyTemp = line;
  229. else nullTemp = line;
  230. }
  231. function buildLine(node) {
  232. var text = [];
  233. for (var cur = node ? node.nextSibling : self.container.firstChild;
  234. cur && (!isBR(cur) || cur.hackBR); cur = cur.nextSibling)
  235. if (!cur.hackBR && cur.currentText) text.push(cur.currentText);
  236. return {from: node, to: cur, text: cleanText(text.join(""))};
  237. }
  238. // Filter out unchanged lines and nodes that are no longer in the
  239. // document. Build up line objects for remaining nodes.
  240. var lines = [];
  241. if (self.firstTouched) self.touched.push(null);
  242. forEach(self.touched, function(node) {
  243. if (node && (node.parentNode != self.container || node.hackBR)) return;
  244. if (node) node.historyTouched = false;
  245. else self.firstTouched = false;
  246. var line = buildLine(node), shadow = self.after(node);
  247. if (!shadow || shadow.text != line.text || shadow.to != line.to) {
  248. lines.push(line);
  249. setTemp(node, line);
  250. }
  251. });
  252. // Get the BR element after/before the given node.
  253. function nextBR(node, dir) {
  254. var link = dir + "Sibling", search = node[link];
  255. while (search && !isBR(search))
  256. search = search[link];
  257. return search;
  258. }
  259. // Assemble line objects into chains by scanning the DOM tree
  260. // around them.
  261. var chains = []; self.touched = [];
  262. forEach(lines, function(line) {
  263. // Note that this makes the loop skip line objects that have
  264. // been pulled into chains by lines before them.
  265. if (!temp(line.from)) return;
  266. var chain = [], curNode = line.from, safe = true;
  267. // Put any line objects (referred to by temp info) before this
  268. // one on the front of the array.
  269. while (true) {
  270. var curLine = temp(curNode);
  271. if (!curLine) {
  272. if (safe) break;
  273. else curLine = buildLine(curNode);
  274. }
  275. chain.unshift(curLine);
  276. setTemp(curNode, null);
  277. if (!curNode) break;
  278. safe = self.after(curNode);
  279. curNode = nextBR(curNode, "previous");
  280. }
  281. curNode = line.to; safe = self.before(line.from);
  282. // Add lines after this one at end of array.
  283. while (true) {
  284. if (!curNode) break;
  285. var curLine = temp(curNode);
  286. if (!curLine) {
  287. if (safe) break;
  288. else curLine = buildLine(curNode);
  289. }
  290. chain.push(curLine);
  291. setTemp(curNode, null);
  292. safe = self.before(curNode);
  293. curNode = nextBR(curNode, "next");
  294. }
  295. chains.push(chain);
  296. });
  297. return chains;
  298. },
  299. // Find the 'shadow' of a given chain by following the links in the
  300. // DOM nodes at its start and end.
  301. shadowChain: function(chain) {
  302. var shadows = [], next = this.after(chain[0].from), end = chain[chain.length - 1].to;
  303. while (true) {
  304. shadows.push(next);
  305. var nextNode = next.to;
  306. if (!nextNode || nextNode == end)
  307. break;
  308. else
  309. next = nextNode.historyAfter || this.before(end);
  310. // (The this.before(end) is a hack -- FF sometimes removes
  311. // properties from BR nodes, in which case the best we can hope
  312. // for is to not break.)
  313. }
  314. return shadows;
  315. },
  316. // Update the DOM tree to contain the lines specified in a given
  317. // chain, link this chain into the DOM nodes.
  318. applyChain: function(chain) {
  319. // Some attempt is made to prevent the cursor from jumping
  320. // randomly when an undo or redo happens. It still behaves a bit
  321. // strange sometimes.
  322. var cursor = select.cursorPos(this.container, false), self = this;
  323. // Remove all nodes in the DOM tree between from and to (null for
  324. // start/end of container).
  325. function removeRange(from, to) {
  326. var pos = from ? from.nextSibling : self.container.firstChild;
  327. while (pos != to) {
  328. var temp = pos.nextSibling;
  329. removeElement(pos);
  330. pos = temp;
  331. }
  332. }
  333. var start = chain[0].from, end = chain[chain.length - 1].to;
  334. // Clear the space where this change has to be made.
  335. removeRange(start, end);
  336. // Insert the content specified by the chain into the DOM tree.
  337. for (var i = 0; i < chain.length; i++) {
  338. var line = chain[i];
  339. // The start and end of the space are already correct, but BR
  340. // tags inside it have to be put back.
  341. if (i > 0)
  342. self.container.insertBefore(line.from, end);
  343. // Add the text.
  344. var node = makePartSpan(fixSpaces(line.text));
  345. self.container.insertBefore(node, end);
  346. // See if the cursor was on this line. Put it back, adjusting
  347. // for changed line length, if it was.
  348. if (cursor && cursor.node == line.from) {
  349. var cursordiff = 0;
  350. var prev = this.after(line.from);
  351. if (prev && i == chain.length - 1) {
  352. // Only adjust if the cursor is after the unchanged part of
  353. // the line.
  354. for (var match = 0; match < cursor.offset &&
  355. line.text.charAt(match) == prev.text.charAt(match); match++){}
  356. if (cursor.offset > match)
  357. cursordiff = line.text.length - prev.text.length;
  358. }
  359. select.setCursorPos(this.container, {node: line.from, offset: Math.max(0, cursor.offset + cursordiff)});
  360. }
  361. // Cursor was in removed line, this is last new line.
  362. else if (cursor && (i == chain.length - 1) && cursor.node && cursor.node.parentNode != this.container) {
  363. select.setCursorPos(this.container, {node: line.from, offset: line.text.length});
  364. }
  365. }
  366. // Anchor the chain in the DOM tree.
  367. this.linkChain(chain);
  368. return start;
  369. }
  370. };