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