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