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