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