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