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