##// END OF EJS Templates
notebook: code Readability. Add dismissing symbols...
Matthias BUSSONNIER -
Show More
@@ -1,828 +1,828
1 1 //----------------------------------------------------------------------------
2 2 // Copyright (C) 2008-2011 The IPython Development Team
3 3 //
4 4 // Distributed under the terms of the BSD License. The full license is in
5 5 // the file COPYING, distributed as part of this software.
6 6 //----------------------------------------------------------------------------
7 7
8 8 //============================================================================
9 9 // CodeCell
10 10 //============================================================================
11 11
12 12 var IPython = (function (IPython) {
13 13
14 14 var utils = IPython.utils;
15 15
16 16 var CodeCell = function (notebook) {
17 17 this.code_mirror = null;
18 18 this.input_prompt_number = ' ';
19 19 this.is_completing = false;
20 20 this.completion_cursor = null;
21 21 this.outputs = [];
22 22 this.collapsed = false;
23 23 this.tooltip_timeout = null;
24 24 IPython.Cell.apply(this, arguments);
25 25 };
26 26
27 27
28 28 CodeCell.prototype = new IPython.Cell();
29 29
30 30
31 31 CodeCell.prototype.create_element = function () {
32 32 var cell = $('<div></div>').addClass('cell border-box-sizing code_cell vbox');
33 33 cell.attr('tabindex','2');
34 34 var input = $('<div></div>').addClass('input hbox');
35 35 input.append($('<div/>').addClass('prompt input_prompt'));
36 36 var input_area = $('<div/>').addClass('input_area box-flex1');
37 37 this.code_mirror = CodeMirror(input_area.get(0), {
38 38 indentUnit : 4,
39 39 mode: 'python',
40 40 theme: 'ipython',
41 41 readOnly: this.read_only,
42 42 onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this)
43 43 });
44 44 input.append(input_area);
45 45 var output = $('<div></div>').addClass('output vbox');
46 46 cell.append(input).append(output);
47 47 this.element = cell;
48 48 this.collapse();
49 49 };
50 50
51 51 //TODO, try to diminish the number of parameters.
52 52 CodeCell.prototype.request_tooltip_after_time = function (pre_cursor,time){
53 53 var that = this;
54 54 if (pre_cursor === "" || pre_cursor === "(" ) {
55 55 // don't do anything if line beggin with '(' or is empty
56 56 } else {
57 57 // Will set a timer to request tooltip in `time`
58 58 that.tooltip_timeout = setTimeout(function(){
59 59 IPython.notebook.request_tool_tip(that, pre_cursor)
60 60 },time);
61 61 }
62 62 };
63 63
64 64 CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) {
65 65 // This method gets called in CodeMirror's onKeyDown/onKeyPress
66 66 // handlers and is used to provide custom key handling. Its return
67 67 // value is used to determine if CodeMirror should ignore the event:
68 68 // true = ignore, false = don't ignore.
69 69
70 70 // note that we are comparing and setting the time to wait at each key press.
71 71 // a better wqy might be to generate a new function on each time change and
72 72 // assign it to CodeCell.prototype.request_tooltip_after_time
73 73 tooltip_wait_time = this.notebook.time_before_tooltip;
74 74 tooltip_on_tab = this.notebook.tooltip_on_tab;
75 75 var that = this;
76 76 // whatever key is pressed, first, cancel the tooltip request before
77 77 // they are sent, and remove tooltip if any
78 78 if(event.type === 'keydown' ){
79 79 that.remove_and_cancel_tooltip();
80 80 }
81 81
82 82 if (event.keyCode === 13 && (event.shiftKey || event.ctrlKey)) {
83 83 // Always ignore shift-enter in CodeMirror as we handle it.
84 84 return true;
85 85 }else if (event.which === 40 && event.type === 'keypress' && tooltip_wait_time >= 0) {
86 86 // triger aon keypress (!) otherwise inconsistent event.which depending on plateform
87 87 // browser and keyboard layout !
88 88 // Pressing '(' , request tooltip, don't forget to reappend it
89 89 var cursor = editor.getCursor();
90 90 var pre_cursor = editor.getRange({line:cursor.line,ch:0},cursor).trim()+'(';
91 91 that.request_tooltip_after_time(pre_cursor,tooltip_wait_time);
92 92 } else if (event.keyCode === 9 && event.type == 'keydown') {
93 93 // Tab completion.
94 94 var cur = editor.getCursor();
95 95 //Do not trim here because of tooltip
96 96 var pre_cursor = editor.getRange({line:cur.line,ch:0},cur);
97 97 if (pre_cursor.trim() === "") {
98 98 // Don't autocomplete if the part of the line before the cursor
99 99 // is empty. In this case, let CodeMirror handle indentation.
100 100 return false;
101 101 } else if ((pre_cursor.substr(-1) === "("|| pre_cursor.substr(-1) === " ") && tooltip_on_tab ) {
102 102 that.request_tooltip_after_time(pre_cursor,0);
103 103 } else {
104 104 pre_cursor.trim();
105 105 // Autocomplete the current line.
106 106 event.stop();
107 107 var line = editor.getLine(cur.line);
108 108 this.is_completing = true;
109 109 this.completion_cursor = cur;
110 110 IPython.notebook.complete_cell(this, line, cur.ch);
111 111 return true;
112 112 }
113 113 } else if (event.keyCode === 8 && event.type == 'keydown') {
114 114 // If backspace and the line ends with 4 spaces, remove them.
115 115 var cur = editor.getCursor();
116 116 var line = editor.getLine(cur.line);
117 117 var ending = line.slice(-4);
118 118 if (ending === ' ') {
119 119 editor.replaceRange('',
120 120 {line: cur.line, ch: cur.ch-4},
121 121 {line: cur.line, ch: cur.ch}
122 122 );
123 123 event.stop();
124 124 return true;
125 125 } else {
126 126 return false;
127 127 }
128 128 } else if (event.keyCode === 76 && event.ctrlKey && event.shiftKey
129 129 && event.type == 'keydown') {
130 130 // toggle line numbers with Ctrl-Shift-L
131 131 this.toggle_line_numbers();
132 132 }
133 133 else {
134 134 // keypress/keyup also trigger on TAB press, and we don't want to
135 135 // use those to disable tab completion.
136 136 if (this.is_completing && event.keyCode !== 9) {
137 137 var ed_cur = editor.getCursor();
138 138 var cc_cur = this.completion_cursor;
139 139 if (ed_cur.line !== cc_cur.line || ed_cur.ch !== cc_cur.ch) {
140 140 this.is_completing = false;
141 141 this.completion_cursor = null;
142 142 }
143 143 }
144 144 return false;
145 145 };
146 146 return false;
147 147 };
148 148
149 149 CodeCell.prototype.remove_and_cancel_tooltip = function() {
150 150 // note that we don't handle closing directly inside the calltip
151 151 // as in the completer, because it is not focusable, so won't
152 152 // get the event.
153 153 if (this.tooltip_timeout != null){
154 154 clearTimeout(this.tooltip_timeout);
155 155 $('#tooltip').remove();
156 156 this.tooltip_timeout = null;
157 157 }
158 158 }
159 159
160 160 CodeCell.prototype.finish_tooltip = function (reply) {
161 161 defstring=reply.definition;
162 162 docstring=reply.docstring;
163 163 if(docstring == null){docstring="<empty docstring>"};
164 164 name=reply.name;
165 165
166 166 var that = this;
167 167 var tooltip = $('<div/>').attr('id', 'tooltip').addClass('tooltip');
168 168 // remove to have the tooltip not Limited in X and Y
169 169 tooltip.addClass('smalltooltip');
170 170 var pre=$('<pre/>').html(utils.fixConsole(docstring));
171 171 var expandlink=$('<a/>').attr('href',"#");
172 172 expandlink.addClass("ui-corner-all"); //rounded corner
173 173 expandlink.attr('role',"button");
174 174 //expandlink.addClass('ui-button');
175 175 //expandlink.addClass('ui-state-default');
176 176 var expandspan=$('<span/>').text('Expand');
177 177 expandspan.addClass('ui-icon');
178 178 expandspan.addClass('ui-icon-plus');
179 179 expandlink.append(expandspan);
180 180 expandlink.attr('id','expanbutton');
181 181 expandlink.click(function(){
182 182 tooltip.removeClass('smalltooltip');
183 183 tooltip.addClass('bigtooltip');
184 184 $('#expanbutton').remove();
185 185 setTimeout(function(){that.code_mirror.focus();}, 50);
186 186 });
187 187 var morelink=$('<a/>').attr('href',"#");
188 188 morelink.attr('role',"button");
189 189 morelink.addClass('ui-button');
190 190 //morelink.addClass("ui-corner-all"); //rounded corner
191 191 //morelink.addClass('ui-state-default');
192 192 var morespan=$('<span/>').text('Open in Pager');
193 193 morespan.addClass('ui-icon');
194 194 morespan.addClass('ui-icon-arrowstop-l-n');
195 195 morelink.append(morespan);
196 196 morelink.click(function(){
197 197 var msg_id = IPython.notebook.kernel.execute(name+"?");
198 198 IPython.notebook.msg_cell_map[msg_id] = IPython.notebook.selected_cell().cell_id;
199 199 that.remove_and_cancel_tooltip();
200 200 setTimeout(function(){that.code_mirror.focus();}, 50);
201 201 });
202 202
203 203 var closelink=$('<a/>').attr('href',"#");
204 204 closelink.attr('role',"button");
205 205 closelink.addClass('ui-button');
206 206 //closelink.addClass("ui-corner-all"); //rounded corner
207 207 //closelink.adClass('ui-state-default'); // grey background and blue cross
208 208 var closespan=$('<span/>').text('Close');
209 209 closespan.addClass('ui-icon');
210 210 closespan.addClass('ui-icon-close');
211 211 closelink.append(closespan);
212 212 closelink.click(function(){
213 213 that.remove_and_cancel_tooltip();
214 214 setTimeout(function(){that.code_mirror.focus();}, 50);
215 215 });
216 216 //construct the tooltip
217 217 tooltip.append(closelink);
218 218 tooltip.append(expandlink);
219 219 tooltip.append(morelink);
220 220 if(defstring){
221 221 defstring_html = $('<pre/>').html(utils.fixConsole(defstring));
222 222 tooltip.append(defstring_html);
223 223 }
224 224 tooltip.append(pre);
225 225 var pos = this.code_mirror.cursorCoords();
226 226 tooltip.css('left',pos.x+'px');
227 227 tooltip.css('top',pos.yBot+'px');
228 228 $('body').append(tooltip);
229 229
230 230 // issues with cross-closing if multiple tooltip in less than 5sec
231 231 // keep it comented for now
232 232 // setTimeout(that.remove_and_cancel_tooltip, 5000);
233 233 };
234 234
235 235 // As you type completer
236 236 CodeCell.prototype.finish_completing = function (matched_text, matches) {
237 237 //return if not completing or nothing to complete
238 238 if (!this.is_completing || matches.length === 0) {return;}
239 239
240 240 // for later readability
241 241 var key = { tab:9,
242 242 esc:27,
243 243 backspace:8,
244 244 space:32,
245 245 shift:16,
246 246 enter:13,
247 247 // _ is 95
248 248 isCompSymbol : function (code)
249 249 {
250 250 return (code > 64 && code <= 90)
251 251 || (code >= 97 && code <= 122)
252 252 || (code == 95)
253 253 },
254 254 dismissAndAppend : function (code)
255 255 {
256 chararr = ['(',')','[',']','+','-','/','\\','.',' '];
256 chararr = '()[]+-/\\. ,=*'.split("");
257 257 codearr = chararr.map(function(x){return x.charCodeAt(0)});
258 258 return jQuery.inArray(code, codearr) != -1;
259 259 }
260 260
261 261 }
262 262
263 263 // smart completion, sort kwarg ending with '='
264 264 var newm = new Array();
265 265 if(this.notebook.smart_completer)
266 266 {
267 267 kwargs = new Array();
268 268 other = new Array();
269 269 for(var i = 0 ; i<matches.length ; ++i){
270 270 if(matches[i].substr(-1) === '='){
271 271 kwargs.push(matches[i]);
272 272 }else{other.push(matches[i]);}
273 273 }
274 274 newm = kwargs.concat(other);
275 275 matches = newm;
276 276 }
277 277 // end sort kwargs
278 278
279 279 // give common prefix of a array of string
280 280 function sharedStart(A){
281 281 if(A.length == 1){return A[0]}
282 282 if(A.length > 1 ){
283 283 var tem1, tem2, s, A = A.slice(0).sort();
284 284 tem1 = A[0];
285 285 s = tem1.length;
286 286 tem2 = A.pop();
287 287 while(s && tem2.indexOf(tem1) == -1){
288 288 tem1 = tem1.substring(0, --s);
289 289 }
290 290 return tem1;
291 291 }
292 292 return "";
293 293 }
294 294
295 295
296 296 //try to check if the user is typing tab at least twice after a word
297 297 // and completion is "done"
298 298 fallback_on_tooltip_after = 2
299 299 if(matches.length == 1 && matched_text === matches[0])
300 300 {
301 301 if(this.npressed >fallback_on_tooltip_after && this.prevmatch==matched_text)
302 302 {
303 303 console.log('Ok, you really want to complete after pressing tab '+this.npressed+' times !');
304 304 console.log('You should understand that there is no (more) completion for that !');
305 305 console.log("I'll show you the tooltip, will you stop bothering me ?");
306 306 this.request_tooltip_after_time(matched_text+'(',0);
307 307 return;
308 308 }
309 309 this.prevmatch = matched_text
310 310 this.npressed = this.npressed+1;
311 311 }
312 312 else
313 313 {
314 314 this.prevmatch = "";
315 315 this.npressed = 0;
316 316 }
317 317 // end fallback on tooltip
318 318 //==================================
319 319 // Real completion logic start here
320 320 var that = this;
321 321 var cur = this.completion_cursor;
322 322 var done = false;
323 323
324 324 // call to dismmiss the completer
325 325 var close = function () {
326 326 if (done) return;
327 327 done = true;
328 328 if (complete != undefined)
329 329 {complete.remove();}
330 330 that.is_completing = false;
331 331 that.completion_cursor = null;
332 332 };
333 333
334 334 // update codemirror with the typed text
335 335 prev = matched_text
336 336 var update = function (inserted_text, event) {
337 337 that.code_mirror.replaceRange(
338 338 inserted_text,
339 339 {line: cur.line, ch: (cur.ch-matched_text.length)},
340 340 {line: cur.line, ch: (cur.ch+prev.length-matched_text.length)}
341 341 );
342 342 prev = inserted_text
343 343 if(event != null){
344 344 event.stopPropagation();
345 345 event.preventDefault();
346 346 }
347 347 };
348 348 // insert the given text and exit the completer
349 349 var insert = function (selected_text, event) {
350 350 update(selected_text)
351 351 close();
352 352 setTimeout(function(){that.code_mirror.focus();}, 50);
353 353 };
354 354
355 355 // insert the curent highlited selection and exit
356 356 var pick = function () {
357 357 insert(select.val()[0],null);
358 358 };
359 359
360 360
361 361 // Define function to clear the completer, refill it with the new
362 362 // matches, update the pseuso typing field. autopick insert match if
363 363 // only one left, in no matches (anymore) dismiss itself by pasting
364 364 // what the user have typed until then
365 365 var complete_with = function(matches,typed_text,autopick,event)
366 366 {
367 367 // If autopick an only one match, past.
368 368 // Used to 'pick' when pressing tab
369 369 if (matches.length < 1) {
370 370 insert(typed_text,event);
371 371 if(event != null){
372 372 event.stopPropagation();
373 373 event.preventDefault();
374 374 }
375 375 } else if (autopick && matches.length == 1) {
376 376 insert(matches[0],event);
377 377 if(event != null){
378 378 event.stopPropagation();
379 379 event.preventDefault();
380 380 }
381 381 }
382 382 //clear the previous completion if any
383 383 update(typed_text,event);
384 384 complete.children().children().remove();
385 385 $('#asyoutype').html("<b>"+matched_text+"</b>"+typed_text.substr(matched_text.length));
386 386 select = $('#asyoutypeselect');
387 387 for (var i = 0; i<matches.length; ++i) {
388 388 select.append($('<option/>').html(matches[i]));
389 389 }
390 390 select.children().first().attr('selected','true');
391 391 }
392 392
393 393 // create html for completer
394 394 var complete = $('<div/>').addClass('completions');
395 395 complete.attr('id','complete');
396 396 complete.append($('<p/>').attr('id', 'asyoutype').html('<b>fixed part</b>user part'));//pseudo input field
397 397
398 398 var select = $('<select/>').attr('multiple','true');
399 399 select.attr('id', 'asyoutypeselect')
400 400 select.attr('size',Math.min(10,matches.length));
401 401 var pos = this.code_mirror.cursorCoords();
402 402
403 403 // TODO: I propose to remove enough horizontal pixel
404 404 // to align the text later
405 405 complete.css('left',pos.x+'px');
406 406 complete.css('top',pos.yBot+'px');
407 407 complete.append(select);
408 408
409 409 $('body').append(complete);
410 410
411 411 // So a first actual completion. see if all the completion start wit
412 412 // the same letter and complete if necessary
413 413 fastForward = sharedStart(matches)
414 414 typed_characters = fastForward.substr(matched_text.length);
415 415 complete_with(matches,matched_text+typed_characters,true,null);
416 416 filterd = matches;
417 417 // Give focus to select, and make it filter the match as the user type
418 418 // by filtering the previous matches. Called by .keypress and .keydown
419 419 var downandpress = function (event,press_or_down) {
420 420 var code = event.which;
421 421 var autopick = false; // auto 'pick' if only one match
422 422 if (press_or_down === 0){
423 423 press = true; down = false; //Are we called from keypress or keydown
424 424 } else if (press_or_down == 1){
425 425 press = false; down = true;
426 426 }
427 427 if (code === key.shift) {
428 428 // nothing on Shift
429 429 return;
430 430 }
431 431 if (key.dismissAndAppend(code) && press) {
432 432 var newchar = String.fromCharCode(code);
433 433 typed_characters = typed_characters+newchar;
434 434 insert(matched_text+typed_characters,event);
435 435 return
436 436 }
437 437 if (code === key.enter) {
438 438 // Pressing ENTER will cause a pick
439 439 event.stopPropagation();
440 440 event.preventDefault();
441 441 pick();
442 442 } else if (code === 38 || code === 40) {
443 443 // We don't want the document keydown handler to handle UP/DOWN,
444 444 // but we want the default action.
445 445 event.stopPropagation();
446 446 } else if ( (code == key.backspace)||(code == key.tab && down) || press || key.isCompSymbol(code)){
447 447 if( key.isCompSymbol(code) && press)
448 448 {
449 449 var newchar = String.fromCharCode(code);
450 450 typed_characters = typed_characters+newchar;
451 451 } else if (code == key.tab) {
452 452 fastForward = sharedStart(filterd)
453 453 ffsub = fastForward.substr(matched_text.length+typed_characters.length);
454 454 typed_characters = typed_characters+ffsub;
455 455 autopick = true;
456 456 } else if (code == key.backspace && down) {
457 457 // cancel if user have erase everything, otherwise decrease
458 458 // what we filter with
459 459 event.preventDefault();
460 460 if (typed_characters.length <= 0)
461 461 {
462 462 insert(matched_text,event)
463 463 return
464 464 }
465 465 typed_characters = typed_characters.substr(0,typed_characters.length-1);
466 466 } else if (press && code != key.backspace && code != key.tab && code != 0){
467 467 insert(matched_text+typed_characters,event);
468 468 return
469 469 } else {
470 470 return
471 471 }
472 472 re = new RegExp("^"+"\%?"+matched_text+typed_characters,"");
473 473 filterd = matches.filter(function(x){return re.test(x)});
474 474 complete_with(filterd,matched_text+typed_characters,autopick,event);
475 475 } else if( code == key.esc) {
476 476 // dismiss the completer and go back to before invoking it
477 477 insert(matched_text,event);
478 478 } else if( press ){ // abort only on .keypress or esc
479 479 // abort with what the user have pressed until now
480 480 console.log('aborting with keycode : '+code+' is down :'+down);
481 481 }
482 482 }
483 483 select.keydown(function (event) {
484 484 downandpress(event,1)
485 485 });
486 486 select.keypress(function (event) {
487 487 downandpress(event,0)
488 488 });
489 489 // Double click also causes a pick.
490 490 // and bind the last actions.
491 491 select.dblclick(pick);
492 492 select.blur(close);
493 493 select.focus();
494 494 };
495 495
496 496 CodeCell.prototype.toggle_line_numbers = function () {
497 497 if (this.code_mirror.getOption('lineNumbers') == false) {
498 498 this.code_mirror.setOption('lineNumbers', true);
499 499 } else {
500 500 this.code_mirror.setOption('lineNumbers', false);
501 501 }
502 502 this.code_mirror.refresh();
503 503 };
504 504
505 505 CodeCell.prototype.select = function () {
506 506 IPython.Cell.prototype.select.apply(this);
507 507 // Todo: this dance is needed because as of CodeMirror 2.12, focus is
508 508 // not causing the cursor to blink if the editor is empty initially.
509 509 // While this seems to fix the issue, this should be fixed
510 510 // in CodeMirror proper.
511 511 var s = this.code_mirror.getValue();
512 512 this.code_mirror.focus();
513 513 if (s === '') this.code_mirror.setValue('');
514 514 };
515 515
516 516
517 517 CodeCell.prototype.select_all = function () {
518 518 var start = {line: 0, ch: 0};
519 519 var nlines = this.code_mirror.lineCount();
520 520 var last_line = this.code_mirror.getLine(nlines-1);
521 521 var end = {line: nlines-1, ch: last_line.length};
522 522 this.code_mirror.setSelection(start, end);
523 523 };
524 524
525 525
526 526 CodeCell.prototype.append_output = function (json) {
527 527 this.expand();
528 528 if (json.output_type === 'pyout') {
529 529 this.append_pyout(json);
530 530 } else if (json.output_type === 'pyerr') {
531 531 this.append_pyerr(json);
532 532 } else if (json.output_type === 'display_data') {
533 533 this.append_display_data(json);
534 534 } else if (json.output_type === 'stream') {
535 535 this.append_stream(json);
536 536 };
537 537 this.outputs.push(json);
538 538 };
539 539
540 540
541 541 CodeCell.prototype.create_output_area = function () {
542 542 var oa = $("<div/>").addClass("hbox output_area");
543 543 oa.append($('<div/>').addClass('prompt'));
544 544 return oa;
545 545 };
546 546
547 547
548 548 CodeCell.prototype.append_pyout = function (json) {
549 549 n = json.prompt_number || ' ';
550 550 var toinsert = this.create_output_area();
551 551 toinsert.find('div.prompt').addClass('output_prompt').html('Out[' + n + ']:');
552 552 this.append_mime_type(json, toinsert);
553 553 this.element.find('div.output').append(toinsert);
554 554 // If we just output latex, typeset it.
555 555 if ((json.latex !== undefined) || (json.html !== undefined)) {
556 556 this.typeset();
557 557 };
558 558 };
559 559
560 560
561 561 CodeCell.prototype.append_pyerr = function (json) {
562 562 var tb = json.traceback;
563 563 if (tb !== undefined && tb.length > 0) {
564 564 var s = '';
565 565 var len = tb.length;
566 566 for (var i=0; i<len; i++) {
567 567 s = s + tb[i] + '\n';
568 568 }
569 569 s = s + '\n';
570 570 var toinsert = this.create_output_area();
571 571 this.append_text(s, toinsert);
572 572 this.element.find('div.output').append(toinsert);
573 573 };
574 574 };
575 575
576 576
577 577 CodeCell.prototype.append_stream = function (json) {
578 578 // temporary fix: if stream undefined (json file written prior to this patch),
579 579 // default to most likely stdout:
580 580 if (json.stream == undefined){
581 581 json.stream = 'stdout';
582 582 }
583 583 var subclass = "output_"+json.stream;
584 584 if (this.outputs.length > 0){
585 585 // have at least one output to consider
586 586 var last = this.outputs[this.outputs.length-1];
587 587 if (last.output_type == 'stream' && json.stream == last.stream){
588 588 // latest output was in the same stream,
589 589 // so append directly into its pre tag
590 590 this.element.find('div.'+subclass).last().find('pre').append(json.text);
591 591 return;
592 592 }
593 593 }
594 594
595 595 // If we got here, attach a new div
596 596 var toinsert = this.create_output_area();
597 597 this.append_text(json.text, toinsert, "output_stream "+subclass);
598 598 this.element.find('div.output').append(toinsert);
599 599 };
600 600
601 601
602 602 CodeCell.prototype.append_display_data = function (json) {
603 603 var toinsert = this.create_output_area();
604 604 this.append_mime_type(json, toinsert);
605 605 this.element.find('div.output').append(toinsert);
606 606 // If we just output latex, typeset it.
607 607 if ( (json.latex !== undefined) || (json.html !== undefined) ) {
608 608 this.typeset();
609 609 };
610 610 };
611 611
612 612
613 613 CodeCell.prototype.append_mime_type = function (json, element) {
614 614 if (json.html !== undefined) {
615 615 this.append_html(json.html, element);
616 616 } else if (json.latex !== undefined) {
617 617 this.append_latex(json.latex, element);
618 618 } else if (json.svg !== undefined) {
619 619 this.append_svg(json.svg, element);
620 620 } else if (json.png !== undefined) {
621 621 this.append_png(json.png, element);
622 622 } else if (json.jpeg !== undefined) {
623 623 this.append_jpeg(json.jpeg, element);
624 624 } else if (json.text !== undefined) {
625 625 this.append_text(json.text, element);
626 626 };
627 627 };
628 628
629 629
630 630 CodeCell.prototype.append_html = function (html, element) {
631 631 var toinsert = $("<div/>").addClass("box_flex1 output_subarea output_html rendered_html");
632 632 toinsert.append(html);
633 633 element.append(toinsert);
634 634 };
635 635
636 636
637 637 CodeCell.prototype.append_text = function (data, element, extra_class) {
638 638 var toinsert = $("<div/>").addClass("box_flex1 output_subarea output_text");
639 639 if (extra_class){
640 640 toinsert.addClass(extra_class);
641 641 }
642 642 toinsert.append($("<pre/>").html(data));
643 643 element.append(toinsert);
644 644 };
645 645
646 646
647 647 CodeCell.prototype.append_svg = function (svg, element) {
648 648 var toinsert = $("<div/>").addClass("box_flex1 output_subarea output_svg");
649 649 toinsert.append(svg);
650 650 element.append(toinsert);
651 651 };
652 652
653 653
654 654 CodeCell.prototype.append_png = function (png, element) {
655 655 var toinsert = $("<div/>").addClass("box_flex1 output_subarea output_png");
656 656 toinsert.append($("<img/>").attr('src','data:image/png;base64,'+png));
657 657 element.append(toinsert);
658 658 };
659 659
660 660
661 661 CodeCell.prototype.append_jpeg = function (jpeg, element) {
662 662 var toinsert = $("<div/>").addClass("box_flex1 output_subarea output_jpeg");
663 663 toinsert.append($("<img/>").attr('src','data:image/jpeg;base64,'+jpeg));
664 664 element.append(toinsert);
665 665 };
666 666
667 667
668 668 CodeCell.prototype.append_latex = function (latex, element) {
669 669 // This method cannot do the typesetting because the latex first has to
670 670 // be on the page.
671 671 var toinsert = $("<div/>").addClass("box_flex1 output_subarea output_latex");
672 672 toinsert.append(latex);
673 673 element.append(toinsert);
674 674 };
675 675
676 676
677 677 CodeCell.prototype.clear_output = function (stdout, stderr, other) {
678 678 var output_div = this.element.find("div.output");
679 679 if (stdout && stderr && other){
680 680 // clear all, no need for logic
681 681 output_div.html("");
682 682 this.outputs = [];
683 683 return;
684 684 }
685 685 // remove html output
686 686 // each output_subarea that has an identifying class is in an output_area
687 687 // which is the element to be removed.
688 688 if (stdout){
689 689 output_div.find("div.output_stdout").parent().remove();
690 690 }
691 691 if (stderr){
692 692 output_div.find("div.output_stderr").parent().remove();
693 693 }
694 694 if (other){
695 695 output_div.find("div.output_subarea").not("div.output_stderr").not("div.output_stdout").parent().remove();
696 696 }
697 697
698 698 // remove cleared outputs from JSON list:
699 699 for (var i = this.outputs.length - 1; i >= 0; i--){
700 700 var out = this.outputs[i];
701 701 var output_type = out.output_type;
702 702 if (output_type == "display_data" && other){
703 703 this.outputs.splice(i,1);
704 704 }else if (output_type == "stream"){
705 705 if (stdout && out.stream == "stdout"){
706 706 this.outputs.splice(i,1);
707 707 }else if (stderr && out.stream == "stderr"){
708 708 this.outputs.splice(i,1);
709 709 }
710 710 }
711 711 }
712 712 };
713 713
714 714
715 715 CodeCell.prototype.clear_input = function () {
716 716 this.code_mirror.setValue('');
717 717 };
718 718
719 719
720 720 CodeCell.prototype.collapse = function () {
721 721 if (!this.collapsed) {
722 722 this.element.find('div.output').hide();
723 723 this.collapsed = true;
724 724 };
725 725 };
726 726
727 727
728 728 CodeCell.prototype.expand = function () {
729 729 if (this.collapsed) {
730 730 this.element.find('div.output').show();
731 731 this.collapsed = false;
732 732 };
733 733 };
734 734
735 735
736 736 CodeCell.prototype.toggle_output = function () {
737 737 if (this.collapsed) {
738 738 this.expand();
739 739 } else {
740 740 this.collapse();
741 741 };
742 742 };
743 743
744 744 CodeCell.prototype.set_input_prompt = function (number) {
745 745 var n = number || '&nbsp;';
746 746 this.input_prompt_number = n;
747 747 this.element.find('div.input_prompt').html('In&nbsp;[' + n + ']:');
748 748 };
749 749
750 750
751 751 CodeCell.prototype.get_code = function () {
752 752 return this.code_mirror.getValue();
753 753 };
754 754
755 755
756 756 CodeCell.prototype.set_code = function (code) {
757 757 return this.code_mirror.setValue(code);
758 758 };
759 759
760 760
761 761 CodeCell.prototype.at_top = function () {
762 762 var cursor = this.code_mirror.getCursor();
763 763 if (cursor.line === 0) {
764 764 return true;
765 765 } else {
766 766 return false;
767 767 }
768 768 };
769 769
770 770
771 771 CodeCell.prototype.at_bottom = function () {
772 772 var cursor = this.code_mirror.getCursor();
773 773 if (cursor.line === (this.code_mirror.lineCount()-1)) {
774 774 return true;
775 775 } else {
776 776 return false;
777 777 }
778 778 };
779 779
780 780
781 781 CodeCell.prototype.fromJSON = function (data) {
782 782 console.log('Import from JSON:', data);
783 783 if (data.cell_type === 'code') {
784 784 if (data.input !== undefined) {
785 785 this.set_code(data.input);
786 786 }
787 787 if (data.prompt_number !== undefined) {
788 788 this.set_input_prompt(data.prompt_number);
789 789 } else {
790 790 this.set_input_prompt();
791 791 };
792 792 var len = data.outputs.length;
793 793 for (var i=0; i<len; i++) {
794 794 this.append_output(data.outputs[i]);
795 795 };
796 796 if (data.collapsed !== undefined) {
797 797 if (data.collapsed) {
798 798 this.collapse();
799 799 };
800 800 };
801 801 };
802 802 };
803 803
804 804
805 805 CodeCell.prototype.toJSON = function () {
806 806 var data = {};
807 807 data.input = this.get_code();
808 808 data.cell_type = 'code';
809 809 if (this.input_prompt_number !== ' ') {
810 810 data.prompt_number = this.input_prompt_number;
811 811 };
812 812 var outputs = [];
813 813 var len = this.outputs.length;
814 814 for (var i=0; i<len; i++) {
815 815 outputs[i] = this.outputs[i];
816 816 };
817 817 data.outputs = outputs;
818 818 data.language = 'python';
819 819 data.collapsed = this.collapsed;
820 820 // console.log('Export to JSON:',data);
821 821 return data;
822 822 };
823 823
824 824
825 825 IPython.CodeCell = CodeCell;
826 826
827 827 return IPython;
828 828 }(IPython));
General Comments 0
You need to be logged in to leave comments. Login now