##// END OF EJS Templates
Merge pull request #6408 from minrk/new-cell-code...
Fernando Perez -
r17786:0f99ba31 merge
parent child Browse files
Show More
@@ -1,563 +1,570
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'base/js/namespace',
6 6 'jquery',
7 7 ], function(IPython, $){
8 8 "use strict";
9 9
10 10 IPython.load_extensions = function () {
11 11 // load one or more IPython notebook extensions with requirejs
12 12
13 13 var extensions = [];
14 14 var extension_names = arguments;
15 15 for (var i = 0; i < extension_names.length; i++) {
16 16 extensions.push("nbextensions/" + arguments[i]);
17 17 }
18 18
19 19 require(extensions,
20 20 function () {
21 21 for (var i = 0; i < arguments.length; i++) {
22 22 var ext = arguments[i];
23 23 var ext_name = extension_names[i];
24 24 // success callback
25 25 console.log("Loaded extension: " + ext_name);
26 26 if (ext && ext.load_ipython_extension !== undefined) {
27 27 ext.load_ipython_extension();
28 28 }
29 29 }
30 30 },
31 31 function (err) {
32 32 // failure callback
33 33 console.log("Failed to load extension(s):", err.requireModules, err);
34 34 }
35 35 );
36 36 };
37 37
38 38 //============================================================================
39 39 // Cross-browser RegEx Split
40 40 //============================================================================
41 41
42 42 // This code has been MODIFIED from the code licensed below to not replace the
43 43 // default browser split. The license is reproduced here.
44 44
45 45 // see http://blog.stevenlevithan.com/archives/cross-browser-split for more info:
46 46 /*!
47 47 * Cross-Browser Split 1.1.1
48 48 * Copyright 2007-2012 Steven Levithan <stevenlevithan.com>
49 49 * Available under the MIT License
50 50 * ECMAScript compliant, uniform cross-browser split method
51 51 */
52 52
53 53 /**
54 54 * Splits a string into an array of strings using a regex or string
55 55 * separator. Matches of the separator are not included in the result array.
56 56 * However, if `separator` is a regex that contains capturing groups,
57 57 * backreferences are spliced into the result each time `separator` is
58 58 * matched. Fixes browser bugs compared to the native
59 59 * `String.prototype.split` and can be used reliably cross-browser.
60 60 * @param {String} str String to split.
61 61 * @param {RegExp|String} separator Regex or string to use for separating
62 62 * the string.
63 63 * @param {Number} [limit] Maximum number of items to include in the result
64 64 * array.
65 65 * @returns {Array} Array of substrings.
66 66 * @example
67 67 *
68 68 * // Basic use
69 69 * regex_split('a b c d', ' ');
70 70 * // -> ['a', 'b', 'c', 'd']
71 71 *
72 72 * // With limit
73 73 * regex_split('a b c d', ' ', 2);
74 74 * // -> ['a', 'b']
75 75 *
76 76 * // Backreferences in result array
77 77 * regex_split('..word1 word2..', /([a-z]+)(\d+)/i);
78 78 * // -> ['..', 'word', '1', ' ', 'word', '2', '..']
79 79 */
80 80 var regex_split = function (str, separator, limit) {
81 81 // If `separator` is not a regex, use `split`
82 82 if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
83 83 return split.call(str, separator, limit);
84 84 }
85 85 var output = [],
86 86 flags = (separator.ignoreCase ? "i" : "") +
87 87 (separator.multiline ? "m" : "") +
88 88 (separator.extended ? "x" : "") + // Proposed for ES6
89 89 (separator.sticky ? "y" : ""), // Firefox 3+
90 90 lastLastIndex = 0,
91 91 // Make `global` and avoid `lastIndex` issues by working with a copy
92 92 separator = new RegExp(separator.source, flags + "g"),
93 93 separator2, match, lastIndex, lastLength;
94 94 str += ""; // Type-convert
95 95
96 96 var compliantExecNpcg = typeof(/()??/.exec("")[1]) === "undefined";
97 97 if (!compliantExecNpcg) {
98 98 // Doesn't need flags gy, but they don't hurt
99 99 separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
100 100 }
101 101 /* Values for `limit`, per the spec:
102 102 * If undefined: 4294967295 // Math.pow(2, 32) - 1
103 103 * If 0, Infinity, or NaN: 0
104 104 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
105 105 * If negative number: 4294967296 - Math.floor(Math.abs(limit))
106 106 * If other: Type-convert, then use the above rules
107 107 */
108 108 limit = typeof(limit) === "undefined" ?
109 109 -1 >>> 0 : // Math.pow(2, 32) - 1
110 110 limit >>> 0; // ToUint32(limit)
111 111 while (match = separator.exec(str)) {
112 112 // `separator.lastIndex` is not reliable cross-browser
113 113 lastIndex = match.index + match[0].length;
114 114 if (lastIndex > lastLastIndex) {
115 115 output.push(str.slice(lastLastIndex, match.index));
116 116 // Fix browsers whose `exec` methods don't consistently return `undefined` for
117 117 // nonparticipating capturing groups
118 118 if (!compliantExecNpcg && match.length > 1) {
119 119 match[0].replace(separator2, function () {
120 120 for (var i = 1; i < arguments.length - 2; i++) {
121 121 if (typeof(arguments[i]) === "undefined") {
122 122 match[i] = undefined;
123 123 }
124 124 }
125 125 });
126 126 }
127 127 if (match.length > 1 && match.index < str.length) {
128 128 Array.prototype.push.apply(output, match.slice(1));
129 129 }
130 130 lastLength = match[0].length;
131 131 lastLastIndex = lastIndex;
132 132 if (output.length >= limit) {
133 133 break;
134 134 }
135 135 }
136 136 if (separator.lastIndex === match.index) {
137 137 separator.lastIndex++; // Avoid an infinite loop
138 138 }
139 139 }
140 140 if (lastLastIndex === str.length) {
141 141 if (lastLength || !separator.test("")) {
142 142 output.push("");
143 143 }
144 144 } else {
145 145 output.push(str.slice(lastLastIndex));
146 146 }
147 147 return output.length > limit ? output.slice(0, limit) : output;
148 148 };
149 149
150 150 //============================================================================
151 151 // End contributed Cross-browser RegEx Split
152 152 //============================================================================
153 153
154 154
155 155 var uuid = function () {
156 156 // http://www.ietf.org/rfc/rfc4122.txt
157 157 var s = [];
158 158 var hexDigits = "0123456789ABCDEF";
159 159 for (var i = 0; i < 32; i++) {
160 160 s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
161 161 }
162 162 s[12] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
163 163 s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
164 164
165 165 var uuid = s.join("");
166 166 return uuid;
167 167 };
168 168
169 169
170 170 //Fix raw text to parse correctly in crazy XML
171 171 function xmlencode(string) {
172 172 return string.replace(/\&/g,'&'+'amp;')
173 173 .replace(/</g,'&'+'lt;')
174 174 .replace(/>/g,'&'+'gt;')
175 175 .replace(/\'/g,'&'+'apos;')
176 176 .replace(/\"/g,'&'+'quot;')
177 177 .replace(/`/g,'&'+'#96;');
178 178 }
179 179
180 180
181 181 //Map from terminal commands to CSS classes
182 182 var ansi_colormap = {
183 183 "01":"ansibold",
184 184
185 185 "30":"ansiblack",
186 186 "31":"ansired",
187 187 "32":"ansigreen",
188 188 "33":"ansiyellow",
189 189 "34":"ansiblue",
190 190 "35":"ansipurple",
191 191 "36":"ansicyan",
192 192 "37":"ansigray",
193 193
194 194 "40":"ansibgblack",
195 195 "41":"ansibgred",
196 196 "42":"ansibggreen",
197 197 "43":"ansibgyellow",
198 198 "44":"ansibgblue",
199 199 "45":"ansibgpurple",
200 200 "46":"ansibgcyan",
201 201 "47":"ansibggray"
202 202 };
203 203
204 204 function _process_numbers(attrs, numbers) {
205 205 // process ansi escapes
206 206 var n = numbers.shift();
207 207 if (ansi_colormap[n]) {
208 208 if ( ! attrs["class"] ) {
209 209 attrs["class"] = ansi_colormap[n];
210 210 } else {
211 211 attrs["class"] += " " + ansi_colormap[n];
212 212 }
213 213 } else if (n == "38" || n == "48") {
214 214 // VT100 256 color or 24 bit RGB
215 215 if (numbers.length < 2) {
216 216 console.log("Not enough fields for VT100 color", numbers);
217 217 return;
218 218 }
219 219
220 220 var index_or_rgb = numbers.shift();
221 221 var r,g,b;
222 222 if (index_or_rgb == "5") {
223 223 // 256 color
224 224 var idx = parseInt(numbers.shift());
225 225 if (idx < 16) {
226 226 // indexed ANSI
227 227 // ignore bright / non-bright distinction
228 228 idx = idx % 8;
229 229 var ansiclass = ansi_colormap[n[0] + (idx % 8).toString()];
230 230 if ( ! attrs["class"] ) {
231 231 attrs["class"] = ansiclass;
232 232 } else {
233 233 attrs["class"] += " " + ansiclass;
234 234 }
235 235 return;
236 236 } else if (idx < 232) {
237 237 // 216 color 6x6x6 RGB
238 238 idx = idx - 16;
239 239 b = idx % 6;
240 240 g = Math.floor(idx / 6) % 6;
241 241 r = Math.floor(idx / 36) % 6;
242 242 // convert to rgb
243 243 r = (r * 51);
244 244 g = (g * 51);
245 245 b = (b * 51);
246 246 } else {
247 247 // grayscale
248 248 idx = idx - 231;
249 249 // it's 1-24 and should *not* include black or white,
250 250 // so a 26 point scale
251 251 r = g = b = Math.floor(idx * 256 / 26);
252 252 }
253 253 } else if (index_or_rgb == "2") {
254 254 // Simple 24 bit RGB
255 255 if (numbers.length > 3) {
256 256 console.log("Not enough fields for RGB", numbers);
257 257 return;
258 258 }
259 259 r = numbers.shift();
260 260 g = numbers.shift();
261 261 b = numbers.shift();
262 262 } else {
263 263 console.log("unrecognized control", numbers);
264 264 return;
265 265 }
266 266 if (r !== undefined) {
267 267 // apply the rgb color
268 268 var line;
269 269 if (n == "38") {
270 270 line = "color: ";
271 271 } else {
272 272 line = "background-color: ";
273 273 }
274 274 line = line + "rgb(" + r + "," + g + "," + b + ");"
275 275 if ( !attrs["style"] ) {
276 276 attrs["style"] = line;
277 277 } else {
278 278 attrs["style"] += " " + line;
279 279 }
280 280 }
281 281 }
282 282 }
283 283
284 284 function ansispan(str) {
285 285 // ansispan function adapted from github.com/mmalecki/ansispan (MIT License)
286 286 // regular ansi escapes (using the table above)
287 287 return str.replace(/\033\[(0?[01]|22|39)?([;\d]+)?m/g, function(match, prefix, pattern) {
288 288 if (!pattern) {
289 289 // [(01|22|39|)m close spans
290 290 return "</span>";
291 291 }
292 292 // consume sequence of color escapes
293 293 var numbers = pattern.match(/\d+/g);
294 294 var attrs = {};
295 295 while (numbers.length > 0) {
296 296 _process_numbers(attrs, numbers);
297 297 }
298 298
299 299 var span = "<span ";
300 300 for (var attr in attrs) {
301 301 var value = attrs[attr];
302 302 span = span + " " + attr + '="' + attrs[attr] + '"';
303 303 }
304 304 return span + ">";
305 305 });
306 306 };
307 307
308 308 // Transform ANSI color escape codes into HTML <span> tags with css
309 309 // classes listed in the above ansi_colormap object. The actual color used
310 310 // are set in the css file.
311 311 function fixConsole(txt) {
312 312 txt = xmlencode(txt);
313 313 var re = /\033\[([\dA-Fa-f;]*?)m/;
314 314 var opened = false;
315 315 var cmds = [];
316 316 var opener = "";
317 317 var closer = "";
318 318
319 319 // Strip all ANSI codes that are not color related. Matches
320 320 // all ANSI codes that do not end with "m".
321 321 var ignored_re = /(?=(\033\[[\d;=]*[a-ln-zA-Z]{1}))\1(?!m)/g;
322 322 txt = txt.replace(ignored_re, "");
323 323
324 324 // color ansi codes
325 325 txt = ansispan(txt);
326 326 return txt;
327 327 }
328 328
329 329 // Remove chunks that should be overridden by the effect of
330 330 // carriage return characters
331 331 function fixCarriageReturn(txt) {
332 332 var tmp = txt;
333 333 do {
334 334 txt = tmp;
335 335 tmp = txt.replace(/\r+\n/gm, '\n'); // \r followed by \n --> newline
336 336 tmp = tmp.replace(/^.*\r+/gm, ''); // Other \r --> clear line
337 337 } while (tmp.length < txt.length);
338 338 return txt;
339 339 }
340 340
341 341 // Locate any URLs and convert them to a anchor tag
342 342 function autoLinkUrls(txt) {
343 343 return txt.replace(/(^|\s)(https?|ftp)(:[^'">\s]+)/gi,
344 344 "$1<a target=\"_blank\" href=\"$2$3\">$2$3</a>");
345 345 }
346 346
347 347 var points_to_pixels = function (points) {
348 348 // A reasonably good way of converting between points and pixels.
349 349 var test = $('<div style="display: none; width: 10000pt; padding:0; border:0;"></div>');
350 350 $(body).append(test);
351 351 var pixel_per_point = test.width()/10000;
352 352 test.remove();
353 353 return Math.floor(points*pixel_per_point);
354 354 };
355 355
356 356 var always_new = function (constructor) {
357 357 // wrapper around contructor to avoid requiring `var a = new constructor()`
358 358 // useful for passing constructors as callbacks,
359 359 // not for programmer laziness.
360 360 // from http://programmers.stackexchange.com/questions/118798
361 361 return function () {
362 362 var obj = Object.create(constructor.prototype);
363 363 constructor.apply(obj, arguments);
364 364 return obj;
365 365 };
366 366 };
367 367
368 368 var url_path_join = function () {
369 369 // join a sequence of url components with '/'
370 370 var url = '';
371 371 for (var i = 0; i < arguments.length; i++) {
372 372 if (arguments[i] === '') {
373 373 continue;
374 374 }
375 375 if (url.length > 0 && url[url.length-1] != '/') {
376 376 url = url + '/' + arguments[i];
377 377 } else {
378 378 url = url + arguments[i];
379 379 }
380 380 }
381 381 url = url.replace(/\/\/+/, '/');
382 382 return url;
383 383 };
384 384
385 385 var parse_url = function (url) {
386 386 // an `a` element with an href allows attr-access to the parsed segments of a URL
387 387 // a = parse_url("http://localhost:8888/path/name#hash")
388 388 // a.protocol = "http:"
389 389 // a.host = "localhost:8888"
390 390 // a.hostname = "localhost"
391 391 // a.port = 8888
392 392 // a.pathname = "/path/name"
393 393 // a.hash = "#hash"
394 394 var a = document.createElement("a");
395 395 a.href = url;
396 396 return a;
397 397 };
398 398
399 399 var encode_uri_components = function (uri) {
400 400 // encode just the components of a multi-segment uri,
401 401 // leaving '/' separators
402 402 return uri.split('/').map(encodeURIComponent).join('/');
403 403 };
404 404
405 405 var url_join_encode = function () {
406 406 // join a sequence of url components with '/',
407 407 // encoding each component with encodeURIComponent
408 408 return encode_uri_components(url_path_join.apply(null, arguments));
409 409 };
410 410
411 411
412 412 var splitext = function (filename) {
413 413 // mimic Python os.path.splitext
414 414 // Returns ['base', '.ext']
415 415 var idx = filename.lastIndexOf('.');
416 416 if (idx > 0) {
417 417 return [filename.slice(0, idx), filename.slice(idx)];
418 418 } else {
419 419 return [filename, ''];
420 420 }
421 421 };
422 422
423 423
424 424 var escape_html = function (text) {
425 425 // escape text to HTML
426 426 return $("<div/>").text(text).html();
427 427 };
428 428
429 429
430 430 var get_body_data = function(key) {
431 431 // get a url-encoded item from body.data and decode it
432 432 // we should never have any encoded URLs anywhere else in code
433 433 // until we are building an actual request
434 434 return decodeURIComponent($('body').data(key));
435 435 };
436 436
437 437 var to_absolute_cursor_pos = function (cm, cursor) {
438 438 // get the absolute cursor position from CodeMirror's col, ch
439 439 if (!cursor) {
440 440 cursor = cm.getCursor();
441 441 }
442 442 var cursor_pos = cursor.ch;
443 443 for (var i = 0; i < cursor.line; i++) {
444 444 cursor_pos += cm.getLine(i).length + 1;
445 445 }
446 446 return cursor_pos;
447 447 };
448 448
449 449 var from_absolute_cursor_pos = function (cm, cursor_pos) {
450 450 // turn absolute cursor postion into CodeMirror col, ch cursor
451 451 var i, line;
452 452 var offset = 0;
453 453 for (i = 0, line=cm.getLine(i); line !== undefined; i++, line=cm.getLine(i)) {
454 454 if (offset + line.length < cursor_pos) {
455 455 offset += line.length + 1;
456 456 } else {
457 457 return {
458 458 line : i,
459 459 ch : cursor_pos - offset,
460 460 };
461 461 }
462 462 }
463 463 // reached end, return endpoint
464 464 return {
465 465 ch : line.length - 1,
466 466 line : i - 1,
467 467 };
468 468 };
469 469
470 470 // http://stackoverflow.com/questions/2400935/browser-detection-in-javascript
471 471 var browser = (function() {
472 472 if (typeof navigator === 'undefined') {
473 473 // navigator undefined in node
474 474 return 'None';
475 475 }
476 476 var N= navigator.appName, ua= navigator.userAgent, tem;
477 477 var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
478 478 if (M && (tem= ua.match(/version\/([\.\d]+)/i)) !== null) M[2]= tem[1];
479 479 M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
480 480 return M;
481 481 })();
482 482
483 483 // http://stackoverflow.com/questions/11219582/how-to-detect-my-browser-version-and-operating-system-using-javascript
484 484 var platform = (function () {
485 485 if (typeof navigator === 'undefined') {
486 486 // navigator undefined in node
487 487 return 'None';
488 488 }
489 489 var OSName="None";
490 490 if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
491 491 if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
492 492 if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
493 493 if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
494 494 return OSName;
495 495 })();
496 496
497 497 var is_or_has = function (a, b) {
498 498 // Is b a child of a or a itself?
499 499 return a.has(b).length !==0 || a.is(b);
500 500 };
501 501
502 502 var is_focused = function (e) {
503 503 // Is element e, or one of its children focused?
504 504 e = $(e);
505 505 var target = $(document.activeElement);
506 506 if (target.length > 0) {
507 507 if (is_or_has(e, target)) {
508 508 return true;
509 509 } else {
510 510 return false;
511 511 }
512 512 } else {
513 513 return false;
514 514 }
515 515 };
516 516
517 var mergeopt = function(_class, options, overwrite){
518 options = options || {};
519 overwrite = overwrite || {};
520 return $.extend(true, {}, _class.options_default, options, overwrite);
521 };
522
517 523 var ajax_error_msg = function (jqXHR) {
518 524 // Return a JSON error message if there is one,
519 525 // otherwise the basic HTTP status text.
520 526 if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
521 527 return jqXHR.responseJSON.message;
522 528 } else {
523 529 return jqXHR.statusText;
524 530 }
525 531 }
526 532 var log_ajax_error = function (jqXHR, status, error) {
527 533 // log ajax failures with informative messages
528 534 var msg = "API request failed (" + jqXHR.status + "): ";
529 535 console.log(jqXHR);
530 536 msg += ajax_error_msg(jqXHR);
531 537 console.log(msg);
532 538 };
533 539
534 540 var utils = {
535 541 regex_split : regex_split,
536 542 uuid : uuid,
537 543 fixConsole : fixConsole,
538 544 fixCarriageReturn : fixCarriageReturn,
539 545 autoLinkUrls : autoLinkUrls,
540 546 points_to_pixels : points_to_pixels,
541 547 get_body_data : get_body_data,
542 548 parse_url : parse_url,
543 549 url_path_join : url_path_join,
544 550 url_join_encode : url_join_encode,
545 551 encode_uri_components : encode_uri_components,
546 552 splitext : splitext,
547 553 escape_html : escape_html,
548 554 always_new : always_new,
549 555 to_absolute_cursor_pos : to_absolute_cursor_pos,
550 556 from_absolute_cursor_pos : from_absolute_cursor_pos,
551 557 browser : browser,
552 558 platform: platform,
553 559 is_or_has : is_or_has,
554 560 is_focused : is_focused,
561 mergeopt: mergeopt,
555 562 ajax_error_msg : ajax_error_msg,
556 563 log_ajax_error : log_ajax_error,
557 564 };
558 565
559 566 // Backwards compatability.
560 567 IPython.utils = utils;
561 568
562 569 return utils;
563 570 });
@@ -1,563 +1,557
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'base/js/namespace',
6 6 'jquery',
7 7 'base/js/utils',
8 8 ], function(IPython, $, utils) {
9 9 // TODO: remove IPython dependency here
10 10 "use strict";
11 11
12 12 // monkey patch CM to be able to syntax highlight cell magics
13 13 // bug reported upstream,
14 14 // see https://github.com/marijnh/CodeMirror2/issues/670
15 15 if(CodeMirror.getMode(1,'text/plain').indent === undefined ){
16 16 CodeMirror.modes.null = function() {
17 17 return {token: function(stream) {stream.skipToEnd();},indent : function(){return 0;}};
18 18 };
19 19 }
20 20
21 21 CodeMirror.patchedGetMode = function(config, mode){
22 22 var cmmode = CodeMirror.getMode(config, mode);
23 23 if(cmmode.indent === null) {
24 24 console.log('patch mode "' , mode, '" on the fly');
25 25 cmmode.indent = function(){return 0;};
26 26 }
27 27 return cmmode;
28 28 };
29 29 // end monkey patching CodeMirror
30 30
31 31 var Cell = function (options) {
32 32 // Constructor
33 33 //
34 34 // The Base `Cell` class from which to inherit.
35 35 //
36 36 // Parameters:
37 37 // options: dictionary
38 38 // Dictionary of keyword arguments.
39 39 // events: $(Events) instance
40 40 // config: dictionary
41 41 // keyboard_manager: KeyboardManager instance
42 42 options = options || {};
43 43 this.keyboard_manager = options.keyboard_manager;
44 44 this.events = options.events;
45 var config = this.mergeopt(Cell, options.config);
45 var config = utils.mergeopt(Cell, options.config);
46 46 // superclass default overwrite our default
47 47
48 48 this.placeholder = config.placeholder || '';
49 49 this.read_only = config.cm_config.readOnly;
50 50 this.selected = false;
51 51 this.rendered = false;
52 52 this.mode = 'command';
53 53 this.metadata = {};
54 54 // load this from metadata later ?
55 55 this.user_highlight = 'auto';
56 56 this.cm_config = config.cm_config;
57 57 this.cell_id = utils.uuid();
58 58 this._options = config;
59 59
60 60 // For JS VM engines optimization, attributes should be all set (even
61 61 // to null) in the constructor, and if possible, if different subclass
62 62 // have new attributes with same name, they should be created in the
63 63 // same order. Easiest is to create and set to null in parent class.
64 64
65 65 this.element = null;
66 66 this.cell_type = this.cell_type || null;
67 67 this.code_mirror = null;
68 68
69 69 this.create_element();
70 70 if (this.element !== null) {
71 71 this.element.data("cell", this);
72 72 this.bind_events();
73 73 this.init_classes();
74 74 }
75 75 };
76 76
77 77 Cell.options_default = {
78 78 cm_config : {
79 79 indentUnit : 4,
80 80 readOnly: false,
81 81 theme: "default",
82 82 extraKeys: {
83 83 "Cmd-Right":"goLineRight",
84 84 "End":"goLineRight",
85 85 "Cmd-Left":"goLineLeft"
86 86 }
87 87 }
88 88 };
89 89
90 90 // FIXME: Workaround CM Bug #332 (Safari segfault on drag)
91 91 // by disabling drag/drop altogether on Safari
92 92 // https://github.com/marijnh/CodeMirror/issues/332
93 93 if (utils.browser[0] == "Safari") {
94 94 Cell.options_default.cm_config.dragDrop = false;
95 95 }
96 96
97 Cell.prototype.mergeopt = function(_class, options, overwrite){
98 options = options || {};
99 overwrite = overwrite || {};
100 return $.extend(true, {}, _class.options_default, options, overwrite);
101 };
102
103 97 /**
104 98 * Empty. Subclasses must implement create_element.
105 99 * This should contain all the code to create the DOM element in notebook
106 100 * and will be called by Base Class constructor.
107 101 * @method create_element
108 102 */
109 103 Cell.prototype.create_element = function () {
110 104 };
111 105
112 106 Cell.prototype.init_classes = function () {
113 107 // Call after this.element exists to initialize the css classes
114 108 // related to selected, rendered and mode.
115 109 if (this.selected) {
116 110 this.element.addClass('selected');
117 111 } else {
118 112 this.element.addClass('unselected');
119 113 }
120 114 if (this.rendered) {
121 115 this.element.addClass('rendered');
122 116 } else {
123 117 this.element.addClass('unrendered');
124 118 }
125 119 if (this.mode === 'edit') {
126 120 this.element.addClass('edit_mode');
127 121 } else {
128 122 this.element.addClass('command_mode');
129 123 }
130 124 };
131 125
132 126 /**
133 127 * Subclasses can implement override bind_events.
134 128 * Be carefull to call the parent method when overwriting as it fires event.
135 129 * this will be triggerd after create_element in constructor.
136 130 * @method bind_events
137 131 */
138 132 Cell.prototype.bind_events = function () {
139 133 var that = this;
140 134 // We trigger events so that Cell doesn't have to depend on Notebook.
141 135 that.element.click(function (event) {
142 136 if (!that.selected) {
143 137 that.events.trigger('select.Cell', {'cell':that});
144 138 }
145 139 });
146 140 that.element.focusin(function (event) {
147 141 if (!that.selected) {
148 142 that.events.trigger('select.Cell', {'cell':that});
149 143 }
150 144 });
151 145 if (this.code_mirror) {
152 146 this.code_mirror.on("change", function(cm, change) {
153 147 that.events.trigger("set_dirty.Notebook", {value: true});
154 148 });
155 149 }
156 150 if (this.code_mirror) {
157 151 this.code_mirror.on('focus', function(cm, change) {
158 152 that.events.trigger('edit_mode.Cell', {cell: that});
159 153 });
160 154 }
161 155 if (this.code_mirror) {
162 156 this.code_mirror.on('blur', function(cm, change) {
163 157 that.events.trigger('command_mode.Cell', {cell: that});
164 158 });
165 159 }
166 160 };
167 161
168 162 /**
169 163 * This method gets called in CodeMirror's onKeyDown/onKeyPress
170 164 * handlers and is used to provide custom key handling.
171 165 *
172 166 * To have custom handling, subclasses should override this method, but still call it
173 167 * in order to process the Edit mode keyboard shortcuts.
174 168 *
175 169 * @method handle_codemirror_keyevent
176 170 * @param {CodeMirror} editor - The codemirror instance bound to the cell
177 171 * @param {event} event - key press event which either should or should not be handled by CodeMirror
178 172 * @return {Boolean} `true` if CodeMirror should ignore the event, `false` Otherwise
179 173 */
180 174 Cell.prototype.handle_codemirror_keyevent = function (editor, event) {
181 175 var shortcuts = this.keyboard_manager.edit_shortcuts;
182 176
183 177 // if this is an edit_shortcuts shortcut, the global keyboard/shortcut
184 178 // manager will handle it
185 179 if (shortcuts.handles(event)) { return true; }
186 180
187 181 return false;
188 182 };
189 183
190 184
191 185 /**
192 186 * Triger typsetting of math by mathjax on current cell element
193 187 * @method typeset
194 188 */
195 189 Cell.prototype.typeset = function () {
196 190 if (window.MathJax) {
197 191 var cell_math = this.element.get(0);
198 192 MathJax.Hub.Queue(["Typeset", MathJax.Hub, cell_math]);
199 193 }
200 194 };
201 195
202 196 /**
203 197 * handle cell level logic when a cell is selected
204 198 * @method select
205 199 * @return is the action being taken
206 200 */
207 201 Cell.prototype.select = function () {
208 202 if (!this.selected) {
209 203 this.element.addClass('selected');
210 204 this.element.removeClass('unselected');
211 205 this.selected = true;
212 206 return true;
213 207 } else {
214 208 return false;
215 209 }
216 210 };
217 211
218 212 /**
219 213 * handle cell level logic when a cell is unselected
220 214 * @method unselect
221 215 * @return is the action being taken
222 216 */
223 217 Cell.prototype.unselect = function () {
224 218 if (this.selected) {
225 219 this.element.addClass('unselected');
226 220 this.element.removeClass('selected');
227 221 this.selected = false;
228 222 return true;
229 223 } else {
230 224 return false;
231 225 }
232 226 };
233 227
234 228 /**
235 229 * handle cell level logic when a cell is rendered
236 230 * @method render
237 231 * @return is the action being taken
238 232 */
239 233 Cell.prototype.render = function () {
240 234 if (!this.rendered) {
241 235 this.element.addClass('rendered');
242 236 this.element.removeClass('unrendered');
243 237 this.rendered = true;
244 238 return true;
245 239 } else {
246 240 return false;
247 241 }
248 242 };
249 243
250 244 /**
251 245 * handle cell level logic when a cell is unrendered
252 246 * @method unrender
253 247 * @return is the action being taken
254 248 */
255 249 Cell.prototype.unrender = function () {
256 250 if (this.rendered) {
257 251 this.element.addClass('unrendered');
258 252 this.element.removeClass('rendered');
259 253 this.rendered = false;
260 254 return true;
261 255 } else {
262 256 return false;
263 257 }
264 258 };
265 259
266 260 /**
267 261 * Delegates keyboard shortcut handling to either IPython keyboard
268 262 * manager when in command mode, or CodeMirror when in edit mode
269 263 *
270 264 * @method handle_keyevent
271 265 * @param {CodeMirror} editor - The codemirror instance bound to the cell
272 266 * @param {event} - key event to be handled
273 267 * @return {Boolean} `true` if CodeMirror should ignore the event, `false` Otherwise
274 268 */
275 269 Cell.prototype.handle_keyevent = function (editor, event) {
276 270
277 271 // console.log('CM', this.mode, event.which, event.type)
278 272
279 273 if (this.mode === 'command') {
280 274 return true;
281 275 } else if (this.mode === 'edit') {
282 276 return this.handle_codemirror_keyevent(editor, event);
283 277 }
284 278 };
285 279
286 280 /**
287 281 * @method at_top
288 282 * @return {Boolean}
289 283 */
290 284 Cell.prototype.at_top = function () {
291 285 var cm = this.code_mirror;
292 286 var cursor = cm.getCursor();
293 287 if (cursor.line === 0 && cursor.ch === 0) {
294 288 return true;
295 289 }
296 290 return false;
297 291 };
298 292
299 293 /**
300 294 * @method at_bottom
301 295 * @return {Boolean}
302 296 * */
303 297 Cell.prototype.at_bottom = function () {
304 298 var cm = this.code_mirror;
305 299 var cursor = cm.getCursor();
306 300 if (cursor.line === (cm.lineCount()-1) && cursor.ch === cm.getLine(cursor.line).length) {
307 301 return true;
308 302 }
309 303 return false;
310 304 };
311 305
312 306 /**
313 307 * enter the command mode for the cell
314 308 * @method command_mode
315 309 * @return is the action being taken
316 310 */
317 311 Cell.prototype.command_mode = function () {
318 312 if (this.mode !== 'command') {
319 313 this.element.addClass('command_mode');
320 314 this.element.removeClass('edit_mode');
321 315 this.mode = 'command';
322 316 return true;
323 317 } else {
324 318 return false;
325 319 }
326 320 };
327 321
328 322 /**
329 323 * enter the edit mode for the cell
330 324 * @method command_mode
331 325 * @return is the action being taken
332 326 */
333 327 Cell.prototype.edit_mode = function () {
334 328 if (this.mode !== 'edit') {
335 329 this.element.addClass('edit_mode');
336 330 this.element.removeClass('command_mode');
337 331 this.mode = 'edit';
338 332 return true;
339 333 } else {
340 334 return false;
341 335 }
342 336 };
343 337
344 338 /**
345 339 * Focus the cell in the DOM sense
346 340 * @method focus_cell
347 341 */
348 342 Cell.prototype.focus_cell = function () {
349 343 this.element.focus();
350 344 };
351 345
352 346 /**
353 347 * Focus the editor area so a user can type
354 348 *
355 349 * NOTE: If codemirror is focused via a mouse click event, you don't want to
356 350 * call this because it will cause a page jump.
357 351 * @method focus_editor
358 352 */
359 353 Cell.prototype.focus_editor = function () {
360 354 this.refresh();
361 355 this.code_mirror.focus();
362 356 };
363 357
364 358 /**
365 359 * Refresh codemirror instance
366 360 * @method refresh
367 361 */
368 362 Cell.prototype.refresh = function () {
369 363 this.code_mirror.refresh();
370 364 };
371 365
372 366 /**
373 367 * should be overritten by subclass
374 368 * @method get_text
375 369 */
376 370 Cell.prototype.get_text = function () {
377 371 };
378 372
379 373 /**
380 374 * should be overritten by subclass
381 375 * @method set_text
382 376 * @param {string} text
383 377 */
384 378 Cell.prototype.set_text = function (text) {
385 379 };
386 380
387 381 /**
388 382 * should be overritten by subclass
389 383 * serialise cell to json.
390 384 * @method toJSON
391 385 **/
392 386 Cell.prototype.toJSON = function () {
393 387 var data = {};
394 388 data.metadata = this.metadata;
395 389 data.cell_type = this.cell_type;
396 390 return data;
397 391 };
398 392
399 393
400 394 /**
401 395 * should be overritten by subclass
402 396 * @method fromJSON
403 397 **/
404 398 Cell.prototype.fromJSON = function (data) {
405 399 if (data.metadata !== undefined) {
406 400 this.metadata = data.metadata;
407 401 }
408 402 this.celltoolbar.rebuild();
409 403 };
410 404
411 405
412 406 /**
413 407 * can the cell be split into two cells
414 408 * @method is_splittable
415 409 **/
416 410 Cell.prototype.is_splittable = function () {
417 411 return true;
418 412 };
419 413
420 414
421 415 /**
422 416 * can the cell be merged with other cells
423 417 * @method is_mergeable
424 418 **/
425 419 Cell.prototype.is_mergeable = function () {
426 420 return true;
427 421 };
428 422
429 423
430 424 /**
431 425 * @return {String} - the text before the cursor
432 426 * @method get_pre_cursor
433 427 **/
434 428 Cell.prototype.get_pre_cursor = function () {
435 429 var cursor = this.code_mirror.getCursor();
436 430 var text = this.code_mirror.getRange({line:0, ch:0}, cursor);
437 431 text = text.replace(/^\n+/, '').replace(/\n+$/, '');
438 432 return text;
439 433 };
440 434
441 435
442 436 /**
443 437 * @return {String} - the text after the cursor
444 438 * @method get_post_cursor
445 439 **/
446 440 Cell.prototype.get_post_cursor = function () {
447 441 var cursor = this.code_mirror.getCursor();
448 442 var last_line_num = this.code_mirror.lineCount()-1;
449 443 var last_line_len = this.code_mirror.getLine(last_line_num).length;
450 444 var end = {line:last_line_num, ch:last_line_len};
451 445 var text = this.code_mirror.getRange(cursor, end);
452 446 text = text.replace(/^\n+/, '').replace(/\n+$/, '');
453 447 return text;
454 448 };
455 449
456 450 /**
457 451 * Show/Hide CodeMirror LineNumber
458 452 * @method show_line_numbers
459 453 *
460 454 * @param value {Bool} show (true), or hide (false) the line number in CodeMirror
461 455 **/
462 456 Cell.prototype.show_line_numbers = function (value) {
463 457 this.code_mirror.setOption('lineNumbers', value);
464 458 this.code_mirror.refresh();
465 459 };
466 460
467 461 /**
468 462 * Toggle CodeMirror LineNumber
469 463 * @method toggle_line_numbers
470 464 **/
471 465 Cell.prototype.toggle_line_numbers = function () {
472 466 var val = this.code_mirror.getOption('lineNumbers');
473 467 this.show_line_numbers(!val);
474 468 };
475 469
476 470 /**
477 471 * Force codemirror highlight mode
478 472 * @method force_highlight
479 473 * @param {object} - CodeMirror mode
480 474 **/
481 475 Cell.prototype.force_highlight = function(mode) {
482 476 this.user_highlight = mode;
483 477 this.auto_highlight();
484 478 };
485 479
486 480 /**
487 481 * Try to autodetect cell highlight mode, or use selected mode
488 482 * @methods _auto_highlight
489 483 * @private
490 484 * @param {String|object|undefined} - CodeMirror mode | 'auto'
491 485 **/
492 486 Cell.prototype._auto_highlight = function (modes) {
493 487 //Here we handle manually selected modes
494 488 var mode;
495 489 if( this.user_highlight !== undefined && this.user_highlight != 'auto' )
496 490 {
497 491 mode = this.user_highlight;
498 492 CodeMirror.autoLoadMode(this.code_mirror, mode);
499 493 this.code_mirror.setOption('mode', mode);
500 494 return;
501 495 }
502 496 var current_mode = this.code_mirror.getOption('mode', mode);
503 497 var first_line = this.code_mirror.getLine(0);
504 498 // loop on every pairs
505 499 for(mode in modes) {
506 500 var regs = modes[mode].reg;
507 501 // only one key every time but regexp can't be keys...
508 502 for(var i=0; i<regs.length; i++) {
509 503 // here we handle non magic_modes
510 504 if(first_line.match(regs[i]) !== null) {
511 505 if(current_mode == mode){
512 506 return;
513 507 }
514 508 if (mode.search('magic_') !== 0) {
515 509 this.code_mirror.setOption('mode', mode);
516 510 CodeMirror.autoLoadMode(this.code_mirror, mode);
517 511 return;
518 512 }
519 513 var open = modes[mode].open || "%%";
520 514 var close = modes[mode].close || "%%end";
521 515 var mmode = mode;
522 516 mode = mmode.substr(6);
523 517 if(current_mode == mode){
524 518 return;
525 519 }
526 520 CodeMirror.autoLoadMode(this.code_mirror, mode);
527 521 // create on the fly a mode that swhitch between
528 522 // plain/text and smth else otherwise `%%` is
529 523 // source of some highlight issues.
530 524 // we use patchedGetMode to circumvent a bug in CM
531 525 CodeMirror.defineMode(mmode , function(config) {
532 526 return CodeMirror.multiplexingMode(
533 527 CodeMirror.patchedGetMode(config, 'text/plain'),
534 528 // always set someting on close
535 529 {open: open, close: close,
536 530 mode: CodeMirror.patchedGetMode(config, mode),
537 531 delimStyle: "delimit"
538 532 }
539 533 );
540 534 });
541 535 this.code_mirror.setOption('mode', mmode);
542 536 return;
543 537 }
544 538 }
545 539 }
546 540 // fallback on default
547 541 var default_mode;
548 542 try {
549 543 default_mode = this._options.cm_config.mode;
550 544 } catch(e) {
551 545 default_mode = 'text/plain';
552 546 }
553 547 if( current_mode === default_mode){
554 548 return;
555 549 }
556 550 this.code_mirror.setOption('mode', default_mode);
557 551 };
558 552
559 553 // Backwards compatibility.
560 554 IPython.Cell = Cell;
561 555
562 556 return {'Cell': Cell};
563 557 });
@@ -1,525 +1,525
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'base/js/namespace',
6 6 'jquery',
7 7 'base/js/utils',
8 8 'base/js/keyboard',
9 9 'notebook/js/cell',
10 10 'notebook/js/outputarea',
11 11 'notebook/js/completer',
12 12 'notebook/js/celltoolbar',
13 13 ], function(IPython, $, utils, keyboard, cell, outputarea, completer, celltoolbar) {
14 14 "use strict";
15 15 var Cell = cell.Cell;
16 16
17 17 /* local util for codemirror */
18 18 var posEq = function(a, b) {return a.line == b.line && a.ch == b.ch;};
19 19
20 20 /**
21 21 *
22 22 * function to delete until previous non blanking space character
23 23 * or first multiple of 4 tabstop.
24 24 * @private
25 25 */
26 26 CodeMirror.commands.delSpaceToPrevTabStop = function(cm){
27 27 var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
28 28 if (!posEq(from, to)) { cm.replaceRange("", from, to); return; }
29 29 var cur = cm.getCursor(), line = cm.getLine(cur.line);
30 30 var tabsize = cm.getOption('tabSize');
31 31 var chToPrevTabStop = cur.ch-(Math.ceil(cur.ch/tabsize)-1)*tabsize;
32 32 from = {ch:cur.ch-chToPrevTabStop,line:cur.line};
33 33 var select = cm.getRange(from,cur);
34 34 if( select.match(/^\ +$/) !== null){
35 35 cm.replaceRange("",from,cur);
36 36 } else {
37 37 cm.deleteH(-1,"char");
38 38 }
39 39 };
40 40
41 41 var keycodes = keyboard.keycodes;
42 42
43 43 var CodeCell = function (kernel, options) {
44 44 // Constructor
45 45 //
46 46 // A Cell conceived to write code.
47 47 //
48 48 // Parameters:
49 49 // kernel: Kernel instance
50 50 // The kernel doesn't have to be set at creation time, in that case
51 51 // it will be null and set_kernel has to be called later.
52 52 // options: dictionary
53 53 // Dictionary of keyword arguments.
54 54 // events: $(Events) instance
55 55 // config: dictionary
56 56 // keyboard_manager: KeyboardManager instance
57 57 // notebook: Notebook instance
58 58 // tooltip: Tooltip instance
59 59 this.kernel = kernel || null;
60 60 this.notebook = options.notebook;
61 61 this.collapsed = false;
62 62 this.events = options.events;
63 63 this.tooltip = options.tooltip;
64 64 this.config = options.config;
65 65
66 66 // create all attributed in constructor function
67 67 // even if null for V8 VM optimisation
68 68 this.input_prompt_number = null;
69 69 this.celltoolbar = null;
70 70 this.output_area = null;
71 71 this.last_msg_id = null;
72 72 this.completer = null;
73 73
74 74
75 75 var cm_overwrite_options = {
76 76 onKeyEvent: $.proxy(this.handle_keyevent,this)
77 77 };
78 78
79 var config = this.mergeopt(CodeCell, this.config, {cm_config: cm_overwrite_options});
79 var config = utils.mergeopt(CodeCell, this.config, {cm_config: cm_overwrite_options});
80 80 Cell.apply(this,[{
81 81 config: config,
82 82 keyboard_manager: options.keyboard_manager,
83 83 events: this.events}]);
84 84
85 85 // Attributes we want to override in this subclass.
86 86 this.cell_type = "code";
87 87
88 88 var that = this;
89 89 this.element.focusout(
90 90 function() { that.auto_highlight(); }
91 91 );
92 92 };
93 93
94 94 CodeCell.options_default = {
95 95 cm_config : {
96 96 extraKeys: {
97 97 "Tab" : "indentMore",
98 98 "Shift-Tab" : "indentLess",
99 99 "Backspace" : "delSpaceToPrevTabStop",
100 100 "Cmd-/" : "toggleComment",
101 101 "Ctrl-/" : "toggleComment"
102 102 },
103 103 mode: 'ipython',
104 104 theme: 'ipython',
105 105 matchBrackets: true,
106 106 // don't auto-close strings because of CodeMirror #2385
107 107 autoCloseBrackets: "()[]{}"
108 108 }
109 109 };
110 110
111 111 CodeCell.msg_cells = {};
112 112
113 113 CodeCell.prototype = new Cell();
114 114
115 115 /**
116 116 * @method auto_highlight
117 117 */
118 118 CodeCell.prototype.auto_highlight = function () {
119 119 this._auto_highlight(this.config.cell_magic_highlight);
120 120 };
121 121
122 122 /** @method create_element */
123 123 CodeCell.prototype.create_element = function () {
124 124 Cell.prototype.create_element.apply(this, arguments);
125 125
126 126 var cell = $('<div></div>').addClass('cell code_cell');
127 127 cell.attr('tabindex','2');
128 128
129 129 var input = $('<div></div>').addClass('input');
130 130 var prompt = $('<div/>').addClass('prompt input_prompt');
131 131 var inner_cell = $('<div/>').addClass('inner_cell');
132 132 this.celltoolbar = new celltoolbar.CellToolbar({
133 133 cell: this,
134 134 notebook: this.notebook});
135 135 inner_cell.append(this.celltoolbar.element);
136 136 var input_area = $('<div/>').addClass('input_area');
137 137 this.code_mirror = new CodeMirror(input_area.get(0), this.cm_config);
138 138 $(this.code_mirror.getInputField()).attr("spellcheck", "false");
139 139 inner_cell.append(input_area);
140 140 input.append(prompt).append(inner_cell);
141 141
142 142 var widget_area = $('<div/>')
143 143 .addClass('widget-area')
144 144 .hide();
145 145 this.widget_area = widget_area;
146 146 var widget_prompt = $('<div/>')
147 147 .addClass('prompt')
148 148 .appendTo(widget_area);
149 149 var widget_subarea = $('<div/>')
150 150 .addClass('widget-subarea')
151 151 .appendTo(widget_area);
152 152 this.widget_subarea = widget_subarea;
153 153 var widget_clear_buton = $('<button />')
154 154 .addClass('close')
155 155 .html('&times;')
156 156 .click(function() {
157 157 widget_area.slideUp('', function(){ widget_subarea.html(''); });
158 158 })
159 159 .appendTo(widget_prompt);
160 160
161 161 var output = $('<div></div>');
162 162 cell.append(input).append(widget_area).append(output);
163 163 this.element = cell;
164 164 this.output_area = new outputarea.OutputArea({
165 165 selector: output,
166 166 prompt_area: true,
167 167 events: this.events,
168 168 keyboard_manager: this.keyboard_manager});
169 169 this.completer = new completer.Completer(this, this.events);
170 170 };
171 171
172 172 /** @method bind_events */
173 173 CodeCell.prototype.bind_events = function () {
174 174 Cell.prototype.bind_events.apply(this);
175 175 var that = this;
176 176
177 177 this.element.focusout(
178 178 function() { that.auto_highlight(); }
179 179 );
180 180 };
181 181
182 182
183 183 /**
184 184 * This method gets called in CodeMirror's onKeyDown/onKeyPress
185 185 * handlers and is used to provide custom key handling. Its return
186 186 * value is used to determine if CodeMirror should ignore the event:
187 187 * true = ignore, false = don't ignore.
188 188 * @method handle_codemirror_keyevent
189 189 */
190 190 CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) {
191 191
192 192 var that = this;
193 193 // whatever key is pressed, first, cancel the tooltip request before
194 194 // they are sent, and remove tooltip if any, except for tab again
195 195 var tooltip_closed = null;
196 196 if (event.type === 'keydown' && event.which != keycodes.tab ) {
197 197 tooltip_closed = this.tooltip.remove_and_cancel_tooltip();
198 198 }
199 199
200 200 var cur = editor.getCursor();
201 201 if (event.keyCode === keycodes.enter){
202 202 this.auto_highlight();
203 203 }
204 204
205 205 if (event.which === keycodes.down && event.type === 'keypress' && this.tooltip.time_before_tooltip >= 0) {
206 206 // triger on keypress (!) otherwise inconsistent event.which depending on plateform
207 207 // browser and keyboard layout !
208 208 // Pressing '(' , request tooltip, don't forget to reappend it
209 209 // The second argument says to hide the tooltip if the docstring
210 210 // is actually empty
211 211 this.tooltip.pending(that, true);
212 212 } else if ( tooltip_closed && event.which === keycodes.esc && event.type === 'keydown') {
213 213 // If tooltip is active, cancel it. The call to
214 214 // remove_and_cancel_tooltip above doesn't pass, force=true.
215 215 // Because of this it won't actually close the tooltip
216 216 // if it is in sticky mode. Thus, we have to check again if it is open
217 217 // and close it with force=true.
218 218 if (!this.tooltip._hidden) {
219 219 this.tooltip.remove_and_cancel_tooltip(true);
220 220 }
221 221 // If we closed the tooltip, don't let CM or the global handlers
222 222 // handle this event.
223 223 event.stop();
224 224 return true;
225 225 } else if (event.keyCode === keycodes.tab && event.type === 'keydown' && event.shiftKey) {
226 226 if (editor.somethingSelected()){
227 227 var anchor = editor.getCursor("anchor");
228 228 var head = editor.getCursor("head");
229 229 if( anchor.line != head.line){
230 230 return false;
231 231 }
232 232 }
233 233 this.tooltip.request(that);
234 234 event.stop();
235 235 return true;
236 236 } else if (event.keyCode === keycodes.tab && event.type == 'keydown') {
237 237 // Tab completion.
238 238 this.tooltip.remove_and_cancel_tooltip();
239 239 if (editor.somethingSelected()) {
240 240 return false;
241 241 }
242 242 var pre_cursor = editor.getRange({line:cur.line,ch:0},cur);
243 243 if (pre_cursor.trim() === "") {
244 244 // Don't autocomplete if the part of the line before the cursor
245 245 // is empty. In this case, let CodeMirror handle indentation.
246 246 return false;
247 247 } else {
248 248 event.stop();
249 249 this.completer.startCompletion();
250 250 return true;
251 251 }
252 252 }
253 253
254 254 // keyboard event wasn't one of those unique to code cells, let's see
255 255 // if it's one of the generic ones (i.e. check edit mode shortcuts)
256 256 return Cell.prototype.handle_codemirror_keyevent.apply(this, [editor, event]);
257 257 };
258 258
259 259 // Kernel related calls.
260 260
261 261 CodeCell.prototype.set_kernel = function (kernel) {
262 262 this.kernel = kernel;
263 263 };
264 264
265 265 /**
266 266 * Execute current code cell to the kernel
267 267 * @method execute
268 268 */
269 269 CodeCell.prototype.execute = function () {
270 270 this.output_area.clear_output();
271 271
272 272 // Clear widget area
273 273 this.widget_subarea.html('');
274 274 this.widget_subarea.height('');
275 275 this.widget_area.height('');
276 276 this.widget_area.hide();
277 277
278 278 this.set_input_prompt('*');
279 279 this.element.addClass("running");
280 280 if (this.last_msg_id) {
281 281 this.kernel.clear_callbacks_for_msg(this.last_msg_id);
282 282 }
283 283 var callbacks = this.get_callbacks();
284 284
285 285 var old_msg_id = this.last_msg_id;
286 286 this.last_msg_id = this.kernel.execute(this.get_text(), callbacks, {silent: false, store_history: true});
287 287 if (old_msg_id) {
288 288 delete CodeCell.msg_cells[old_msg_id];
289 289 }
290 290 CodeCell.msg_cells[this.last_msg_id] = this;
291 291 };
292 292
293 293 /**
294 294 * Construct the default callbacks for
295 295 * @method get_callbacks
296 296 */
297 297 CodeCell.prototype.get_callbacks = function () {
298 298 return {
299 299 shell : {
300 300 reply : $.proxy(this._handle_execute_reply, this),
301 301 payload : {
302 302 set_next_input : $.proxy(this._handle_set_next_input, this),
303 303 page : $.proxy(this._open_with_pager, this)
304 304 }
305 305 },
306 306 iopub : {
307 307 output : $.proxy(this.output_area.handle_output, this.output_area),
308 308 clear_output : $.proxy(this.output_area.handle_clear_output, this.output_area),
309 309 },
310 310 input : $.proxy(this._handle_input_request, this)
311 311 };
312 312 };
313 313
314 314 CodeCell.prototype._open_with_pager = function (payload) {
315 315 this.events.trigger('open_with_text.Pager', payload);
316 316 };
317 317
318 318 /**
319 319 * @method _handle_execute_reply
320 320 * @private
321 321 */
322 322 CodeCell.prototype._handle_execute_reply = function (msg) {
323 323 this.set_input_prompt(msg.content.execution_count);
324 324 this.element.removeClass("running");
325 325 this.events.trigger('set_dirty.Notebook', {value: true});
326 326 };
327 327
328 328 /**
329 329 * @method _handle_set_next_input
330 330 * @private
331 331 */
332 332 CodeCell.prototype._handle_set_next_input = function (payload) {
333 333 var data = {'cell': this, 'text': payload.text};
334 334 this.events.trigger('set_next_input.Notebook', data);
335 335 };
336 336
337 337 /**
338 338 * @method _handle_input_request
339 339 * @private
340 340 */
341 341 CodeCell.prototype._handle_input_request = function (msg) {
342 342 this.output_area.append_raw_input(msg);
343 343 };
344 344
345 345
346 346 // Basic cell manipulation.
347 347
348 348 CodeCell.prototype.select = function () {
349 349 var cont = Cell.prototype.select.apply(this);
350 350 if (cont) {
351 351 this.code_mirror.refresh();
352 352 this.auto_highlight();
353 353 }
354 354 return cont;
355 355 };
356 356
357 357 CodeCell.prototype.render = function () {
358 358 var cont = Cell.prototype.render.apply(this);
359 359 // Always execute, even if we are already in the rendered state
360 360 return cont;
361 361 };
362 362
363 363 CodeCell.prototype.unrender = function () {
364 364 // CodeCell is always rendered
365 365 return false;
366 366 };
367 367
368 368 CodeCell.prototype.select_all = function () {
369 369 var start = {line: 0, ch: 0};
370 370 var nlines = this.code_mirror.lineCount();
371 371 var last_line = this.code_mirror.getLine(nlines-1);
372 372 var end = {line: nlines-1, ch: last_line.length};
373 373 this.code_mirror.setSelection(start, end);
374 374 };
375 375
376 376
377 377 CodeCell.prototype.collapse_output = function () {
378 378 this.collapsed = true;
379 379 this.output_area.collapse();
380 380 };
381 381
382 382
383 383 CodeCell.prototype.expand_output = function () {
384 384 this.collapsed = false;
385 385 this.output_area.expand();
386 386 this.output_area.unscroll_area();
387 387 };
388 388
389 389 CodeCell.prototype.scroll_output = function () {
390 390 this.output_area.expand();
391 391 this.output_area.scroll_if_long();
392 392 };
393 393
394 394 CodeCell.prototype.toggle_output = function () {
395 395 this.collapsed = Boolean(1 - this.collapsed);
396 396 this.output_area.toggle_output();
397 397 };
398 398
399 399 CodeCell.prototype.toggle_output_scroll = function () {
400 400 this.output_area.toggle_scroll();
401 401 };
402 402
403 403
404 404 CodeCell.input_prompt_classical = function (prompt_value, lines_number) {
405 405 var ns;
406 406 if (prompt_value === undefined) {
407 407 ns = "&nbsp;";
408 408 } else {
409 409 ns = encodeURIComponent(prompt_value);
410 410 }
411 411 return 'In&nbsp;[' + ns + ']:';
412 412 };
413 413
414 414 CodeCell.input_prompt_continuation = function (prompt_value, lines_number) {
415 415 var html = [CodeCell.input_prompt_classical(prompt_value, lines_number)];
416 416 for(var i=1; i < lines_number; i++) {
417 417 html.push(['...:']);
418 418 }
419 419 return html.join('<br/>');
420 420 };
421 421
422 422 CodeCell.input_prompt_function = CodeCell.input_prompt_classical;
423 423
424 424
425 425 CodeCell.prototype.set_input_prompt = function (number) {
426 426 var nline = 1;
427 427 if (this.code_mirror !== undefined) {
428 428 nline = this.code_mirror.lineCount();
429 429 }
430 430 this.input_prompt_number = number;
431 431 var prompt_html = CodeCell.input_prompt_function(this.input_prompt_number, nline);
432 432 // This HTML call is okay because the user contents are escaped.
433 433 this.element.find('div.input_prompt').html(prompt_html);
434 434 };
435 435
436 436
437 437 CodeCell.prototype.clear_input = function () {
438 438 this.code_mirror.setValue('');
439 439 };
440 440
441 441
442 442 CodeCell.prototype.get_text = function () {
443 443 return this.code_mirror.getValue();
444 444 };
445 445
446 446
447 447 CodeCell.prototype.set_text = function (code) {
448 448 return this.code_mirror.setValue(code);
449 449 };
450 450
451 451
452 452 CodeCell.prototype.clear_output = function (wait) {
453 453 this.output_area.clear_output(wait);
454 454 this.set_input_prompt();
455 455 };
456 456
457 457
458 458 // JSON serialization
459 459
460 460 CodeCell.prototype.fromJSON = function (data) {
461 461 Cell.prototype.fromJSON.apply(this, arguments);
462 462 if (data.cell_type === 'code') {
463 463 if (data.input !== undefined) {
464 464 this.set_text(data.input);
465 465 // make this value the starting point, so that we can only undo
466 466 // to this state, instead of a blank cell
467 467 this.code_mirror.clearHistory();
468 468 this.auto_highlight();
469 469 }
470 470 if (data.prompt_number !== undefined) {
471 471 this.set_input_prompt(data.prompt_number);
472 472 } else {
473 473 this.set_input_prompt();
474 474 }
475 475 this.output_area.trusted = data.trusted || false;
476 476 this.output_area.fromJSON(data.outputs);
477 477 if (data.collapsed !== undefined) {
478 478 if (data.collapsed) {
479 479 this.collapse_output();
480 480 } else {
481 481 this.expand_output();
482 482 }
483 483 }
484 484 }
485 485 };
486 486
487 487
488 488 CodeCell.prototype.toJSON = function () {
489 489 var data = Cell.prototype.toJSON.apply(this);
490 490 data.input = this.get_text();
491 491 // is finite protect against undefined and '*' value
492 492 if (isFinite(this.input_prompt_number)) {
493 493 data.prompt_number = this.input_prompt_number;
494 494 }
495 495 var outputs = this.output_area.toJSON();
496 496 data.outputs = outputs;
497 497 data.language = 'python';
498 498 data.trusted = this.output_area.trusted;
499 499 data.collapsed = this.collapsed;
500 500 return data;
501 501 };
502 502
503 503 /**
504 504 * handle cell level logic when a cell is unselected
505 505 * @method unselect
506 506 * @return is the action being taken
507 507 */
508 508 CodeCell.prototype.unselect = function () {
509 509 var cont = Cell.prototype.unselect.apply(this);
510 510 if (cont) {
511 511 // When a code cell is usnelected, make sure that the corresponding
512 512 // tooltip and completer to that cell is closed.
513 513 this.tooltip.remove_and_cancel_tooltip(true);
514 514 if (this.completer !== null) {
515 515 this.completer.close();
516 516 }
517 517 }
518 518 return cont;
519 519 };
520 520
521 521 // Backwards compatability.
522 522 IPython.CodeCell = CodeCell;
523 523
524 524 return {'CodeCell': CodeCell};
525 525 });
@@ -1,2620 +1,2644
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'base/js/namespace',
6 6 'jquery',
7 7 'base/js/utils',
8 8 'base/js/dialog',
9 9 'notebook/js/textcell',
10 10 'notebook/js/codecell',
11 11 'services/sessions/js/session',
12 12 'notebook/js/celltoolbar',
13 13 'components/marked/lib/marked',
14 14 'highlight',
15 15 'notebook/js/mathjaxutils',
16 16 'base/js/keyboard',
17 17 'notebook/js/tooltip',
18 18 'notebook/js/celltoolbarpresets/default',
19 19 'notebook/js/celltoolbarpresets/rawcell',
20 20 'notebook/js/celltoolbarpresets/slideshow',
21 21 ], function (
22 22 IPython,
23 23 $,
24 24 utils,
25 25 dialog,
26 26 textcell,
27 27 codecell,
28 28 session,
29 29 celltoolbar,
30 30 marked,
31 31 hljs,
32 32 mathjaxutils,
33 33 keyboard,
34 34 tooltip,
35 35 default_celltoolbar,
36 36 rawcell_celltoolbar,
37 37 slideshow_celltoolbar
38 38 ) {
39 39
40 40 var Notebook = function (selector, options) {
41 41 // Constructor
42 42 //
43 43 // A notebook contains and manages cells.
44 44 //
45 45 // Parameters:
46 46 // selector: string
47 47 // options: dictionary
48 48 // Dictionary of keyword arguments.
49 49 // events: $(Events) instance
50 50 // keyboard_manager: KeyboardManager instance
51 51 // save_widget: SaveWidget instance
52 52 // config: dictionary
53 53 // base_url : string
54 54 // notebook_path : string
55 55 // notebook_name : string
56 this.config = options.config || {};
56 this.config = utils.mergeopt(Notebook, options.config);
57 57 this.base_url = options.base_url;
58 58 this.notebook_path = options.notebook_path;
59 59 this.notebook_name = options.notebook_name;
60 60 this.events = options.events;
61 61 this.keyboard_manager = options.keyboard_manager;
62 62 this.save_widget = options.save_widget;
63 63 this.tooltip = new tooltip.Tooltip(this.events);
64 64 this.ws_url = options.ws_url;
65 65 this._session_starting = false;
66 this.default_cell_type = this.config.default_cell_type || 'code';
66 67 // default_kernel_name is a temporary measure while we implement proper
67 68 // kernel selection and delayed start. Do not rely on it.
68 69 this.default_kernel_name = 'python';
69 70 // TODO: This code smells (and the other `= this` line a couple lines down)
70 71 // We need a better way to deal with circular instance references.
71 72 this.keyboard_manager.notebook = this;
72 73 this.save_widget.notebook = this;
73 74
74 75 mathjaxutils.init();
75 76
76 77 if (marked) {
77 78 marked.setOptions({
78 79 gfm : true,
79 80 tables: true,
80 81 langPrefix: "language-",
81 82 highlight: function(code, lang) {
82 83 if (!lang) {
83 84 // no language, no highlight
84 85 return code;
85 86 }
86 87 var highlighted;
87 88 try {
88 89 highlighted = hljs.highlight(lang, code, false);
89 90 } catch(err) {
90 91 highlighted = hljs.highlightAuto(code);
91 92 }
92 93 return highlighted.value;
93 94 }
94 95 });
95 96 }
96 97
97 98 this.element = $(selector);
98 99 this.element.scroll();
99 100 this.element.data("notebook", this);
100 101 this.next_prompt_number = 1;
101 102 this.session = null;
102 103 this.kernel = null;
103 104 this.clipboard = null;
104 105 this.undelete_backup = null;
105 106 this.undelete_index = null;
106 107 this.undelete_below = false;
107 108 this.paste_enabled = false;
108 109 // It is important to start out in command mode to match the intial mode
109 110 // of the KeyboardManager.
110 111 this.mode = 'command';
111 112 this.set_dirty(false);
112 113 this.metadata = {};
113 114 this._checkpoint_after_save = false;
114 115 this.last_checkpoint = null;
115 116 this.checkpoints = [];
116 117 this.autosave_interval = 0;
117 118 this.autosave_timer = null;
118 119 // autosave *at most* every two minutes
119 120 this.minimum_autosave_interval = 120000;
120 121 // single worksheet for now
121 122 this.worksheet_metadata = {};
122 123 this.notebook_name_blacklist_re = /[\/\\:]/;
123 124 this.nbformat = 3; // Increment this when changing the nbformat
124 125 this.nbformat_minor = 0; // Increment this when changing the nbformat
125 126 this.codemirror_mode = 'ipython';
126 127 this.create_elements();
127 128 this.bind_events();
128 129 this.save_notebook = function() { // don't allow save until notebook_loaded
129 130 this.save_notebook_error(null, null, "Load failed, save is disabled");
130 131 };
131 132
132 133 // Trigger cell toolbar registration.
133 134 default_celltoolbar.register(this);
134 135 rawcell_celltoolbar.register(this);
135 136 slideshow_celltoolbar.register(this);
136 137 };
138
139 Notebook.options_default = {
140 // can be any cell type, or the special values of
141 // 'above', 'below', or 'selected' to get the value from another cell.
142 Notebook: {
143 default_cell_type: 'code',
144 }
145 };
137 146
138 147
139 148 /**
140 149 * Create an HTML and CSS representation of the notebook.
141 150 *
142 151 * @method create_elements
143 152 */
144 153 Notebook.prototype.create_elements = function () {
145 154 var that = this;
146 155 this.element.attr('tabindex','-1');
147 156 this.container = $("<div/>").addClass("container").attr("id", "notebook-container");
148 157 // We add this end_space div to the end of the notebook div to:
149 158 // i) provide a margin between the last cell and the end of the notebook
150 159 // ii) to prevent the div from scrolling up when the last cell is being
151 160 // edited, but is too low on the page, which browsers will do automatically.
152 161 var end_space = $('<div/>').addClass('end_space');
153 162 end_space.dblclick(function (e) {
154 163 var ncells = that.ncells();
155 164 that.insert_cell_below('code',ncells-1);
156 165 });
157 166 this.element.append(this.container);
158 167 this.container.append(end_space);
159 168 };
160 169
161 170 /**
162 171 * Bind JavaScript events: key presses and custom IPython events.
163 172 *
164 173 * @method bind_events
165 174 */
166 175 Notebook.prototype.bind_events = function () {
167 176 var that = this;
168 177
169 178 this.events.on('set_next_input.Notebook', function (event, data) {
170 179 var index = that.find_cell_index(data.cell);
171 180 var new_cell = that.insert_cell_below('code',index);
172 181 new_cell.set_text(data.text);
173 182 that.dirty = true;
174 183 });
175 184
176 185 this.events.on('set_dirty.Notebook', function (event, data) {
177 186 that.dirty = data.value;
178 187 });
179 188
180 189 this.events.on('trust_changed.Notebook', function (event, data) {
181 190 that.trusted = data.value;
182 191 });
183 192
184 193 this.events.on('select.Cell', function (event, data) {
185 194 var index = that.find_cell_index(data.cell);
186 195 that.select(index);
187 196 });
188 197
189 198 this.events.on('edit_mode.Cell', function (event, data) {
190 199 that.handle_edit_mode(data.cell);
191 200 });
192 201
193 202 this.events.on('command_mode.Cell', function (event, data) {
194 203 that.handle_command_mode(data.cell);
195 204 });
196 205
197 206 this.events.on('status_autorestarting.Kernel', function () {
198 207 dialog.modal({
199 208 notebook: that,
200 209 keyboard_manager: that.keyboard_manager,
201 210 title: "Kernel Restarting",
202 211 body: "The kernel appears to have died. It will restart automatically.",
203 212 buttons: {
204 213 OK : {
205 214 class : "btn-primary"
206 215 }
207 216 }
208 217 });
209 218 });
210 219
211 220 this.events.on('spec_changed.Kernel', function(event, data) {
212 221 that.set_kernelspec_metadata(data);
213 222 if (data.codemirror_mode) {
214 223 that.set_codemirror_mode(data.codemirror_mode);
215 224 }
216 225 });
217 226
218 227 var collapse_time = function (time) {
219 228 var app_height = $('#ipython-main-app').height(); // content height
220 229 var splitter_height = $('div#pager_splitter').outerHeight(true);
221 230 var new_height = app_height - splitter_height;
222 231 that.element.animate({height : new_height + 'px'}, time);
223 232 };
224 233
225 234 this.element.bind('collapse_pager', function (event, extrap) {
226 235 var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
227 236 collapse_time(time);
228 237 });
229 238
230 239 var expand_time = function (time) {
231 240 var app_height = $('#ipython-main-app').height(); // content height
232 241 var splitter_height = $('div#pager_splitter').outerHeight(true);
233 242 var pager_height = $('div#pager').outerHeight(true);
234 243 var new_height = app_height - pager_height - splitter_height;
235 244 that.element.animate({height : new_height + 'px'}, time);
236 245 };
237 246
238 247 this.element.bind('expand_pager', function (event, extrap) {
239 248 var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
240 249 expand_time(time);
241 250 });
242 251
243 252 // Firefox 22 broke $(window).on("beforeunload")
244 253 // I'm not sure why or how.
245 254 window.onbeforeunload = function (e) {
246 255 // TODO: Make killing the kernel configurable.
247 256 var kill_kernel = false;
248 257 if (kill_kernel) {
249 258 that.session.kill_kernel();
250 259 }
251 260 // if we are autosaving, trigger an autosave on nav-away.
252 261 // still warn, because if we don't the autosave may fail.
253 262 if (that.dirty) {
254 263 if ( that.autosave_interval ) {
255 264 // schedule autosave in a timeout
256 265 // this gives you a chance to forcefully discard changes
257 266 // by reloading the page if you *really* want to.
258 267 // the timer doesn't start until you *dismiss* the dialog.
259 268 setTimeout(function () {
260 269 if (that.dirty) {
261 270 that.save_notebook();
262 271 }
263 272 }, 1000);
264 273 return "Autosave in progress, latest changes may be lost.";
265 274 } else {
266 275 return "Unsaved changes will be lost.";
267 276 }
268 277 }
269 278 // Null is the *only* return value that will make the browser not
270 279 // pop up the "don't leave" dialog.
271 280 return null;
272 281 };
273 282 };
274 283
275 284 /**
276 285 * Set the dirty flag, and trigger the set_dirty.Notebook event
277 286 *
278 287 * @method set_dirty
279 288 */
280 289 Notebook.prototype.set_dirty = function (value) {
281 290 if (value === undefined) {
282 291 value = true;
283 292 }
284 293 if (this.dirty == value) {
285 294 return;
286 295 }
287 296 this.events.trigger('set_dirty.Notebook', {value: value});
288 297 };
289 298
290 299 /**
291 300 * Scroll the top of the page to a given cell.
292 301 *
293 302 * @method scroll_to_cell
294 303 * @param {Number} cell_number An index of the cell to view
295 304 * @param {Number} time Animation time in milliseconds
296 305 * @return {Number} Pixel offset from the top of the container
297 306 */
298 307 Notebook.prototype.scroll_to_cell = function (cell_number, time) {
299 308 var cells = this.get_cells();
300 309 time = time || 0;
301 310 cell_number = Math.min(cells.length-1,cell_number);
302 311 cell_number = Math.max(0 ,cell_number);
303 312 var scroll_value = cells[cell_number].element.position().top-cells[0].element.position().top ;
304 313 this.element.animate({scrollTop:scroll_value}, time);
305 314 return scroll_value;
306 315 };
307 316
308 317 /**
309 318 * Scroll to the bottom of the page.
310 319 *
311 320 * @method scroll_to_bottom
312 321 */
313 322 Notebook.prototype.scroll_to_bottom = function () {
314 323 this.element.animate({scrollTop:this.element.get(0).scrollHeight}, 0);
315 324 };
316 325
317 326 /**
318 327 * Scroll to the top of the page.
319 328 *
320 329 * @method scroll_to_top
321 330 */
322 331 Notebook.prototype.scroll_to_top = function () {
323 332 this.element.animate({scrollTop:0}, 0);
324 333 };
325 334
326 335 // Edit Notebook metadata
327 336
328 337 Notebook.prototype.edit_metadata = function () {
329 338 var that = this;
330 339 dialog.edit_metadata({
331 340 md: this.metadata,
332 341 callback: function (md) {
333 342 that.metadata = md;
334 343 },
335 344 name: 'Notebook',
336 345 notebook: this,
337 346 keyboard_manager: this.keyboard_manager});
338 347 };
339 348
340 349 Notebook.prototype.set_kernelspec_metadata = function(ks) {
341 350 var tostore = {};
342 351 $.map(ks, function(value, field) {
343 352 if (field !== 'argv' && field !== 'env') {
344 353 tostore[field] = value;
345 354 }
346 355 });
347 356 this.metadata.kernelspec = tostore;
348 357 }
349 358
350 359 // Cell indexing, retrieval, etc.
351 360
352 361 /**
353 362 * Get all cell elements in the notebook.
354 363 *
355 364 * @method get_cell_elements
356 365 * @return {jQuery} A selector of all cell elements
357 366 */
358 367 Notebook.prototype.get_cell_elements = function () {
359 368 return this.container.children("div.cell");
360 369 };
361 370
362 371 /**
363 372 * Get a particular cell element.
364 373 *
365 374 * @method get_cell_element
366 375 * @param {Number} index An index of a cell to select
367 376 * @return {jQuery} A selector of the given cell.
368 377 */
369 378 Notebook.prototype.get_cell_element = function (index) {
370 379 var result = null;
371 380 var e = this.get_cell_elements().eq(index);
372 381 if (e.length !== 0) {
373 382 result = e;
374 383 }
375 384 return result;
376 385 };
377 386
378 387 /**
379 388 * Try to get a particular cell by msg_id.
380 389 *
381 390 * @method get_msg_cell
382 391 * @param {String} msg_id A message UUID
383 392 * @return {Cell} Cell or null if no cell was found.
384 393 */
385 394 Notebook.prototype.get_msg_cell = function (msg_id) {
386 395 return codecell.CodeCell.msg_cells[msg_id] || null;
387 396 };
388 397
389 398 /**
390 399 * Count the cells in this notebook.
391 400 *
392 401 * @method ncells
393 402 * @return {Number} The number of cells in this notebook
394 403 */
395 404 Notebook.prototype.ncells = function () {
396 405 return this.get_cell_elements().length;
397 406 };
398 407
399 408 /**
400 409 * Get all Cell objects in this notebook.
401 410 *
402 411 * @method get_cells
403 412 * @return {Array} This notebook's Cell objects
404 413 */
405 414 // TODO: we are often calling cells as cells()[i], which we should optimize
406 415 // to cells(i) or a new method.
407 416 Notebook.prototype.get_cells = function () {
408 417 return this.get_cell_elements().toArray().map(function (e) {
409 418 return $(e).data("cell");
410 419 });
411 420 };
412 421
413 422 /**
414 423 * Get a Cell object from this notebook.
415 424 *
416 425 * @method get_cell
417 426 * @param {Number} index An index of a cell to retrieve
418 427 * @return {Cell} A particular cell
419 428 */
420 429 Notebook.prototype.get_cell = function (index) {
421 430 var result = null;
422 431 var ce = this.get_cell_element(index);
423 432 if (ce !== null) {
424 433 result = ce.data('cell');
425 434 }
426 435 return result;
427 436 };
428 437
429 438 /**
430 439 * Get the cell below a given cell.
431 440 *
432 441 * @method get_next_cell
433 442 * @param {Cell} cell The provided cell
434 443 * @return {Cell} The next cell
435 444 */
436 445 Notebook.prototype.get_next_cell = function (cell) {
437 446 var result = null;
438 447 var index = this.find_cell_index(cell);
439 448 if (this.is_valid_cell_index(index+1)) {
440 449 result = this.get_cell(index+1);
441 450 }
442 451 return result;
443 452 };
444 453
445 454 /**
446 455 * Get the cell above a given cell.
447 456 *
448 457 * @method get_prev_cell
449 458 * @param {Cell} cell The provided cell
450 459 * @return {Cell} The previous cell
451 460 */
452 461 Notebook.prototype.get_prev_cell = function (cell) {
453 462 // TODO: off-by-one
454 463 // nb.get_prev_cell(nb.get_cell(1)) is null
455 464 var result = null;
456 465 var index = this.find_cell_index(cell);
457 466 if (index !== null && index > 1) {
458 467 result = this.get_cell(index-1);
459 468 }
460 469 return result;
461 470 };
462 471
463 472 /**
464 473 * Get the numeric index of a given cell.
465 474 *
466 475 * @method find_cell_index
467 476 * @param {Cell} cell The provided cell
468 477 * @return {Number} The cell's numeric index
469 478 */
470 479 Notebook.prototype.find_cell_index = function (cell) {
471 480 var result = null;
472 481 this.get_cell_elements().filter(function (index) {
473 482 if ($(this).data("cell") === cell) {
474 483 result = index;
475 484 }
476 485 });
477 486 return result;
478 487 };
479 488
480 489 /**
481 490 * Get a given index , or the selected index if none is provided.
482 491 *
483 492 * @method index_or_selected
484 493 * @param {Number} index A cell's index
485 494 * @return {Number} The given index, or selected index if none is provided.
486 495 */
487 496 Notebook.prototype.index_or_selected = function (index) {
488 497 var i;
489 498 if (index === undefined || index === null) {
490 499 i = this.get_selected_index();
491 500 if (i === null) {
492 501 i = 0;
493 502 }
494 503 } else {
495 504 i = index;
496 505 }
497 506 return i;
498 507 };
499 508
500 509 /**
501 510 * Get the currently selected cell.
502 511 * @method get_selected_cell
503 512 * @return {Cell} The selected cell
504 513 */
505 514 Notebook.prototype.get_selected_cell = function () {
506 515 var index = this.get_selected_index();
507 516 return this.get_cell(index);
508 517 };
509 518
510 519 /**
511 520 * Check whether a cell index is valid.
512 521 *
513 522 * @method is_valid_cell_index
514 523 * @param {Number} index A cell index
515 524 * @return True if the index is valid, false otherwise
516 525 */
517 526 Notebook.prototype.is_valid_cell_index = function (index) {
518 527 if (index !== null && index >= 0 && index < this.ncells()) {
519 528 return true;
520 529 } else {
521 530 return false;
522 531 }
523 532 };
524 533
525 534 /**
526 535 * Get the index of the currently selected cell.
527 536
528 537 * @method get_selected_index
529 538 * @return {Number} The selected cell's numeric index
530 539 */
531 540 Notebook.prototype.get_selected_index = function () {
532 541 var result = null;
533 542 this.get_cell_elements().filter(function (index) {
534 543 if ($(this).data("cell").selected === true) {
535 544 result = index;
536 545 }
537 546 });
538 547 return result;
539 548 };
540 549
541 550
542 551 // Cell selection.
543 552
544 553 /**
545 554 * Programmatically select a cell.
546 555 *
547 556 * @method select
548 557 * @param {Number} index A cell's index
549 558 * @return {Notebook} This notebook
550 559 */
551 560 Notebook.prototype.select = function (index) {
552 561 if (this.is_valid_cell_index(index)) {
553 562 var sindex = this.get_selected_index();
554 563 if (sindex !== null && index !== sindex) {
555 564 // If we are about to select a different cell, make sure we are
556 565 // first in command mode.
557 566 if (this.mode !== 'command') {
558 567 this.command_mode();
559 568 }
560 569 this.get_cell(sindex).unselect();
561 570 }
562 571 var cell = this.get_cell(index);
563 572 cell.select();
564 573 if (cell.cell_type === 'heading') {
565 574 this.events.trigger('selected_cell_type_changed.Notebook',
566 575 {'cell_type':cell.cell_type,level:cell.level}
567 576 );
568 577 } else {
569 578 this.events.trigger('selected_cell_type_changed.Notebook',
570 579 {'cell_type':cell.cell_type}
571 580 );
572 581 }
573 582 }
574 583 return this;
575 584 };
576 585
577 586 /**
578 587 * Programmatically select the next cell.
579 588 *
580 589 * @method select_next
581 590 * @return {Notebook} This notebook
582 591 */
583 592 Notebook.prototype.select_next = function () {
584 593 var index = this.get_selected_index();
585 594 this.select(index+1);
586 595 return this;
587 596 };
588 597
589 598 /**
590 599 * Programmatically select the previous cell.
591 600 *
592 601 * @method select_prev
593 602 * @return {Notebook} This notebook
594 603 */
595 604 Notebook.prototype.select_prev = function () {
596 605 var index = this.get_selected_index();
597 606 this.select(index-1);
598 607 return this;
599 608 };
600 609
601 610
602 611 // Edit/Command mode
603 612
604 613 /**
605 614 * Gets the index of the cell that is in edit mode.
606 615 *
607 616 * @method get_edit_index
608 617 *
609 618 * @return index {int}
610 619 **/
611 620 Notebook.prototype.get_edit_index = function () {
612 621 var result = null;
613 622 this.get_cell_elements().filter(function (index) {
614 623 if ($(this).data("cell").mode === 'edit') {
615 624 result = index;
616 625 }
617 626 });
618 627 return result;
619 628 };
620 629
621 630 /**
622 631 * Handle when a a cell blurs and the notebook should enter command mode.
623 632 *
624 633 * @method handle_command_mode
625 634 * @param [cell] {Cell} Cell to enter command mode on.
626 635 **/
627 636 Notebook.prototype.handle_command_mode = function (cell) {
628 637 if (this.mode !== 'command') {
629 638 cell.command_mode();
630 639 this.mode = 'command';
631 640 this.events.trigger('command_mode.Notebook');
632 641 this.keyboard_manager.command_mode();
633 642 }
634 643 };
635 644
636 645 /**
637 646 * Make the notebook enter command mode.
638 647 *
639 648 * @method command_mode
640 649 **/
641 650 Notebook.prototype.command_mode = function () {
642 651 var cell = this.get_cell(this.get_edit_index());
643 652 if (cell && this.mode !== 'command') {
644 653 // We don't call cell.command_mode, but rather call cell.focus_cell()
645 654 // which will blur and CM editor and trigger the call to
646 655 // handle_command_mode.
647 656 cell.focus_cell();
648 657 }
649 658 };
650 659
651 660 /**
652 661 * Handle when a cell fires it's edit_mode event.
653 662 *
654 663 * @method handle_edit_mode
655 664 * @param [cell] {Cell} Cell to enter edit mode on.
656 665 **/
657 666 Notebook.prototype.handle_edit_mode = function (cell) {
658 667 if (cell && this.mode !== 'edit') {
659 668 cell.edit_mode();
660 669 this.mode = 'edit';
661 670 this.events.trigger('edit_mode.Notebook');
662 671 this.keyboard_manager.edit_mode();
663 672 }
664 673 };
665 674
666 675 /**
667 676 * Make a cell enter edit mode.
668 677 *
669 678 * @method edit_mode
670 679 **/
671 680 Notebook.prototype.edit_mode = function () {
672 681 var cell = this.get_selected_cell();
673 682 if (cell && this.mode !== 'edit') {
674 683 cell.unrender();
675 684 cell.focus_editor();
676 685 }
677 686 };
678 687
679 688 /**
680 689 * Focus the currently selected cell.
681 690 *
682 691 * @method focus_cell
683 692 **/
684 693 Notebook.prototype.focus_cell = function () {
685 694 var cell = this.get_selected_cell();
686 695 if (cell === null) {return;} // No cell is selected
687 696 cell.focus_cell();
688 697 };
689 698
690 699 // Cell movement
691 700
692 701 /**
693 702 * Move given (or selected) cell up and select it.
694 703 *
695 704 * @method move_cell_up
696 705 * @param [index] {integer} cell index
697 706 * @return {Notebook} This notebook
698 707 **/
699 708 Notebook.prototype.move_cell_up = function (index) {
700 709 var i = this.index_or_selected(index);
701 710 if (this.is_valid_cell_index(i) && i > 0) {
702 711 var pivot = this.get_cell_element(i-1);
703 712 var tomove = this.get_cell_element(i);
704 713 if (pivot !== null && tomove !== null) {
705 714 tomove.detach();
706 715 pivot.before(tomove);
707 716 this.select(i-1);
708 717 var cell = this.get_selected_cell();
709 718 cell.focus_cell();
710 719 }
711 720 this.set_dirty(true);
712 721 }
713 722 return this;
714 723 };
715 724
716 725
717 726 /**
718 727 * Move given (or selected) cell down and select it
719 728 *
720 729 * @method move_cell_down
721 730 * @param [index] {integer} cell index
722 731 * @return {Notebook} This notebook
723 732 **/
724 733 Notebook.prototype.move_cell_down = function (index) {
725 734 var i = this.index_or_selected(index);
726 735 if (this.is_valid_cell_index(i) && this.is_valid_cell_index(i+1)) {
727 736 var pivot = this.get_cell_element(i+1);
728 737 var tomove = this.get_cell_element(i);
729 738 if (pivot !== null && tomove !== null) {
730 739 tomove.detach();
731 740 pivot.after(tomove);
732 741 this.select(i+1);
733 742 var cell = this.get_selected_cell();
734 743 cell.focus_cell();
735 744 }
736 745 }
737 746 this.set_dirty();
738 747 return this;
739 748 };
740 749
741 750
742 751 // Insertion, deletion.
743 752
744 753 /**
745 754 * Delete a cell from the notebook.
746 755 *
747 756 * @method delete_cell
748 757 * @param [index] A cell's numeric index
749 758 * @return {Notebook} This notebook
750 759 */
751 760 Notebook.prototype.delete_cell = function (index) {
752 761 var i = this.index_or_selected(index);
753 762 var cell = this.get_selected_cell();
754 763 this.undelete_backup = cell.toJSON();
755 764 $('#undelete_cell').removeClass('disabled');
756 765 if (this.is_valid_cell_index(i)) {
757 766 var old_ncells = this.ncells();
758 767 var ce = this.get_cell_element(i);
759 768 ce.remove();
760 769 if (i === 0) {
761 770 // Always make sure we have at least one cell.
762 771 if (old_ncells === 1) {
763 772 this.insert_cell_below('code');
764 773 }
765 774 this.select(0);
766 775 this.undelete_index = 0;
767 776 this.undelete_below = false;
768 777 } else if (i === old_ncells-1 && i !== 0) {
769 778 this.select(i-1);
770 779 this.undelete_index = i - 1;
771 780 this.undelete_below = true;
772 781 } else {
773 782 this.select(i);
774 783 this.undelete_index = i;
775 784 this.undelete_below = false;
776 785 }
777 786 this.events.trigger('delete.Cell', {'cell': cell, 'index': i});
778 787 this.set_dirty(true);
779 788 }
780 789 return this;
781 790 };
782 791
783 792 /**
784 793 * Restore the most recently deleted cell.
785 794 *
786 795 * @method undelete
787 796 */
788 797 Notebook.prototype.undelete_cell = function() {
789 798 if (this.undelete_backup !== null && this.undelete_index !== null) {
790 799 var current_index = this.get_selected_index();
791 800 if (this.undelete_index < current_index) {
792 801 current_index = current_index + 1;
793 802 }
794 803 if (this.undelete_index >= this.ncells()) {
795 804 this.select(this.ncells() - 1);
796 805 }
797 806 else {
798 807 this.select(this.undelete_index);
799 808 }
800 809 var cell_data = this.undelete_backup;
801 810 var new_cell = null;
802 811 if (this.undelete_below) {
803 812 new_cell = this.insert_cell_below(cell_data.cell_type);
804 813 } else {
805 814 new_cell = this.insert_cell_above(cell_data.cell_type);
806 815 }
807 816 new_cell.fromJSON(cell_data);
808 817 if (this.undelete_below) {
809 818 this.select(current_index+1);
810 819 } else {
811 820 this.select(current_index);
812 821 }
813 822 this.undelete_backup = null;
814 823 this.undelete_index = null;
815 824 }
816 825 $('#undelete_cell').addClass('disabled');
817 826 };
818 827
819 828 /**
820 829 * Insert a cell so that after insertion the cell is at given index.
821 830 *
822 831 * If cell type is not provided, it will default to the type of the
823 832 * currently active cell.
824 833 *
825 834 * Similar to insert_above, but index parameter is mandatory
826 835 *
827 836 * Index will be brought back into the accessible range [0,n]
828 837 *
829 838 * @method insert_cell_at_index
830 839 * @param [type] {string} in ['code','markdown','heading'], defaults to 'code'
831 840 * @param [index] {int} a valid index where to insert cell
832 841 *
833 842 * @return cell {cell|null} created cell or null
834 843 **/
835 844 Notebook.prototype.insert_cell_at_index = function(type, index){
836 845
837 846 var ncells = this.ncells();
838 index = Math.min(index,ncells);
839 index = Math.max(index,0);
847 index = Math.min(index, ncells);
848 index = Math.max(index, 0);
840 849 var cell = null;
841 type = type || this.get_selected_cell().cell_type;
850 type = type || this.default_cell_type;
851 if (type === 'above') {
852 if (index > 0) {
853 type = this.get_cell(index-1).cell_type;
854 } else {
855 type = 'code';
856 }
857 } else if (type === 'below') {
858 if (index < ncells) {
859 type = this.get_cell(index).cell_type;
860 } else {
861 type = 'code';
862 }
863 } else if (type === 'selected') {
864 type = this.get_selected_cell().cell_type;
865 }
842 866
843 867 if (ncells === 0 || this.is_valid_cell_index(index) || index === ncells) {
844 868 var cell_options = {
845 869 events: this.events,
846 870 config: this.config,
847 871 keyboard_manager: this.keyboard_manager,
848 872 notebook: this,
849 873 tooltip: this.tooltip,
850 874 };
851 875 if (type === 'code') {
852 876 cell = new codecell.CodeCell(this.kernel, cell_options);
853 877 cell.set_input_prompt();
854 878 } else if (type === 'markdown') {
855 879 cell = new textcell.MarkdownCell(cell_options);
856 880 } else if (type === 'raw') {
857 881 cell = new textcell.RawCell(cell_options);
858 882 } else if (type === 'heading') {
859 883 cell = new textcell.HeadingCell(cell_options);
860 884 }
861 885
862 886 if(this._insert_element_at_index(cell.element,index)) {
863 887 cell.render();
864 888 this.events.trigger('create.Cell', {'cell': cell, 'index': index});
865 889 cell.refresh();
866 890 // We used to select the cell after we refresh it, but there
867 891 // are now cases were this method is called where select is
868 892 // not appropriate. The selection logic should be handled by the
869 893 // caller of the the top level insert_cell methods.
870 894 this.set_dirty(true);
871 895 }
872 896 }
873 897 return cell;
874 898
875 899 };
876 900
877 901 /**
878 902 * Insert an element at given cell index.
879 903 *
880 904 * @method _insert_element_at_index
881 905 * @param element {dom element} a cell element
882 906 * @param [index] {int} a valid index where to inser cell
883 907 * @private
884 908 *
885 909 * return true if everything whent fine.
886 910 **/
887 911 Notebook.prototype._insert_element_at_index = function(element, index){
888 912 if (element === undefined){
889 913 return false;
890 914 }
891 915
892 916 var ncells = this.ncells();
893 917
894 918 if (ncells === 0) {
895 919 // special case append if empty
896 920 this.element.find('div.end_space').before(element);
897 921 } else if ( ncells === index ) {
898 922 // special case append it the end, but not empty
899 923 this.get_cell_element(index-1).after(element);
900 924 } else if (this.is_valid_cell_index(index)) {
901 925 // otherwise always somewhere to append to
902 926 this.get_cell_element(index).before(element);
903 927 } else {
904 928 return false;
905 929 }
906 930
907 931 if (this.undelete_index !== null && index <= this.undelete_index) {
908 932 this.undelete_index = this.undelete_index + 1;
909 933 this.set_dirty(true);
910 934 }
911 935 return true;
912 936 };
913 937
914 938 /**
915 939 * Insert a cell of given type above given index, or at top
916 940 * of notebook if index smaller than 0.
917 941 *
918 942 * default index value is the one of currently selected cell
919 943 *
920 944 * @method insert_cell_above
921 945 * @param [type] {string} cell type
922 946 * @param [index] {integer}
923 947 *
924 948 * @return handle to created cell or null
925 949 **/
926 950 Notebook.prototype.insert_cell_above = function (type, index) {
927 951 index = this.index_or_selected(index);
928 952 return this.insert_cell_at_index(type, index);
929 953 };
930 954
931 955 /**
932 956 * Insert a cell of given type below given index, or at bottom
933 957 * of notebook if index greater than number of cells
934 958 *
935 959 * default index value is the one of currently selected cell
936 960 *
937 961 * @method insert_cell_below
938 962 * @param [type] {string} cell type
939 963 * @param [index] {integer}
940 964 *
941 965 * @return handle to created cell or null
942 966 *
943 967 **/
944 968 Notebook.prototype.insert_cell_below = function (type, index) {
945 969 index = this.index_or_selected(index);
946 970 return this.insert_cell_at_index(type, index+1);
947 971 };
948 972
949 973
950 974 /**
951 975 * Insert cell at end of notebook
952 976 *
953 977 * @method insert_cell_at_bottom
954 978 * @param {String} type cell type
955 979 *
956 980 * @return the added cell; or null
957 981 **/
958 982 Notebook.prototype.insert_cell_at_bottom = function (type){
959 983 var len = this.ncells();
960 984 return this.insert_cell_below(type,len-1);
961 985 };
962 986
963 987 /**
964 988 * Turn a cell into a code cell.
965 989 *
966 990 * @method to_code
967 991 * @param {Number} [index] A cell's index
968 992 */
969 993 Notebook.prototype.to_code = function (index) {
970 994 var i = this.index_or_selected(index);
971 995 if (this.is_valid_cell_index(i)) {
972 996 var source_element = this.get_cell_element(i);
973 997 var source_cell = source_element.data("cell");
974 998 if (!(source_cell instanceof codecell.CodeCell)) {
975 999 var target_cell = this.insert_cell_below('code',i);
976 1000 var text = source_cell.get_text();
977 1001 if (text === source_cell.placeholder) {
978 1002 text = '';
979 1003 }
980 1004 target_cell.set_text(text);
981 1005 // make this value the starting point, so that we can only undo
982 1006 // to this state, instead of a blank cell
983 1007 target_cell.code_mirror.clearHistory();
984 1008 source_element.remove();
985 1009 this.select(i);
986 1010 var cursor = source_cell.code_mirror.getCursor();
987 1011 target_cell.code_mirror.setCursor(cursor);
988 1012 this.set_dirty(true);
989 1013 }
990 1014 }
991 1015 };
992 1016
993 1017 /**
994 1018 * Turn a cell into a Markdown cell.
995 1019 *
996 1020 * @method to_markdown
997 1021 * @param {Number} [index] A cell's index
998 1022 */
999 1023 Notebook.prototype.to_markdown = function (index) {
1000 1024 var i = this.index_or_selected(index);
1001 1025 if (this.is_valid_cell_index(i)) {
1002 1026 var source_element = this.get_cell_element(i);
1003 1027 var source_cell = source_element.data("cell");
1004 1028 if (!(source_cell instanceof textcell.MarkdownCell)) {
1005 1029 var target_cell = this.insert_cell_below('markdown',i);
1006 1030 var text = source_cell.get_text();
1007 1031 if (text === source_cell.placeholder) {
1008 1032 text = '';
1009 1033 }
1010 1034 // We must show the editor before setting its contents
1011 1035 target_cell.unrender();
1012 1036 target_cell.set_text(text);
1013 1037 // make this value the starting point, so that we can only undo
1014 1038 // to this state, instead of a blank cell
1015 1039 target_cell.code_mirror.clearHistory();
1016 1040 source_element.remove();
1017 1041 this.select(i);
1018 1042 if ((source_cell instanceof textcell.TextCell) && source_cell.rendered) {
1019 1043 target_cell.render();
1020 1044 }
1021 1045 var cursor = source_cell.code_mirror.getCursor();
1022 1046 target_cell.code_mirror.setCursor(cursor);
1023 1047 this.set_dirty(true);
1024 1048 }
1025 1049 }
1026 1050 };
1027 1051
1028 1052 /**
1029 1053 * Turn a cell into a raw text cell.
1030 1054 *
1031 1055 * @method to_raw
1032 1056 * @param {Number} [index] A cell's index
1033 1057 */
1034 1058 Notebook.prototype.to_raw = function (index) {
1035 1059 var i = this.index_or_selected(index);
1036 1060 if (this.is_valid_cell_index(i)) {
1037 1061 var source_element = this.get_cell_element(i);
1038 1062 var source_cell = source_element.data("cell");
1039 1063 var target_cell = null;
1040 1064 if (!(source_cell instanceof textcell.RawCell)) {
1041 1065 target_cell = this.insert_cell_below('raw',i);
1042 1066 var text = source_cell.get_text();
1043 1067 if (text === source_cell.placeholder) {
1044 1068 text = '';
1045 1069 }
1046 1070 // We must show the editor before setting its contents
1047 1071 target_cell.unrender();
1048 1072 target_cell.set_text(text);
1049 1073 // make this value the starting point, so that we can only undo
1050 1074 // to this state, instead of a blank cell
1051 1075 target_cell.code_mirror.clearHistory();
1052 1076 source_element.remove();
1053 1077 this.select(i);
1054 1078 var cursor = source_cell.code_mirror.getCursor();
1055 1079 target_cell.code_mirror.setCursor(cursor);
1056 1080 this.set_dirty(true);
1057 1081 }
1058 1082 }
1059 1083 };
1060 1084
1061 1085 /**
1062 1086 * Turn a cell into a heading cell.
1063 1087 *
1064 1088 * @method to_heading
1065 1089 * @param {Number} [index] A cell's index
1066 1090 * @param {Number} [level] A heading level (e.g., 1 becomes &lt;h1&gt;)
1067 1091 */
1068 1092 Notebook.prototype.to_heading = function (index, level) {
1069 1093 level = level || 1;
1070 1094 var i = this.index_or_selected(index);
1071 1095 if (this.is_valid_cell_index(i)) {
1072 1096 var source_element = this.get_cell_element(i);
1073 1097 var source_cell = source_element.data("cell");
1074 1098 var target_cell = null;
1075 1099 if (source_cell instanceof textcell.HeadingCell) {
1076 1100 source_cell.set_level(level);
1077 1101 } else {
1078 1102 target_cell = this.insert_cell_below('heading',i);
1079 1103 var text = source_cell.get_text();
1080 1104 if (text === source_cell.placeholder) {
1081 1105 text = '';
1082 1106 }
1083 1107 // We must show the editor before setting its contents
1084 1108 target_cell.set_level(level);
1085 1109 target_cell.unrender();
1086 1110 target_cell.set_text(text);
1087 1111 // make this value the starting point, so that we can only undo
1088 1112 // to this state, instead of a blank cell
1089 1113 target_cell.code_mirror.clearHistory();
1090 1114 source_element.remove();
1091 1115 this.select(i);
1092 1116 var cursor = source_cell.code_mirror.getCursor();
1093 1117 target_cell.code_mirror.setCursor(cursor);
1094 1118 if ((source_cell instanceof textcell.TextCell) && source_cell.rendered) {
1095 1119 target_cell.render();
1096 1120 }
1097 1121 }
1098 1122 this.set_dirty(true);
1099 1123 this.events.trigger('selected_cell_type_changed.Notebook',
1100 1124 {'cell_type':'heading',level:level}
1101 1125 );
1102 1126 }
1103 1127 };
1104 1128
1105 1129
1106 1130 // Cut/Copy/Paste
1107 1131
1108 1132 /**
1109 1133 * Enable UI elements for pasting cells.
1110 1134 *
1111 1135 * @method enable_paste
1112 1136 */
1113 1137 Notebook.prototype.enable_paste = function () {
1114 1138 var that = this;
1115 1139 if (!this.paste_enabled) {
1116 1140 $('#paste_cell_replace').removeClass('disabled')
1117 1141 .on('click', function () {that.paste_cell_replace();});
1118 1142 $('#paste_cell_above').removeClass('disabled')
1119 1143 .on('click', function () {that.paste_cell_above();});
1120 1144 $('#paste_cell_below').removeClass('disabled')
1121 1145 .on('click', function () {that.paste_cell_below();});
1122 1146 this.paste_enabled = true;
1123 1147 }
1124 1148 };
1125 1149
1126 1150 /**
1127 1151 * Disable UI elements for pasting cells.
1128 1152 *
1129 1153 * @method disable_paste
1130 1154 */
1131 1155 Notebook.prototype.disable_paste = function () {
1132 1156 if (this.paste_enabled) {
1133 1157 $('#paste_cell_replace').addClass('disabled').off('click');
1134 1158 $('#paste_cell_above').addClass('disabled').off('click');
1135 1159 $('#paste_cell_below').addClass('disabled').off('click');
1136 1160 this.paste_enabled = false;
1137 1161 }
1138 1162 };
1139 1163
1140 1164 /**
1141 1165 * Cut a cell.
1142 1166 *
1143 1167 * @method cut_cell
1144 1168 */
1145 1169 Notebook.prototype.cut_cell = function () {
1146 1170 this.copy_cell();
1147 1171 this.delete_cell();
1148 1172 };
1149 1173
1150 1174 /**
1151 1175 * Copy a cell.
1152 1176 *
1153 1177 * @method copy_cell
1154 1178 */
1155 1179 Notebook.prototype.copy_cell = function () {
1156 1180 var cell = this.get_selected_cell();
1157 1181 this.clipboard = cell.toJSON();
1158 1182 this.enable_paste();
1159 1183 };
1160 1184
1161 1185 /**
1162 1186 * Replace the selected cell with a cell in the clipboard.
1163 1187 *
1164 1188 * @method paste_cell_replace
1165 1189 */
1166 1190 Notebook.prototype.paste_cell_replace = function () {
1167 1191 if (this.clipboard !== null && this.paste_enabled) {
1168 1192 var cell_data = this.clipboard;
1169 1193 var new_cell = this.insert_cell_above(cell_data.cell_type);
1170 1194 new_cell.fromJSON(cell_data);
1171 1195 var old_cell = this.get_next_cell(new_cell);
1172 1196 this.delete_cell(this.find_cell_index(old_cell));
1173 1197 this.select(this.find_cell_index(new_cell));
1174 1198 }
1175 1199 };
1176 1200
1177 1201 /**
1178 1202 * Paste a cell from the clipboard above the selected cell.
1179 1203 *
1180 1204 * @method paste_cell_above
1181 1205 */
1182 1206 Notebook.prototype.paste_cell_above = function () {
1183 1207 if (this.clipboard !== null && this.paste_enabled) {
1184 1208 var cell_data = this.clipboard;
1185 1209 var new_cell = this.insert_cell_above(cell_data.cell_type);
1186 1210 new_cell.fromJSON(cell_data);
1187 1211 new_cell.focus_cell();
1188 1212 }
1189 1213 };
1190 1214
1191 1215 /**
1192 1216 * Paste a cell from the clipboard below the selected cell.
1193 1217 *
1194 1218 * @method paste_cell_below
1195 1219 */
1196 1220 Notebook.prototype.paste_cell_below = function () {
1197 1221 if (this.clipboard !== null && this.paste_enabled) {
1198 1222 var cell_data = this.clipboard;
1199 1223 var new_cell = this.insert_cell_below(cell_data.cell_type);
1200 1224 new_cell.fromJSON(cell_data);
1201 1225 new_cell.focus_cell();
1202 1226 }
1203 1227 };
1204 1228
1205 1229 // Split/merge
1206 1230
1207 1231 /**
1208 1232 * Split the selected cell into two, at the cursor.
1209 1233 *
1210 1234 * @method split_cell
1211 1235 */
1212 1236 Notebook.prototype.split_cell = function () {
1213 1237 var mdc = textcell.MarkdownCell;
1214 1238 var rc = textcell.RawCell;
1215 1239 var cell = this.get_selected_cell();
1216 1240 if (cell.is_splittable()) {
1217 1241 var texta = cell.get_pre_cursor();
1218 1242 var textb = cell.get_post_cursor();
1219 1243 cell.set_text(textb);
1220 1244 var new_cell = this.insert_cell_above(cell.cell_type);
1221 1245 // Unrender the new cell so we can call set_text.
1222 1246 new_cell.unrender();
1223 1247 new_cell.set_text(texta);
1224 1248 }
1225 1249 };
1226 1250
1227 1251 /**
1228 1252 * Combine the selected cell into the cell above it.
1229 1253 *
1230 1254 * @method merge_cell_above
1231 1255 */
1232 1256 Notebook.prototype.merge_cell_above = function () {
1233 1257 var mdc = textcell.MarkdownCell;
1234 1258 var rc = textcell.RawCell;
1235 1259 var index = this.get_selected_index();
1236 1260 var cell = this.get_cell(index);
1237 1261 var render = cell.rendered;
1238 1262 if (!cell.is_mergeable()) {
1239 1263 return;
1240 1264 }
1241 1265 if (index > 0) {
1242 1266 var upper_cell = this.get_cell(index-1);
1243 1267 if (!upper_cell.is_mergeable()) {
1244 1268 return;
1245 1269 }
1246 1270 var upper_text = upper_cell.get_text();
1247 1271 var text = cell.get_text();
1248 1272 if (cell instanceof codecell.CodeCell) {
1249 1273 cell.set_text(upper_text+'\n'+text);
1250 1274 } else {
1251 1275 cell.unrender(); // Must unrender before we set_text.
1252 1276 cell.set_text(upper_text+'\n\n'+text);
1253 1277 if (render) {
1254 1278 // The rendered state of the final cell should match
1255 1279 // that of the original selected cell;
1256 1280 cell.render();
1257 1281 }
1258 1282 }
1259 1283 this.delete_cell(index-1);
1260 1284 this.select(this.find_cell_index(cell));
1261 1285 }
1262 1286 };
1263 1287
1264 1288 /**
1265 1289 * Combine the selected cell into the cell below it.
1266 1290 *
1267 1291 * @method merge_cell_below
1268 1292 */
1269 1293 Notebook.prototype.merge_cell_below = function () {
1270 1294 var mdc = textcell.MarkdownCell;
1271 1295 var rc = textcell.RawCell;
1272 1296 var index = this.get_selected_index();
1273 1297 var cell = this.get_cell(index);
1274 1298 var render = cell.rendered;
1275 1299 if (!cell.is_mergeable()) {
1276 1300 return;
1277 1301 }
1278 1302 if (index < this.ncells()-1) {
1279 1303 var lower_cell = this.get_cell(index+1);
1280 1304 if (!lower_cell.is_mergeable()) {
1281 1305 return;
1282 1306 }
1283 1307 var lower_text = lower_cell.get_text();
1284 1308 var text = cell.get_text();
1285 1309 if (cell instanceof codecell.CodeCell) {
1286 1310 cell.set_text(text+'\n'+lower_text);
1287 1311 } else {
1288 1312 cell.unrender(); // Must unrender before we set_text.
1289 1313 cell.set_text(text+'\n\n'+lower_text);
1290 1314 if (render) {
1291 1315 // The rendered state of the final cell should match
1292 1316 // that of the original selected cell;
1293 1317 cell.render();
1294 1318 }
1295 1319 }
1296 1320 this.delete_cell(index+1);
1297 1321 this.select(this.find_cell_index(cell));
1298 1322 }
1299 1323 };
1300 1324
1301 1325
1302 1326 // Cell collapsing and output clearing
1303 1327
1304 1328 /**
1305 1329 * Hide a cell's output.
1306 1330 *
1307 1331 * @method collapse_output
1308 1332 * @param {Number} index A cell's numeric index
1309 1333 */
1310 1334 Notebook.prototype.collapse_output = function (index) {
1311 1335 var i = this.index_or_selected(index);
1312 1336 var cell = this.get_cell(i);
1313 1337 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1314 1338 cell.collapse_output();
1315 1339 this.set_dirty(true);
1316 1340 }
1317 1341 };
1318 1342
1319 1343 /**
1320 1344 * Hide each code cell's output area.
1321 1345 *
1322 1346 * @method collapse_all_output
1323 1347 */
1324 1348 Notebook.prototype.collapse_all_output = function () {
1325 1349 $.map(this.get_cells(), function (cell, i) {
1326 1350 if (cell instanceof codecell.CodeCell) {
1327 1351 cell.collapse_output();
1328 1352 }
1329 1353 });
1330 1354 // this should not be set if the `collapse` key is removed from nbformat
1331 1355 this.set_dirty(true);
1332 1356 };
1333 1357
1334 1358 /**
1335 1359 * Show a cell's output.
1336 1360 *
1337 1361 * @method expand_output
1338 1362 * @param {Number} index A cell's numeric index
1339 1363 */
1340 1364 Notebook.prototype.expand_output = function (index) {
1341 1365 var i = this.index_or_selected(index);
1342 1366 var cell = this.get_cell(i);
1343 1367 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1344 1368 cell.expand_output();
1345 1369 this.set_dirty(true);
1346 1370 }
1347 1371 };
1348 1372
1349 1373 /**
1350 1374 * Expand each code cell's output area, and remove scrollbars.
1351 1375 *
1352 1376 * @method expand_all_output
1353 1377 */
1354 1378 Notebook.prototype.expand_all_output = function () {
1355 1379 $.map(this.get_cells(), function (cell, i) {
1356 1380 if (cell instanceof codecell.CodeCell) {
1357 1381 cell.expand_output();
1358 1382 }
1359 1383 });
1360 1384 // this should not be set if the `collapse` key is removed from nbformat
1361 1385 this.set_dirty(true);
1362 1386 };
1363 1387
1364 1388 /**
1365 1389 * Clear the selected CodeCell's output area.
1366 1390 *
1367 1391 * @method clear_output
1368 1392 * @param {Number} index A cell's numeric index
1369 1393 */
1370 1394 Notebook.prototype.clear_output = function (index) {
1371 1395 var i = this.index_or_selected(index);
1372 1396 var cell = this.get_cell(i);
1373 1397 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1374 1398 cell.clear_output();
1375 1399 this.set_dirty(true);
1376 1400 }
1377 1401 };
1378 1402
1379 1403 /**
1380 1404 * Clear each code cell's output area.
1381 1405 *
1382 1406 * @method clear_all_output
1383 1407 */
1384 1408 Notebook.prototype.clear_all_output = function () {
1385 1409 $.map(this.get_cells(), function (cell, i) {
1386 1410 if (cell instanceof codecell.CodeCell) {
1387 1411 cell.clear_output();
1388 1412 }
1389 1413 });
1390 1414 this.set_dirty(true);
1391 1415 };
1392 1416
1393 1417 /**
1394 1418 * Scroll the selected CodeCell's output area.
1395 1419 *
1396 1420 * @method scroll_output
1397 1421 * @param {Number} index A cell's numeric index
1398 1422 */
1399 1423 Notebook.prototype.scroll_output = function (index) {
1400 1424 var i = this.index_or_selected(index);
1401 1425 var cell = this.get_cell(i);
1402 1426 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1403 1427 cell.scroll_output();
1404 1428 this.set_dirty(true);
1405 1429 }
1406 1430 };
1407 1431
1408 1432 /**
1409 1433 * Expand each code cell's output area, and add a scrollbar for long output.
1410 1434 *
1411 1435 * @method scroll_all_output
1412 1436 */
1413 1437 Notebook.prototype.scroll_all_output = function () {
1414 1438 $.map(this.get_cells(), function (cell, i) {
1415 1439 if (cell instanceof codecell.CodeCell) {
1416 1440 cell.scroll_output();
1417 1441 }
1418 1442 });
1419 1443 // this should not be set if the `collapse` key is removed from nbformat
1420 1444 this.set_dirty(true);
1421 1445 };
1422 1446
1423 1447 /** Toggle whether a cell's output is collapsed or expanded.
1424 1448 *
1425 1449 * @method toggle_output
1426 1450 * @param {Number} index A cell's numeric index
1427 1451 */
1428 1452 Notebook.prototype.toggle_output = function (index) {
1429 1453 var i = this.index_or_selected(index);
1430 1454 var cell = this.get_cell(i);
1431 1455 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1432 1456 cell.toggle_output();
1433 1457 this.set_dirty(true);
1434 1458 }
1435 1459 };
1436 1460
1437 1461 /**
1438 1462 * Hide/show the output of all cells.
1439 1463 *
1440 1464 * @method toggle_all_output
1441 1465 */
1442 1466 Notebook.prototype.toggle_all_output = function () {
1443 1467 $.map(this.get_cells(), function (cell, i) {
1444 1468 if (cell instanceof codecell.CodeCell) {
1445 1469 cell.toggle_output();
1446 1470 }
1447 1471 });
1448 1472 // this should not be set if the `collapse` key is removed from nbformat
1449 1473 this.set_dirty(true);
1450 1474 };
1451 1475
1452 1476 /**
1453 1477 * Toggle a scrollbar for long cell outputs.
1454 1478 *
1455 1479 * @method toggle_output_scroll
1456 1480 * @param {Number} index A cell's numeric index
1457 1481 */
1458 1482 Notebook.prototype.toggle_output_scroll = function (index) {
1459 1483 var i = this.index_or_selected(index);
1460 1484 var cell = this.get_cell(i);
1461 1485 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1462 1486 cell.toggle_output_scroll();
1463 1487 this.set_dirty(true);
1464 1488 }
1465 1489 };
1466 1490
1467 1491 /**
1468 1492 * Toggle the scrolling of long output on all cells.
1469 1493 *
1470 1494 * @method toggle_all_output_scrolling
1471 1495 */
1472 1496 Notebook.prototype.toggle_all_output_scroll = function () {
1473 1497 $.map(this.get_cells(), function (cell, i) {
1474 1498 if (cell instanceof codecell.CodeCell) {
1475 1499 cell.toggle_output_scroll();
1476 1500 }
1477 1501 });
1478 1502 // this should not be set if the `collapse` key is removed from nbformat
1479 1503 this.set_dirty(true);
1480 1504 };
1481 1505
1482 1506 // Other cell functions: line numbers, ...
1483 1507
1484 1508 /**
1485 1509 * Toggle line numbers in the selected cell's input area.
1486 1510 *
1487 1511 * @method cell_toggle_line_numbers
1488 1512 */
1489 1513 Notebook.prototype.cell_toggle_line_numbers = function() {
1490 1514 this.get_selected_cell().toggle_line_numbers();
1491 1515 };
1492 1516
1493 1517 /**
1494 1518 * Set the codemirror mode for all code cells, including the default for
1495 1519 * new code cells.
1496 1520 *
1497 1521 * @method set_codemirror_mode
1498 1522 */
1499 1523 Notebook.prototype.set_codemirror_mode = function(newmode){
1500 1524 if (newmode === this.codemirror_mode) {
1501 1525 return;
1502 1526 }
1503 1527 this.codemirror_mode = newmode;
1504 1528 codecell.CodeCell.options_default.cm_config.mode = newmode;
1505 1529 modename = newmode.name || newmode
1506 1530
1507 1531 that = this;
1508 1532 CodeMirror.requireMode(modename, function(){
1509 1533 $.map(that.get_cells(), function(cell, i) {
1510 1534 if (cell.cell_type === 'code'){
1511 1535 cell.code_mirror.setOption('mode', newmode);
1512 1536 // This is currently redundant, because cm_config ends up as
1513 1537 // codemirror's own .options object, but I don't want to
1514 1538 // rely on that.
1515 1539 cell.cm_config.mode = newmode;
1516 1540 }
1517 1541 });
1518 1542 })
1519 1543 };
1520 1544
1521 1545 // Session related things
1522 1546
1523 1547 /**
1524 1548 * Start a new session and set it on each code cell.
1525 1549 *
1526 1550 * @method start_session
1527 1551 */
1528 1552 Notebook.prototype.start_session = function (kernel_name) {
1529 1553 var that = this;
1530 1554 if (kernel_name === undefined) {
1531 1555 kernel_name = this.default_kernel_name;
1532 1556 }
1533 1557 if (this._session_starting) {
1534 1558 throw new session.SessionAlreadyStarting();
1535 1559 }
1536 1560 this._session_starting = true;
1537 1561
1538 1562 if (this.session !== null) {
1539 1563 var s = this.session;
1540 1564 this.session = null;
1541 1565 // need to start the new session in a callback after delete,
1542 1566 // because javascript does not guarantee the ordering of AJAX requests (?!)
1543 1567 s.delete(function () {
1544 1568 // on successful delete, start new session
1545 1569 that._session_starting = false;
1546 1570 that.start_session(kernel_name);
1547 1571 }, function (jqXHR, status, error) {
1548 1572 // log the failed delete, but still create a new session
1549 1573 // 404 just means it was already deleted by someone else,
1550 1574 // but other errors are possible.
1551 1575 utils.log_ajax_error(jqXHR, status, error);
1552 1576 that._session_starting = false;
1553 1577 that.start_session(kernel_name);
1554 1578 }
1555 1579 );
1556 1580 return;
1557 1581 }
1558 1582
1559 1583
1560 1584
1561 1585 this.session = new session.Session({
1562 1586 base_url: this.base_url,
1563 1587 ws_url: this.ws_url,
1564 1588 notebook_path: this.notebook_path,
1565 1589 notebook_name: this.notebook_name,
1566 1590 // For now, create all sessions with the 'python' kernel, which is the
1567 1591 // default. Later, the user will be able to select kernels. This is
1568 1592 // overridden if KernelManager.kernel_cmd is specified for the server.
1569 1593 kernel_name: kernel_name,
1570 1594 notebook: this});
1571 1595
1572 1596 this.session.start(
1573 1597 $.proxy(this._session_started, this),
1574 1598 $.proxy(this._session_start_failed, this)
1575 1599 );
1576 1600 };
1577 1601
1578 1602
1579 1603 /**
1580 1604 * Once a session is started, link the code cells to the kernel and pass the
1581 1605 * comm manager to the widget manager
1582 1606 *
1583 1607 */
1584 1608 Notebook.prototype._session_started = function (){
1585 1609 this._session_starting = false;
1586 1610 this.kernel = this.session.kernel;
1587 1611 var ncells = this.ncells();
1588 1612 for (var i=0; i<ncells; i++) {
1589 1613 var cell = this.get_cell(i);
1590 1614 if (cell instanceof codecell.CodeCell) {
1591 1615 cell.set_kernel(this.session.kernel);
1592 1616 }
1593 1617 }
1594 1618 };
1595 1619 Notebook.prototype._session_start_failed = function (jqxhr, status, error){
1596 1620 this._session_starting = false;
1597 1621 utils.log_ajax_error(jqxhr, status, error);
1598 1622 };
1599 1623
1600 1624 /**
1601 1625 * Prompt the user to restart the IPython kernel.
1602 1626 *
1603 1627 * @method restart_kernel
1604 1628 */
1605 1629 Notebook.prototype.restart_kernel = function () {
1606 1630 var that = this;
1607 1631 dialog.modal({
1608 1632 notebook: this,
1609 1633 keyboard_manager: this.keyboard_manager,
1610 1634 title : "Restart kernel or continue running?",
1611 1635 body : $("<p/>").text(
1612 1636 'Do you want to restart the current kernel? You will lose all variables defined in it.'
1613 1637 ),
1614 1638 buttons : {
1615 1639 "Continue running" : {},
1616 1640 "Restart" : {
1617 1641 "class" : "btn-danger",
1618 1642 "click" : function() {
1619 1643 that.session.restart_kernel();
1620 1644 }
1621 1645 }
1622 1646 }
1623 1647 });
1624 1648 };
1625 1649
1626 1650 /**
1627 1651 * Execute or render cell outputs and go into command mode.
1628 1652 *
1629 1653 * @method execute_cell
1630 1654 */
1631 1655 Notebook.prototype.execute_cell = function () {
1632 1656 // mode = shift, ctrl, alt
1633 1657 var cell = this.get_selected_cell();
1634 1658 var cell_index = this.find_cell_index(cell);
1635 1659
1636 1660 cell.execute();
1637 1661 this.command_mode();
1638 1662 this.set_dirty(true);
1639 1663 };
1640 1664
1641 1665 /**
1642 1666 * Execute or render cell outputs and insert a new cell below.
1643 1667 *
1644 1668 * @method execute_cell_and_insert_below
1645 1669 */
1646 1670 Notebook.prototype.execute_cell_and_insert_below = function () {
1647 1671 var cell = this.get_selected_cell();
1648 1672 var cell_index = this.find_cell_index(cell);
1649 1673
1650 1674 cell.execute();
1651 1675
1652 1676 // If we are at the end always insert a new cell and return
1653 1677 if (cell_index === (this.ncells()-1)) {
1654 1678 this.command_mode();
1655 1679 this.insert_cell_below();
1656 1680 this.select(cell_index+1);
1657 1681 this.edit_mode();
1658 1682 this.scroll_to_bottom();
1659 1683 this.set_dirty(true);
1660 1684 return;
1661 1685 }
1662 1686
1663 1687 this.command_mode();
1664 1688 this.insert_cell_below();
1665 1689 this.select(cell_index+1);
1666 1690 this.edit_mode();
1667 1691 this.set_dirty(true);
1668 1692 };
1669 1693
1670 1694 /**
1671 1695 * Execute or render cell outputs and select the next cell.
1672 1696 *
1673 1697 * @method execute_cell_and_select_below
1674 1698 */
1675 1699 Notebook.prototype.execute_cell_and_select_below = function () {
1676 1700
1677 1701 var cell = this.get_selected_cell();
1678 1702 var cell_index = this.find_cell_index(cell);
1679 1703
1680 1704 cell.execute();
1681 1705
1682 1706 // If we are at the end always insert a new cell and return
1683 1707 if (cell_index === (this.ncells()-1)) {
1684 1708 this.command_mode();
1685 1709 this.insert_cell_below();
1686 1710 this.select(cell_index+1);
1687 1711 this.edit_mode();
1688 1712 this.scroll_to_bottom();
1689 1713 this.set_dirty(true);
1690 1714 return;
1691 1715 }
1692 1716
1693 1717 this.command_mode();
1694 1718 this.select(cell_index+1);
1695 1719 this.focus_cell();
1696 1720 this.set_dirty(true);
1697 1721 };
1698 1722
1699 1723 /**
1700 1724 * Execute all cells below the selected cell.
1701 1725 *
1702 1726 * @method execute_cells_below
1703 1727 */
1704 1728 Notebook.prototype.execute_cells_below = function () {
1705 1729 this.execute_cell_range(this.get_selected_index(), this.ncells());
1706 1730 this.scroll_to_bottom();
1707 1731 };
1708 1732
1709 1733 /**
1710 1734 * Execute all cells above the selected cell.
1711 1735 *
1712 1736 * @method execute_cells_above
1713 1737 */
1714 1738 Notebook.prototype.execute_cells_above = function () {
1715 1739 this.execute_cell_range(0, this.get_selected_index());
1716 1740 };
1717 1741
1718 1742 /**
1719 1743 * Execute all cells.
1720 1744 *
1721 1745 * @method execute_all_cells
1722 1746 */
1723 1747 Notebook.prototype.execute_all_cells = function () {
1724 1748 this.execute_cell_range(0, this.ncells());
1725 1749 this.scroll_to_bottom();
1726 1750 };
1727 1751
1728 1752 /**
1729 1753 * Execute a contiguous range of cells.
1730 1754 *
1731 1755 * @method execute_cell_range
1732 1756 * @param {Number} start Index of the first cell to execute (inclusive)
1733 1757 * @param {Number} end Index of the last cell to execute (exclusive)
1734 1758 */
1735 1759 Notebook.prototype.execute_cell_range = function (start, end) {
1736 1760 this.command_mode();
1737 1761 for (var i=start; i<end; i++) {
1738 1762 this.select(i);
1739 1763 this.execute_cell();
1740 1764 }
1741 1765 };
1742 1766
1743 1767 // Persistance and loading
1744 1768
1745 1769 /**
1746 1770 * Getter method for this notebook's name.
1747 1771 *
1748 1772 * @method get_notebook_name
1749 1773 * @return {String} This notebook's name (excluding file extension)
1750 1774 */
1751 1775 Notebook.prototype.get_notebook_name = function () {
1752 1776 var nbname = this.notebook_name.substring(0,this.notebook_name.length-6);
1753 1777 return nbname;
1754 1778 };
1755 1779
1756 1780 /**
1757 1781 * Setter method for this notebook's name.
1758 1782 *
1759 1783 * @method set_notebook_name
1760 1784 * @param {String} name A new name for this notebook
1761 1785 */
1762 1786 Notebook.prototype.set_notebook_name = function (name) {
1763 1787 this.notebook_name = name;
1764 1788 };
1765 1789
1766 1790 /**
1767 1791 * Check that a notebook's name is valid.
1768 1792 *
1769 1793 * @method test_notebook_name
1770 1794 * @param {String} nbname A name for this notebook
1771 1795 * @return {Boolean} True if the name is valid, false if invalid
1772 1796 */
1773 1797 Notebook.prototype.test_notebook_name = function (nbname) {
1774 1798 nbname = nbname || '';
1775 1799 if (nbname.length>0 && !this.notebook_name_blacklist_re.test(nbname)) {
1776 1800 return true;
1777 1801 } else {
1778 1802 return false;
1779 1803 }
1780 1804 };
1781 1805
1782 1806 /**
1783 1807 * Load a notebook from JSON (.ipynb).
1784 1808 *
1785 1809 * This currently handles one worksheet: others are deleted.
1786 1810 *
1787 1811 * @method fromJSON
1788 1812 * @param {Object} data JSON representation of a notebook
1789 1813 */
1790 1814 Notebook.prototype.fromJSON = function (data) {
1791 1815 var content = data.content;
1792 1816 var ncells = this.ncells();
1793 1817 var i;
1794 1818 for (i=0; i<ncells; i++) {
1795 1819 // Always delete cell 0 as they get renumbered as they are deleted.
1796 1820 this.delete_cell(0);
1797 1821 }
1798 1822 // Save the metadata and name.
1799 1823 this.metadata = content.metadata;
1800 1824 this.notebook_name = data.name;
1801 1825 var trusted = true;
1802 1826
1803 1827 // Trigger an event changing the kernel spec - this will set the default
1804 1828 // codemirror mode
1805 1829 if (this.metadata.kernelspec !== undefined) {
1806 1830 this.events.trigger('spec_changed.Kernel', this.metadata.kernelspec);
1807 1831 }
1808 1832
1809 1833 // Only handle 1 worksheet for now.
1810 1834 var worksheet = content.worksheets[0];
1811 1835 if (worksheet !== undefined) {
1812 1836 if (worksheet.metadata) {
1813 1837 this.worksheet_metadata = worksheet.metadata;
1814 1838 }
1815 1839 var new_cells = worksheet.cells;
1816 1840 ncells = new_cells.length;
1817 1841 var cell_data = null;
1818 1842 var new_cell = null;
1819 1843 for (i=0; i<ncells; i++) {
1820 1844 cell_data = new_cells[i];
1821 1845 // VERSIONHACK: plaintext -> raw
1822 1846 // handle never-released plaintext name for raw cells
1823 1847 if (cell_data.cell_type === 'plaintext'){
1824 1848 cell_data.cell_type = 'raw';
1825 1849 }
1826 1850
1827 1851 new_cell = this.insert_cell_at_index(cell_data.cell_type, i);
1828 1852 new_cell.fromJSON(cell_data);
1829 1853 if (new_cell.cell_type == 'code' && !new_cell.output_area.trusted) {
1830 1854 trusted = false;
1831 1855 }
1832 1856 }
1833 1857 }
1834 1858 if (trusted != this.trusted) {
1835 1859 this.trusted = trusted;
1836 1860 this.events.trigger("trust_changed.Notebook", trusted);
1837 1861 }
1838 1862 if (content.worksheets.length > 1) {
1839 1863 dialog.modal({
1840 1864 notebook: this,
1841 1865 keyboard_manager: this.keyboard_manager,
1842 1866 title : "Multiple worksheets",
1843 1867 body : "This notebook has " + data.worksheets.length + " worksheets, " +
1844 1868 "but this version of IPython can only handle the first. " +
1845 1869 "If you save this notebook, worksheets after the first will be lost.",
1846 1870 buttons : {
1847 1871 OK : {
1848 1872 class : "btn-danger"
1849 1873 }
1850 1874 }
1851 1875 });
1852 1876 }
1853 1877 };
1854 1878
1855 1879 /**
1856 1880 * Dump this notebook into a JSON-friendly object.
1857 1881 *
1858 1882 * @method toJSON
1859 1883 * @return {Object} A JSON-friendly representation of this notebook.
1860 1884 */
1861 1885 Notebook.prototype.toJSON = function () {
1862 1886 var cells = this.get_cells();
1863 1887 var ncells = cells.length;
1864 1888 var cell_array = new Array(ncells);
1865 1889 var trusted = true;
1866 1890 for (var i=0; i<ncells; i++) {
1867 1891 var cell = cells[i];
1868 1892 if (cell.cell_type == 'code' && !cell.output_area.trusted) {
1869 1893 trusted = false;
1870 1894 }
1871 1895 cell_array[i] = cell.toJSON();
1872 1896 }
1873 1897 var data = {
1874 1898 // Only handle 1 worksheet for now.
1875 1899 worksheets : [{
1876 1900 cells: cell_array,
1877 1901 metadata: this.worksheet_metadata
1878 1902 }],
1879 1903 metadata : this.metadata
1880 1904 };
1881 1905 if (trusted != this.trusted) {
1882 1906 this.trusted = trusted;
1883 1907 this.events.trigger("trust_changed.Notebook", trusted);
1884 1908 }
1885 1909 return data;
1886 1910 };
1887 1911
1888 1912 /**
1889 1913 * Start an autosave timer, for periodically saving the notebook.
1890 1914 *
1891 1915 * @method set_autosave_interval
1892 1916 * @param {Integer} interval the autosave interval in milliseconds
1893 1917 */
1894 1918 Notebook.prototype.set_autosave_interval = function (interval) {
1895 1919 var that = this;
1896 1920 // clear previous interval, so we don't get simultaneous timers
1897 1921 if (this.autosave_timer) {
1898 1922 clearInterval(this.autosave_timer);
1899 1923 }
1900 1924
1901 1925 this.autosave_interval = this.minimum_autosave_interval = interval;
1902 1926 if (interval) {
1903 1927 this.autosave_timer = setInterval(function() {
1904 1928 if (that.dirty) {
1905 1929 that.save_notebook();
1906 1930 }
1907 1931 }, interval);
1908 1932 this.events.trigger("autosave_enabled.Notebook", interval);
1909 1933 } else {
1910 1934 this.autosave_timer = null;
1911 1935 this.events.trigger("autosave_disabled.Notebook");
1912 1936 }
1913 1937 };
1914 1938
1915 1939 /**
1916 1940 * Save this notebook on the server. This becomes a notebook instance's
1917 1941 * .save_notebook method *after* the entire notebook has been loaded.
1918 1942 *
1919 1943 * @method save_notebook
1920 1944 */
1921 1945 Notebook.prototype.save_notebook = function (extra_settings) {
1922 1946 // Create a JSON model to be sent to the server.
1923 1947 var model = {};
1924 1948 model.name = this.notebook_name;
1925 1949 model.path = this.notebook_path;
1926 1950 model.type = 'notebook';
1927 1951 model.format = 'json';
1928 1952 model.content = this.toJSON();
1929 1953 model.content.nbformat = this.nbformat;
1930 1954 model.content.nbformat_minor = this.nbformat_minor;
1931 1955 // time the ajax call for autosave tuning purposes.
1932 1956 var start = new Date().getTime();
1933 1957 // We do the call with settings so we can set cache to false.
1934 1958 var settings = {
1935 1959 processData : false,
1936 1960 cache : false,
1937 1961 type : "PUT",
1938 1962 data : JSON.stringify(model),
1939 1963 headers : {'Content-Type': 'application/json'},
1940 1964 success : $.proxy(this.save_notebook_success, this, start),
1941 1965 error : $.proxy(this.save_notebook_error, this)
1942 1966 };
1943 1967 if (extra_settings) {
1944 1968 for (var key in extra_settings) {
1945 1969 settings[key] = extra_settings[key];
1946 1970 }
1947 1971 }
1948 1972 this.events.trigger('notebook_saving.Notebook');
1949 1973 var url = utils.url_join_encode(
1950 1974 this.base_url,
1951 1975 'api/contents',
1952 1976 this.notebook_path,
1953 1977 this.notebook_name
1954 1978 );
1955 1979 $.ajax(url, settings);
1956 1980 };
1957 1981
1958 1982 /**
1959 1983 * Success callback for saving a notebook.
1960 1984 *
1961 1985 * @method save_notebook_success
1962 1986 * @param {Integer} start the time when the save request started
1963 1987 * @param {Object} data JSON representation of a notebook
1964 1988 * @param {String} status Description of response status
1965 1989 * @param {jqXHR} xhr jQuery Ajax object
1966 1990 */
1967 1991 Notebook.prototype.save_notebook_success = function (start, data, status, xhr) {
1968 1992 this.set_dirty(false);
1969 1993 this.events.trigger('notebook_saved.Notebook');
1970 1994 this._update_autosave_interval(start);
1971 1995 if (this._checkpoint_after_save) {
1972 1996 this.create_checkpoint();
1973 1997 this._checkpoint_after_save = false;
1974 1998 }
1975 1999 };
1976 2000
1977 2001 /**
1978 2002 * update the autosave interval based on how long the last save took
1979 2003 *
1980 2004 * @method _update_autosave_interval
1981 2005 * @param {Integer} timestamp when the save request started
1982 2006 */
1983 2007 Notebook.prototype._update_autosave_interval = function (start) {
1984 2008 var duration = (new Date().getTime() - start);
1985 2009 if (this.autosave_interval) {
1986 2010 // new save interval: higher of 10x save duration or parameter (default 30 seconds)
1987 2011 var interval = Math.max(10 * duration, this.minimum_autosave_interval);
1988 2012 // round to 10 seconds, otherwise we will be setting a new interval too often
1989 2013 interval = 10000 * Math.round(interval / 10000);
1990 2014 // set new interval, if it's changed
1991 2015 if (interval != this.autosave_interval) {
1992 2016 this.set_autosave_interval(interval);
1993 2017 }
1994 2018 }
1995 2019 };
1996 2020
1997 2021 /**
1998 2022 * Failure callback for saving a notebook.
1999 2023 *
2000 2024 * @method save_notebook_error
2001 2025 * @param {jqXHR} xhr jQuery Ajax object
2002 2026 * @param {String} status Description of response status
2003 2027 * @param {String} error HTTP error message
2004 2028 */
2005 2029 Notebook.prototype.save_notebook_error = function (xhr, status, error) {
2006 2030 this.events.trigger('notebook_save_failed.Notebook', [xhr, status, error]);
2007 2031 };
2008 2032
2009 2033 /**
2010 2034 * Explicitly trust the output of this notebook.
2011 2035 *
2012 2036 * @method trust_notebook
2013 2037 */
2014 2038 Notebook.prototype.trust_notebook = function (extra_settings) {
2015 2039 var body = $("<div>").append($("<p>")
2016 2040 .text("A trusted IPython notebook may execute hidden malicious code ")
2017 2041 .append($("<strong>")
2018 2042 .append(
2019 2043 $("<em>").text("when you open it")
2020 2044 )
2021 2045 ).append(".").append(
2022 2046 " Selecting trust will immediately reload this notebook in a trusted state."
2023 2047 ).append(
2024 2048 " For more information, see the "
2025 2049 ).append($("<a>").attr("href", "http://ipython.org/ipython-doc/2/notebook/security.html")
2026 2050 .text("IPython security documentation")
2027 2051 ).append(".")
2028 2052 );
2029 2053
2030 2054 var nb = this;
2031 2055 dialog.modal({
2032 2056 notebook: this,
2033 2057 keyboard_manager: this.keyboard_manager,
2034 2058 title: "Trust this notebook?",
2035 2059 body: body,
2036 2060
2037 2061 buttons: {
2038 2062 Cancel : {},
2039 2063 Trust : {
2040 2064 class : "btn-danger",
2041 2065 click : function () {
2042 2066 var cells = nb.get_cells();
2043 2067 for (var i = 0; i < cells.length; i++) {
2044 2068 var cell = cells[i];
2045 2069 if (cell.cell_type == 'code') {
2046 2070 cell.output_area.trusted = true;
2047 2071 }
2048 2072 }
2049 2073 this.events.on('notebook_saved.Notebook', function () {
2050 2074 window.location.reload();
2051 2075 });
2052 2076 nb.save_notebook();
2053 2077 }
2054 2078 }
2055 2079 }
2056 2080 });
2057 2081 };
2058 2082
2059 2083 Notebook.prototype.new_notebook = function(){
2060 2084 var path = this.notebook_path;
2061 2085 var base_url = this.base_url;
2062 2086 var settings = {
2063 2087 processData : false,
2064 2088 cache : false,
2065 2089 type : "POST",
2066 2090 dataType : "json",
2067 2091 async : false,
2068 2092 success : function (data, status, xhr){
2069 2093 var notebook_name = data.name;
2070 2094 window.open(
2071 2095 utils.url_join_encode(
2072 2096 base_url,
2073 2097 'notebooks',
2074 2098 path,
2075 2099 notebook_name
2076 2100 ),
2077 2101 '_blank'
2078 2102 );
2079 2103 },
2080 2104 error : utils.log_ajax_error,
2081 2105 };
2082 2106 var url = utils.url_join_encode(
2083 2107 base_url,
2084 2108 'api/contents',
2085 2109 path
2086 2110 );
2087 2111 $.ajax(url,settings);
2088 2112 };
2089 2113
2090 2114
2091 2115 Notebook.prototype.copy_notebook = function(){
2092 2116 var path = this.notebook_path;
2093 2117 var base_url = this.base_url;
2094 2118 var settings = {
2095 2119 processData : false,
2096 2120 cache : false,
2097 2121 type : "POST",
2098 2122 dataType : "json",
2099 2123 data : JSON.stringify({copy_from : this.notebook_name}),
2100 2124 async : false,
2101 2125 success : function (data, status, xhr) {
2102 2126 window.open(utils.url_join_encode(
2103 2127 base_url,
2104 2128 'notebooks',
2105 2129 data.path,
2106 2130 data.name
2107 2131 ), '_blank');
2108 2132 },
2109 2133 error : utils.log_ajax_error,
2110 2134 };
2111 2135 var url = utils.url_join_encode(
2112 2136 base_url,
2113 2137 'api/contents',
2114 2138 path
2115 2139 );
2116 2140 $.ajax(url,settings);
2117 2141 };
2118 2142
2119 2143 Notebook.prototype.rename = function (nbname) {
2120 2144 var that = this;
2121 2145 if (!nbname.match(/\.ipynb$/)) {
2122 2146 nbname = nbname + ".ipynb";
2123 2147 }
2124 2148 var data = {name: nbname};
2125 2149 var settings = {
2126 2150 processData : false,
2127 2151 cache : false,
2128 2152 type : "PATCH",
2129 2153 data : JSON.stringify(data),
2130 2154 dataType: "json",
2131 2155 headers : {'Content-Type': 'application/json'},
2132 2156 success : $.proxy(that.rename_success, this),
2133 2157 error : $.proxy(that.rename_error, this)
2134 2158 };
2135 2159 this.events.trigger('rename_notebook.Notebook', data);
2136 2160 var url = utils.url_join_encode(
2137 2161 this.base_url,
2138 2162 'api/contents',
2139 2163 this.notebook_path,
2140 2164 this.notebook_name
2141 2165 );
2142 2166 $.ajax(url, settings);
2143 2167 };
2144 2168
2145 2169 Notebook.prototype.delete = function () {
2146 2170 var that = this;
2147 2171 var settings = {
2148 2172 processData : false,
2149 2173 cache : false,
2150 2174 type : "DELETE",
2151 2175 dataType: "json",
2152 2176 error : utils.log_ajax_error,
2153 2177 };
2154 2178 var url = utils.url_join_encode(
2155 2179 this.base_url,
2156 2180 'api/contents',
2157 2181 this.notebook_path,
2158 2182 this.notebook_name
2159 2183 );
2160 2184 $.ajax(url, settings);
2161 2185 };
2162 2186
2163 2187
2164 2188 Notebook.prototype.rename_success = function (json, status, xhr) {
2165 2189 var name = this.notebook_name = json.name;
2166 2190 var path = json.path;
2167 2191 this.session.rename_notebook(name, path);
2168 2192 this.events.trigger('notebook_renamed.Notebook', json);
2169 2193 };
2170 2194
2171 2195 Notebook.prototype.rename_error = function (xhr, status, error) {
2172 2196 var that = this;
2173 2197 var dialog_body = $('<div/>').append(
2174 2198 $("<p/>").text('This notebook name already exists.')
2175 2199 );
2176 2200 this.events.trigger('notebook_rename_failed.Notebook', [xhr, status, error]);
2177 2201 dialog.modal({
2178 2202 notebook: this,
2179 2203 keyboard_manager: this.keyboard_manager,
2180 2204 title: "Notebook Rename Error!",
2181 2205 body: dialog_body,
2182 2206 buttons : {
2183 2207 "Cancel": {},
2184 2208 "OK": {
2185 2209 class: "btn-primary",
2186 2210 click: function () {
2187 2211 this.save_widget.rename_notebook({notebook:that});
2188 2212 }}
2189 2213 },
2190 2214 open : function (event, ui) {
2191 2215 var that = $(this);
2192 2216 // Upon ENTER, click the OK button.
2193 2217 that.find('input[type="text"]').keydown(function (event, ui) {
2194 2218 if (event.which === this.keyboard.keycodes.enter) {
2195 2219 that.find('.btn-primary').first().click();
2196 2220 }
2197 2221 });
2198 2222 that.find('input[type="text"]').focus();
2199 2223 }
2200 2224 });
2201 2225 };
2202 2226
2203 2227 /**
2204 2228 * Request a notebook's data from the server.
2205 2229 *
2206 2230 * @method load_notebook
2207 2231 * @param {String} notebook_name and path A notebook to load
2208 2232 */
2209 2233 Notebook.prototype.load_notebook = function (notebook_name, notebook_path) {
2210 2234 var that = this;
2211 2235 this.notebook_name = notebook_name;
2212 2236 this.notebook_path = notebook_path;
2213 2237 // We do the call with settings so we can set cache to false.
2214 2238 var settings = {
2215 2239 processData : false,
2216 2240 cache : false,
2217 2241 type : "GET",
2218 2242 dataType : "json",
2219 2243 success : $.proxy(this.load_notebook_success,this),
2220 2244 error : $.proxy(this.load_notebook_error,this),
2221 2245 };
2222 2246 this.events.trigger('notebook_loading.Notebook');
2223 2247 var url = utils.url_join_encode(
2224 2248 this.base_url,
2225 2249 'api/contents',
2226 2250 this.notebook_path,
2227 2251 this.notebook_name
2228 2252 );
2229 2253 $.ajax(url, settings);
2230 2254 };
2231 2255
2232 2256 /**
2233 2257 * Success callback for loading a notebook from the server.
2234 2258 *
2235 2259 * Load notebook data from the JSON response.
2236 2260 *
2237 2261 * @method load_notebook_success
2238 2262 * @param {Object} data JSON representation of a notebook
2239 2263 * @param {String} status Description of response status
2240 2264 * @param {jqXHR} xhr jQuery Ajax object
2241 2265 */
2242 2266 Notebook.prototype.load_notebook_success = function (data, status, xhr) {
2243 2267 this.fromJSON(data);
2244 2268 if (this.ncells() === 0) {
2245 2269 this.insert_cell_below('code');
2246 2270 this.edit_mode(0);
2247 2271 } else {
2248 2272 this.select(0);
2249 2273 this.handle_command_mode(this.get_cell(0));
2250 2274 }
2251 2275 this.set_dirty(false);
2252 2276 this.scroll_to_top();
2253 2277 if (data.orig_nbformat !== undefined && data.nbformat !== data.orig_nbformat) {
2254 2278 var msg = "This notebook has been converted from an older " +
2255 2279 "notebook format (v"+data.orig_nbformat+") to the current notebook " +
2256 2280 "format (v"+data.nbformat+"). The next time you save this notebook, the " +
2257 2281 "newer notebook format will be used and older versions of IPython " +
2258 2282 "may not be able to read it. To keep the older version, close the " +
2259 2283 "notebook without saving it.";
2260 2284 dialog.modal({
2261 2285 notebook: this,
2262 2286 keyboard_manager: this.keyboard_manager,
2263 2287 title : "Notebook converted",
2264 2288 body : msg,
2265 2289 buttons : {
2266 2290 OK : {
2267 2291 class : "btn-primary"
2268 2292 }
2269 2293 }
2270 2294 });
2271 2295 } else if (data.orig_nbformat_minor !== undefined && data.nbformat_minor !== data.orig_nbformat_minor) {
2272 2296 var that = this;
2273 2297 var orig_vs = 'v' + data.nbformat + '.' + data.orig_nbformat_minor;
2274 2298 var this_vs = 'v' + data.nbformat + '.' + this.nbformat_minor;
2275 2299 var msg = "This notebook is version " + orig_vs + ", but we only fully support up to " +
2276 2300 this_vs + ". You can still work with this notebook, but some features " +
2277 2301 "introduced in later notebook versions may not be available.";
2278 2302
2279 2303 dialog.modal({
2280 2304 notebook: this,
2281 2305 keyboard_manager: this.keyboard_manager,
2282 2306 title : "Newer Notebook",
2283 2307 body : msg,
2284 2308 buttons : {
2285 2309 OK : {
2286 2310 class : "btn-danger"
2287 2311 }
2288 2312 }
2289 2313 });
2290 2314
2291 2315 }
2292 2316
2293 2317 // Create the session after the notebook is completely loaded to prevent
2294 2318 // code execution upon loading, which is a security risk.
2295 2319 if (this.session === null) {
2296 2320 var kernelspec = this.metadata.kernelspec || {};
2297 2321 var kernel_name = kernelspec.name || this.default_kernel_name;
2298 2322
2299 2323 this.start_session(kernel_name);
2300 2324 }
2301 2325 // load our checkpoint list
2302 2326 this.list_checkpoints();
2303 2327
2304 2328 // load toolbar state
2305 2329 if (this.metadata.celltoolbar) {
2306 2330 celltoolbar.CellToolbar.global_show();
2307 2331 celltoolbar.CellToolbar.activate_preset(this.metadata.celltoolbar);
2308 2332 } else {
2309 2333 celltoolbar.CellToolbar.global_hide();
2310 2334 }
2311 2335
2312 2336 // now that we're fully loaded, it is safe to restore save functionality
2313 2337 delete(this.save_notebook);
2314 2338 this.events.trigger('notebook_loaded.Notebook');
2315 2339 };
2316 2340
2317 2341 /**
2318 2342 * Failure callback for loading a notebook from the server.
2319 2343 *
2320 2344 * @method load_notebook_error
2321 2345 * @param {jqXHR} xhr jQuery Ajax object
2322 2346 * @param {String} status Description of response status
2323 2347 * @param {String} error HTTP error message
2324 2348 */
2325 2349 Notebook.prototype.load_notebook_error = function (xhr, status, error) {
2326 2350 this.events.trigger('notebook_load_failed.Notebook', [xhr, status, error]);
2327 2351 utils.log_ajax_error(xhr, status, error);
2328 2352 var msg;
2329 2353 if (xhr.status === 400) {
2330 2354 msg = escape(utils.ajax_error_msg(xhr));
2331 2355 } else if (xhr.status === 500) {
2332 2356 msg = "An unknown error occurred while loading this notebook. " +
2333 2357 "This version can load notebook formats " +
2334 2358 "v" + this.nbformat + " or earlier. See the server log for details.";
2335 2359 }
2336 2360 dialog.modal({
2337 2361 notebook: this,
2338 2362 keyboard_manager: this.keyboard_manager,
2339 2363 title: "Error loading notebook",
2340 2364 body : msg,
2341 2365 buttons : {
2342 2366 "OK": {}
2343 2367 }
2344 2368 });
2345 2369 };
2346 2370
2347 2371 /********************* checkpoint-related *********************/
2348 2372
2349 2373 /**
2350 2374 * Save the notebook then immediately create a checkpoint.
2351 2375 *
2352 2376 * @method save_checkpoint
2353 2377 */
2354 2378 Notebook.prototype.save_checkpoint = function () {
2355 2379 this._checkpoint_after_save = true;
2356 2380 this.save_notebook();
2357 2381 };
2358 2382
2359 2383 /**
2360 2384 * Add a checkpoint for this notebook.
2361 2385 * for use as a callback from checkpoint creation.
2362 2386 *
2363 2387 * @method add_checkpoint
2364 2388 */
2365 2389 Notebook.prototype.add_checkpoint = function (checkpoint) {
2366 2390 var found = false;
2367 2391 for (var i = 0; i < this.checkpoints.length; i++) {
2368 2392 var existing = this.checkpoints[i];
2369 2393 if (existing.id == checkpoint.id) {
2370 2394 found = true;
2371 2395 this.checkpoints[i] = checkpoint;
2372 2396 break;
2373 2397 }
2374 2398 }
2375 2399 if (!found) {
2376 2400 this.checkpoints.push(checkpoint);
2377 2401 }
2378 2402 this.last_checkpoint = this.checkpoints[this.checkpoints.length - 1];
2379 2403 };
2380 2404
2381 2405 /**
2382 2406 * List checkpoints for this notebook.
2383 2407 *
2384 2408 * @method list_checkpoints
2385 2409 */
2386 2410 Notebook.prototype.list_checkpoints = function () {
2387 2411 var url = utils.url_join_encode(
2388 2412 this.base_url,
2389 2413 'api/contents',
2390 2414 this.notebook_path,
2391 2415 this.notebook_name,
2392 2416 'checkpoints'
2393 2417 );
2394 2418 $.get(url).done(
2395 2419 $.proxy(this.list_checkpoints_success, this)
2396 2420 ).fail(
2397 2421 $.proxy(this.list_checkpoints_error, this)
2398 2422 );
2399 2423 };
2400 2424
2401 2425 /**
2402 2426 * Success callback for listing checkpoints.
2403 2427 *
2404 2428 * @method list_checkpoint_success
2405 2429 * @param {Object} data JSON representation of a checkpoint
2406 2430 * @param {String} status Description of response status
2407 2431 * @param {jqXHR} xhr jQuery Ajax object
2408 2432 */
2409 2433 Notebook.prototype.list_checkpoints_success = function (data, status, xhr) {
2410 2434 data = $.parseJSON(data);
2411 2435 this.checkpoints = data;
2412 2436 if (data.length) {
2413 2437 this.last_checkpoint = data[data.length - 1];
2414 2438 } else {
2415 2439 this.last_checkpoint = null;
2416 2440 }
2417 2441 this.events.trigger('checkpoints_listed.Notebook', [data]);
2418 2442 };
2419 2443
2420 2444 /**
2421 2445 * Failure callback for listing a checkpoint.
2422 2446 *
2423 2447 * @method list_checkpoint_error
2424 2448 * @param {jqXHR} xhr jQuery Ajax object
2425 2449 * @param {String} status Description of response status
2426 2450 * @param {String} error_msg HTTP error message
2427 2451 */
2428 2452 Notebook.prototype.list_checkpoints_error = function (xhr, status, error_msg) {
2429 2453 this.events.trigger('list_checkpoints_failed.Notebook');
2430 2454 };
2431 2455
2432 2456 /**
2433 2457 * Create a checkpoint of this notebook on the server from the most recent save.
2434 2458 *
2435 2459 * @method create_checkpoint
2436 2460 */
2437 2461 Notebook.prototype.create_checkpoint = function () {
2438 2462 var url = utils.url_join_encode(
2439 2463 this.base_url,
2440 2464 'api/contents',
2441 2465 this.notebook_path,
2442 2466 this.notebook_name,
2443 2467 'checkpoints'
2444 2468 );
2445 2469 $.post(url).done(
2446 2470 $.proxy(this.create_checkpoint_success, this)
2447 2471 ).fail(
2448 2472 $.proxy(this.create_checkpoint_error, this)
2449 2473 );
2450 2474 };
2451 2475
2452 2476 /**
2453 2477 * Success callback for creating a checkpoint.
2454 2478 *
2455 2479 * @method create_checkpoint_success
2456 2480 * @param {Object} data JSON representation of a checkpoint
2457 2481 * @param {String} status Description of response status
2458 2482 * @param {jqXHR} xhr jQuery Ajax object
2459 2483 */
2460 2484 Notebook.prototype.create_checkpoint_success = function (data, status, xhr) {
2461 2485 data = $.parseJSON(data);
2462 2486 this.add_checkpoint(data);
2463 2487 this.events.trigger('checkpoint_created.Notebook', data);
2464 2488 };
2465 2489
2466 2490 /**
2467 2491 * Failure callback for creating a checkpoint.
2468 2492 *
2469 2493 * @method create_checkpoint_error
2470 2494 * @param {jqXHR} xhr jQuery Ajax object
2471 2495 * @param {String} status Description of response status
2472 2496 * @param {String} error_msg HTTP error message
2473 2497 */
2474 2498 Notebook.prototype.create_checkpoint_error = function (xhr, status, error_msg) {
2475 2499 this.events.trigger('checkpoint_failed.Notebook');
2476 2500 };
2477 2501
2478 2502 Notebook.prototype.restore_checkpoint_dialog = function (checkpoint) {
2479 2503 var that = this;
2480 2504 checkpoint = checkpoint || this.last_checkpoint;
2481 2505 if ( ! checkpoint ) {
2482 2506 console.log("restore dialog, but no checkpoint to restore to!");
2483 2507 return;
2484 2508 }
2485 2509 var body = $('<div/>').append(
2486 2510 $('<p/>').addClass("p-space").text(
2487 2511 "Are you sure you want to revert the notebook to " +
2488 2512 "the latest checkpoint?"
2489 2513 ).append(
2490 2514 $("<strong/>").text(
2491 2515 " This cannot be undone."
2492 2516 )
2493 2517 )
2494 2518 ).append(
2495 2519 $('<p/>').addClass("p-space").text("The checkpoint was last updated at:")
2496 2520 ).append(
2497 2521 $('<p/>').addClass("p-space").text(
2498 2522 Date(checkpoint.last_modified)
2499 2523 ).css("text-align", "center")
2500 2524 );
2501 2525
2502 2526 dialog.modal({
2503 2527 notebook: this,
2504 2528 keyboard_manager: this.keyboard_manager,
2505 2529 title : "Revert notebook to checkpoint",
2506 2530 body : body,
2507 2531 buttons : {
2508 2532 Revert : {
2509 2533 class : "btn-danger",
2510 2534 click : function () {
2511 2535 that.restore_checkpoint(checkpoint.id);
2512 2536 }
2513 2537 },
2514 2538 Cancel : {}
2515 2539 }
2516 2540 });
2517 2541 };
2518 2542
2519 2543 /**
2520 2544 * Restore the notebook to a checkpoint state.
2521 2545 *
2522 2546 * @method restore_checkpoint
2523 2547 * @param {String} checkpoint ID
2524 2548 */
2525 2549 Notebook.prototype.restore_checkpoint = function (checkpoint) {
2526 2550 this.events.trigger('notebook_restoring.Notebook', checkpoint);
2527 2551 var url = utils.url_join_encode(
2528 2552 this.base_url,
2529 2553 'api/contents',
2530 2554 this.notebook_path,
2531 2555 this.notebook_name,
2532 2556 'checkpoints',
2533 2557 checkpoint
2534 2558 );
2535 2559 $.post(url).done(
2536 2560 $.proxy(this.restore_checkpoint_success, this)
2537 2561 ).fail(
2538 2562 $.proxy(this.restore_checkpoint_error, this)
2539 2563 );
2540 2564 };
2541 2565
2542 2566 /**
2543 2567 * Success callback for restoring a notebook to a checkpoint.
2544 2568 *
2545 2569 * @method restore_checkpoint_success
2546 2570 * @param {Object} data (ignored, should be empty)
2547 2571 * @param {String} status Description of response status
2548 2572 * @param {jqXHR} xhr jQuery Ajax object
2549 2573 */
2550 2574 Notebook.prototype.restore_checkpoint_success = function (data, status, xhr) {
2551 2575 this.events.trigger('checkpoint_restored.Notebook');
2552 2576 this.load_notebook(this.notebook_name, this.notebook_path);
2553 2577 };
2554 2578
2555 2579 /**
2556 2580 * Failure callback for restoring a notebook to a checkpoint.
2557 2581 *
2558 2582 * @method restore_checkpoint_error
2559 2583 * @param {jqXHR} xhr jQuery Ajax object
2560 2584 * @param {String} status Description of response status
2561 2585 * @param {String} error_msg HTTP error message
2562 2586 */
2563 2587 Notebook.prototype.restore_checkpoint_error = function (xhr, status, error_msg) {
2564 2588 this.events.trigger('checkpoint_restore_failed.Notebook');
2565 2589 };
2566 2590
2567 2591 /**
2568 2592 * Delete a notebook checkpoint.
2569 2593 *
2570 2594 * @method delete_checkpoint
2571 2595 * @param {String} checkpoint ID
2572 2596 */
2573 2597 Notebook.prototype.delete_checkpoint = function (checkpoint) {
2574 2598 this.events.trigger('notebook_restoring.Notebook', checkpoint);
2575 2599 var url = utils.url_join_encode(
2576 2600 this.base_url,
2577 2601 'api/contents',
2578 2602 this.notebook_path,
2579 2603 this.notebook_name,
2580 2604 'checkpoints',
2581 2605 checkpoint
2582 2606 );
2583 2607 $.ajax(url, {
2584 2608 type: 'DELETE',
2585 2609 success: $.proxy(this.delete_checkpoint_success, this),
2586 2610 error: $.proxy(this.delete_checkpoint_error, this)
2587 2611 });
2588 2612 };
2589 2613
2590 2614 /**
2591 2615 * Success callback for deleting a notebook checkpoint
2592 2616 *
2593 2617 * @method delete_checkpoint_success
2594 2618 * @param {Object} data (ignored, should be empty)
2595 2619 * @param {String} status Description of response status
2596 2620 * @param {jqXHR} xhr jQuery Ajax object
2597 2621 */
2598 2622 Notebook.prototype.delete_checkpoint_success = function (data, status, xhr) {
2599 2623 this.events.trigger('checkpoint_deleted.Notebook', data);
2600 2624 this.load_notebook(this.notebook_name, this.notebook_path);
2601 2625 };
2602 2626
2603 2627 /**
2604 2628 * Failure callback for deleting a notebook checkpoint.
2605 2629 *
2606 2630 * @method delete_checkpoint_error
2607 2631 * @param {jqXHR} xhr jQuery Ajax object
2608 2632 * @param {String} status Description of response status
2609 2633 * @param {String} error HTTP error message
2610 2634 */
2611 2635 Notebook.prototype.delete_checkpoint_error = function (xhr, status, error) {
2612 2636 this.events.trigger('checkpoint_delete_failed.Notebook', [xhr, status, error]);
2613 2637 };
2614 2638
2615 2639
2616 2640 // For backwards compatability.
2617 2641 IPython.Notebook = Notebook;
2618 2642
2619 2643 return {'Notebook': Notebook};
2620 2644 });
@@ -1,449 +1,450
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'base/js/namespace',
6 'base/js/utils',
6 7 'jquery',
7 8 'notebook/js/cell',
8 9 'base/js/security',
9 10 'notebook/js/mathjaxutils',
10 11 'notebook/js/celltoolbar',
11 12 'components/marked/lib/marked',
12 ], function(IPython, $, cell, security, mathjaxutils, celltoolbar, marked) {
13 ], function(IPython, utils, $, cell, security, mathjaxutils, celltoolbar, marked) {
13 14 "use strict";
14 15 var Cell = cell.Cell;
15 16
16 17 var TextCell = function (options) {
17 18 // Constructor
18 19 //
19 20 // Construct a new TextCell, codemirror mode is by default 'htmlmixed',
20 21 // and cell type is 'text' cell start as not redered.
21 22 //
22 23 // Parameters:
23 24 // options: dictionary
24 25 // Dictionary of keyword arguments.
25 26 // events: $(Events) instance
26 27 // config: dictionary
27 28 // keyboard_manager: KeyboardManager instance
28 29 // notebook: Notebook instance
29 30 options = options || {};
30 31
31 32 // in all TextCell/Cell subclasses
32 33 // do not assign most of members here, just pass it down
33 34 // in the options dict potentially overwriting what you wish.
34 35 // they will be assigned in the base class.
35 36 this.notebook = options.notebook;
36 37 this.events = options.events;
37 38 this.config = options.config;
38 39
39 40 // we cannot put this as a class key as it has handle to "this".
40 41 var cm_overwrite_options = {
41 42 onKeyEvent: $.proxy(this.handle_keyevent,this)
42 43 };
43 var config = this.mergeopt(TextCell, this.config, {cm_config:cm_overwrite_options});
44 var config = utils.mergeopt(TextCell, this.config, {cm_config:cm_overwrite_options});
44 45 Cell.apply(this, [{
45 46 config: config,
46 47 keyboard_manager: options.keyboard_manager,
47 48 events: this.events}]);
48 49
49 50 this.cell_type = this.cell_type || 'text';
50 51 mathjaxutils = mathjaxutils;
51 52 this.rendered = false;
52 53 };
53 54
54 55 TextCell.prototype = new Cell();
55 56
56 57 TextCell.options_default = {
57 58 cm_config : {
58 59 extraKeys: {"Tab": "indentMore","Shift-Tab" : "indentLess"},
59 60 mode: 'htmlmixed',
60 61 lineWrapping : true,
61 62 }
62 63 };
63 64
64 65
65 66 /**
66 67 * Create the DOM element of the TextCell
67 68 * @method create_element
68 69 * @private
69 70 */
70 71 TextCell.prototype.create_element = function () {
71 72 Cell.prototype.create_element.apply(this, arguments);
72 73
73 74 var cell = $("<div>").addClass('cell text_cell');
74 75 cell.attr('tabindex','2');
75 76
76 77 var prompt = $('<div/>').addClass('prompt input_prompt');
77 78 cell.append(prompt);
78 79 var inner_cell = $('<div/>').addClass('inner_cell');
79 80 this.celltoolbar = new celltoolbar.CellToolbar({
80 81 cell: this,
81 82 notebook: this.notebook});
82 83 inner_cell.append(this.celltoolbar.element);
83 84 var input_area = $('<div/>').addClass('input_area');
84 85 this.code_mirror = new CodeMirror(input_area.get(0), this.cm_config);
85 86 // The tabindex=-1 makes this div focusable.
86 87 var render_area = $('<div/>').addClass('text_cell_render rendered_html')
87 88 .attr('tabindex','-1');
88 89 inner_cell.append(input_area).append(render_area);
89 90 cell.append(inner_cell);
90 91 this.element = cell;
91 92 };
92 93
93 94
94 95 /**
95 96 * Bind the DOM evet to cell actions
96 97 * Need to be called after TextCell.create_element
97 98 * @private
98 99 * @method bind_event
99 100 */
100 101 TextCell.prototype.bind_events = function () {
101 102 Cell.prototype.bind_events.apply(this);
102 103 var that = this;
103 104
104 105 this.element.dblclick(function () {
105 106 if (that.selected === false) {
106 107 this.events.trigger('select.Cell', {'cell':that});
107 108 }
108 109 var cont = that.unrender();
109 110 if (cont) {
110 111 that.focus_editor();
111 112 }
112 113 });
113 114 };
114 115
115 116 // Cell level actions
116 117
117 118 TextCell.prototype.select = function () {
118 119 var cont = Cell.prototype.select.apply(this);
119 120 if (cont) {
120 121 if (this.mode === 'edit') {
121 122 this.code_mirror.refresh();
122 123 }
123 124 }
124 125 return cont;
125 126 };
126 127
127 128 TextCell.prototype.unrender = function () {
128 129 if (this.read_only) return;
129 130 var cont = Cell.prototype.unrender.apply(this);
130 131 if (cont) {
131 132 var text_cell = this.element;
132 133 var output = text_cell.find("div.text_cell_render");
133 134 output.hide();
134 135 text_cell.find('div.input_area').show();
135 136 if (this.get_text() === this.placeholder) {
136 137 this.set_text('');
137 138 }
138 139 this.refresh();
139 140 }
140 141 return cont;
141 142 };
142 143
143 144 TextCell.prototype.execute = function () {
144 145 this.render();
145 146 };
146 147
147 148 /**
148 149 * setter: {{#crossLink "TextCell/set_text"}}{{/crossLink}}
149 150 * @method get_text
150 151 * @retrun {string} CodeMirror current text value
151 152 */
152 153 TextCell.prototype.get_text = function() {
153 154 return this.code_mirror.getValue();
154 155 };
155 156
156 157 /**
157 158 * @param {string} text - Codemiror text value
158 159 * @see TextCell#get_text
159 160 * @method set_text
160 161 * */
161 162 TextCell.prototype.set_text = function(text) {
162 163 this.code_mirror.setValue(text);
163 164 this.unrender();
164 165 this.code_mirror.refresh();
165 166 };
166 167
167 168 /**
168 169 * setter :{{#crossLink "TextCell/set_rendered"}}{{/crossLink}}
169 170 * @method get_rendered
170 171 * */
171 172 TextCell.prototype.get_rendered = function() {
172 173 return this.element.find('div.text_cell_render').html();
173 174 };
174 175
175 176 /**
176 177 * @method set_rendered
177 178 */
178 179 TextCell.prototype.set_rendered = function(text) {
179 180 this.element.find('div.text_cell_render').html(text);
180 181 };
181 182
182 183
183 184 /**
184 185 * Create Text cell from JSON
185 186 * @param {json} data - JSON serialized text-cell
186 187 * @method fromJSON
187 188 */
188 189 TextCell.prototype.fromJSON = function (data) {
189 190 Cell.prototype.fromJSON.apply(this, arguments);
190 191 if (data.cell_type === this.cell_type) {
191 192 if (data.source !== undefined) {
192 193 this.set_text(data.source);
193 194 // make this value the starting point, so that we can only undo
194 195 // to this state, instead of a blank cell
195 196 this.code_mirror.clearHistory();
196 197 // TODO: This HTML needs to be treated as potentially dangerous
197 198 // user input and should be handled before set_rendered.
198 199 this.set_rendered(data.rendered || '');
199 200 this.rendered = false;
200 201 this.render();
201 202 }
202 203 }
203 204 };
204 205
205 206 /** Generate JSON from cell
206 207 * @return {object} cell data serialised to json
207 208 */
208 209 TextCell.prototype.toJSON = function () {
209 210 var data = Cell.prototype.toJSON.apply(this);
210 211 data.source = this.get_text();
211 212 if (data.source == this.placeholder) {
212 213 data.source = "";
213 214 }
214 215 return data;
215 216 };
216 217
217 218
218 219 var MarkdownCell = function (options) {
219 220 // Constructor
220 221 //
221 222 // Parameters:
222 223 // options: dictionary
223 224 // Dictionary of keyword arguments.
224 225 // events: $(Events) instance
225 226 // config: dictionary
226 227 // keyboard_manager: KeyboardManager instance
227 228 // notebook: Notebook instance
228 229 options = options || {};
229 var config = this.mergeopt(MarkdownCell, options.config);
230 var config = utils.mergeopt(MarkdownCell, options.config);
230 231 TextCell.apply(this, [$.extend({}, options, {config: config})]);
231 232
232 233 this.cell_type = 'markdown';
233 234 };
234 235
235 236 MarkdownCell.options_default = {
236 237 cm_config: {
237 238 mode: 'ipythongfm'
238 239 },
239 240 placeholder: "Type *Markdown* and LaTeX: $\\alpha^2$"
240 241 };
241 242
242 243 MarkdownCell.prototype = new TextCell();
243 244
244 245 /**
245 246 * @method render
246 247 */
247 248 MarkdownCell.prototype.render = function () {
248 249 var cont = TextCell.prototype.render.apply(this);
249 250 if (cont) {
250 251 var text = this.get_text();
251 252 var math = null;
252 253 if (text === "") { text = this.placeholder; }
253 254 var text_and_math = mathjaxutils.remove_math(text);
254 255 text = text_and_math[0];
255 256 math = text_and_math[1];
256 257 var html = marked.parser(marked.lexer(text));
257 258 html = mathjaxutils.replace_math(html, math);
258 259 html = security.sanitize_html(html);
259 260 html = $($.parseHTML(html));
260 261 // links in markdown cells should open in new tabs
261 262 html.find("a[href]").not('[href^="#"]').attr("target", "_blank");
262 263 this.set_rendered(html);
263 264 this.element.find('div.input_area').hide();
264 265 this.element.find("div.text_cell_render").show();
265 266 this.typeset();
266 267 }
267 268 return cont;
268 269 };
269 270
270 271
271 272 var RawCell = function (options) {
272 273 // Constructor
273 274 //
274 275 // Parameters:
275 276 // options: dictionary
276 277 // Dictionary of keyword arguments.
277 278 // events: $(Events) instance
278 279 // config: dictionary
279 280 // keyboard_manager: KeyboardManager instance
280 281 // notebook: Notebook instance
281 282 options = options || {};
282 var config = this.mergeopt(RawCell, options.config);
283 var config = utils.mergeopt(RawCell, options.config);
283 284 TextCell.apply(this, [$.extend({}, options, {config: config})]);
284 285
285 286 // RawCell should always hide its rendered div
286 287 this.element.find('div.text_cell_render').hide();
287 288 this.cell_type = 'raw';
288 289 };
289 290
290 291 RawCell.options_default = {
291 292 placeholder : "Write raw LaTeX or other formats here, for use with nbconvert. " +
292 293 "It will not be rendered in the notebook. " +
293 294 "When passing through nbconvert, a Raw Cell's content is added to the output unmodified."
294 295 };
295 296
296 297 RawCell.prototype = new TextCell();
297 298
298 299 /** @method bind_events **/
299 300 RawCell.prototype.bind_events = function () {
300 301 TextCell.prototype.bind_events.apply(this);
301 302 var that = this;
302 303 this.element.focusout(function() {
303 304 that.auto_highlight();
304 305 that.render();
305 306 });
306 307
307 308 this.code_mirror.on('focus', function() { that.unrender(); });
308 309 };
309 310
310 311 /**
311 312 * Trigger autodetection of highlight scheme for current cell
312 313 * @method auto_highlight
313 314 */
314 315 RawCell.prototype.auto_highlight = function () {
315 316 this._auto_highlight(this.config.raw_cell_highlight);
316 317 };
317 318
318 319 /** @method render **/
319 320 RawCell.prototype.render = function () {
320 321 var cont = TextCell.prototype.render.apply(this);
321 322 if (cont){
322 323 var text = this.get_text();
323 324 if (text === "") { text = this.placeholder; }
324 325 this.set_text(text);
325 326 this.element.removeClass('rendered');
326 327 }
327 328 return cont;
328 329 };
329 330
330 331
331 332 var HeadingCell = function (options) {
332 333 // Constructor
333 334 //
334 335 // Parameters:
335 336 // options: dictionary
336 337 // Dictionary of keyword arguments.
337 338 // events: $(Events) instance
338 339 // config: dictionary
339 340 // keyboard_manager: KeyboardManager instance
340 341 // notebook: Notebook instance
341 342 options = options || {};
342 var config = this.mergeopt(HeadingCell, options.config);
343 var config = utils.mergeopt(HeadingCell, options.config);
343 344 TextCell.apply(this, [$.extend({}, options, {config: config})]);
344 345
345 346 this.level = 1;
346 347 this.cell_type = 'heading';
347 348 };
348 349
349 350 HeadingCell.options_default = {
350 351 cm_config: {
351 352 theme: 'heading-1'
352 353 },
353 354 placeholder: "Type Heading Here"
354 355 };
355 356
356 357 HeadingCell.prototype = new TextCell();
357 358
358 359 /** @method fromJSON */
359 360 HeadingCell.prototype.fromJSON = function (data) {
360 361 if (data.level !== undefined){
361 362 this.level = data.level;
362 363 }
363 364 TextCell.prototype.fromJSON.apply(this, arguments);
364 365 this.code_mirror.setOption("theme", "heading-"+this.level);
365 366 };
366 367
367 368
368 369 /** @method toJSON */
369 370 HeadingCell.prototype.toJSON = function () {
370 371 var data = TextCell.prototype.toJSON.apply(this);
371 372 data.level = this.get_level();
372 373 return data;
373 374 };
374 375
375 376 /**
376 377 * Change heading level of cell, and re-render
377 378 * @method set_level
378 379 */
379 380 HeadingCell.prototype.set_level = function (level) {
380 381 this.level = level;
381 382 this.code_mirror.setOption("theme", "heading-"+level);
382 383
383 384 if (this.rendered) {
384 385 this.rendered = false;
385 386 this.render();
386 387 }
387 388 };
388 389
389 390 /** The depth of header cell, based on html (h1 to h6)
390 391 * @method get_level
391 392 * @return {integer} level - for 1 to 6
392 393 */
393 394 HeadingCell.prototype.get_level = function () {
394 395 return this.level;
395 396 };
396 397
397 398
398 399 HeadingCell.prototype.get_rendered = function () {
399 400 var r = this.element.find("div.text_cell_render");
400 401 return r.children().first().html();
401 402 };
402 403
403 404 HeadingCell.prototype.render = function () {
404 405 var cont = TextCell.prototype.render.apply(this);
405 406 if (cont) {
406 407 var text = this.get_text();
407 408 var math = null;
408 409 // Markdown headings must be a single line
409 410 text = text.replace(/\n/g, ' ');
410 411 if (text === "") { text = this.placeholder; }
411 412 text = new Array(this.level + 1).join("#") + " " + text;
412 413 var text_and_math = mathjaxutils.remove_math(text);
413 414 text = text_and_math[0];
414 415 math = text_and_math[1];
415 416 var html = marked.parser(marked.lexer(text));
416 417 html = mathjaxutils.replace_math(html, math);
417 418 html = security.sanitize_html(html);
418 419 var h = $($.parseHTML(html));
419 420 // add id and linkback anchor
420 421 var hash = h.text().replace(/ /g, '-');
421 422 h.attr('id', hash);
422 423 h.append(
423 424 $('<a/>')
424 425 .addClass('anchor-link')
425 426 .attr('href', '#' + hash)
426 427 .text('ΒΆ')
427 428 );
428 429 this.set_rendered(h);
429 430 this.element.find('div.input_area').hide();
430 431 this.element.find("div.text_cell_render").show();
431 432 this.typeset();
432 433 }
433 434 return cont;
434 435 };
435 436
436 437 // Backwards compatability.
437 438 IPython.TextCell = TextCell;
438 439 IPython.MarkdownCell = MarkdownCell;
439 440 IPython.RawCell = RawCell;
440 441 IPython.HeadingCell = HeadingCell;
441 442
442 443 var textcell = {
443 444 'TextCell': TextCell,
444 445 'MarkdownCell': MarkdownCell,
445 446 'RawCell': RawCell,
446 447 'HeadingCell': HeadingCell,
447 448 };
448 449 return textcell;
449 450 });
@@ -1,42 +1,77
1 1
2 2 // Test
3 3 casper.notebook_test(function () {
4 4 var a = 'print("a")';
5 5 var index = this.append_cell(a);
6 6 this.execute_cell_then(index);
7 7
8 8 var b = 'print("b")';
9 9 index = this.append_cell(b);
10 10 this.execute_cell_then(index);
11 11
12 12 var c = 'print("c")';
13 13 index = this.append_cell(c);
14 14 this.execute_cell_then(index);
15
15
16 this.thenEvaluate(function() {
17 IPython.notebook.default_cell_type = 'code';
18 });
19
16 20 this.then(function () {
17 21 // Cell insertion
18 22 this.select_cell(2);
23 this.trigger_keydown('m'); // Make it markdown
19 24 this.trigger_keydown('a'); // Creates one cell
20 25 this.test.assertEquals(this.get_cell_text(2), '', 'a; New cell 2 text is empty');
21 this.test.assertEquals(this.get_cell(2).cell_type, 'code', 'a; inserts a code cell when on code cell');
26 this.test.assertEquals(this.get_cell(2).cell_type, 'code', 'a; inserts a code cell');
22 27 this.validate_notebook_state('a', 'command', 2);
23 28 this.trigger_keydown('b'); // Creates one cell
24 29 this.test.assertEquals(this.get_cell_text(2), '', 'b; Cell 2 text is still empty');
25 30 this.test.assertEquals(this.get_cell_text(3), '', 'b; New cell 3 text is empty');
26 this.test.assertEquals(this.get_cell(3).cell_type, 'code', 'b; inserts a code cell when on code cell');
31 this.test.assertEquals(this.get_cell(3).cell_type, 'code', 'b; inserts a code cell');
27 32 this.validate_notebook_state('b', 'command', 3);
28 33 });
34
35 this.thenEvaluate(function() {
36 IPython.notebook.default_cell_type = 'selected';
37 });
38
29 39 this.then(function () {
30 // Cell insertion
31 40 this.select_cell(2);
32 41 this.trigger_keydown('m'); // switch it to markdown for the next test
33 this.trigger_keydown('a'); // Creates one cell
34 this.test.assertEquals(this.get_cell_text(2), '', 'a; New cell 2 text is empty');
35 this.test.assertEquals(this.get_cell(2).cell_type, 'markdown', 'a; inserts a markdown cell when on markdown cell');
36 this.validate_notebook_state('a', 'command', 2);
37 this.trigger_keydown('b'); // Creates one cell
38 this.test.assertEquals(this.get_cell_text(2), '', 'b; Cell 2 text is still empty');
39 this.test.assertEquals(this.get_cell(3).cell_type, 'markdown', 'b; inserts a markdown cell when on markdown cell');
40 this.validate_notebook_state('b', 'command', 3);
42 this.test.assertEquals(this.get_cell(2).cell_type, 'markdown', 'test cell is markdown');
43 this.trigger_keydown('a'); // new cell above
44 this.test.assertEquals(this.get_cell(2).cell_type, 'markdown', 'a; inserts a markdown cell when markdown selected');
45 this.trigger_keydown('b'); // new cell below
46 this.test.assertEquals(this.get_cell(3).cell_type, 'markdown', 'b; inserts a markdown cell when markdown selected');
47 });
48
49 this.thenEvaluate(function() {
50 IPython.notebook.default_cell_type = 'above';
51 });
52
53 this.then(function () {
54 this.select_cell(2);
55 this.trigger_keydown('1'); // switch it to heading for the next test
56 this.test.assertEquals(this.get_cell(2).cell_type, 'heading', 'test cell is heading');
57 this.trigger_keydown('b'); // new cell below
58 this.test.assertEquals(this.get_cell(3).cell_type, 'heading', 'b; inserts a heading cell below heading cell');
59 this.trigger_keydown('a'); // new cell above
60 this.test.assertEquals(this.get_cell(3).cell_type, 'heading', 'a; inserts a heading cell below heading cell');
61 });
62
63 this.thenEvaluate(function() {
64 IPython.notebook.default_cell_type = 'below';
65 });
66
67 this.then(function () {
68 this.select_cell(2);
69 this.trigger_keydown('r'); // switch it to markdown for the next test
70 this.test.assertEquals(this.get_cell(2).cell_type, 'raw', 'test cell is raw');
71 this.trigger_keydown('a'); // new cell above
72 this.test.assertEquals(this.get_cell(2).cell_type, 'raw', 'a; inserts a raw cell above raw cell');
73 this.trigger_keydown('y'); // switch it to code for the next test
74 this.trigger_keydown('b'); // new cell below
75 this.test.assertEquals(this.get_cell(3).cell_type, 'raw', 'b; inserts a raw cell above raw cell');
41 76 });
42 77 });
General Comments 0
You need to be logged in to leave comments. Login now