##// END OF EJS Templates
move mergeopt to utils...
MinRK -
Show More
@@ -1,563 +1,570 b''
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 b''
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 b''
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,453 +1,454 b''
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 if (this.celltoolbar.ui_controls_list.length) {
141 142 this.celltoolbar.show();
142 143 }
143 144 return cont;
144 145 };
145 146
146 147 TextCell.prototype.execute = function () {
147 148 this.render();
148 149 };
149 150
150 151 /**
151 152 * setter: {{#crossLink "TextCell/set_text"}}{{/crossLink}}
152 153 * @method get_text
153 154 * @retrun {string} CodeMirror current text value
154 155 */
155 156 TextCell.prototype.get_text = function() {
156 157 return this.code_mirror.getValue();
157 158 };
158 159
159 160 /**
160 161 * @param {string} text - Codemiror text value
161 162 * @see TextCell#get_text
162 163 * @method set_text
163 164 * */
164 165 TextCell.prototype.set_text = function(text) {
165 166 this.code_mirror.setValue(text);
166 167 this.unrender();
167 168 this.code_mirror.refresh();
168 169 };
169 170
170 171 /**
171 172 * setter :{{#crossLink "TextCell/set_rendered"}}{{/crossLink}}
172 173 * @method get_rendered
173 174 * */
174 175 TextCell.prototype.get_rendered = function() {
175 176 return this.element.find('div.text_cell_render').html();
176 177 };
177 178
178 179 /**
179 180 * @method set_rendered
180 181 */
181 182 TextCell.prototype.set_rendered = function(text) {
182 183 this.element.find('div.text_cell_render').html(text);
183 184 this.celltoolbar.hide();
184 185 };
185 186
186 187
187 188 /**
188 189 * Create Text cell from JSON
189 190 * @param {json} data - JSON serialized text-cell
190 191 * @method fromJSON
191 192 */
192 193 TextCell.prototype.fromJSON = function (data) {
193 194 Cell.prototype.fromJSON.apply(this, arguments);
194 195 if (data.cell_type === this.cell_type) {
195 196 if (data.source !== undefined) {
196 197 this.set_text(data.source);
197 198 // make this value the starting point, so that we can only undo
198 199 // to this state, instead of a blank cell
199 200 this.code_mirror.clearHistory();
200 201 // TODO: This HTML needs to be treated as potentially dangerous
201 202 // user input and should be handled before set_rendered.
202 203 this.set_rendered(data.rendered || '');
203 204 this.rendered = false;
204 205 this.render();
205 206 }
206 207 }
207 208 };
208 209
209 210 /** Generate JSON from cell
210 211 * @return {object} cell data serialised to json
211 212 */
212 213 TextCell.prototype.toJSON = function () {
213 214 var data = Cell.prototype.toJSON.apply(this);
214 215 data.source = this.get_text();
215 216 if (data.source == this.placeholder) {
216 217 data.source = "";
217 218 }
218 219 return data;
219 220 };
220 221
221 222
222 223 var MarkdownCell = function (options) {
223 224 // Constructor
224 225 //
225 226 // Parameters:
226 227 // options: dictionary
227 228 // Dictionary of keyword arguments.
228 229 // events: $(Events) instance
229 230 // config: dictionary
230 231 // keyboard_manager: KeyboardManager instance
231 232 // notebook: Notebook instance
232 233 options = options || {};
233 var config = this.mergeopt(MarkdownCell, options.config);
234 var config = utils.mergeopt(MarkdownCell, options.config);
234 235 TextCell.apply(this, [$.extend({}, options, {config: config})]);
235 236
236 237 this.cell_type = 'markdown';
237 238 };
238 239
239 240 MarkdownCell.options_default = {
240 241 cm_config: {
241 242 mode: 'ipythongfm'
242 243 },
243 244 placeholder: "Type *Markdown* and LaTeX: $\\alpha^2$"
244 245 };
245 246
246 247 MarkdownCell.prototype = new TextCell();
247 248
248 249 /**
249 250 * @method render
250 251 */
251 252 MarkdownCell.prototype.render = function () {
252 253 var cont = TextCell.prototype.render.apply(this);
253 254 if (cont) {
254 255 var text = this.get_text();
255 256 var math = null;
256 257 if (text === "") { text = this.placeholder; }
257 258 var text_and_math = mathjaxutils.remove_math(text);
258 259 text = text_and_math[0];
259 260 math = text_and_math[1];
260 261 var html = marked.parser(marked.lexer(text));
261 262 html = mathjaxutils.replace_math(html, math);
262 263 html = security.sanitize_html(html);
263 264 html = $($.parseHTML(html));
264 265 // links in markdown cells should open in new tabs
265 266 html.find("a[href]").not('[href^="#"]').attr("target", "_blank");
266 267 this.set_rendered(html);
267 268 this.element.find('div.input_area').hide();
268 269 this.element.find("div.text_cell_render").show();
269 270 this.typeset();
270 271 }
271 272 return cont;
272 273 };
273 274
274 275
275 276 var RawCell = function (options) {
276 277 // Constructor
277 278 //
278 279 // Parameters:
279 280 // options: dictionary
280 281 // Dictionary of keyword arguments.
281 282 // events: $(Events) instance
282 283 // config: dictionary
283 284 // keyboard_manager: KeyboardManager instance
284 285 // notebook: Notebook instance
285 286 options = options || {};
286 var config = this.mergeopt(RawCell, options.config);
287 var config = utils.mergeopt(RawCell, options.config);
287 288 TextCell.apply(this, [$.extend({}, options, {config: config})]);
288 289
289 290 // RawCell should always hide its rendered div
290 291 this.element.find('div.text_cell_render').hide();
291 292 this.cell_type = 'raw';
292 293 };
293 294
294 295 RawCell.options_default = {
295 296 placeholder : "Write raw LaTeX or other formats here, for use with nbconvert. " +
296 297 "It will not be rendered in the notebook. " +
297 298 "When passing through nbconvert, a Raw Cell's content is added to the output unmodified."
298 299 };
299 300
300 301 RawCell.prototype = new TextCell();
301 302
302 303 /** @method bind_events **/
303 304 RawCell.prototype.bind_events = function () {
304 305 TextCell.prototype.bind_events.apply(this);
305 306 var that = this;
306 307 this.element.focusout(function() {
307 308 that.auto_highlight();
308 309 that.render();
309 310 });
310 311
311 312 this.code_mirror.on('focus', function() { that.unrender(); });
312 313 };
313 314
314 315 /**
315 316 * Trigger autodetection of highlight scheme for current cell
316 317 * @method auto_highlight
317 318 */
318 319 RawCell.prototype.auto_highlight = function () {
319 320 this._auto_highlight(this.config.raw_cell_highlight);
320 321 };
321 322
322 323 /** @method render **/
323 324 RawCell.prototype.render = function () {
324 325 var cont = TextCell.prototype.render.apply(this);
325 326 if (cont){
326 327 var text = this.get_text();
327 328 if (text === "") { text = this.placeholder; }
328 329 this.set_text(text);
329 330 this.element.removeClass('rendered');
330 331 }
331 332 return cont;
332 333 };
333 334
334 335
335 336 var HeadingCell = function (options) {
336 337 // Constructor
337 338 //
338 339 // Parameters:
339 340 // options: dictionary
340 341 // Dictionary of keyword arguments.
341 342 // events: $(Events) instance
342 343 // config: dictionary
343 344 // keyboard_manager: KeyboardManager instance
344 345 // notebook: Notebook instance
345 346 options = options || {};
346 var config = this.mergeopt(HeadingCell, options.config);
347 var config = utils.mergeopt(HeadingCell, options.config);
347 348 TextCell.apply(this, [$.extend({}, options, {config: config})]);
348 349
349 350 this.level = 1;
350 351 this.cell_type = 'heading';
351 352 };
352 353
353 354 HeadingCell.options_default = {
354 355 cm_config: {
355 356 theme: 'heading-1'
356 357 },
357 358 placeholder: "Type Heading Here"
358 359 };
359 360
360 361 HeadingCell.prototype = new TextCell();
361 362
362 363 /** @method fromJSON */
363 364 HeadingCell.prototype.fromJSON = function (data) {
364 365 if (data.level !== undefined){
365 366 this.level = data.level;
366 367 }
367 368 TextCell.prototype.fromJSON.apply(this, arguments);
368 369 this.code_mirror.setOption("theme", "heading-"+this.level);
369 370 };
370 371
371 372
372 373 /** @method toJSON */
373 374 HeadingCell.prototype.toJSON = function () {
374 375 var data = TextCell.prototype.toJSON.apply(this);
375 376 data.level = this.get_level();
376 377 return data;
377 378 };
378 379
379 380 /**
380 381 * Change heading level of cell, and re-render
381 382 * @method set_level
382 383 */
383 384 HeadingCell.prototype.set_level = function (level) {
384 385 this.level = level;
385 386 this.code_mirror.setOption("theme", "heading-"+level);
386 387
387 388 if (this.rendered) {
388 389 this.rendered = false;
389 390 this.render();
390 391 }
391 392 };
392 393
393 394 /** The depth of header cell, based on html (h1 to h6)
394 395 * @method get_level
395 396 * @return {integer} level - for 1 to 6
396 397 */
397 398 HeadingCell.prototype.get_level = function () {
398 399 return this.level;
399 400 };
400 401
401 402
402 403 HeadingCell.prototype.get_rendered = function () {
403 404 var r = this.element.find("div.text_cell_render");
404 405 return r.children().first().html();
405 406 };
406 407
407 408 HeadingCell.prototype.render = function () {
408 409 var cont = TextCell.prototype.render.apply(this);
409 410 if (cont) {
410 411 var text = this.get_text();
411 412 var math = null;
412 413 // Markdown headings must be a single line
413 414 text = text.replace(/\n/g, ' ');
414 415 if (text === "") { text = this.placeholder; }
415 416 text = new Array(this.level + 1).join("#") + " " + text;
416 417 var text_and_math = mathjaxutils.remove_math(text);
417 418 text = text_and_math[0];
418 419 math = text_and_math[1];
419 420 var html = marked.parser(marked.lexer(text));
420 421 html = mathjaxutils.replace_math(html, math);
421 422 html = security.sanitize_html(html);
422 423 var h = $($.parseHTML(html));
423 424 // add id and linkback anchor
424 425 var hash = h.text().replace(/ /g, '-');
425 426 h.attr('id', hash);
426 427 h.append(
427 428 $('<a/>')
428 429 .addClass('anchor-link')
429 430 .attr('href', '#' + hash)
430 431 .text('¶')
431 432 );
432 433 this.set_rendered(h);
433 434 this.element.find('div.input_area').hide();
434 435 this.element.find("div.text_cell_render").show();
435 436 this.typeset();
436 437 }
437 438 return cont;
438 439 };
439 440
440 441 // Backwards compatability.
441 442 IPython.TextCell = TextCell;
442 443 IPython.MarkdownCell = MarkdownCell;
443 444 IPython.RawCell = RawCell;
444 445 IPython.HeadingCell = HeadingCell;
445 446
446 447 var textcell = {
447 448 'TextCell': TextCell,
448 449 'MarkdownCell': MarkdownCell,
449 450 'RawCell': RawCell,
450 451 'HeadingCell': HeadingCell,
451 452 };
452 453 return textcell;
453 454 });
General Comments 0
You need to be logged in to leave comments. Login now