##// END OF EJS Templates
split focuses the top of the newly created cell
Paul Ivanov -
Show More
@@ -1,2085 +1,2087 b''
1 1 //----------------------------------------------------------------------------
2 2 // Copyright (C) 2008-2011 The IPython Development Team
3 3 //
4 4 // Distributed under the terms of the BSD License. The full license is in
5 5 // the file COPYING, distributed as part of this software.
6 6 //----------------------------------------------------------------------------
7 7
8 8 //============================================================================
9 9 // Notebook
10 10 //============================================================================
11 11
12 12 var IPython = (function (IPython) {
13 13 "use strict";
14 14
15 15 var utils = IPython.utils;
16 16 var key = IPython.utils.keycodes;
17 17
18 18 /**
19 19 * A notebook contains and manages cells.
20 20 *
21 21 * @class Notebook
22 22 * @constructor
23 23 * @param {String} selector A jQuery selector for the notebook's DOM element
24 24 * @param {Object} [options] A config object
25 25 */
26 26 var Notebook = function (selector, options) {
27 27 var options = options || {};
28 28 this._baseProjectUrl = options.baseProjectUrl;
29 29
30 30 this.element = $(selector);
31 31 this.element.scroll();
32 32 this.element.data("notebook", this);
33 33 this.next_prompt_number = 1;
34 34 this.kernel = null;
35 35 this.clipboard = null;
36 36 this.undelete_backup = null;
37 37 this.undelete_index = null;
38 38 this.undelete_below = false;
39 39 this.paste_enabled = false;
40 40 this.set_dirty(false);
41 41 this.metadata = {};
42 42 this._checkpoint_after_save = false;
43 43 this.last_checkpoint = null;
44 44 this.checkpoints = [];
45 45 this.autosave_interval = 0;
46 46 this.autosave_timer = null;
47 47 // autosave *at most* every two minutes
48 48 this.minimum_autosave_interval = 120000;
49 49 // single worksheet for now
50 50 this.worksheet_metadata = {};
51 51 this.control_key_active = false;
52 52 this.notebook_id = null;
53 53 this.notebook_name = null;
54 54 this.notebook_name_blacklist_re = /[\/\\:]/;
55 55 this.nbformat = 3 // Increment this when changing the nbformat
56 56 this.nbformat_minor = 0 // Increment this when changing the nbformat
57 57 this.style();
58 58 this.create_elements();
59 59 this.bind_events();
60 60 };
61 61
62 62 /**
63 63 * Tweak the notebook's CSS style.
64 64 *
65 65 * @method style
66 66 */
67 67 Notebook.prototype.style = function () {
68 68 $('div#notebook').addClass('border-box-sizing');
69 69 };
70 70
71 71 /**
72 72 * Get the root URL of the notebook server.
73 73 *
74 74 * @method baseProjectUrl
75 75 * @return {String} The base project URL
76 76 */
77 77 Notebook.prototype.baseProjectUrl = function(){
78 78 return this._baseProjectUrl || $('body').data('baseProjectUrl');
79 79 };
80 80
81 81 /**
82 82 * Create an HTML and CSS representation of the notebook.
83 83 *
84 84 * @method create_elements
85 85 */
86 86 Notebook.prototype.create_elements = function () {
87 87 // We add this end_space div to the end of the notebook div to:
88 88 // i) provide a margin between the last cell and the end of the notebook
89 89 // ii) to prevent the div from scrolling up when the last cell is being
90 90 // edited, but is too low on the page, which browsers will do automatically.
91 91 var that = this;
92 92 this.container = $("<div/>").addClass("container").attr("id", "notebook-container");
93 93 var end_space = $('<div/>').addClass('end_space');
94 94 end_space.dblclick(function (e) {
95 95 var ncells = that.ncells();
96 96 that.insert_cell_below('code',ncells-1);
97 97 });
98 98 this.element.append(this.container);
99 99 this.container.append(end_space);
100 100 $('div#notebook').addClass('border-box-sizing');
101 101 };
102 102
103 103 /**
104 104 * Bind JavaScript events: key presses and custom IPython events.
105 105 *
106 106 * @method bind_events
107 107 */
108 108 Notebook.prototype.bind_events = function () {
109 109 var that = this;
110 110
111 111 $([IPython.events]).on('set_next_input.Notebook', function (event, data) {
112 112 var index = that.find_cell_index(data.cell);
113 113 var new_cell = that.insert_cell_below('code',index);
114 114 new_cell.set_text(data.text);
115 115 that.dirty = true;
116 116 });
117 117
118 118 $([IPython.events]).on('set_dirty.Notebook', function (event, data) {
119 119 that.dirty = data.value;
120 120 });
121 121
122 122 $([IPython.events]).on('select.Cell', function (event, data) {
123 123 var index = that.find_cell_index(data.cell);
124 124 that.select(index);
125 125 });
126 126
127 127 $([IPython.events]).on('status_autorestarting.Kernel', function () {
128 128 IPython.dialog.modal({
129 129 title: "Kernel Restarting",
130 130 body: "The kernel appears to have died. It will restart automatically.",
131 131 buttons: {
132 132 OK : {
133 133 class : "btn-primary"
134 134 }
135 135 }
136 136 });
137 137 });
138 138
139 139
140 140 $(document).keydown(function (event) {
141 141
142 142 // Save (CTRL+S) or (AppleKey+S)
143 143 //metaKey = applekey on mac
144 144 if ((event.ctrlKey || event.metaKey) && event.keyCode==83) {
145 145 that.save_checkpoint();
146 146 event.preventDefault();
147 147 return false;
148 148 } else if (event.which === key.ESC) {
149 149 // Intercept escape at highest level to avoid closing
150 150 // websocket connection with firefox
151 151 IPython.pager.collapse();
152 152 event.preventDefault();
153 153 } else if (event.which === key.SHIFT) {
154 154 // ignore shift keydown
155 155 return true;
156 156 }
157 157 if (event.which === key.UPARROW && !event.shiftKey) {
158 158 var cell = that.get_selected_cell();
159 159 if (cell && cell.at_top()) {
160 160 event.preventDefault();
161 161 that.select_prev();
162 162 };
163 163 } else if (event.which === key.DOWNARROW && !event.shiftKey) {
164 164 var cell = that.get_selected_cell();
165 165 if (cell && cell.at_bottom()) {
166 166 event.preventDefault();
167 167 that.select_next();
168 168 };
169 169 } else if (event.which === key.ENTER && event.shiftKey) {
170 170 that.execute_selected_cell();
171 171 return false;
172 172 } else if (event.which === key.ENTER && event.altKey) {
173 173 // Execute code cell, and insert new in place
174 174 that.execute_selected_cell();
175 175 // Only insert a new cell, if we ended up in an already populated cell
176 176 if (/\S/.test(that.get_selected_cell().get_text()) == true) {
177 177 that.insert_cell_above('code');
178 178 }
179 179 return false;
180 180 } else if (event.which === key.ENTER && event.ctrlKey) {
181 181 that.execute_selected_cell({terminal:true});
182 182 return false;
183 183 } else if (event.which === 77 && event.ctrlKey && that.control_key_active == false) {
184 184 that.control_key_active = true;
185 185 return false;
186 186 } else if (event.which === 88 && that.control_key_active) {
187 187 // Cut selected cell = x
188 188 that.cut_cell();
189 189 that.control_key_active = false;
190 190 return false;
191 191 } else if (event.which === 67 && that.control_key_active) {
192 192 // Copy selected cell = c
193 193 that.copy_cell();
194 194 that.control_key_active = false;
195 195 return false;
196 196 } else if (event.which === 86 && that.control_key_active) {
197 197 // Paste below selected cell = v
198 198 that.paste_cell_below();
199 199 that.control_key_active = false;
200 200 return false;
201 201 } else if (event.which === 68 && that.control_key_active) {
202 202 // Delete selected cell = d
203 203 that.delete_cell();
204 204 that.control_key_active = false;
205 205 return false;
206 206 } else if (event.which === 65 && that.control_key_active) {
207 207 // Insert code cell above selected = a
208 208 that.insert_cell_above('code');
209 209 that.control_key_active = false;
210 210 return false;
211 211 } else if (event.which === 66 && that.control_key_active) {
212 212 // Insert code cell below selected = b
213 213 that.insert_cell_below('code');
214 214 that.control_key_active = false;
215 215 return false;
216 216 } else if (event.which === 89 && that.control_key_active) {
217 217 // To code = y
218 218 that.to_code();
219 219 that.control_key_active = false;
220 220 return false;
221 221 } else if (event.which === 77 && that.control_key_active) {
222 222 // To markdown = m
223 223 that.to_markdown();
224 224 that.control_key_active = false;
225 225 return false;
226 226 } else if (event.which === 84 && that.control_key_active) {
227 227 // To Raw = t
228 228 that.to_raw();
229 229 that.control_key_active = false;
230 230 return false;
231 231 } else if (event.which === 49 && that.control_key_active) {
232 232 // To Heading 1 = 1
233 233 that.to_heading(undefined, 1);
234 234 that.control_key_active = false;
235 235 return false;
236 236 } else if (event.which === 50 && that.control_key_active) {
237 237 // To Heading 2 = 2
238 238 that.to_heading(undefined, 2);
239 239 that.control_key_active = false;
240 240 return false;
241 241 } else if (event.which === 51 && that.control_key_active) {
242 242 // To Heading 3 = 3
243 243 that.to_heading(undefined, 3);
244 244 that.control_key_active = false;
245 245 return false;
246 246 } else if (event.which === 52 && that.control_key_active) {
247 247 // To Heading 4 = 4
248 248 that.to_heading(undefined, 4);
249 249 that.control_key_active = false;
250 250 return false;
251 251 } else if (event.which === 53 && that.control_key_active) {
252 252 // To Heading 5 = 5
253 253 that.to_heading(undefined, 5);
254 254 that.control_key_active = false;
255 255 return false;
256 256 } else if (event.which === 54 && that.control_key_active) {
257 257 // To Heading 6 = 6
258 258 that.to_heading(undefined, 6);
259 259 that.control_key_active = false;
260 260 return false;
261 261 } else if (event.which === 79 && that.control_key_active) {
262 262 // Toggle output = o
263 263 if (event.shiftKey){
264 264 that.toggle_output_scroll();
265 265 } else {
266 266 that.toggle_output();
267 267 }
268 268 that.control_key_active = false;
269 269 return false;
270 270 } else if (event.which === 83 && that.control_key_active) {
271 271 // Save notebook = s
272 272 that.save_checkpoint();
273 273 that.control_key_active = false;
274 274 return false;
275 275 } else if (event.which === 74 && that.control_key_active) {
276 276 // Move cell down = j
277 277 that.move_cell_down();
278 278 that.control_key_active = false;
279 279 return false;
280 280 } else if (event.which === 75 && that.control_key_active) {
281 281 // Move cell up = k
282 282 that.move_cell_up();
283 283 that.control_key_active = false;
284 284 return false;
285 285 } else if (event.which === 80 && that.control_key_active) {
286 286 // Select previous = p
287 287 that.select_prev();
288 288 that.control_key_active = false;
289 289 return false;
290 290 } else if (event.which === 78 && that.control_key_active) {
291 291 // Select next = n
292 292 that.select_next();
293 293 that.control_key_active = false;
294 294 return false;
295 295 } else if (event.which === 76 && that.control_key_active) {
296 296 // Toggle line numbers = l
297 297 that.cell_toggle_line_numbers();
298 298 that.control_key_active = false;
299 299 return false;
300 300 } else if (event.which === 73 && that.control_key_active) {
301 301 // Interrupt kernel = i
302 302 that.kernel.interrupt();
303 303 that.control_key_active = false;
304 304 return false;
305 305 } else if (event.which === 190 && that.control_key_active) {
306 306 // Restart kernel = . # matches qt console
307 307 that.restart_kernel();
308 308 that.control_key_active = false;
309 309 return false;
310 310 } else if (event.which === 72 && that.control_key_active) {
311 311 // Show keyboard shortcuts = h
312 312 IPython.quick_help.show_keyboard_shortcuts();
313 313 that.control_key_active = false;
314 314 return false;
315 315 } else if (event.which === 90 && that.control_key_active) {
316 316 // Undo last cell delete = z
317 317 that.undelete();
318 318 that.control_key_active = false;
319 319 return false;
320 320 } else if (event.which === 189 && that.control_key_active) {
321 321 // Split cell = -
322 322 that.split_cell();
323 323 that.control_key_active = false;
324 324 return false;
325 325 } else if (that.control_key_active) {
326 326 that.control_key_active = false;
327 327 return true;
328 328 }
329 329 return true;
330 330 });
331 331
332 332 var collapse_time = function(time){
333 333 var app_height = $('#ipython-main-app').height(); // content height
334 334 var splitter_height = $('div#pager_splitter').outerHeight(true);
335 335 var new_height = app_height - splitter_height;
336 336 that.element.animate({height : new_height + 'px'}, time);
337 337 }
338 338
339 339 this.element.bind('collapse_pager', function (event,extrap) {
340 340 var time = (extrap != undefined) ? ((extrap.duration != undefined ) ? extrap.duration : 'fast') : 'fast';
341 341 collapse_time(time);
342 342 });
343 343
344 344 var expand_time = function(time) {
345 345 var app_height = $('#ipython-main-app').height(); // content height
346 346 var splitter_height = $('div#pager_splitter').outerHeight(true);
347 347 var pager_height = $('div#pager').outerHeight(true);
348 348 var new_height = app_height - pager_height - splitter_height;
349 349 that.element.animate({height : new_height + 'px'}, time);
350 350 }
351 351
352 352 this.element.bind('expand_pager', function (event, extrap) {
353 353 var time = (extrap != undefined) ? ((extrap.duration != undefined ) ? extrap.duration : 'fast') : 'fast';
354 354 expand_time(time);
355 355 });
356 356
357 357 // Firefox 22 broke $(window).on("beforeunload")
358 358 // I'm not sure why or how.
359 359 window.onbeforeunload = function (e) {
360 360 // TODO: Make killing the kernel configurable.
361 361 var kill_kernel = false;
362 362 if (kill_kernel) {
363 363 that.kernel.kill();
364 364 }
365 365 // if we are autosaving, trigger an autosave on nav-away.
366 366 // still warn, because if we don't the autosave may fail.
367 367 if (that.dirty) {
368 368 if ( that.autosave_interval ) {
369 369 // schedule autosave in a timeout
370 370 // this gives you a chance to forcefully discard changes
371 371 // by reloading the page if you *really* want to.
372 372 // the timer doesn't start until you *dismiss* the dialog.
373 373 setTimeout(function () {
374 374 if (that.dirty) {
375 375 that.save_notebook();
376 376 }
377 377 }, 1000);
378 378 return "Autosave in progress, latest changes may be lost.";
379 379 } else {
380 380 return "Unsaved changes will be lost.";
381 381 }
382 382 };
383 383 // Null is the *only* return value that will make the browser not
384 384 // pop up the "don't leave" dialog.
385 385 return null;
386 386 };
387 387 };
388 388
389 389 /**
390 390 * Set the dirty flag, and trigger the set_dirty.Notebook event
391 391 *
392 392 * @method set_dirty
393 393 */
394 394 Notebook.prototype.set_dirty = function (value) {
395 395 if (value === undefined) {
396 396 value = true;
397 397 }
398 398 if (this.dirty == value) {
399 399 return;
400 400 }
401 401 $([IPython.events]).trigger('set_dirty.Notebook', {value: value});
402 402 };
403 403
404 404 /**
405 405 * Scroll the top of the page to a given cell.
406 406 *
407 407 * @method scroll_to_cell
408 408 * @param {Number} cell_number An index of the cell to view
409 409 * @param {Number} time Animation time in milliseconds
410 410 * @return {Number} Pixel offset from the top of the container
411 411 */
412 412 Notebook.prototype.scroll_to_cell = function (cell_number, time) {
413 413 var cells = this.get_cells();
414 414 var time = time || 0;
415 415 cell_number = Math.min(cells.length-1,cell_number);
416 416 cell_number = Math.max(0 ,cell_number);
417 417 var scroll_value = cells[cell_number].element.position().top-cells[0].element.position().top ;
418 418 this.element.animate({scrollTop:scroll_value}, time);
419 419 return scroll_value;
420 420 };
421 421
422 422 /**
423 423 * Scroll to the bottom of the page.
424 424 *
425 425 * @method scroll_to_bottom
426 426 */
427 427 Notebook.prototype.scroll_to_bottom = function () {
428 428 this.element.animate({scrollTop:this.element.get(0).scrollHeight}, 0);
429 429 };
430 430
431 431 /**
432 432 * Scroll to the top of the page.
433 433 *
434 434 * @method scroll_to_top
435 435 */
436 436 Notebook.prototype.scroll_to_top = function () {
437 437 this.element.animate({scrollTop:0}, 0);
438 438 };
439 439
440 440 // Edit Notebook metadata
441 441
442 442 Notebook.prototype.edit_metadata = function () {
443 443 var that = this;
444 444 IPython.dialog.edit_metadata(this.metadata, function (md) {
445 445 that.metadata = md;
446 446 }, 'Notebook');
447 447 };
448 448
449 449 // Cell indexing, retrieval, etc.
450 450
451 451 /**
452 452 * Get all cell elements in the notebook.
453 453 *
454 454 * @method get_cell_elements
455 455 * @return {jQuery} A selector of all cell elements
456 456 */
457 457 Notebook.prototype.get_cell_elements = function () {
458 458 return this.container.children("div.cell");
459 459 };
460 460
461 461 /**
462 462 * Get a particular cell element.
463 463 *
464 464 * @method get_cell_element
465 465 * @param {Number} index An index of a cell to select
466 466 * @return {jQuery} A selector of the given cell.
467 467 */
468 468 Notebook.prototype.get_cell_element = function (index) {
469 469 var result = null;
470 470 var e = this.get_cell_elements().eq(index);
471 471 if (e.length !== 0) {
472 472 result = e;
473 473 }
474 474 return result;
475 475 };
476 476
477 477 /**
478 478 * Count the cells in this notebook.
479 479 *
480 480 * @method ncells
481 481 * @return {Number} The number of cells in this notebook
482 482 */
483 483 Notebook.prototype.ncells = function () {
484 484 return this.get_cell_elements().length;
485 485 };
486 486
487 487 /**
488 488 * Get all Cell objects in this notebook.
489 489 *
490 490 * @method get_cells
491 491 * @return {Array} This notebook's Cell objects
492 492 */
493 493 // TODO: we are often calling cells as cells()[i], which we should optimize
494 494 // to cells(i) or a new method.
495 495 Notebook.prototype.get_cells = function () {
496 496 return this.get_cell_elements().toArray().map(function (e) {
497 497 return $(e).data("cell");
498 498 });
499 499 };
500 500
501 501 /**
502 502 * Get a Cell object from this notebook.
503 503 *
504 504 * @method get_cell
505 505 * @param {Number} index An index of a cell to retrieve
506 506 * @return {Cell} A particular cell
507 507 */
508 508 Notebook.prototype.get_cell = function (index) {
509 509 var result = null;
510 510 var ce = this.get_cell_element(index);
511 511 if (ce !== null) {
512 512 result = ce.data('cell');
513 513 }
514 514 return result;
515 515 }
516 516
517 517 /**
518 518 * Get the cell below a given cell.
519 519 *
520 520 * @method get_next_cell
521 521 * @param {Cell} cell The provided cell
522 522 * @return {Cell} The next cell
523 523 */
524 524 Notebook.prototype.get_next_cell = function (cell) {
525 525 var result = null;
526 526 var index = this.find_cell_index(cell);
527 527 if (this.is_valid_cell_index(index+1)) {
528 528 result = this.get_cell(index+1);
529 529 }
530 530 return result;
531 531 }
532 532
533 533 /**
534 534 * Get the cell above a given cell.
535 535 *
536 536 * @method get_prev_cell
537 537 * @param {Cell} cell The provided cell
538 538 * @return {Cell} The previous cell
539 539 */
540 540 Notebook.prototype.get_prev_cell = function (cell) {
541 541 // TODO: off-by-one
542 542 // nb.get_prev_cell(nb.get_cell(1)) is null
543 543 var result = null;
544 544 var index = this.find_cell_index(cell);
545 545 if (index !== null && index > 1) {
546 546 result = this.get_cell(index-1);
547 547 }
548 548 return result;
549 549 }
550 550
551 551 /**
552 552 * Get the numeric index of a given cell.
553 553 *
554 554 * @method find_cell_index
555 555 * @param {Cell} cell The provided cell
556 556 * @return {Number} The cell's numeric index
557 557 */
558 558 Notebook.prototype.find_cell_index = function (cell) {
559 559 var result = null;
560 560 this.get_cell_elements().filter(function (index) {
561 561 if ($(this).data("cell") === cell) {
562 562 result = index;
563 563 };
564 564 });
565 565 return result;
566 566 };
567 567
568 568 /**
569 569 * Get a given index , or the selected index if none is provided.
570 570 *
571 571 * @method index_or_selected
572 572 * @param {Number} index A cell's index
573 573 * @return {Number} The given index, or selected index if none is provided.
574 574 */
575 575 Notebook.prototype.index_or_selected = function (index) {
576 576 var i;
577 577 if (index === undefined || index === null) {
578 578 i = this.get_selected_index();
579 579 if (i === null) {
580 580 i = 0;
581 581 }
582 582 } else {
583 583 i = index;
584 584 }
585 585 return i;
586 586 };
587 587
588 588 /**
589 589 * Get the currently selected cell.
590 590 * @method get_selected_cell
591 591 * @return {Cell} The selected cell
592 592 */
593 593 Notebook.prototype.get_selected_cell = function () {
594 594 var index = this.get_selected_index();
595 595 return this.get_cell(index);
596 596 };
597 597
598 598 /**
599 599 * Check whether a cell index is valid.
600 600 *
601 601 * @method is_valid_cell_index
602 602 * @param {Number} index A cell index
603 603 * @return True if the index is valid, false otherwise
604 604 */
605 605 Notebook.prototype.is_valid_cell_index = function (index) {
606 606 if (index !== null && index >= 0 && index < this.ncells()) {
607 607 return true;
608 608 } else {
609 609 return false;
610 610 };
611 611 }
612 612
613 613 /**
614 614 * Get the index of the currently selected cell.
615 615
616 616 * @method get_selected_index
617 617 * @return {Number} The selected cell's numeric index
618 618 */
619 619 Notebook.prototype.get_selected_index = function () {
620 620 var result = null;
621 621 this.get_cell_elements().filter(function (index) {
622 622 if ($(this).data("cell").selected === true) {
623 623 result = index;
624 624 };
625 625 });
626 626 return result;
627 627 };
628 628
629 629
630 630 // Cell selection.
631 631
632 632 /**
633 633 * Programmatically select a cell.
634 634 *
635 635 * @method select
636 636 * @param {Number} index A cell's index
637 637 * @return {Notebook} This notebook
638 638 */
639 639 Notebook.prototype.select = function (index) {
640 640 if (this.is_valid_cell_index(index)) {
641 641 var sindex = this.get_selected_index()
642 642 if (sindex !== null && index !== sindex) {
643 643 this.get_cell(sindex).unselect();
644 644 };
645 645 var cell = this.get_cell(index);
646 646 cell.select();
647 647 if (cell.cell_type === 'heading') {
648 648 $([IPython.events]).trigger('selected_cell_type_changed.Notebook',
649 649 {'cell_type':cell.cell_type,level:cell.level}
650 650 );
651 651 } else {
652 652 $([IPython.events]).trigger('selected_cell_type_changed.Notebook',
653 653 {'cell_type':cell.cell_type}
654 654 );
655 655 };
656 656 };
657 657 return this;
658 658 };
659 659
660 660 /**
661 661 * Programmatically select the next cell.
662 662 *
663 663 * @method select_next
664 664 * @return {Notebook} This notebook
665 665 */
666 666 Notebook.prototype.select_next = function () {
667 667 var index = this.get_selected_index();
668 668 this.select(index+1);
669 669 return this;
670 670 };
671 671
672 672 /**
673 673 * Programmatically select the previous cell.
674 674 *
675 675 * @method select_prev
676 676 * @return {Notebook} This notebook
677 677 */
678 678 Notebook.prototype.select_prev = function () {
679 679 var index = this.get_selected_index();
680 680 this.select(index-1);
681 681 return this;
682 682 };
683 683
684 684
685 685 // Cell movement
686 686
687 687 /**
688 688 * Move given (or selected) cell up and select it.
689 689 *
690 690 * @method move_cell_up
691 691 * @param [index] {integer} cell index
692 692 * @return {Notebook} This notebook
693 693 **/
694 694 Notebook.prototype.move_cell_up = function (index) {
695 695 var i = this.index_or_selected(index);
696 696 if (this.is_valid_cell_index(i) && i > 0) {
697 697 var pivot = this.get_cell_element(i-1);
698 698 var tomove = this.get_cell_element(i);
699 699 if (pivot !== null && tomove !== null) {
700 700 tomove.detach();
701 701 pivot.before(tomove);
702 702 this.select(i-1);
703 703 };
704 704 this.set_dirty(true);
705 705 };
706 706 return this;
707 707 };
708 708
709 709
710 710 /**
711 711 * Move given (or selected) cell down and select it
712 712 *
713 713 * @method move_cell_down
714 714 * @param [index] {integer} cell index
715 715 * @return {Notebook} This notebook
716 716 **/
717 717 Notebook.prototype.move_cell_down = function (index) {
718 718 var i = this.index_or_selected(index);
719 719 if ( this.is_valid_cell_index(i) && this.is_valid_cell_index(i+1)) {
720 720 var pivot = this.get_cell_element(i+1);
721 721 var tomove = this.get_cell_element(i);
722 722 if (pivot !== null && tomove !== null) {
723 723 tomove.detach();
724 724 pivot.after(tomove);
725 725 this.select(i+1);
726 726 };
727 727 };
728 728 this.set_dirty();
729 729 return this;
730 730 };
731 731
732 732
733 733 // Insertion, deletion.
734 734
735 735 /**
736 736 * Delete a cell from the notebook.
737 737 *
738 738 * @method delete_cell
739 739 * @param [index] A cell's numeric index
740 740 * @return {Notebook} This notebook
741 741 */
742 742 Notebook.prototype.delete_cell = function (index) {
743 743 var i = this.index_or_selected(index);
744 744 var cell = this.get_selected_cell();
745 745 this.undelete_backup = cell.toJSON();
746 746 $('#undelete_cell').removeClass('disabled');
747 747 if (this.is_valid_cell_index(i)) {
748 748 var ce = this.get_cell_element(i);
749 749 ce.remove();
750 750 if (i === (this.ncells())) {
751 751 this.select(i-1);
752 752 this.undelete_index = i - 1;
753 753 this.undelete_below = true;
754 754 } else {
755 755 this.select(i);
756 756 this.undelete_index = i;
757 757 this.undelete_below = false;
758 758 };
759 759 $([IPython.events]).trigger('delete.Cell', {'cell': cell, 'index': i});
760 760 this.set_dirty(true);
761 761 };
762 762 return this;
763 763 };
764 764
765 765 /**
766 766 * Insert a cell so that after insertion the cell is at given index.
767 767 *
768 768 * Similar to insert_above, but index parameter is mandatory
769 769 *
770 770 * Index will be brought back into the accissible range [0,n]
771 771 *
772 772 * @method insert_cell_at_index
773 773 * @param type {string} in ['code','markdown','heading']
774 774 * @param [index] {int} a valid index where to inser cell
775 775 *
776 776 * @return cell {cell|null} created cell or null
777 777 **/
778 778 Notebook.prototype.insert_cell_at_index = function(type, index){
779 779
780 780 var ncells = this.ncells();
781 781 var index = Math.min(index,ncells);
782 782 index = Math.max(index,0);
783 783 var cell = null;
784 784
785 785 if (ncells === 0 || this.is_valid_cell_index(index) || index === ncells) {
786 786 if (type === 'code') {
787 787 cell = new IPython.CodeCell(this.kernel);
788 788 cell.set_input_prompt();
789 789 } else if (type === 'markdown') {
790 790 cell = new IPython.MarkdownCell();
791 791 } else if (type === 'raw') {
792 792 cell = new IPython.RawCell();
793 793 } else if (type === 'heading') {
794 794 cell = new IPython.HeadingCell();
795 795 }
796 796
797 797 if(this._insert_element_at_index(cell.element,index)){
798 798 cell.render();
799 799 this.select(this.find_cell_index(cell));
800 800 $([IPython.events]).trigger('create.Cell', {'cell': cell, 'index': index});
801 801 this.set_dirty(true);
802 802 }
803 803 }
804 804 return cell;
805 805
806 806 };
807 807
808 808 /**
809 809 * Insert an element at given cell index.
810 810 *
811 811 * @method _insert_element_at_index
812 812 * @param element {dom element} a cell element
813 813 * @param [index] {int} a valid index where to inser cell
814 814 * @private
815 815 *
816 816 * return true if everything whent fine.
817 817 **/
818 818 Notebook.prototype._insert_element_at_index = function(element, index){
819 819 if (element === undefined){
820 820 return false;
821 821 }
822 822
823 823 var ncells = this.ncells();
824 824
825 825 if (ncells === 0) {
826 826 // special case append if empty
827 827 this.element.find('div.end_space').before(element);
828 828 } else if ( ncells === index ) {
829 829 // special case append it the end, but not empty
830 830 this.get_cell_element(index-1).after(element);
831 831 } else if (this.is_valid_cell_index(index)) {
832 832 // otherwise always somewhere to append to
833 833 this.get_cell_element(index).before(element);
834 834 } else {
835 835 return false;
836 836 }
837 837
838 838 if (this.undelete_index !== null && index <= this.undelete_index) {
839 839 this.undelete_index = this.undelete_index + 1;
840 840 this.set_dirty(true);
841 841 }
842 842 return true;
843 843 };
844 844
845 845 /**
846 846 * Insert a cell of given type above given index, or at top
847 847 * of notebook if index smaller than 0.
848 848 *
849 849 * default index value is the one of currently selected cell
850 850 *
851 851 * @method insert_cell_above
852 852 * @param type {string} cell type
853 853 * @param [index] {integer}
854 854 *
855 855 * @return handle to created cell or null
856 856 **/
857 857 Notebook.prototype.insert_cell_above = function (type, index) {
858 858 index = this.index_or_selected(index);
859 859 return this.insert_cell_at_index(type, index);
860 860 };
861 861
862 862 /**
863 863 * Insert a cell of given type below given index, or at bottom
864 864 * of notebook if index greater thatn number of cell
865 865 *
866 866 * default index value is the one of currently selected cell
867 867 *
868 868 * @method insert_cell_below
869 869 * @param type {string} cell type
870 870 * @param [index] {integer}
871 871 *
872 872 * @return handle to created cell or null
873 873 *
874 874 **/
875 875 Notebook.prototype.insert_cell_below = function (type, index) {
876 876 index = this.index_or_selected(index);
877 877 return this.insert_cell_at_index(type, index+1);
878 878 };
879 879
880 880
881 881 /**
882 882 * Insert cell at end of notebook
883 883 *
884 884 * @method insert_cell_at_bottom
885 885 * @param {String} type cell type
886 886 *
887 887 * @return the added cell; or null
888 888 **/
889 889 Notebook.prototype.insert_cell_at_bottom = function (type){
890 890 var len = this.ncells();
891 891 return this.insert_cell_below(type,len-1);
892 892 };
893 893
894 894 /**
895 895 * Turn a cell into a code cell.
896 896 *
897 897 * @method to_code
898 898 * @param {Number} [index] A cell's index
899 899 */
900 900 Notebook.prototype.to_code = function (index) {
901 901 var i = this.index_or_selected(index);
902 902 if (this.is_valid_cell_index(i)) {
903 903 var source_element = this.get_cell_element(i);
904 904 var source_cell = source_element.data("cell");
905 905 if (!(source_cell instanceof IPython.CodeCell)) {
906 906 var target_cell = this.insert_cell_below('code',i);
907 907 var text = source_cell.get_text();
908 908 if (text === source_cell.placeholder) {
909 909 text = '';
910 910 }
911 911 target_cell.set_text(text);
912 912 // make this value the starting point, so that we can only undo
913 913 // to this state, instead of a blank cell
914 914 target_cell.code_mirror.clearHistory();
915 915 source_element.remove();
916 916 this.set_dirty(true);
917 917 };
918 918 };
919 919 };
920 920
921 921 /**
922 922 * Turn a cell into a Markdown cell.
923 923 *
924 924 * @method to_markdown
925 925 * @param {Number} [index] A cell's index
926 926 */
927 927 Notebook.prototype.to_markdown = function (index) {
928 928 var i = this.index_or_selected(index);
929 929 if (this.is_valid_cell_index(i)) {
930 930 var source_element = this.get_cell_element(i);
931 931 var source_cell = source_element.data("cell");
932 932 if (!(source_cell instanceof IPython.MarkdownCell)) {
933 933 var target_cell = this.insert_cell_below('markdown',i);
934 934 var text = source_cell.get_text();
935 935 if (text === source_cell.placeholder) {
936 936 text = '';
937 937 };
938 938 // The edit must come before the set_text.
939 939 target_cell.edit();
940 940 target_cell.set_text(text);
941 941 // make this value the starting point, so that we can only undo
942 942 // to this state, instead of a blank cell
943 943 target_cell.code_mirror.clearHistory();
944 944 source_element.remove();
945 945 this.set_dirty(true);
946 946 };
947 947 };
948 948 };
949 949
950 950 /**
951 951 * Turn a cell into a raw text cell.
952 952 *
953 953 * @method to_raw
954 954 * @param {Number} [index] A cell's index
955 955 */
956 956 Notebook.prototype.to_raw = function (index) {
957 957 var i = this.index_or_selected(index);
958 958 if (this.is_valid_cell_index(i)) {
959 959 var source_element = this.get_cell_element(i);
960 960 var source_cell = source_element.data("cell");
961 961 var target_cell = null;
962 962 if (!(source_cell instanceof IPython.RawCell)) {
963 963 target_cell = this.insert_cell_below('raw',i);
964 964 var text = source_cell.get_text();
965 965 if (text === source_cell.placeholder) {
966 966 text = '';
967 967 };
968 968 // The edit must come before the set_text.
969 969 target_cell.edit();
970 970 target_cell.set_text(text);
971 971 // make this value the starting point, so that we can only undo
972 972 // to this state, instead of a blank cell
973 973 target_cell.code_mirror.clearHistory();
974 974 source_element.remove();
975 975 this.set_dirty(true);
976 976 };
977 977 };
978 978 };
979 979
980 980 /**
981 981 * Turn a cell into a heading cell.
982 982 *
983 983 * @method to_heading
984 984 * @param {Number} [index] A cell's index
985 985 * @param {Number} [level] A heading level (e.g., 1 becomes &lt;h1&gt;)
986 986 */
987 987 Notebook.prototype.to_heading = function (index, level) {
988 988 level = level || 1;
989 989 var i = this.index_or_selected(index);
990 990 if (this.is_valid_cell_index(i)) {
991 991 var source_element = this.get_cell_element(i);
992 992 var source_cell = source_element.data("cell");
993 993 var target_cell = null;
994 994 if (source_cell instanceof IPython.HeadingCell) {
995 995 source_cell.set_level(level);
996 996 } else {
997 997 target_cell = this.insert_cell_below('heading',i);
998 998 var text = source_cell.get_text();
999 999 if (text === source_cell.placeholder) {
1000 1000 text = '';
1001 1001 };
1002 1002 // The edit must come before the set_text.
1003 1003 target_cell.set_level(level);
1004 1004 target_cell.edit();
1005 1005 target_cell.set_text(text);
1006 1006 // make this value the starting point, so that we can only undo
1007 1007 // to this state, instead of a blank cell
1008 1008 target_cell.code_mirror.clearHistory();
1009 1009 source_element.remove();
1010 1010 this.set_dirty(true);
1011 1011 };
1012 1012 $([IPython.events]).trigger('selected_cell_type_changed.Notebook',
1013 1013 {'cell_type':'heading',level:level}
1014 1014 );
1015 1015 };
1016 1016 };
1017 1017
1018 1018
1019 1019 // Cut/Copy/Paste
1020 1020
1021 1021 /**
1022 1022 * Enable UI elements for pasting cells.
1023 1023 *
1024 1024 * @method enable_paste
1025 1025 */
1026 1026 Notebook.prototype.enable_paste = function () {
1027 1027 var that = this;
1028 1028 if (!this.paste_enabled) {
1029 1029 $('#paste_cell_replace').removeClass('disabled')
1030 1030 .on('click', function () {that.paste_cell_replace();});
1031 1031 $('#paste_cell_above').removeClass('disabled')
1032 1032 .on('click', function () {that.paste_cell_above();});
1033 1033 $('#paste_cell_below').removeClass('disabled')
1034 1034 .on('click', function () {that.paste_cell_below();});
1035 1035 this.paste_enabled = true;
1036 1036 };
1037 1037 };
1038 1038
1039 1039 /**
1040 1040 * Disable UI elements for pasting cells.
1041 1041 *
1042 1042 * @method disable_paste
1043 1043 */
1044 1044 Notebook.prototype.disable_paste = function () {
1045 1045 if (this.paste_enabled) {
1046 1046 $('#paste_cell_replace').addClass('disabled').off('click');
1047 1047 $('#paste_cell_above').addClass('disabled').off('click');
1048 1048 $('#paste_cell_below').addClass('disabled').off('click');
1049 1049 this.paste_enabled = false;
1050 1050 };
1051 1051 };
1052 1052
1053 1053 /**
1054 1054 * Cut a cell.
1055 1055 *
1056 1056 * @method cut_cell
1057 1057 */
1058 1058 Notebook.prototype.cut_cell = function () {
1059 1059 this.copy_cell();
1060 1060 this.delete_cell();
1061 1061 }
1062 1062
1063 1063 /**
1064 1064 * Copy a cell.
1065 1065 *
1066 1066 * @method copy_cell
1067 1067 */
1068 1068 Notebook.prototype.copy_cell = function () {
1069 1069 var cell = this.get_selected_cell();
1070 1070 this.clipboard = cell.toJSON();
1071 1071 this.enable_paste();
1072 1072 };
1073 1073
1074 1074 /**
1075 1075 * Replace the selected cell with a cell in the clipboard.
1076 1076 *
1077 1077 * @method paste_cell_replace
1078 1078 */
1079 1079 Notebook.prototype.paste_cell_replace = function () {
1080 1080 if (this.clipboard !== null && this.paste_enabled) {
1081 1081 var cell_data = this.clipboard;
1082 1082 var new_cell = this.insert_cell_above(cell_data.cell_type);
1083 1083 new_cell.fromJSON(cell_data);
1084 1084 var old_cell = this.get_next_cell(new_cell);
1085 1085 this.delete_cell(this.find_cell_index(old_cell));
1086 1086 this.select(this.find_cell_index(new_cell));
1087 1087 };
1088 1088 };
1089 1089
1090 1090 /**
1091 1091 * Paste a cell from the clipboard above the selected cell.
1092 1092 *
1093 1093 * @method paste_cell_above
1094 1094 */
1095 1095 Notebook.prototype.paste_cell_above = function () {
1096 1096 if (this.clipboard !== null && this.paste_enabled) {
1097 1097 var cell_data = this.clipboard;
1098 1098 var new_cell = this.insert_cell_above(cell_data.cell_type);
1099 1099 new_cell.fromJSON(cell_data);
1100 1100 };
1101 1101 };
1102 1102
1103 1103 /**
1104 1104 * Paste a cell from the clipboard below the selected cell.
1105 1105 *
1106 1106 * @method paste_cell_below
1107 1107 */
1108 1108 Notebook.prototype.paste_cell_below = function () {
1109 1109 if (this.clipboard !== null && this.paste_enabled) {
1110 1110 var cell_data = this.clipboard;
1111 1111 var new_cell = this.insert_cell_below(cell_data.cell_type);
1112 1112 new_cell.fromJSON(cell_data);
1113 1113 };
1114 1114 };
1115 1115
1116 1116 // Cell undelete
1117 1117
1118 1118 /**
1119 1119 * Restore the most recently deleted cell.
1120 1120 *
1121 1121 * @method undelete
1122 1122 */
1123 1123 Notebook.prototype.undelete = function() {
1124 1124 if (this.undelete_backup !== null && this.undelete_index !== null) {
1125 1125 var current_index = this.get_selected_index();
1126 1126 if (this.undelete_index < current_index) {
1127 1127 current_index = current_index + 1;
1128 1128 }
1129 1129 if (this.undelete_index >= this.ncells()) {
1130 1130 this.select(this.ncells() - 1);
1131 1131 }
1132 1132 else {
1133 1133 this.select(this.undelete_index);
1134 1134 }
1135 1135 var cell_data = this.undelete_backup;
1136 1136 var new_cell = null;
1137 1137 if (this.undelete_below) {
1138 1138 new_cell = this.insert_cell_below(cell_data.cell_type);
1139 1139 } else {
1140 1140 new_cell = this.insert_cell_above(cell_data.cell_type);
1141 1141 }
1142 1142 new_cell.fromJSON(cell_data);
1143 1143 this.select(current_index);
1144 1144 this.undelete_backup = null;
1145 1145 this.undelete_index = null;
1146 1146 }
1147 1147 $('#undelete_cell').addClass('disabled');
1148 1148 }
1149 1149
1150 1150 // Split/merge
1151 1151
1152 1152 /**
1153 1153 * Split the selected cell into two, at the cursor.
1154 1154 *
1155 1155 * @method split_cell
1156 1156 */
1157 1157 Notebook.prototype.split_cell = function () {
1158 1158 // Todo: implement spliting for other cell types.
1159 1159 var cell = this.get_selected_cell();
1160 1160 if (cell.is_splittable()) {
1161 1161 var texta = cell.get_pre_cursor();
1162 1162 var textb = cell.get_post_cursor();
1163 1163 if (cell instanceof IPython.CodeCell) {
1164 1164 cell.set_text(textb);
1165 1165 var new_cell = this.insert_cell_above('code');
1166 1166 new_cell.set_text(texta);
1167 this.select_next();
1167 1168 } else if (cell instanceof IPython.MarkdownCell) {
1168 1169 cell.set_text(textb);
1169 1170 cell.render();
1170 1171 var new_cell = this.insert_cell_above('markdown');
1171 1172 new_cell.edit(); // editor must be visible to call set_text
1172 1173 new_cell.set_text(texta);
1173 1174 new_cell.render();
1175 this.select_next();
1174 1176 }
1175 1177 };
1176 1178 };
1177 1179
1178 1180 /**
1179 1181 * Combine the selected cell into the cell above it.
1180 1182 *
1181 1183 * @method merge_cell_above
1182 1184 */
1183 1185 Notebook.prototype.merge_cell_above = function () {
1184 1186 var index = this.get_selected_index();
1185 1187 var cell = this.get_cell(index);
1186 1188 if (!cell.is_mergeable()) {
1187 1189 return;
1188 1190 }
1189 1191 if (index > 0) {
1190 1192 var upper_cell = this.get_cell(index-1);
1191 1193 if (!upper_cell.is_mergeable()) {
1192 1194 return;
1193 1195 }
1194 1196 var upper_text = upper_cell.get_text();
1195 1197 var text = cell.get_text();
1196 1198 if (cell instanceof IPython.CodeCell) {
1197 1199 cell.set_text(upper_text+'\n'+text);
1198 1200 } else if (cell instanceof IPython.MarkdownCell) {
1199 1201 cell.edit();
1200 1202 cell.set_text(upper_text+'\n'+text);
1201 1203 cell.render();
1202 1204 };
1203 1205 this.delete_cell(index-1);
1204 1206 this.select(this.find_cell_index(cell));
1205 1207 };
1206 1208 };
1207 1209
1208 1210 /**
1209 1211 * Combine the selected cell into the cell below it.
1210 1212 *
1211 1213 * @method merge_cell_below
1212 1214 */
1213 1215 Notebook.prototype.merge_cell_below = function () {
1214 1216 var index = this.get_selected_index();
1215 1217 var cell = this.get_cell(index);
1216 1218 if (!cell.is_mergeable()) {
1217 1219 return;
1218 1220 }
1219 1221 if (index < this.ncells()-1) {
1220 1222 var lower_cell = this.get_cell(index+1);
1221 1223 if (!lower_cell.is_mergeable()) {
1222 1224 return;
1223 1225 }
1224 1226 var lower_text = lower_cell.get_text();
1225 1227 var text = cell.get_text();
1226 1228 if (cell instanceof IPython.CodeCell) {
1227 1229 cell.set_text(text+'\n'+lower_text);
1228 1230 } else if (cell instanceof IPython.MarkdownCell) {
1229 1231 cell.edit();
1230 1232 cell.set_text(text+'\n'+lower_text);
1231 1233 cell.render();
1232 1234 };
1233 1235 this.delete_cell(index+1);
1234 1236 this.select(this.find_cell_index(cell));
1235 1237 };
1236 1238 };
1237 1239
1238 1240
1239 1241 // Cell collapsing and output clearing
1240 1242
1241 1243 /**
1242 1244 * Hide a cell's output.
1243 1245 *
1244 1246 * @method collapse
1245 1247 * @param {Number} index A cell's numeric index
1246 1248 */
1247 1249 Notebook.prototype.collapse = function (index) {
1248 1250 var i = this.index_or_selected(index);
1249 1251 this.get_cell(i).collapse();
1250 1252 this.set_dirty(true);
1251 1253 };
1252 1254
1253 1255 /**
1254 1256 * Show a cell's output.
1255 1257 *
1256 1258 * @method expand
1257 1259 * @param {Number} index A cell's numeric index
1258 1260 */
1259 1261 Notebook.prototype.expand = function (index) {
1260 1262 var i = this.index_or_selected(index);
1261 1263 this.get_cell(i).expand();
1262 1264 this.set_dirty(true);
1263 1265 };
1264 1266
1265 1267 /** Toggle whether a cell's output is collapsed or expanded.
1266 1268 *
1267 1269 * @method toggle_output
1268 1270 * @param {Number} index A cell's numeric index
1269 1271 */
1270 1272 Notebook.prototype.toggle_output = function (index) {
1271 1273 var i = this.index_or_selected(index);
1272 1274 this.get_cell(i).toggle_output();
1273 1275 this.set_dirty(true);
1274 1276 };
1275 1277
1276 1278 /**
1277 1279 * Toggle a scrollbar for long cell outputs.
1278 1280 *
1279 1281 * @method toggle_output_scroll
1280 1282 * @param {Number} index A cell's numeric index
1281 1283 */
1282 1284 Notebook.prototype.toggle_output_scroll = function (index) {
1283 1285 var i = this.index_or_selected(index);
1284 1286 this.get_cell(i).toggle_output_scroll();
1285 1287 };
1286 1288
1287 1289 /**
1288 1290 * Hide each code cell's output area.
1289 1291 *
1290 1292 * @method collapse_all_output
1291 1293 */
1292 1294 Notebook.prototype.collapse_all_output = function () {
1293 1295 var ncells = this.ncells();
1294 1296 var cells = this.get_cells();
1295 1297 for (var i=0; i<ncells; i++) {
1296 1298 if (cells[i] instanceof IPython.CodeCell) {
1297 1299 cells[i].output_area.collapse();
1298 1300 }
1299 1301 };
1300 1302 // this should not be set if the `collapse` key is removed from nbformat
1301 1303 this.set_dirty(true);
1302 1304 };
1303 1305
1304 1306 /**
1305 1307 * Expand each code cell's output area, and add a scrollbar for long output.
1306 1308 *
1307 1309 * @method scroll_all_output
1308 1310 */
1309 1311 Notebook.prototype.scroll_all_output = function () {
1310 1312 var ncells = this.ncells();
1311 1313 var cells = this.get_cells();
1312 1314 for (var i=0; i<ncells; i++) {
1313 1315 if (cells[i] instanceof IPython.CodeCell) {
1314 1316 cells[i].output_area.expand();
1315 1317 cells[i].output_area.scroll_if_long();
1316 1318 }
1317 1319 };
1318 1320 // this should not be set if the `collapse` key is removed from nbformat
1319 1321 this.set_dirty(true);
1320 1322 };
1321 1323
1322 1324 /**
1323 1325 * Expand each code cell's output area, and remove scrollbars.
1324 1326 *
1325 1327 * @method expand_all_output
1326 1328 */
1327 1329 Notebook.prototype.expand_all_output = function () {
1328 1330 var ncells = this.ncells();
1329 1331 var cells = this.get_cells();
1330 1332 for (var i=0; i<ncells; i++) {
1331 1333 if (cells[i] instanceof IPython.CodeCell) {
1332 1334 cells[i].output_area.expand();
1333 1335 cells[i].output_area.unscroll_area();
1334 1336 }
1335 1337 };
1336 1338 // this should not be set if the `collapse` key is removed from nbformat
1337 1339 this.set_dirty(true);
1338 1340 };
1339 1341
1340 1342 /**
1341 1343 * Clear each code cell's output area.
1342 1344 *
1343 1345 * @method clear_all_output
1344 1346 */
1345 1347 Notebook.prototype.clear_all_output = function () {
1346 1348 var ncells = this.ncells();
1347 1349 var cells = this.get_cells();
1348 1350 for (var i=0; i<ncells; i++) {
1349 1351 if (cells[i] instanceof IPython.CodeCell) {
1350 1352 cells[i].clear_output();
1351 1353 // Make all In[] prompts blank, as well
1352 1354 // TODO: make this configurable (via checkbox?)
1353 1355 cells[i].set_input_prompt();
1354 1356 }
1355 1357 };
1356 1358 this.set_dirty(true);
1357 1359 };
1358 1360
1359 1361
1360 1362 // Other cell functions: line numbers, ...
1361 1363
1362 1364 /**
1363 1365 * Toggle line numbers in the selected cell's input area.
1364 1366 *
1365 1367 * @method cell_toggle_line_numbers
1366 1368 */
1367 1369 Notebook.prototype.cell_toggle_line_numbers = function() {
1368 1370 this.get_selected_cell().toggle_line_numbers();
1369 1371 };
1370 1372
1371 1373 // Kernel related things
1372 1374
1373 1375 /**
1374 1376 * Start a new kernel and set it on each code cell.
1375 1377 *
1376 1378 * @method start_kernel
1377 1379 */
1378 1380 Notebook.prototype.start_kernel = function () {
1379 1381 var base_url = $('body').data('baseKernelUrl') + "kernels";
1380 1382 this.kernel = new IPython.Kernel(base_url);
1381 1383 this.kernel.start({notebook: this.notebook_id});
1382 1384 // Now that the kernel has been created, tell the CodeCells about it.
1383 1385 var ncells = this.ncells();
1384 1386 for (var i=0; i<ncells; i++) {
1385 1387 var cell = this.get_cell(i);
1386 1388 if (cell instanceof IPython.CodeCell) {
1387 1389 cell.set_kernel(this.kernel)
1388 1390 };
1389 1391 };
1390 1392 };
1391 1393
1392 1394 /**
1393 1395 * Prompt the user to restart the IPython kernel.
1394 1396 *
1395 1397 * @method restart_kernel
1396 1398 */
1397 1399 Notebook.prototype.restart_kernel = function () {
1398 1400 var that = this;
1399 1401 IPython.dialog.modal({
1400 1402 title : "Restart kernel or continue running?",
1401 1403 body : $("<p/>").html(
1402 1404 'Do you want to restart the current kernel? You will lose all variables defined in it.'
1403 1405 ),
1404 1406 buttons : {
1405 1407 "Continue running" : {},
1406 1408 "Restart" : {
1407 1409 "class" : "btn-danger",
1408 1410 "click" : function() {
1409 1411 that.kernel.restart();
1410 1412 }
1411 1413 }
1412 1414 }
1413 1415 });
1414 1416 };
1415 1417
1416 1418 /**
1417 1419 * Run the selected cell.
1418 1420 *
1419 1421 * Execute or render cell outputs.
1420 1422 *
1421 1423 * @method execute_selected_cell
1422 1424 * @param {Object} options Customize post-execution behavior
1423 1425 */
1424 1426 Notebook.prototype.execute_selected_cell = function (options) {
1425 1427 // add_new: should a new cell be added if we are at the end of the nb
1426 1428 // terminal: execute in terminal mode, which stays in the current cell
1427 1429 var default_options = {terminal: false, add_new: true};
1428 1430 $.extend(default_options, options);
1429 1431 var that = this;
1430 1432 var cell = that.get_selected_cell();
1431 1433 var cell_index = that.find_cell_index(cell);
1432 1434 if (cell instanceof IPython.CodeCell) {
1433 1435 cell.execute();
1434 1436 }
1435 1437 if (default_options.terminal) {
1436 1438 cell.select_all();
1437 1439 } else {
1438 1440 if ((cell_index === (that.ncells()-1)) && default_options.add_new) {
1439 1441 that.insert_cell_below('code');
1440 1442 // If we are adding a new cell at the end, scroll down to show it.
1441 1443 that.scroll_to_bottom();
1442 1444 } else {
1443 1445 that.select(cell_index+1);
1444 1446 };
1445 1447 };
1446 1448 this.set_dirty(true);
1447 1449 };
1448 1450
1449 1451 /**
1450 1452 * Execute all cells below the selected cell.
1451 1453 *
1452 1454 * @method execute_cells_below
1453 1455 */
1454 1456 Notebook.prototype.execute_cells_below = function () {
1455 1457 this.execute_cell_range(this.get_selected_index(), this.ncells());
1456 1458 this.scroll_to_bottom();
1457 1459 };
1458 1460
1459 1461 /**
1460 1462 * Execute all cells above the selected cell.
1461 1463 *
1462 1464 * @method execute_cells_above
1463 1465 */
1464 1466 Notebook.prototype.execute_cells_above = function () {
1465 1467 this.execute_cell_range(0, this.get_selected_index());
1466 1468 };
1467 1469
1468 1470 /**
1469 1471 * Execute all cells.
1470 1472 *
1471 1473 * @method execute_all_cells
1472 1474 */
1473 1475 Notebook.prototype.execute_all_cells = function () {
1474 1476 this.execute_cell_range(0, this.ncells());
1475 1477 this.scroll_to_bottom();
1476 1478 };
1477 1479
1478 1480 /**
1479 1481 * Execute a contiguous range of cells.
1480 1482 *
1481 1483 * @method execute_cell_range
1482 1484 * @param {Number} start Index of the first cell to execute (inclusive)
1483 1485 * @param {Number} end Index of the last cell to execute (exclusive)
1484 1486 */
1485 1487 Notebook.prototype.execute_cell_range = function (start, end) {
1486 1488 for (var i=start; i<end; i++) {
1487 1489 this.select(i);
1488 1490 this.execute_selected_cell({add_new:false});
1489 1491 };
1490 1492 };
1491 1493
1492 1494 // Persistance and loading
1493 1495
1494 1496 /**
1495 1497 * Getter method for this notebook's ID.
1496 1498 *
1497 1499 * @method get_notebook_id
1498 1500 * @return {String} This notebook's ID
1499 1501 */
1500 1502 Notebook.prototype.get_notebook_id = function () {
1501 1503 return this.notebook_id;
1502 1504 };
1503 1505
1504 1506 /**
1505 1507 * Getter method for this notebook's name.
1506 1508 *
1507 1509 * @method get_notebook_name
1508 1510 * @return {String} This notebook's name
1509 1511 */
1510 1512 Notebook.prototype.get_notebook_name = function () {
1511 1513 return this.notebook_name;
1512 1514 };
1513 1515
1514 1516 /**
1515 1517 * Setter method for this notebook's name.
1516 1518 *
1517 1519 * @method set_notebook_name
1518 1520 * @param {String} name A new name for this notebook
1519 1521 */
1520 1522 Notebook.prototype.set_notebook_name = function (name) {
1521 1523 this.notebook_name = name;
1522 1524 };
1523 1525
1524 1526 /**
1525 1527 * Check that a notebook's name is valid.
1526 1528 *
1527 1529 * @method test_notebook_name
1528 1530 * @param {String} nbname A name for this notebook
1529 1531 * @return {Boolean} True if the name is valid, false if invalid
1530 1532 */
1531 1533 Notebook.prototype.test_notebook_name = function (nbname) {
1532 1534 nbname = nbname || '';
1533 1535 if (this.notebook_name_blacklist_re.test(nbname) == false && nbname.length>0) {
1534 1536 return true;
1535 1537 } else {
1536 1538 return false;
1537 1539 };
1538 1540 };
1539 1541
1540 1542 /**
1541 1543 * Load a notebook from JSON (.ipynb).
1542 1544 *
1543 1545 * This currently handles one worksheet: others are deleted.
1544 1546 *
1545 1547 * @method fromJSON
1546 1548 * @param {Object} data JSON representation of a notebook
1547 1549 */
1548 1550 Notebook.prototype.fromJSON = function (data) {
1549 1551 var ncells = this.ncells();
1550 1552 var i;
1551 1553 for (i=0; i<ncells; i++) {
1552 1554 // Always delete cell 0 as they get renumbered as they are deleted.
1553 1555 this.delete_cell(0);
1554 1556 };
1555 1557 // Save the metadata and name.
1556 1558 this.metadata = data.metadata;
1557 1559 this.notebook_name = data.metadata.name;
1558 1560 // Only handle 1 worksheet for now.
1559 1561 var worksheet = data.worksheets[0];
1560 1562 if (worksheet !== undefined) {
1561 1563 if (worksheet.metadata) {
1562 1564 this.worksheet_metadata = worksheet.metadata;
1563 1565 }
1564 1566 var new_cells = worksheet.cells;
1565 1567 ncells = new_cells.length;
1566 1568 var cell_data = null;
1567 1569 var new_cell = null;
1568 1570 for (i=0; i<ncells; i++) {
1569 1571 cell_data = new_cells[i];
1570 1572 // VERSIONHACK: plaintext -> raw
1571 1573 // handle never-released plaintext name for raw cells
1572 1574 if (cell_data.cell_type === 'plaintext'){
1573 1575 cell_data.cell_type = 'raw';
1574 1576 }
1575 1577
1576 1578 new_cell = this.insert_cell_below(cell_data.cell_type);
1577 1579 new_cell.fromJSON(cell_data);
1578 1580 };
1579 1581 };
1580 1582 if (data.worksheets.length > 1) {
1581 1583 IPython.dialog.modal({
1582 1584 title : "Multiple worksheets",
1583 1585 body : "This notebook has " + data.worksheets.length + " worksheets, " +
1584 1586 "but this version of IPython can only handle the first. " +
1585 1587 "If you save this notebook, worksheets after the first will be lost.",
1586 1588 buttons : {
1587 1589 OK : {
1588 1590 class : "btn-danger"
1589 1591 }
1590 1592 }
1591 1593 });
1592 1594 }
1593 1595 };
1594 1596
1595 1597 /**
1596 1598 * Dump this notebook into a JSON-friendly object.
1597 1599 *
1598 1600 * @method toJSON
1599 1601 * @return {Object} A JSON-friendly representation of this notebook.
1600 1602 */
1601 1603 Notebook.prototype.toJSON = function () {
1602 1604 var cells = this.get_cells();
1603 1605 var ncells = cells.length;
1604 1606 var cell_array = new Array(ncells);
1605 1607 for (var i=0; i<ncells; i++) {
1606 1608 cell_array[i] = cells[i].toJSON();
1607 1609 };
1608 1610 var data = {
1609 1611 // Only handle 1 worksheet for now.
1610 1612 worksheets : [{
1611 1613 cells: cell_array,
1612 1614 metadata: this.worksheet_metadata
1613 1615 }],
1614 1616 metadata : this.metadata
1615 1617 };
1616 1618 return data;
1617 1619 };
1618 1620
1619 1621 /**
1620 1622 * Start an autosave timer, for periodically saving the notebook.
1621 1623 *
1622 1624 * @method set_autosave_interval
1623 1625 * @param {Integer} interval the autosave interval in milliseconds
1624 1626 */
1625 1627 Notebook.prototype.set_autosave_interval = function (interval) {
1626 1628 var that = this;
1627 1629 // clear previous interval, so we don't get simultaneous timers
1628 1630 if (this.autosave_timer) {
1629 1631 clearInterval(this.autosave_timer);
1630 1632 }
1631 1633
1632 1634 this.autosave_interval = this.minimum_autosave_interval = interval;
1633 1635 if (interval) {
1634 1636 this.autosave_timer = setInterval(function() {
1635 1637 if (that.dirty) {
1636 1638 that.save_notebook();
1637 1639 }
1638 1640 }, interval);
1639 1641 $([IPython.events]).trigger("autosave_enabled.Notebook", interval);
1640 1642 } else {
1641 1643 this.autosave_timer = null;
1642 1644 $([IPython.events]).trigger("autosave_disabled.Notebook");
1643 1645 };
1644 1646 };
1645 1647
1646 1648 /**
1647 1649 * Save this notebook on the server.
1648 1650 *
1649 1651 * @method save_notebook
1650 1652 */
1651 1653 Notebook.prototype.save_notebook = function () {
1652 1654 // We may want to move the name/id/nbformat logic inside toJSON?
1653 1655 var data = this.toJSON();
1654 1656 data.metadata.name = this.notebook_name;
1655 1657 data.nbformat = this.nbformat;
1656 1658 data.nbformat_minor = this.nbformat_minor;
1657 1659
1658 1660 // time the ajax call for autosave tuning purposes.
1659 1661 var start = new Date().getTime();
1660 1662
1661 1663 // We do the call with settings so we can set cache to false.
1662 1664 var settings = {
1663 1665 processData : false,
1664 1666 cache : false,
1665 1667 type : "PUT",
1666 1668 data : JSON.stringify(data),
1667 1669 headers : {'Content-Type': 'application/json'},
1668 1670 success : $.proxy(this.save_notebook_success, this, start),
1669 1671 error : $.proxy(this.save_notebook_error, this)
1670 1672 };
1671 1673 $([IPython.events]).trigger('notebook_saving.Notebook');
1672 1674 var url = this.baseProjectUrl() + 'notebooks/' + this.notebook_id;
1673 1675 $.ajax(url, settings);
1674 1676 };
1675 1677
1676 1678 /**
1677 1679 * Success callback for saving a notebook.
1678 1680 *
1679 1681 * @method save_notebook_success
1680 1682 * @param {Integer} start the time when the save request started
1681 1683 * @param {Object} data JSON representation of a notebook
1682 1684 * @param {String} status Description of response status
1683 1685 * @param {jqXHR} xhr jQuery Ajax object
1684 1686 */
1685 1687 Notebook.prototype.save_notebook_success = function (start, data, status, xhr) {
1686 1688 this.set_dirty(false);
1687 1689 $([IPython.events]).trigger('notebook_saved.Notebook');
1688 1690 this._update_autosave_interval(start);
1689 1691 if (this._checkpoint_after_save) {
1690 1692 this.create_checkpoint();
1691 1693 this._checkpoint_after_save = false;
1692 1694 };
1693 1695 };
1694 1696
1695 1697 /**
1696 1698 * update the autosave interval based on how long the last save took
1697 1699 *
1698 1700 * @method _update_autosave_interval
1699 1701 * @param {Integer} timestamp when the save request started
1700 1702 */
1701 1703 Notebook.prototype._update_autosave_interval = function (start) {
1702 1704 var duration = (new Date().getTime() - start);
1703 1705 if (this.autosave_interval) {
1704 1706 // new save interval: higher of 10x save duration or parameter (default 30 seconds)
1705 1707 var interval = Math.max(10 * duration, this.minimum_autosave_interval);
1706 1708 // round to 10 seconds, otherwise we will be setting a new interval too often
1707 1709 interval = 10000 * Math.round(interval / 10000);
1708 1710 // set new interval, if it's changed
1709 1711 if (interval != this.autosave_interval) {
1710 1712 this.set_autosave_interval(interval);
1711 1713 }
1712 1714 }
1713 1715 };
1714 1716
1715 1717 /**
1716 1718 * Failure callback for saving a notebook.
1717 1719 *
1718 1720 * @method save_notebook_error
1719 1721 * @param {jqXHR} xhr jQuery Ajax object
1720 1722 * @param {String} status Description of response status
1721 1723 * @param {String} error_msg HTTP error message
1722 1724 */
1723 1725 Notebook.prototype.save_notebook_error = function (xhr, status, error_msg) {
1724 1726 $([IPython.events]).trigger('notebook_save_failed.Notebook');
1725 1727 };
1726 1728
1727 1729 /**
1728 1730 * Request a notebook's data from the server.
1729 1731 *
1730 1732 * @method load_notebook
1731 1733 * @param {String} notebook_id A notebook to load
1732 1734 */
1733 1735 Notebook.prototype.load_notebook = function (notebook_id) {
1734 1736 var that = this;
1735 1737 this.notebook_id = notebook_id;
1736 1738 // We do the call with settings so we can set cache to false.
1737 1739 var settings = {
1738 1740 processData : false,
1739 1741 cache : false,
1740 1742 type : "GET",
1741 1743 dataType : "json",
1742 1744 success : $.proxy(this.load_notebook_success,this),
1743 1745 error : $.proxy(this.load_notebook_error,this),
1744 1746 };
1745 1747 $([IPython.events]).trigger('notebook_loading.Notebook');
1746 1748 var url = this.baseProjectUrl() + 'notebooks/' + this.notebook_id;
1747 1749 $.ajax(url, settings);
1748 1750 };
1749 1751
1750 1752 /**
1751 1753 * Success callback for loading a notebook from the server.
1752 1754 *
1753 1755 * Load notebook data from the JSON response.
1754 1756 *
1755 1757 * @method load_notebook_success
1756 1758 * @param {Object} data JSON representation of a notebook
1757 1759 * @param {String} status Description of response status
1758 1760 * @param {jqXHR} xhr jQuery Ajax object
1759 1761 */
1760 1762 Notebook.prototype.load_notebook_success = function (data, status, xhr) {
1761 1763 this.fromJSON(data);
1762 1764 if (this.ncells() === 0) {
1763 1765 this.insert_cell_below('code');
1764 1766 };
1765 1767 this.set_dirty(false);
1766 1768 this.select(0);
1767 1769 this.scroll_to_top();
1768 1770 if (data.orig_nbformat !== undefined && data.nbformat !== data.orig_nbformat) {
1769 1771 var msg = "This notebook has been converted from an older " +
1770 1772 "notebook format (v"+data.orig_nbformat+") to the current notebook " +
1771 1773 "format (v"+data.nbformat+"). The next time you save this notebook, the " +
1772 1774 "newer notebook format will be used and older versions of IPython " +
1773 1775 "may not be able to read it. To keep the older version, close the " +
1774 1776 "notebook without saving it.";
1775 1777 IPython.dialog.modal({
1776 1778 title : "Notebook converted",
1777 1779 body : msg,
1778 1780 buttons : {
1779 1781 OK : {
1780 1782 class : "btn-primary"
1781 1783 }
1782 1784 }
1783 1785 });
1784 1786 } else if (data.orig_nbformat_minor !== undefined && data.nbformat_minor !== data.orig_nbformat_minor) {
1785 1787 var that = this;
1786 1788 var orig_vs = 'v' + data.nbformat + '.' + data.orig_nbformat_minor;
1787 1789 var this_vs = 'v' + data.nbformat + '.' + this.nbformat_minor;
1788 1790 var msg = "This notebook is version " + orig_vs + ", but we only fully support up to " +
1789 1791 this_vs + ". You can still work with this notebook, but some features " +
1790 1792 "introduced in later notebook versions may not be available."
1791 1793
1792 1794 IPython.dialog.modal({
1793 1795 title : "Newer Notebook",
1794 1796 body : msg,
1795 1797 buttons : {
1796 1798 OK : {
1797 1799 class : "btn-danger"
1798 1800 }
1799 1801 }
1800 1802 });
1801 1803
1802 1804 }
1803 1805
1804 1806 // Create the kernel after the notebook is completely loaded to prevent
1805 1807 // code execution upon loading, which is a security risk.
1806 1808 this.start_kernel();
1807 1809 // load our checkpoint list
1808 1810 IPython.notebook.list_checkpoints();
1809 1811
1810 1812 $([IPython.events]).trigger('notebook_loaded.Notebook');
1811 1813 };
1812 1814
1813 1815 /**
1814 1816 * Failure callback for loading a notebook from the server.
1815 1817 *
1816 1818 * @method load_notebook_error
1817 1819 * @param {jqXHR} xhr jQuery Ajax object
1818 1820 * @param {String} textStatus Description of response status
1819 1821 * @param {String} errorThrow HTTP error message
1820 1822 */
1821 1823 Notebook.prototype.load_notebook_error = function (xhr, textStatus, errorThrow) {
1822 1824 if (xhr.status === 400) {
1823 1825 var msg = errorThrow;
1824 1826 } else if (xhr.status === 500) {
1825 1827 var msg = "An unknown error occurred while loading this notebook. " +
1826 1828 "This version can load notebook formats " +
1827 1829 "v" + this.nbformat + " or earlier.";
1828 1830 }
1829 1831 IPython.dialog.modal({
1830 1832 title: "Error loading notebook",
1831 1833 body : msg,
1832 1834 buttons : {
1833 1835 "OK": {}
1834 1836 }
1835 1837 });
1836 1838 }
1837 1839
1838 1840 /********************* checkpoint-related *********************/
1839 1841
1840 1842 /**
1841 1843 * Save the notebook then immediately create a checkpoint.
1842 1844 *
1843 1845 * @method save_checkpoint
1844 1846 */
1845 1847 Notebook.prototype.save_checkpoint = function () {
1846 1848 this._checkpoint_after_save = true;
1847 1849 this.save_notebook();
1848 1850 };
1849 1851
1850 1852 /**
1851 1853 * Add a checkpoint for this notebook.
1852 1854 * for use as a callback from checkpoint creation.
1853 1855 *
1854 1856 * @method add_checkpoint
1855 1857 */
1856 1858 Notebook.prototype.add_checkpoint = function (checkpoint) {
1857 1859 var found = false;
1858 1860 for (var i = 0; i < this.checkpoints.length; i++) {
1859 1861 var existing = this.checkpoints[i];
1860 1862 if (existing.checkpoint_id == checkpoint.checkpoint_id) {
1861 1863 found = true;
1862 1864 this.checkpoints[i] = checkpoint;
1863 1865 break;
1864 1866 }
1865 1867 }
1866 1868 if (!found) {
1867 1869 this.checkpoints.push(checkpoint);
1868 1870 }
1869 1871 this.last_checkpoint = this.checkpoints[this.checkpoints.length - 1];
1870 1872 };
1871 1873
1872 1874 /**
1873 1875 * List checkpoints for this notebook.
1874 1876 *
1875 1877 * @method list_checkpoints
1876 1878 */
1877 1879 Notebook.prototype.list_checkpoints = function () {
1878 1880 var url = this.baseProjectUrl() + 'notebooks/' + this.notebook_id + '/checkpoints';
1879 1881 $.get(url).done(
1880 1882 $.proxy(this.list_checkpoints_success, this)
1881 1883 ).fail(
1882 1884 $.proxy(this.list_checkpoints_error, this)
1883 1885 );
1884 1886 };
1885 1887
1886 1888 /**
1887 1889 * Success callback for listing checkpoints.
1888 1890 *
1889 1891 * @method list_checkpoint_success
1890 1892 * @param {Object} data JSON representation of a checkpoint
1891 1893 * @param {String} status Description of response status
1892 1894 * @param {jqXHR} xhr jQuery Ajax object
1893 1895 */
1894 1896 Notebook.prototype.list_checkpoints_success = function (data, status, xhr) {
1895 1897 var data = $.parseJSON(data);
1896 1898 this.checkpoints = data;
1897 1899 if (data.length) {
1898 1900 this.last_checkpoint = data[data.length - 1];
1899 1901 } else {
1900 1902 this.last_checkpoint = null;
1901 1903 }
1902 1904 $([IPython.events]).trigger('checkpoints_listed.Notebook', [data]);
1903 1905 };
1904 1906
1905 1907 /**
1906 1908 * Failure callback for listing a checkpoint.
1907 1909 *
1908 1910 * @method list_checkpoint_error
1909 1911 * @param {jqXHR} xhr jQuery Ajax object
1910 1912 * @param {String} status Description of response status
1911 1913 * @param {String} error_msg HTTP error message
1912 1914 */
1913 1915 Notebook.prototype.list_checkpoints_error = function (xhr, status, error_msg) {
1914 1916 $([IPython.events]).trigger('list_checkpoints_failed.Notebook');
1915 1917 };
1916 1918
1917 1919 /**
1918 1920 * Create a checkpoint of this notebook on the server from the most recent save.
1919 1921 *
1920 1922 * @method create_checkpoint
1921 1923 */
1922 1924 Notebook.prototype.create_checkpoint = function () {
1923 1925 var url = this.baseProjectUrl() + 'notebooks/' + this.notebook_id + '/checkpoints';
1924 1926 $.post(url).done(
1925 1927 $.proxy(this.create_checkpoint_success, this)
1926 1928 ).fail(
1927 1929 $.proxy(this.create_checkpoint_error, this)
1928 1930 );
1929 1931 };
1930 1932
1931 1933 /**
1932 1934 * Success callback for creating a checkpoint.
1933 1935 *
1934 1936 * @method create_checkpoint_success
1935 1937 * @param {Object} data JSON representation of a checkpoint
1936 1938 * @param {String} status Description of response status
1937 1939 * @param {jqXHR} xhr jQuery Ajax object
1938 1940 */
1939 1941 Notebook.prototype.create_checkpoint_success = function (data, status, xhr) {
1940 1942 var data = $.parseJSON(data);
1941 1943 this.add_checkpoint(data);
1942 1944 $([IPython.events]).trigger('checkpoint_created.Notebook', data);
1943 1945 };
1944 1946
1945 1947 /**
1946 1948 * Failure callback for creating a checkpoint.
1947 1949 *
1948 1950 * @method create_checkpoint_error
1949 1951 * @param {jqXHR} xhr jQuery Ajax object
1950 1952 * @param {String} status Description of response status
1951 1953 * @param {String} error_msg HTTP error message
1952 1954 */
1953 1955 Notebook.prototype.create_checkpoint_error = function (xhr, status, error_msg) {
1954 1956 $([IPython.events]).trigger('checkpoint_failed.Notebook');
1955 1957 };
1956 1958
1957 1959 Notebook.prototype.restore_checkpoint_dialog = function (checkpoint) {
1958 1960 var that = this;
1959 1961 var checkpoint = checkpoint || this.last_checkpoint;
1960 1962 if ( ! checkpoint ) {
1961 1963 console.log("restore dialog, but no checkpoint to restore to!");
1962 1964 return;
1963 1965 }
1964 1966 var body = $('<div/>').append(
1965 1967 $('<p/>').addClass("p-space").text(
1966 1968 "Are you sure you want to revert the notebook to " +
1967 1969 "the latest checkpoint?"
1968 1970 ).append(
1969 1971 $("<strong/>").text(
1970 1972 " This cannot be undone."
1971 1973 )
1972 1974 )
1973 1975 ).append(
1974 1976 $('<p/>').addClass("p-space").text("The checkpoint was last updated at:")
1975 1977 ).append(
1976 1978 $('<p/>').addClass("p-space").text(
1977 1979 Date(checkpoint.last_modified)
1978 1980 ).css("text-align", "center")
1979 1981 );
1980 1982
1981 1983 IPython.dialog.modal({
1982 1984 title : "Revert notebook to checkpoint",
1983 1985 body : body,
1984 1986 buttons : {
1985 1987 Revert : {
1986 1988 class : "btn-danger",
1987 1989 click : function () {
1988 1990 that.restore_checkpoint(checkpoint.checkpoint_id);
1989 1991 }
1990 1992 },
1991 1993 Cancel : {}
1992 1994 }
1993 1995 });
1994 1996 }
1995 1997
1996 1998 /**
1997 1999 * Restore the notebook to a checkpoint state.
1998 2000 *
1999 2001 * @method restore_checkpoint
2000 2002 * @param {String} checkpoint ID
2001 2003 */
2002 2004 Notebook.prototype.restore_checkpoint = function (checkpoint) {
2003 2005 $([IPython.events]).trigger('checkpoint_restoring.Notebook', checkpoint);
2004 2006 var url = this.baseProjectUrl() + 'notebooks/' + this.notebook_id + '/checkpoints/' + checkpoint;
2005 2007 $.post(url).done(
2006 2008 $.proxy(this.restore_checkpoint_success, this)
2007 2009 ).fail(
2008 2010 $.proxy(this.restore_checkpoint_error, this)
2009 2011 );
2010 2012 };
2011 2013
2012 2014 /**
2013 2015 * Success callback for restoring a notebook to a checkpoint.
2014 2016 *
2015 2017 * @method restore_checkpoint_success
2016 2018 * @param {Object} data (ignored, should be empty)
2017 2019 * @param {String} status Description of response status
2018 2020 * @param {jqXHR} xhr jQuery Ajax object
2019 2021 */
2020 2022 Notebook.prototype.restore_checkpoint_success = function (data, status, xhr) {
2021 2023 $([IPython.events]).trigger('checkpoint_restored.Notebook');
2022 2024 this.load_notebook(this.notebook_id);
2023 2025 };
2024 2026
2025 2027 /**
2026 2028 * Failure callback for restoring a notebook to a checkpoint.
2027 2029 *
2028 2030 * @method restore_checkpoint_error
2029 2031 * @param {jqXHR} xhr jQuery Ajax object
2030 2032 * @param {String} status Description of response status
2031 2033 * @param {String} error_msg HTTP error message
2032 2034 */
2033 2035 Notebook.prototype.restore_checkpoint_error = function (xhr, status, error_msg) {
2034 2036 $([IPython.events]).trigger('checkpoint_restore_failed.Notebook');
2035 2037 };
2036 2038
2037 2039 /**
2038 2040 * Delete a notebook checkpoint.
2039 2041 *
2040 2042 * @method delete_checkpoint
2041 2043 * @param {String} checkpoint ID
2042 2044 */
2043 2045 Notebook.prototype.delete_checkpoint = function (checkpoint) {
2044 2046 $([IPython.events]).trigger('checkpoint_deleting.Notebook', checkpoint);
2045 2047 var url = this.baseProjectUrl() + 'notebooks/' + this.notebook_id + '/checkpoints/' + checkpoint;
2046 2048 $.ajax(url, {
2047 2049 type: 'DELETE',
2048 2050 success: $.proxy(this.delete_checkpoint_success, this),
2049 2051 error: $.proxy(this.delete_notebook_error,this)
2050 2052 });
2051 2053 };
2052 2054
2053 2055 /**
2054 2056 * Success callback for deleting a notebook checkpoint
2055 2057 *
2056 2058 * @method delete_checkpoint_success
2057 2059 * @param {Object} data (ignored, should be empty)
2058 2060 * @param {String} status Description of response status
2059 2061 * @param {jqXHR} xhr jQuery Ajax object
2060 2062 */
2061 2063 Notebook.prototype.delete_checkpoint_success = function (data, status, xhr) {
2062 2064 $([IPython.events]).trigger('checkpoint_deleted.Notebook', data);
2063 2065 this.load_notebook(this.notebook_id);
2064 2066 };
2065 2067
2066 2068 /**
2067 2069 * Failure callback for deleting a notebook checkpoint.
2068 2070 *
2069 2071 * @method delete_checkpoint_error
2070 2072 * @param {jqXHR} xhr jQuery Ajax object
2071 2073 * @param {String} status Description of response status
2072 2074 * @param {String} error_msg HTTP error message
2073 2075 */
2074 2076 Notebook.prototype.delete_checkpoint_error = function (xhr, status, error_msg) {
2075 2077 $([IPython.events]).trigger('checkpoint_delete_failed.Notebook');
2076 2078 };
2077 2079
2078 2080
2079 2081 IPython.Notebook = Notebook;
2080 2082
2081 2083
2082 2084 return IPython;
2083 2085
2084 2086 }(IPython));
2085 2087
General Comments 0
You need to be logged in to leave comments. Login now