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