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