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