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