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