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