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