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