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