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