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