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