##// END OF EJS Templates
Merge pull request #3850 from minrk/store_history...
Min RK -
r11872:55dfcbc9 merge
parent child Browse files
Show More
@@ -1,443 +1,443 b''
1 //----------------------------------------------------------------------------
1 //----------------------------------------------------------------------------
2 // Copyright (C) 2008-2011 The IPython Development Team
2 // Copyright (C) 2008-2011 The IPython Development Team
3 //
3 //
4 // Distributed under the terms of the BSD License. The full license is in
4 // Distributed under the terms of the BSD License. The full license is in
5 // the file COPYING, distributed as part of this software.
5 // the file COPYING, distributed as part of this software.
6 //----------------------------------------------------------------------------
6 //----------------------------------------------------------------------------
7
7
8 //============================================================================
8 //============================================================================
9 // CodeCell
9 // CodeCell
10 //============================================================================
10 //============================================================================
11 /**
11 /**
12 * An extendable module that provide base functionnality to create cell for notebook.
12 * An extendable module that provide base functionnality to create cell for notebook.
13 * @module IPython
13 * @module IPython
14 * @namespace IPython
14 * @namespace IPython
15 * @submodule CodeCell
15 * @submodule CodeCell
16 */
16 */
17
17
18
18
19 /* local util for codemirror */
19 /* local util for codemirror */
20 var posEq = function(a, b) {return a.line == b.line && a.ch == b.ch;}
20 var posEq = function(a, b) {return a.line == b.line && a.ch == b.ch;}
21
21
22 /**
22 /**
23 *
23 *
24 * function to delete until previous non blanking space character
24 * function to delete until previous non blanking space character
25 * or first multiple of 4 tabstop.
25 * or first multiple of 4 tabstop.
26 * @private
26 * @private
27 */
27 */
28 CodeMirror.commands.delSpaceToPrevTabStop = function(cm){
28 CodeMirror.commands.delSpaceToPrevTabStop = function(cm){
29 var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
29 var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
30 if (!posEq(from, to)) {cm.replaceRange("", from, to); return}
30 if (!posEq(from, to)) {cm.replaceRange("", from, to); return}
31 var cur = cm.getCursor(), line = cm.getLine(cur.line);
31 var cur = cm.getCursor(), line = cm.getLine(cur.line);
32 var tabsize = cm.getOption('tabSize');
32 var tabsize = cm.getOption('tabSize');
33 var chToPrevTabStop = cur.ch-(Math.ceil(cur.ch/tabsize)-1)*tabsize;
33 var chToPrevTabStop = cur.ch-(Math.ceil(cur.ch/tabsize)-1)*tabsize;
34 var from = {ch:cur.ch-chToPrevTabStop,line:cur.line}
34 var from = {ch:cur.ch-chToPrevTabStop,line:cur.line}
35 var select = cm.getRange(from,cur)
35 var select = cm.getRange(from,cur)
36 if( select.match(/^\ +$/) != null){
36 if( select.match(/^\ +$/) != null){
37 cm.replaceRange("",from,cur)
37 cm.replaceRange("",from,cur)
38 } else {
38 } else {
39 cm.deleteH(-1,"char")
39 cm.deleteH(-1,"char")
40 }
40 }
41 };
41 };
42
42
43
43
44 var IPython = (function (IPython) {
44 var IPython = (function (IPython) {
45 "use strict";
45 "use strict";
46
46
47 var utils = IPython.utils;
47 var utils = IPython.utils;
48 var key = IPython.utils.keycodes;
48 var key = IPython.utils.keycodes;
49
49
50 /**
50 /**
51 * A Cell conceived to write code.
51 * A Cell conceived to write code.
52 *
52 *
53 * The kernel doesn't have to be set at creation time, in that case
53 * The kernel doesn't have to be set at creation time, in that case
54 * it will be null and set_kernel has to be called later.
54 * it will be null and set_kernel has to be called later.
55 * @class CodeCell
55 * @class CodeCell
56 * @extends IPython.Cell
56 * @extends IPython.Cell
57 *
57 *
58 * @constructor
58 * @constructor
59 * @param {Object|null} kernel
59 * @param {Object|null} kernel
60 * @param {object|undefined} [options]
60 * @param {object|undefined} [options]
61 * @param [options.cm_config] {object} config to pass to CodeMirror
61 * @param [options.cm_config] {object} config to pass to CodeMirror
62 */
62 */
63 var CodeCell = function (kernel, options) {
63 var CodeCell = function (kernel, options) {
64 this.kernel = kernel || null;
64 this.kernel = kernel || null;
65 this.code_mirror = null;
65 this.code_mirror = null;
66 this.input_prompt_number = null;
66 this.input_prompt_number = null;
67 this.collapsed = false;
67 this.collapsed = false;
68 this.default_mode = 'ipython';
68 this.default_mode = 'ipython';
69 this.cell_type = "code";
69 this.cell_type = "code";
70
70
71
71
72 var cm_overwrite_options = {
72 var cm_overwrite_options = {
73 onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this)
73 onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this)
74 };
74 };
75
75
76 options = this.mergeopt(CodeCell, options, {cm_config:cm_overwrite_options});
76 options = this.mergeopt(CodeCell, options, {cm_config:cm_overwrite_options});
77
77
78 IPython.Cell.apply(this,[options]);
78 IPython.Cell.apply(this,[options]);
79
79
80 var that = this;
80 var that = this;
81 this.element.focusout(
81 this.element.focusout(
82 function() { that.auto_highlight(); }
82 function() { that.auto_highlight(); }
83 );
83 );
84 };
84 };
85
85
86 CodeCell.options_default = {
86 CodeCell.options_default = {
87 cm_config : {
87 cm_config : {
88 extraKeys: {
88 extraKeys: {
89 "Tab" : "indentMore",
89 "Tab" : "indentMore",
90 "Shift-Tab" : "indentLess",
90 "Shift-Tab" : "indentLess",
91 "Backspace" : "delSpaceToPrevTabStop",
91 "Backspace" : "delSpaceToPrevTabStop",
92 "Cmd-/" : "toggleComment",
92 "Cmd-/" : "toggleComment",
93 "Ctrl-/" : "toggleComment"
93 "Ctrl-/" : "toggleComment"
94 },
94 },
95 mode: 'ipython',
95 mode: 'ipython',
96 theme: 'ipython',
96 theme: 'ipython',
97 matchBrackets: true
97 matchBrackets: true
98 }
98 }
99 };
99 };
100
100
101
101
102 CodeCell.prototype = new IPython.Cell();
102 CodeCell.prototype = new IPython.Cell();
103
103
104 /**
104 /**
105 * @method auto_highlight
105 * @method auto_highlight
106 */
106 */
107 CodeCell.prototype.auto_highlight = function () {
107 CodeCell.prototype.auto_highlight = function () {
108 this._auto_highlight(IPython.config.cell_magic_highlight)
108 this._auto_highlight(IPython.config.cell_magic_highlight)
109 };
109 };
110
110
111 /** @method create_element */
111 /** @method create_element */
112 CodeCell.prototype.create_element = function () {
112 CodeCell.prototype.create_element = function () {
113 IPython.Cell.prototype.create_element.apply(this, arguments);
113 IPython.Cell.prototype.create_element.apply(this, arguments);
114
114
115 var cell = $('<div></div>').addClass('cell border-box-sizing code_cell');
115 var cell = $('<div></div>').addClass('cell border-box-sizing code_cell');
116 cell.attr('tabindex','2');
116 cell.attr('tabindex','2');
117
117
118 this.celltoolbar = new IPython.CellToolbar(this);
118 this.celltoolbar = new IPython.CellToolbar(this);
119
119
120 var input = $('<div></div>').addClass('input');
120 var input = $('<div></div>').addClass('input');
121 var vbox = $('<div/>').addClass('vbox box-flex1')
121 var vbox = $('<div/>').addClass('vbox box-flex1')
122 input.append($('<div/>').addClass('prompt input_prompt'));
122 input.append($('<div/>').addClass('prompt input_prompt'));
123 vbox.append(this.celltoolbar.element);
123 vbox.append(this.celltoolbar.element);
124 var input_area = $('<div/>').addClass('input_area');
124 var input_area = $('<div/>').addClass('input_area');
125 this.code_mirror = CodeMirror(input_area.get(0), this.cm_config);
125 this.code_mirror = CodeMirror(input_area.get(0), this.cm_config);
126 $(this.code_mirror.getInputField()).attr("spellcheck", "false");
126 $(this.code_mirror.getInputField()).attr("spellcheck", "false");
127 vbox.append(input_area);
127 vbox.append(input_area);
128 input.append(vbox);
128 input.append(vbox);
129 var output = $('<div></div>');
129 var output = $('<div></div>');
130 cell.append(input).append(output);
130 cell.append(input).append(output);
131 this.element = cell;
131 this.element = cell;
132 this.output_area = new IPython.OutputArea(output, true);
132 this.output_area = new IPython.OutputArea(output, true);
133
133
134 // construct a completer only if class exist
134 // construct a completer only if class exist
135 // otherwise no print view
135 // otherwise no print view
136 if (IPython.Completer !== undefined)
136 if (IPython.Completer !== undefined)
137 {
137 {
138 this.completer = new IPython.Completer(this);
138 this.completer = new IPython.Completer(this);
139 }
139 }
140 };
140 };
141
141
142 /**
142 /**
143 * This method gets called in CodeMirror's onKeyDown/onKeyPress
143 * This method gets called in CodeMirror's onKeyDown/onKeyPress
144 * handlers and is used to provide custom key handling. Its return
144 * handlers and is used to provide custom key handling. Its return
145 * value is used to determine if CodeMirror should ignore the event:
145 * value is used to determine if CodeMirror should ignore the event:
146 * true = ignore, false = don't ignore.
146 * true = ignore, false = don't ignore.
147 * @method handle_codemirror_keyevent
147 * @method handle_codemirror_keyevent
148 */
148 */
149 CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) {
149 CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) {
150
150
151 var that = this;
151 var that = this;
152 // whatever key is pressed, first, cancel the tooltip request before
152 // whatever key is pressed, first, cancel the tooltip request before
153 // they are sent, and remove tooltip if any, except for tab again
153 // they are sent, and remove tooltip if any, except for tab again
154 if (event.type === 'keydown' && event.which != key.TAB ) {
154 if (event.type === 'keydown' && event.which != key.TAB ) {
155 IPython.tooltip.remove_and_cancel_tooltip();
155 IPython.tooltip.remove_and_cancel_tooltip();
156 };
156 };
157
157
158 var cur = editor.getCursor();
158 var cur = editor.getCursor();
159 if (event.keyCode === key.ENTER){
159 if (event.keyCode === key.ENTER){
160 this.auto_highlight();
160 this.auto_highlight();
161 }
161 }
162
162
163 if (event.keyCode === key.ENTER && (event.shiftKey || event.ctrlKey)) {
163 if (event.keyCode === key.ENTER && (event.shiftKey || event.ctrlKey)) {
164 // Always ignore shift-enter in CodeMirror as we handle it.
164 // Always ignore shift-enter in CodeMirror as we handle it.
165 return true;
165 return true;
166 } else if (event.which === 40 && event.type === 'keypress' && IPython.tooltip.time_before_tooltip >= 0) {
166 } else if (event.which === 40 && event.type === 'keypress' && IPython.tooltip.time_before_tooltip >= 0) {
167 // triger on keypress (!) otherwise inconsistent event.which depending on plateform
167 // triger on keypress (!) otherwise inconsistent event.which depending on plateform
168 // browser and keyboard layout !
168 // browser and keyboard layout !
169 // Pressing '(' , request tooltip, don't forget to reappend it
169 // Pressing '(' , request tooltip, don't forget to reappend it
170 // The second argument says to hide the tooltip if the docstring
170 // The second argument says to hide the tooltip if the docstring
171 // is actually empty
171 // is actually empty
172 IPython.tooltip.pending(that, true);
172 IPython.tooltip.pending(that, true);
173 } else if (event.which === key.UPARROW && event.type === 'keydown') {
173 } else if (event.which === key.UPARROW && event.type === 'keydown') {
174 // If we are not at the top, let CM handle the up arrow and
174 // If we are not at the top, let CM handle the up arrow and
175 // prevent the global keydown handler from handling it.
175 // prevent the global keydown handler from handling it.
176 if (!that.at_top()) {
176 if (!that.at_top()) {
177 event.stop();
177 event.stop();
178 return false;
178 return false;
179 } else {
179 } else {
180 return true;
180 return true;
181 };
181 };
182 } else if (event.which === key.ESC) {
182 } else if (event.which === key.ESC) {
183 IPython.tooltip.remove_and_cancel_tooltip(true);
183 IPython.tooltip.remove_and_cancel_tooltip(true);
184 return true;
184 return true;
185 } else if (event.which === key.DOWNARROW && event.type === 'keydown') {
185 } else if (event.which === key.DOWNARROW && event.type === 'keydown') {
186 // If we are not at the bottom, let CM handle the down arrow and
186 // If we are not at the bottom, let CM handle the down arrow and
187 // prevent the global keydown handler from handling it.
187 // prevent the global keydown handler from handling it.
188 if (!that.at_bottom()) {
188 if (!that.at_bottom()) {
189 event.stop();
189 event.stop();
190 return false;
190 return false;
191 } else {
191 } else {
192 return true;
192 return true;
193 };
193 };
194 } else if (event.keyCode === key.TAB && event.type == 'keydown' && event.shiftKey) {
194 } else if (event.keyCode === key.TAB && event.type == 'keydown' && event.shiftKey) {
195 if (editor.somethingSelected()){
195 if (editor.somethingSelected()){
196 var anchor = editor.getCursor("anchor");
196 var anchor = editor.getCursor("anchor");
197 var head = editor.getCursor("head");
197 var head = editor.getCursor("head");
198 if( anchor.line != head.line){
198 if( anchor.line != head.line){
199 return false;
199 return false;
200 }
200 }
201 }
201 }
202 IPython.tooltip.request(that);
202 IPython.tooltip.request(that);
203 event.stop();
203 event.stop();
204 return true;
204 return true;
205 } else if (event.keyCode === key.TAB && event.type == 'keydown') {
205 } else if (event.keyCode === key.TAB && event.type == 'keydown') {
206 // Tab completion.
206 // Tab completion.
207 //Do not trim here because of tooltip
207 //Do not trim here because of tooltip
208 if (editor.somethingSelected()){return false}
208 if (editor.somethingSelected()){return false}
209 var pre_cursor = editor.getRange({line:cur.line,ch:0},cur);
209 var pre_cursor = editor.getRange({line:cur.line,ch:0},cur);
210 if (pre_cursor.trim() === "") {
210 if (pre_cursor.trim() === "") {
211 // Don't autocomplete if the part of the line before the cursor
211 // Don't autocomplete if the part of the line before the cursor
212 // is empty. In this case, let CodeMirror handle indentation.
212 // is empty. In this case, let CodeMirror handle indentation.
213 return false;
213 return false;
214 } else if ((pre_cursor.substr(-1) === "("|| pre_cursor.substr(-1) === " ") && IPython.config.tooltip_on_tab ) {
214 } else if ((pre_cursor.substr(-1) === "("|| pre_cursor.substr(-1) === " ") && IPython.config.tooltip_on_tab ) {
215 IPython.tooltip.request(that);
215 IPython.tooltip.request(that);
216 // Prevent the event from bubbling up.
216 // Prevent the event from bubbling up.
217 event.stop();
217 event.stop();
218 // Prevent CodeMirror from handling the tab.
218 // Prevent CodeMirror from handling the tab.
219 return true;
219 return true;
220 } else {
220 } else {
221 event.stop();
221 event.stop();
222 this.completer.startCompletion();
222 this.completer.startCompletion();
223 return true;
223 return true;
224 };
224 };
225 } else {
225 } else {
226 // keypress/keyup also trigger on TAB press, and we don't want to
226 // keypress/keyup also trigger on TAB press, and we don't want to
227 // use those to disable tab completion.
227 // use those to disable tab completion.
228 return false;
228 return false;
229 };
229 };
230 return false;
230 return false;
231 };
231 };
232
232
233
233
234 // Kernel related calls.
234 // Kernel related calls.
235
235
236 CodeCell.prototype.set_kernel = function (kernel) {
236 CodeCell.prototype.set_kernel = function (kernel) {
237 this.kernel = kernel;
237 this.kernel = kernel;
238 }
238 }
239
239
240 /**
240 /**
241 * Execute current code cell to the kernel
241 * Execute current code cell to the kernel
242 * @method execute
242 * @method execute
243 */
243 */
244 CodeCell.prototype.execute = function () {
244 CodeCell.prototype.execute = function () {
245 this.output_area.clear_output(true, true, true);
245 this.output_area.clear_output(true, true, true);
246 this.set_input_prompt('*');
246 this.set_input_prompt('*');
247 this.element.addClass("running");
247 this.element.addClass("running");
248 var callbacks = {
248 var callbacks = {
249 'execute_reply': $.proxy(this._handle_execute_reply, this),
249 'execute_reply': $.proxy(this._handle_execute_reply, this),
250 'output': $.proxy(this.output_area.handle_output, this.output_area),
250 'output': $.proxy(this.output_area.handle_output, this.output_area),
251 'clear_output': $.proxy(this.output_area.handle_clear_output, this.output_area),
251 'clear_output': $.proxy(this.output_area.handle_clear_output, this.output_area),
252 'set_next_input': $.proxy(this._handle_set_next_input, this),
252 'set_next_input': $.proxy(this._handle_set_next_input, this),
253 'input_request': $.proxy(this._handle_input_request, this)
253 'input_request': $.proxy(this._handle_input_request, this)
254 };
254 };
255 var msg_id = this.kernel.execute(this.get_text(), callbacks, {silent: false});
255 var msg_id = this.kernel.execute(this.get_text(), callbacks, {silent: false, store_history: true});
256 };
256 };
257
257
258 /**
258 /**
259 * @method _handle_execute_reply
259 * @method _handle_execute_reply
260 * @private
260 * @private
261 */
261 */
262 CodeCell.prototype._handle_execute_reply = function (content) {
262 CodeCell.prototype._handle_execute_reply = function (content) {
263 this.set_input_prompt(content.execution_count);
263 this.set_input_prompt(content.execution_count);
264 this.element.removeClass("running");
264 this.element.removeClass("running");
265 $([IPython.events]).trigger('set_dirty.Notebook', {value: true});
265 $([IPython.events]).trigger('set_dirty.Notebook', {value: true});
266 }
266 }
267
267
268 /**
268 /**
269 * @method _handle_set_next_input
269 * @method _handle_set_next_input
270 * @private
270 * @private
271 */
271 */
272 CodeCell.prototype._handle_set_next_input = function (text) {
272 CodeCell.prototype._handle_set_next_input = function (text) {
273 var data = {'cell': this, 'text': text}
273 var data = {'cell': this, 'text': text}
274 $([IPython.events]).trigger('set_next_input.Notebook', data);
274 $([IPython.events]).trigger('set_next_input.Notebook', data);
275 }
275 }
276
276
277 /**
277 /**
278 * @method _handle_input_request
278 * @method _handle_input_request
279 * @private
279 * @private
280 */
280 */
281 CodeCell.prototype._handle_input_request = function (content) {
281 CodeCell.prototype._handle_input_request = function (content) {
282 this.output_area.append_raw_input(content);
282 this.output_area.append_raw_input(content);
283 }
283 }
284
284
285
285
286 // Basic cell manipulation.
286 // Basic cell manipulation.
287
287
288 CodeCell.prototype.select = function () {
288 CodeCell.prototype.select = function () {
289 IPython.Cell.prototype.select.apply(this);
289 IPython.Cell.prototype.select.apply(this);
290 this.code_mirror.refresh();
290 this.code_mirror.refresh();
291 this.code_mirror.focus();
291 this.code_mirror.focus();
292 this.auto_highlight();
292 this.auto_highlight();
293 // We used to need an additional refresh() after the focus, but
293 // We used to need an additional refresh() after the focus, but
294 // it appears that this has been fixed in CM. This bug would show
294 // it appears that this has been fixed in CM. This bug would show
295 // up on FF when a newly loaded markdown cell was edited.
295 // up on FF when a newly loaded markdown cell was edited.
296 };
296 };
297
297
298
298
299 CodeCell.prototype.select_all = function () {
299 CodeCell.prototype.select_all = function () {
300 var start = {line: 0, ch: 0};
300 var start = {line: 0, ch: 0};
301 var nlines = this.code_mirror.lineCount();
301 var nlines = this.code_mirror.lineCount();
302 var last_line = this.code_mirror.getLine(nlines-1);
302 var last_line = this.code_mirror.getLine(nlines-1);
303 var end = {line: nlines-1, ch: last_line.length};
303 var end = {line: nlines-1, ch: last_line.length};
304 this.code_mirror.setSelection(start, end);
304 this.code_mirror.setSelection(start, end);
305 };
305 };
306
306
307
307
308 CodeCell.prototype.collapse = function () {
308 CodeCell.prototype.collapse = function () {
309 this.collapsed = true;
309 this.collapsed = true;
310 this.output_area.collapse();
310 this.output_area.collapse();
311 };
311 };
312
312
313
313
314 CodeCell.prototype.expand = function () {
314 CodeCell.prototype.expand = function () {
315 this.collapsed = false;
315 this.collapsed = false;
316 this.output_area.expand();
316 this.output_area.expand();
317 };
317 };
318
318
319
319
320 CodeCell.prototype.toggle_output = function () {
320 CodeCell.prototype.toggle_output = function () {
321 this.collapsed = Boolean(1 - this.collapsed);
321 this.collapsed = Boolean(1 - this.collapsed);
322 this.output_area.toggle_output();
322 this.output_area.toggle_output();
323 };
323 };
324
324
325
325
326 CodeCell.prototype.toggle_output_scroll = function () {
326 CodeCell.prototype.toggle_output_scroll = function () {
327 this.output_area.toggle_scroll();
327 this.output_area.toggle_scroll();
328 };
328 };
329
329
330
330
331 CodeCell.input_prompt_classical = function (prompt_value, lines_number) {
331 CodeCell.input_prompt_classical = function (prompt_value, lines_number) {
332 var ns = prompt_value || "&nbsp;";
332 var ns = prompt_value || "&nbsp;";
333 return 'In&nbsp;[' + ns + ']:'
333 return 'In&nbsp;[' + ns + ']:'
334 };
334 };
335
335
336 CodeCell.input_prompt_continuation = function (prompt_value, lines_number) {
336 CodeCell.input_prompt_continuation = function (prompt_value, lines_number) {
337 var html = [CodeCell.input_prompt_classical(prompt_value, lines_number)];
337 var html = [CodeCell.input_prompt_classical(prompt_value, lines_number)];
338 for(var i=1; i < lines_number; i++){html.push(['...:'])};
338 for(var i=1; i < lines_number; i++){html.push(['...:'])};
339 return html.join('</br>')
339 return html.join('</br>')
340 };
340 };
341
341
342 CodeCell.input_prompt_function = CodeCell.input_prompt_classical;
342 CodeCell.input_prompt_function = CodeCell.input_prompt_classical;
343
343
344
344
345 CodeCell.prototype.set_input_prompt = function (number) {
345 CodeCell.prototype.set_input_prompt = function (number) {
346 var nline = 1
346 var nline = 1
347 if( this.code_mirror != undefined) {
347 if( this.code_mirror != undefined) {
348 nline = this.code_mirror.lineCount();
348 nline = this.code_mirror.lineCount();
349 }
349 }
350 this.input_prompt_number = number;
350 this.input_prompt_number = number;
351 var prompt_html = CodeCell.input_prompt_function(this.input_prompt_number, nline);
351 var prompt_html = CodeCell.input_prompt_function(this.input_prompt_number, nline);
352 this.element.find('div.input_prompt').html(prompt_html);
352 this.element.find('div.input_prompt').html(prompt_html);
353 };
353 };
354
354
355
355
356 CodeCell.prototype.clear_input = function () {
356 CodeCell.prototype.clear_input = function () {
357 this.code_mirror.setValue('');
357 this.code_mirror.setValue('');
358 };
358 };
359
359
360
360
361 CodeCell.prototype.get_text = function () {
361 CodeCell.prototype.get_text = function () {
362 return this.code_mirror.getValue();
362 return this.code_mirror.getValue();
363 };
363 };
364
364
365
365
366 CodeCell.prototype.set_text = function (code) {
366 CodeCell.prototype.set_text = function (code) {
367 return this.code_mirror.setValue(code);
367 return this.code_mirror.setValue(code);
368 };
368 };
369
369
370
370
371 CodeCell.prototype.at_top = function () {
371 CodeCell.prototype.at_top = function () {
372 var cursor = this.code_mirror.getCursor();
372 var cursor = this.code_mirror.getCursor();
373 if (cursor.line === 0 && cursor.ch === 0) {
373 if (cursor.line === 0 && cursor.ch === 0) {
374 return true;
374 return true;
375 } else {
375 } else {
376 return false;
376 return false;
377 }
377 }
378 };
378 };
379
379
380
380
381 CodeCell.prototype.at_bottom = function () {
381 CodeCell.prototype.at_bottom = function () {
382 var cursor = this.code_mirror.getCursor();
382 var cursor = this.code_mirror.getCursor();
383 if (cursor.line === (this.code_mirror.lineCount()-1) && cursor.ch === this.code_mirror.getLine(cursor.line).length) {
383 if (cursor.line === (this.code_mirror.lineCount()-1) && cursor.ch === this.code_mirror.getLine(cursor.line).length) {
384 return true;
384 return true;
385 } else {
385 } else {
386 return false;
386 return false;
387 }
387 }
388 };
388 };
389
389
390
390
391 CodeCell.prototype.clear_output = function (stdout, stderr, other) {
391 CodeCell.prototype.clear_output = function (stdout, stderr, other) {
392 this.output_area.clear_output(stdout, stderr, other);
392 this.output_area.clear_output(stdout, stderr, other);
393 };
393 };
394
394
395
395
396 // JSON serialization
396 // JSON serialization
397
397
398 CodeCell.prototype.fromJSON = function (data) {
398 CodeCell.prototype.fromJSON = function (data) {
399 IPython.Cell.prototype.fromJSON.apply(this, arguments);
399 IPython.Cell.prototype.fromJSON.apply(this, arguments);
400 if (data.cell_type === 'code') {
400 if (data.cell_type === 'code') {
401 if (data.input !== undefined) {
401 if (data.input !== undefined) {
402 this.set_text(data.input);
402 this.set_text(data.input);
403 // make this value the starting point, so that we can only undo
403 // make this value the starting point, so that we can only undo
404 // to this state, instead of a blank cell
404 // to this state, instead of a blank cell
405 this.code_mirror.clearHistory();
405 this.code_mirror.clearHistory();
406 this.auto_highlight();
406 this.auto_highlight();
407 }
407 }
408 if (data.prompt_number !== undefined) {
408 if (data.prompt_number !== undefined) {
409 this.set_input_prompt(data.prompt_number);
409 this.set_input_prompt(data.prompt_number);
410 } else {
410 } else {
411 this.set_input_prompt();
411 this.set_input_prompt();
412 };
412 };
413 this.output_area.fromJSON(data.outputs);
413 this.output_area.fromJSON(data.outputs);
414 if (data.collapsed !== undefined) {
414 if (data.collapsed !== undefined) {
415 if (data.collapsed) {
415 if (data.collapsed) {
416 this.collapse();
416 this.collapse();
417 } else {
417 } else {
418 this.expand();
418 this.expand();
419 };
419 };
420 };
420 };
421 };
421 };
422 };
422 };
423
423
424
424
425 CodeCell.prototype.toJSON = function () {
425 CodeCell.prototype.toJSON = function () {
426 var data = IPython.Cell.prototype.toJSON.apply(this);
426 var data = IPython.Cell.prototype.toJSON.apply(this);
427 data.input = this.get_text();
427 data.input = this.get_text();
428 data.cell_type = 'code';
428 data.cell_type = 'code';
429 if (this.input_prompt_number) {
429 if (this.input_prompt_number) {
430 data.prompt_number = this.input_prompt_number;
430 data.prompt_number = this.input_prompt_number;
431 };
431 };
432 var outputs = this.output_area.toJSON();
432 var outputs = this.output_area.toJSON();
433 data.outputs = outputs;
433 data.outputs = outputs;
434 data.language = 'python';
434 data.language = 'python';
435 data.collapsed = this.collapsed;
435 data.collapsed = this.collapsed;
436 return data;
436 return data;
437 };
437 };
438
438
439
439
440 IPython.CodeCell = CodeCell;
440 IPython.CodeCell = CodeCell;
441
441
442 return IPython;
442 return IPython;
443 }(IPython));
443 }(IPython));
@@ -1,366 +1,367 b''
1 //----------------------------------------------------------------------------
1 //----------------------------------------------------------------------------
2 // Copyright (C) 2008-2011 The IPython Development Team
2 // Copyright (C) 2008-2011 The IPython Development Team
3 //
3 //
4 // Distributed under the terms of the BSD License. The full license is in
4 // Distributed under the terms of the BSD License. The full license is in
5 // the file COPYING, distributed as part of this software.
5 // the file COPYING, distributed as part of this software.
6 //----------------------------------------------------------------------------
6 //----------------------------------------------------------------------------
7 //============================================================================
7 //============================================================================
8 // Tooltip
8 // Tooltip
9 //============================================================================
9 //============================================================================
10 //
10 //
11 // you can set the autocall time by setting `IPython.tooltip.time_before_tooltip` in ms
11 // you can set the autocall time by setting `IPython.tooltip.time_before_tooltip` in ms
12 //
12 //
13 // you can configure the differents action of pressing tab several times in a row by
13 // you can configure the differents action of pressing tab several times in a row by
14 // setting/appending different fonction in the array
14 // setting/appending different fonction in the array
15 // IPython.tooltip.tabs_functions
15 // IPython.tooltip.tabs_functions
16 //
16 //
17 // eg :
17 // eg :
18 // IPython.tooltip.tabs_functions[4] = function (){console.log('this is the action of the 4th tab pressing')}
18 // IPython.tooltip.tabs_functions[4] = function (){console.log('this is the action of the 4th tab pressing')}
19 //
19 //
20 var IPython = (function (IPython) {
20 var IPython = (function (IPython) {
21 "use strict";
21 "use strict";
22
22
23 var utils = IPython.utils;
23 var utils = IPython.utils;
24
24
25 // tooltip constructor
25 // tooltip constructor
26 var Tooltip = function () {
26 var Tooltip = function () {
27 var that = this;
27 var that = this;
28 this.time_before_tooltip = 1200;
28 this.time_before_tooltip = 1200;
29
29
30 // handle to html
30 // handle to html
31 this.tooltip = $('#tooltip');
31 this.tooltip = $('#tooltip');
32 this._hidden = true;
32 this._hidden = true;
33
33
34 // variable for consecutive call
34 // variable for consecutive call
35 this._old_cell = null;
35 this._old_cell = null;
36 this._old_request = null;
36 this._old_request = null;
37 this._consecutive_counter = 0;
37 this._consecutive_counter = 0;
38
38
39 // 'sticky ?'
39 // 'sticky ?'
40 this._sticky = false;
40 this._sticky = false;
41
41
42 // display tooltip if the docstring is empty?
42 // display tooltip if the docstring is empty?
43 this._hide_if_no_docstring = false;
43 this._hide_if_no_docstring = false;
44
44
45 // contain the button in the upper right corner
45 // contain the button in the upper right corner
46 this.buttons = $('<div/>').addClass('tooltipbuttons');
46 this.buttons = $('<div/>').addClass('tooltipbuttons');
47
47
48 // will contain the docstring
48 // will contain the docstring
49 this.text = $('<div/>').addClass('tooltiptext').addClass('smalltooltip');
49 this.text = $('<div/>').addClass('tooltiptext').addClass('smalltooltip');
50
50
51 // build the buttons menu on the upper right
51 // build the buttons menu on the upper right
52 // expand the tooltip to see more
52 // expand the tooltip to see more
53 var expandlink = $('<a/>').attr('href', "#").addClass("ui-corner-all") //rounded corner
53 var expandlink = $('<a/>').attr('href', "#").addClass("ui-corner-all") //rounded corner
54 .attr('role', "button").attr('id', 'expanbutton').attr('title', 'Grow the tooltip vertically (press tab 2 times)').click(function () {
54 .attr('role', "button").attr('id', 'expanbutton').attr('title', 'Grow the tooltip vertically (press tab 2 times)').click(function () {
55 that.expand()
55 that.expand()
56 }).append(
56 }).append(
57 $('<span/>').text('Expand').addClass('ui-icon').addClass('ui-icon-plus'));
57 $('<span/>').text('Expand').addClass('ui-icon').addClass('ui-icon-plus'));
58
58
59 // open in pager
59 // open in pager
60 var morelink = $('<a/>').attr('href', "#").attr('role', "button").addClass('ui-button').attr('title', 'show the current docstring in pager (press tab 4 times)');
60 var morelink = $('<a/>').attr('href', "#").attr('role', "button").addClass('ui-button').attr('title', 'show the current docstring in pager (press tab 4 times)');
61 var morespan = $('<span/>').text('Open in Pager').addClass('ui-icon').addClass('ui-icon-arrowstop-l-n');
61 var morespan = $('<span/>').text('Open in Pager').addClass('ui-icon').addClass('ui-icon-arrowstop-l-n');
62 morelink.append(morespan);
62 morelink.append(morespan);
63 morelink.click(function () {
63 morelink.click(function () {
64 that.showInPager(that._old_cell);
64 that.showInPager(that._old_cell);
65 });
65 });
66
66
67 // close the tooltip
67 // close the tooltip
68 var closelink = $('<a/>').attr('href', "#").attr('role', "button").addClass('ui-button');
68 var closelink = $('<a/>').attr('href', "#").attr('role', "button").addClass('ui-button');
69 var closespan = $('<span/>').text('Close').addClass('ui-icon').addClass('ui-icon-close');
69 var closespan = $('<span/>').text('Close').addClass('ui-icon').addClass('ui-icon-close');
70 closelink.append(closespan);
70 closelink.append(closespan);
71 closelink.click(function () {
71 closelink.click(function () {
72 that.remove_and_cancel_tooltip(true);
72 that.remove_and_cancel_tooltip(true);
73 });
73 });
74
74
75 this._clocklink = $('<a/>').attr('href', "#");
75 this._clocklink = $('<a/>').attr('href', "#");
76 this._clocklink.attr('role', "button");
76 this._clocklink.attr('role', "button");
77 this._clocklink.addClass('ui-button');
77 this._clocklink.addClass('ui-button');
78 this._clocklink.attr('title', 'Tootip is not dismissed while typing for 10 seconds');
78 this._clocklink.attr('title', 'Tootip is not dismissed while typing for 10 seconds');
79 var clockspan = $('<span/>').text('Close');
79 var clockspan = $('<span/>').text('Close');
80 clockspan.addClass('ui-icon');
80 clockspan.addClass('ui-icon');
81 clockspan.addClass('ui-icon-clock');
81 clockspan.addClass('ui-icon-clock');
82 this._clocklink.append(clockspan);
82 this._clocklink.append(clockspan);
83 this._clocklink.click(function () {
83 this._clocklink.click(function () {
84 that.cancel_stick();
84 that.cancel_stick();
85 });
85 });
86
86
87
87
88
88
89
89
90 //construct the tooltip
90 //construct the tooltip
91 // add in the reverse order you want them to appear
91 // add in the reverse order you want them to appear
92 this.buttons.append(closelink);
92 this.buttons.append(closelink);
93 this.buttons.append(expandlink);
93 this.buttons.append(expandlink);
94 this.buttons.append(morelink);
94 this.buttons.append(morelink);
95 this.buttons.append(this._clocklink);
95 this.buttons.append(this._clocklink);
96 this._clocklink.hide();
96 this._clocklink.hide();
97
97
98
98
99 // we need a phony element to make the small arrow
99 // we need a phony element to make the small arrow
100 // of the tooltip in css
100 // of the tooltip in css
101 // we will move the arrow later
101 // we will move the arrow later
102 this.arrow = $('<div/>').addClass('pretooltiparrow');
102 this.arrow = $('<div/>').addClass('pretooltiparrow');
103 this.tooltip.append(this.buttons);
103 this.tooltip.append(this.buttons);
104 this.tooltip.append(this.arrow);
104 this.tooltip.append(this.arrow);
105 this.tooltip.append(this.text);
105 this.tooltip.append(this.text);
106
106
107 // function that will be called if you press tab 1, 2, 3... times in a row
107 // function that will be called if you press tab 1, 2, 3... times in a row
108 this.tabs_functions = [function (cell, text) {
108 this.tabs_functions = [function (cell, text) {
109 that._request_tooltip(cell, text);
109 that._request_tooltip(cell, text);
110 }, function () {
110 }, function () {
111 that.expand();
111 that.expand();
112 }, function () {
112 }, function () {
113 that.stick();
113 that.stick();
114 }, function (cell) {
114 }, function (cell) {
115 that.cancel_stick();
115 that.cancel_stick();
116 that.showInPager(cell);
116 that.showInPager(cell);
117 }];
117 }];
118 // call after all the tabs function above have bee call to clean their effects
118 // call after all the tabs function above have bee call to clean their effects
119 // if necessary
119 // if necessary
120 this.reset_tabs_function = function (cell, text) {
120 this.reset_tabs_function = function (cell, text) {
121 this._old_cell = (cell) ? cell : null;
121 this._old_cell = (cell) ? cell : null;
122 this._old_request = (text) ? text : null;
122 this._old_request = (text) ? text : null;
123 this._consecutive_counter = 0;
123 this._consecutive_counter = 0;
124 }
124 }
125 };
125 };
126
126
127 Tooltip.prototype.showInPager = function (cell) {
127 Tooltip.prototype.showInPager = function (cell) {
128 // reexecute last call in pager by appending ? to show back in pager
128 // reexecute last call in pager by appending ? to show back in pager
129 var that = this;
129 var that = this;
130 var empty = function () {};
130 var empty = function () {};
131 cell.kernel.execute(
131 cell.kernel.execute(
132 that.name + '?', {
132 that.name + '?', {
133 'execute_reply': empty,
133 'execute_reply': empty,
134 'output': empty,
134 'output': empty,
135 'clear_output': empty,
135 'clear_output': empty,
136 'cell': cell
136 'cell': cell
137 }, {
137 }, {
138 'silent': false
138 'silent': false,
139 'store_history': true
139 });
140 });
140 this.remove_and_cancel_tooltip();
141 this.remove_and_cancel_tooltip();
141 }
142 }
142
143
143 // grow the tooltip verticaly
144 // grow the tooltip verticaly
144 Tooltip.prototype.expand = function () {
145 Tooltip.prototype.expand = function () {
145 this.text.removeClass('smalltooltip');
146 this.text.removeClass('smalltooltip');
146 this.text.addClass('bigtooltip');
147 this.text.addClass('bigtooltip');
147 $('#expanbutton').hide('slow');
148 $('#expanbutton').hide('slow');
148 }
149 }
149
150
150 // deal with all the logic of hiding the tooltip
151 // deal with all the logic of hiding the tooltip
151 // and reset it's status
152 // and reset it's status
152 Tooltip.prototype._hide = function () {
153 Tooltip.prototype._hide = function () {
153 this.tooltip.fadeOut('fast');
154 this.tooltip.fadeOut('fast');
154 $('#expanbutton').show('slow');
155 $('#expanbutton').show('slow');
155 this.text.removeClass('bigtooltip');
156 this.text.removeClass('bigtooltip');
156 this.text.addClass('smalltooltip');
157 this.text.addClass('smalltooltip');
157 // keep scroll top to be sure to always see the first line
158 // keep scroll top to be sure to always see the first line
158 this.text.scrollTop(0);
159 this.text.scrollTop(0);
159 this._hidden = true;
160 this._hidden = true;
160 this.code_mirror = null;
161 this.code_mirror = null;
161 }
162 }
162
163
163 Tooltip.prototype.remove_and_cancel_tooltip = function (force) {
164 Tooltip.prototype.remove_and_cancel_tooltip = function (force) {
164 // note that we don't handle closing directly inside the calltip
165 // note that we don't handle closing directly inside the calltip
165 // as in the completer, because it is not focusable, so won't
166 // as in the completer, because it is not focusable, so won't
166 // get the event.
167 // get the event.
167 if (this._sticky == false || force == true) {
168 if (this._sticky == false || force == true) {
168 this.cancel_stick();
169 this.cancel_stick();
169 this._hide();
170 this._hide();
170 }
171 }
171 this.cancel_pending();
172 this.cancel_pending();
172 this.reset_tabs_function();
173 this.reset_tabs_function();
173 }
174 }
174
175
175 // cancel autocall done after '(' for example.
176 // cancel autocall done after '(' for example.
176 Tooltip.prototype.cancel_pending = function () {
177 Tooltip.prototype.cancel_pending = function () {
177 if (this._tooltip_timeout != null) {
178 if (this._tooltip_timeout != null) {
178 clearTimeout(this._tooltip_timeout);
179 clearTimeout(this._tooltip_timeout);
179 this._tooltip_timeout = null;
180 this._tooltip_timeout = null;
180 }
181 }
181 }
182 }
182
183
183 // will trigger tooltip after timeout
184 // will trigger tooltip after timeout
184 Tooltip.prototype.pending = function (cell, hide_if_no_docstring) {
185 Tooltip.prototype.pending = function (cell, hide_if_no_docstring) {
185 var that = this;
186 var that = this;
186 this._tooltip_timeout = setTimeout(function () {
187 this._tooltip_timeout = setTimeout(function () {
187 that.request(cell, hide_if_no_docstring)
188 that.request(cell, hide_if_no_docstring)
188 }, that.time_before_tooltip);
189 }, that.time_before_tooltip);
189 }
190 }
190
191
191 Tooltip.prototype._request_tooltip = function (cell, func) {
192 Tooltip.prototype._request_tooltip = function (cell, func) {
192 // use internally just to make the request to the kernel
193 // use internally just to make the request to the kernel
193 // Feel free to shorten this logic if you are better
194 // Feel free to shorten this logic if you are better
194 // than me in regEx
195 // than me in regEx
195 // basicaly you shoul be able to get xxx.xxx.xxx from
196 // basicaly you shoul be able to get xxx.xxx.xxx from
196 // something(range(10), kwarg=smth) ; xxx.xxx.xxx( firstarg, rand(234,23), kwarg1=2,
197 // something(range(10), kwarg=smth) ; xxx.xxx.xxx( firstarg, rand(234,23), kwarg1=2,
197 // remove everything between matchin bracket (need to iterate)
198 // remove everything between matchin bracket (need to iterate)
198 var matchBracket = /\([^\(\)]+\)/g;
199 var matchBracket = /\([^\(\)]+\)/g;
199 var endBracket = /\([^\(]*$/g;
200 var endBracket = /\([^\(]*$/g;
200 var oldfunc = func;
201 var oldfunc = func;
201
202
202 func = func.replace(matchBracket, "");
203 func = func.replace(matchBracket, "");
203 while (oldfunc != func) {
204 while (oldfunc != func) {
204 oldfunc = func;
205 oldfunc = func;
205 func = func.replace(matchBracket, "");
206 func = func.replace(matchBracket, "");
206 }
207 }
207 // remove everything after last open bracket
208 // remove everything after last open bracket
208 func = func.replace(endBracket, "");
209 func = func.replace(endBracket, "");
209
210
210 var re = /[a-z_][0-9a-z._]+$/gi; // casse insensitive
211 var re = /[a-z_][0-9a-z._]+$/gi; // casse insensitive
211 var callbacks = {
212 var callbacks = {
212 'object_info_reply': $.proxy(this._show, this)
213 'object_info_reply': $.proxy(this._show, this)
213 }
214 }
214 var msg_id = cell.kernel.object_info_request(re.exec(func), callbacks);
215 var msg_id = cell.kernel.object_info_request(re.exec(func), callbacks);
215 }
216 }
216
217
217 // make an imediate completion request
218 // make an imediate completion request
218 Tooltip.prototype.request = function (cell, hide_if_no_docstring) {
219 Tooltip.prototype.request = function (cell, hide_if_no_docstring) {
219 // request(codecell)
220 // request(codecell)
220 // Deal with extracting the text from the cell and counting
221 // Deal with extracting the text from the cell and counting
221 // call in a row
222 // call in a row
222 this.cancel_pending();
223 this.cancel_pending();
223 var editor = cell.code_mirror;
224 var editor = cell.code_mirror;
224 var cursor = editor.getCursor();
225 var cursor = editor.getCursor();
225 var text = editor.getRange({
226 var text = editor.getRange({
226 line: cursor.line,
227 line: cursor.line,
227 ch: 0
228 ch: 0
228 }, cursor).trim();
229 }, cursor).trim();
229
230
230 this._hide_if_no_docstring = hide_if_no_docstring;
231 this._hide_if_no_docstring = hide_if_no_docstring;
231
232
232 if(editor.somethingSelected()){
233 if(editor.somethingSelected()){
233 text = editor.getSelection();
234 text = editor.getSelection();
234 }
235 }
235
236
236 // need a permanent handel to code_mirror for future auto recall
237 // need a permanent handel to code_mirror for future auto recall
237 this.code_mirror = editor;
238 this.code_mirror = editor;
238
239
239 // now we treat the different number of keypress
240 // now we treat the different number of keypress
240 // first if same cell, same text, increment counter by 1
241 // first if same cell, same text, increment counter by 1
241 if (this._old_cell == cell && this._old_request == text && this._hidden == false) {
242 if (this._old_cell == cell && this._old_request == text && this._hidden == false) {
242 this._consecutive_counter++;
243 this._consecutive_counter++;
243 } else {
244 } else {
244 // else reset
245 // else reset
245 this.cancel_stick();
246 this.cancel_stick();
246 this.reset_tabs_function (cell, text);
247 this.reset_tabs_function (cell, text);
247 }
248 }
248
249
249 // don't do anything if line beggin with '(' or is empty
250 // don't do anything if line beggin with '(' or is empty
250 if (text === "" || text === "(") {
251 if (text === "" || text === "(") {
251 return;
252 return;
252 }
253 }
253
254
254 this.tabs_functions[this._consecutive_counter](cell, text);
255 this.tabs_functions[this._consecutive_counter](cell, text);
255
256
256 // then if we are at the end of list function, reset
257 // then if we are at the end of list function, reset
257 if (this._consecutive_counter == this.tabs_functions.length) this.reset_tabs_function (cell, text);
258 if (this._consecutive_counter == this.tabs_functions.length) this.reset_tabs_function (cell, text);
258
259
259 return;
260 return;
260 }
261 }
261
262
262 // cancel the option of having the tooltip to stick
263 // cancel the option of having the tooltip to stick
263 Tooltip.prototype.cancel_stick = function () {
264 Tooltip.prototype.cancel_stick = function () {
264 clearTimeout(this._stick_timeout);
265 clearTimeout(this._stick_timeout);
265 this._stick_timeout = null;
266 this._stick_timeout = null;
266 this._clocklink.hide('slow');
267 this._clocklink.hide('slow');
267 this._sticky = false;
268 this._sticky = false;
268 }
269 }
269
270
270 // put the tooltip in a sicky state for 10 seconds
271 // put the tooltip in a sicky state for 10 seconds
271 // it won't be removed by remove_and_cancell() unless you called with
272 // it won't be removed by remove_and_cancell() unless you called with
272 // the first parameter set to true.
273 // the first parameter set to true.
273 // remove_and_cancell_tooltip(true)
274 // remove_and_cancell_tooltip(true)
274 Tooltip.prototype.stick = function (time) {
275 Tooltip.prototype.stick = function (time) {
275 time = (time != undefined) ? time : 10;
276 time = (time != undefined) ? time : 10;
276 var that = this;
277 var that = this;
277 this._sticky = true;
278 this._sticky = true;
278 this._clocklink.show('slow');
279 this._clocklink.show('slow');
279 this._stick_timeout = setTimeout(function () {
280 this._stick_timeout = setTimeout(function () {
280 that._sticky = false;
281 that._sticky = false;
281 that._clocklink.hide('slow');
282 that._clocklink.hide('slow');
282 }, time * 1000);
283 }, time * 1000);
283 }
284 }
284
285
285 // should be called with the kernel reply to actually show the tooltip
286 // should be called with the kernel reply to actually show the tooltip
286 Tooltip.prototype._show = function (reply) {
287 Tooltip.prototype._show = function (reply) {
287 // move the bubble if it is not hidden
288 // move the bubble if it is not hidden
288 // otherwise fade it
289 // otherwise fade it
289 this.name = reply.name;
290 this.name = reply.name;
290
291
291 // do some math to have the tooltip arrow on more or less on left or right
292 // do some math to have the tooltip arrow on more or less on left or right
292 // width of the editor
293 // width of the editor
293 var w = $(this.code_mirror.getScrollerElement()).width();
294 var w = $(this.code_mirror.getScrollerElement()).width();
294 // ofset of the editor
295 // ofset of the editor
295 var o = $(this.code_mirror.getScrollerElement()).offset();
296 var o = $(this.code_mirror.getScrollerElement()).offset();
296
297
297 // whatever anchor/head order but arrow at mid x selection
298 // whatever anchor/head order but arrow at mid x selection
298 var anchor = this.code_mirror.cursorCoords(false);
299 var anchor = this.code_mirror.cursorCoords(false);
299 var head = this.code_mirror.cursorCoords(true);
300 var head = this.code_mirror.cursorCoords(true);
300 var xinit = (head.left+anchor.left)/2;
301 var xinit = (head.left+anchor.left)/2;
301 var xinter = o.left + (xinit - o.left) / w * (w - 450);
302 var xinter = o.left + (xinit - o.left) / w * (w - 450);
302 var posarrowleft = xinit - xinter;
303 var posarrowleft = xinit - xinter;
303
304
304 if (this._hidden == false) {
305 if (this._hidden == false) {
305 this.tooltip.animate({
306 this.tooltip.animate({
306 'left': xinter - 30 + 'px',
307 'left': xinter - 30 + 'px',
307 'top': (head.bottom + 10) + 'px'
308 'top': (head.bottom + 10) + 'px'
308 });
309 });
309 } else {
310 } else {
310 this.tooltip.css({
311 this.tooltip.css({
311 'left': xinter - 30 + 'px'
312 'left': xinter - 30 + 'px'
312 });
313 });
313 this.tooltip.css({
314 this.tooltip.css({
314 'top': (head.bottom + 10) + 'px'
315 'top': (head.bottom + 10) + 'px'
315 });
316 });
316 }
317 }
317 this.arrow.animate({
318 this.arrow.animate({
318 'left': posarrowleft + 'px'
319 'left': posarrowleft + 'px'
319 });
320 });
320
321
321 // build docstring
322 // build docstring
322 var defstring = reply.call_def;
323 var defstring = reply.call_def;
323 if (defstring == null) {
324 if (defstring == null) {
324 defstring = reply.init_definition;
325 defstring = reply.init_definition;
325 }
326 }
326 if (defstring == null) {
327 if (defstring == null) {
327 defstring = reply.definition;
328 defstring = reply.definition;
328 }
329 }
329
330
330 var docstring = reply.call_docstring;
331 var docstring = reply.call_docstring;
331 if (docstring == null) {
332 if (docstring == null) {
332 docstring = reply.init_docstring;
333 docstring = reply.init_docstring;
333 }
334 }
334 if (docstring == null) {
335 if (docstring == null) {
335 docstring = reply.docstring;
336 docstring = reply.docstring;
336 }
337 }
337
338
338 if (docstring == null) {
339 if (docstring == null) {
339 // For reals this time, no docstring
340 // For reals this time, no docstring
340 if (this._hide_if_no_docstring) {
341 if (this._hide_if_no_docstring) {
341 return;
342 return;
342 } else {
343 } else {
343 docstring = "<empty docstring>";
344 docstring = "<empty docstring>";
344 }
345 }
345 }
346 }
346
347
347 this.tooltip.fadeIn('fast');
348 this.tooltip.fadeIn('fast');
348 this._hidden = false;
349 this._hidden = false;
349 this.text.children().remove();
350 this.text.children().remove();
350
351
351 var pre = $('<pre/>').html(utils.fixConsole(docstring));
352 var pre = $('<pre/>').html(utils.fixConsole(docstring));
352 if (defstring) {
353 if (defstring) {
353 var defstring_html = $('<pre/>').html(utils.fixConsole(defstring));
354 var defstring_html = $('<pre/>').html(utils.fixConsole(defstring));
354 this.text.append(defstring_html);
355 this.text.append(defstring_html);
355 }
356 }
356 this.text.append(pre);
357 this.text.append(pre);
357 // keep scroll top to be sure to always see the first line
358 // keep scroll top to be sure to always see the first line
358 this.text.scrollTop(0);
359 this.text.scrollTop(0);
359 }
360 }
360
361
361
362
362 IPython.Tooltip = Tooltip;
363 IPython.Tooltip = Tooltip;
363
364
364 return IPython;
365 return IPython;
365
366
366 }(IPython));
367 }(IPython));
@@ -1,501 +1,502 b''
1 //----------------------------------------------------------------------------
1 //----------------------------------------------------------------------------
2 // Copyright (C) 2008-2011 The IPython Development Team
2 // Copyright (C) 2008-2011 The IPython Development Team
3 //
3 //
4 // Distributed under the terms of the BSD License. The full license is in
4 // Distributed under the terms of the BSD License. The full license is in
5 // the file COPYING, distributed as part of this software.
5 // the file COPYING, distributed as part of this software.
6 //----------------------------------------------------------------------------
6 //----------------------------------------------------------------------------
7
7
8 //============================================================================
8 //============================================================================
9 // Kernel
9 // Kernel
10 //============================================================================
10 //============================================================================
11
11
12 /**
12 /**
13 * @module IPython
13 * @module IPython
14 * @namespace IPython
14 * @namespace IPython
15 * @submodule Kernel
15 * @submodule Kernel
16 */
16 */
17
17
18 var IPython = (function (IPython) {
18 var IPython = (function (IPython) {
19
19
20 var utils = IPython.utils;
20 var utils = IPython.utils;
21
21
22 // Initialization and connection.
22 // Initialization and connection.
23 /**
23 /**
24 * A Kernel Class to communicate with the Python kernel
24 * A Kernel Class to communicate with the Python kernel
25 * @Class Kernel
25 * @Class Kernel
26 */
26 */
27 var Kernel = function (base_url) {
27 var Kernel = function (base_url) {
28 this.kernel_id = null;
28 this.kernel_id = null;
29 this.shell_channel = null;
29 this.shell_channel = null;
30 this.iopub_channel = null;
30 this.iopub_channel = null;
31 this.stdin_channel = null;
31 this.stdin_channel = null;
32 this.base_url = base_url;
32 this.base_url = base_url;
33 this.running = false;
33 this.running = false;
34 this.username = "username";
34 this.username = "username";
35 this.session_id = utils.uuid();
35 this.session_id = utils.uuid();
36 this._msg_callbacks = {};
36 this._msg_callbacks = {};
37
37
38 if (typeof(WebSocket) !== 'undefined') {
38 if (typeof(WebSocket) !== 'undefined') {
39 this.WebSocket = WebSocket;
39 this.WebSocket = WebSocket;
40 } else if (typeof(MozWebSocket) !== 'undefined') {
40 } else if (typeof(MozWebSocket) !== 'undefined') {
41 this.WebSocket = MozWebSocket;
41 this.WebSocket = MozWebSocket;
42 } else {
42 } else {
43 alert('Your browser does not have WebSocket support, please try Chrome, Safari or Firefox β‰₯ 6. Firefox 4 and 5 are also supported by you have to enable WebSockets in about:config.');
43 alert('Your browser does not have WebSocket support, please try Chrome, Safari or Firefox β‰₯ 6. Firefox 4 and 5 are also supported by you have to enable WebSockets in about:config.');
44 };
44 };
45 this.bind_events();
45 this.bind_events();
46 };
46 };
47
47
48
48
49 Kernel.prototype._get_msg = function (msg_type, content) {
49 Kernel.prototype._get_msg = function (msg_type, content) {
50 var msg = {
50 var msg = {
51 header : {
51 header : {
52 msg_id : utils.uuid(),
52 msg_id : utils.uuid(),
53 username : this.username,
53 username : this.username,
54 session : this.session_id,
54 session : this.session_id,
55 msg_type : msg_type
55 msg_type : msg_type
56 },
56 },
57 metadata : {},
57 metadata : {},
58 content : content,
58 content : content,
59 parent_header : {}
59 parent_header : {}
60 };
60 };
61 return msg;
61 return msg;
62 };
62 };
63
63
64 Kernel.prototype.bind_events = function() {
64 Kernel.prototype.bind_events = function() {
65 var that = this;
65 var that = this;
66 $([IPython.events]).on('send_input_reply.Kernel', function(evt, data) {
66 $([IPython.events]).on('send_input_reply.Kernel', function(evt, data) {
67 that.send_input_reply(data);
67 that.send_input_reply(data);
68 });
68 });
69 }
69 }
70
70
71 /**
71 /**
72 * Start the Python kernel
72 * Start the Python kernel
73 * @method start
73 * @method start
74 */
74 */
75 Kernel.prototype.start = function (notebook_id) {
75 Kernel.prototype.start = function (notebook_id) {
76 var that = this;
76 var that = this;
77 if (!this.running) {
77 if (!this.running) {
78 var qs = $.param({notebook:notebook_id});
78 var qs = $.param({notebook:notebook_id});
79 var url = this.base_url + '?' + qs;
79 var url = this.base_url + '?' + qs;
80 $.post(url,
80 $.post(url,
81 $.proxy(that._kernel_started,that),
81 $.proxy(that._kernel_started,that),
82 'json'
82 'json'
83 );
83 );
84 };
84 };
85 };
85 };
86
86
87 /**
87 /**
88 * Restart the python kernel.
88 * Restart the python kernel.
89 *
89 *
90 * Emit a 'status_restarting.Kernel' event with
90 * Emit a 'status_restarting.Kernel' event with
91 * the current object as parameter
91 * the current object as parameter
92 *
92 *
93 * @method restart
93 * @method restart
94 */
94 */
95 Kernel.prototype.restart = function () {
95 Kernel.prototype.restart = function () {
96 $([IPython.events]).trigger('status_restarting.Kernel', {kernel: this});
96 $([IPython.events]).trigger('status_restarting.Kernel', {kernel: this});
97 var that = this;
97 var that = this;
98 if (this.running) {
98 if (this.running) {
99 this.stop_channels();
99 this.stop_channels();
100 var url = this.kernel_url + "/restart";
100 var url = this.kernel_url + "/restart";
101 $.post(url,
101 $.post(url,
102 $.proxy(that._kernel_started, that),
102 $.proxy(that._kernel_started, that),
103 'json'
103 'json'
104 );
104 );
105 };
105 };
106 };
106 };
107
107
108
108
109 Kernel.prototype._kernel_started = function (json) {
109 Kernel.prototype._kernel_started = function (json) {
110 console.log("Kernel started: ", json.kernel_id);
110 console.log("Kernel started: ", json.kernel_id);
111 this.running = true;
111 this.running = true;
112 this.kernel_id = json.kernel_id;
112 this.kernel_id = json.kernel_id;
113 var ws_url = json.ws_url;
113 var ws_url = json.ws_url;
114 if (ws_url.match(/wss?:\/\//) == null) {
114 if (ws_url.match(/wss?:\/\//) == null) {
115 // trailing 's' in https will become wss for secure web sockets
115 // trailing 's' in https will become wss for secure web sockets
116 prot = location.protocol.replace('http', 'ws') + "//";
116 prot = location.protocol.replace('http', 'ws') + "//";
117 ws_url = prot + location.host + ws_url;
117 ws_url = prot + location.host + ws_url;
118 };
118 };
119 this.ws_url = ws_url;
119 this.ws_url = ws_url;
120 this.kernel_url = this.base_url + "/" + this.kernel_id;
120 this.kernel_url = this.base_url + "/" + this.kernel_id;
121 this.start_channels();
121 this.start_channels();
122 $([IPython.events]).trigger('status_started.Kernel', {kernel: this});
122 $([IPython.events]).trigger('status_started.Kernel', {kernel: this});
123 };
123 };
124
124
125
125
126 Kernel.prototype._websocket_closed = function(ws_url, early) {
126 Kernel.prototype._websocket_closed = function(ws_url, early) {
127 this.stop_channels();
127 this.stop_channels();
128 $([IPython.events]).trigger('websocket_closed.Kernel',
128 $([IPython.events]).trigger('websocket_closed.Kernel',
129 {ws_url: ws_url, kernel: this, early: early}
129 {ws_url: ws_url, kernel: this, early: early}
130 );
130 );
131 };
131 };
132
132
133 /**
133 /**
134 * Start the `shell`and `iopub` channels.
134 * Start the `shell`and `iopub` channels.
135 * Will stop and restart them if they already exist.
135 * Will stop and restart them if they already exist.
136 *
136 *
137 * @method start_channels
137 * @method start_channels
138 */
138 */
139 Kernel.prototype.start_channels = function () {
139 Kernel.prototype.start_channels = function () {
140 var that = this;
140 var that = this;
141 this.stop_channels();
141 this.stop_channels();
142 var ws_url = this.ws_url + this.kernel_url;
142 var ws_url = this.ws_url + this.kernel_url;
143 console.log("Starting WebSockets:", ws_url);
143 console.log("Starting WebSockets:", ws_url);
144 this.shell_channel = new this.WebSocket(ws_url + "/shell");
144 this.shell_channel = new this.WebSocket(ws_url + "/shell");
145 this.stdin_channel = new this.WebSocket(ws_url + "/stdin");
145 this.stdin_channel = new this.WebSocket(ws_url + "/stdin");
146 this.iopub_channel = new this.WebSocket(ws_url + "/iopub");
146 this.iopub_channel = new this.WebSocket(ws_url + "/iopub");
147 send_cookie = function(){
147 send_cookie = function(){
148 // send the session id so the Session object Python-side
148 // send the session id so the Session object Python-side
149 // has the same identity
149 // has the same identity
150 this.send(that.session_id + ':' + document.cookie);
150 this.send(that.session_id + ':' + document.cookie);
151 };
151 };
152 var already_called_onclose = false; // only alert once
152 var already_called_onclose = false; // only alert once
153 var ws_closed_early = function(evt){
153 var ws_closed_early = function(evt){
154 if (already_called_onclose){
154 if (already_called_onclose){
155 return;
155 return;
156 }
156 }
157 already_called_onclose = true;
157 already_called_onclose = true;
158 if ( ! evt.wasClean ){
158 if ( ! evt.wasClean ){
159 that._websocket_closed(ws_url, true);
159 that._websocket_closed(ws_url, true);
160 }
160 }
161 };
161 };
162 var ws_closed_late = function(evt){
162 var ws_closed_late = function(evt){
163 if (already_called_onclose){
163 if (already_called_onclose){
164 return;
164 return;
165 }
165 }
166 already_called_onclose = true;
166 already_called_onclose = true;
167 if ( ! evt.wasClean ){
167 if ( ! evt.wasClean ){
168 that._websocket_closed(ws_url, false);
168 that._websocket_closed(ws_url, false);
169 }
169 }
170 };
170 };
171 var channels = [this.shell_channel, this.iopub_channel, this.stdin_channel];
171 var channels = [this.shell_channel, this.iopub_channel, this.stdin_channel];
172 for (var i=0; i < channels.length; i++) {
172 for (var i=0; i < channels.length; i++) {
173 channels[i].onopen = send_cookie;
173 channels[i].onopen = send_cookie;
174 channels[i].onclose = ws_closed_early;
174 channels[i].onclose = ws_closed_early;
175 }
175 }
176 // switch from early-close to late-close message after 1s
176 // switch from early-close to late-close message after 1s
177 setTimeout(function() {
177 setTimeout(function() {
178 for (var i=0; i < channels.length; i++) {
178 for (var i=0; i < channels.length; i++) {
179 if (channels[i] !== null) {
179 if (channels[i] !== null) {
180 channels[i].onclose = ws_closed_late;
180 channels[i].onclose = ws_closed_late;
181 }
181 }
182 }
182 }
183 }, 1000);
183 }, 1000);
184 this.shell_channel.onmessage = $.proxy(this._handle_shell_reply, this);
184 this.shell_channel.onmessage = $.proxy(this._handle_shell_reply, this);
185 this.iopub_channel.onmessage = $.proxy(this._handle_iopub_reply, this);
185 this.iopub_channel.onmessage = $.proxy(this._handle_iopub_reply, this);
186 this.stdin_channel.onmessage = $.proxy(this._handle_input_request, this);
186 this.stdin_channel.onmessage = $.proxy(this._handle_input_request, this);
187 };
187 };
188
188
189 /**
189 /**
190 * Start the `shell`and `iopub` channels.
190 * Start the `shell`and `iopub` channels.
191 * @method stop_channels
191 * @method stop_channels
192 */
192 */
193 Kernel.prototype.stop_channels = function () {
193 Kernel.prototype.stop_channels = function () {
194 var channels = [this.shell_channel, this.iopub_channel, this.stdin_channel];
194 var channels = [this.shell_channel, this.iopub_channel, this.stdin_channel];
195 for (var i=0; i < channels.length; i++) {
195 for (var i=0; i < channels.length; i++) {
196 if ( channels[i] !== null ) {
196 if ( channels[i] !== null ) {
197 channels[i].onclose = function (evt) {};
197 channels[i].onclose = function (evt) {};
198 channels[i].close();
198 channels[i].close();
199 }
199 }
200 };
200 };
201 this.shell_channel = this.iopub_channel = this.stdin_channel = null;
201 this.shell_channel = this.iopub_channel = this.stdin_channel = null;
202 };
202 };
203
203
204 // Main public methods.
204 // Main public methods.
205
205
206 /**
206 /**
207 * Get info on object asynchronoulsy
207 * Get info on object asynchronoulsy
208 *
208 *
209 * @async
209 * @async
210 * @param objname {string}
210 * @param objname {string}
211 * @param callback {dict}
211 * @param callback {dict}
212 * @method object_info_request
212 * @method object_info_request
213 *
213 *
214 * @example
214 * @example
215 *
215 *
216 * When calling this method pass a callbacks structure of the form:
216 * When calling this method pass a callbacks structure of the form:
217 *
217 *
218 * callbacks = {
218 * callbacks = {
219 * 'object_info_reply': object_info_reply_callback
219 * 'object_info_reply': object_info_reply_callback
220 * }
220 * }
221 *
221 *
222 * The `object_info_reply_callback` will be passed the content object of the
222 * The `object_info_reply_callback` will be passed the content object of the
223 *
223 *
224 * `object_into_reply` message documented in
224 * `object_into_reply` message documented in
225 * [IPython dev documentation](http://ipython.org/ipython-doc/dev/development/messaging.html#object-information)
225 * [IPython dev documentation](http://ipython.org/ipython-doc/dev/development/messaging.html#object-information)
226 */
226 */
227 Kernel.prototype.object_info_request = function (objname, callbacks) {
227 Kernel.prototype.object_info_request = function (objname, callbacks) {
228 if(typeof(objname)!=null && objname!=null)
228 if(typeof(objname)!=null && objname!=null)
229 {
229 {
230 var content = {
230 var content = {
231 oname : objname.toString(),
231 oname : objname.toString(),
232 detail_level : 0,
232 detail_level : 0,
233 };
233 };
234 var msg = this._get_msg("object_info_request", content);
234 var msg = this._get_msg("object_info_request", content);
235 this.shell_channel.send(JSON.stringify(msg));
235 this.shell_channel.send(JSON.stringify(msg));
236 this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
236 this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
237 return msg.header.msg_id;
237 return msg.header.msg_id;
238 }
238 }
239 return;
239 return;
240 }
240 }
241
241
242 /**
242 /**
243 * Execute given code into kernel, and pass result to callback.
243 * Execute given code into kernel, and pass result to callback.
244 *
244 *
245 * TODO: document input_request in callbacks
245 * TODO: document input_request in callbacks
246 *
246 *
247 * @async
247 * @async
248 * @method execute
248 * @method execute
249 * @param {string} code
249 * @param {string} code
250 * @param [callbacks] {Object} With the optional following keys
250 * @param [callbacks] {Object} With the optional following keys
251 * @param callbacks.'execute_reply' {function}
251 * @param callbacks.'execute_reply' {function}
252 * @param callbacks.'output' {function}
252 * @param callbacks.'output' {function}
253 * @param callbacks.'clear_output' {function}
253 * @param callbacks.'clear_output' {function}
254 * @param callbacks.'set_next_input' {function}
254 * @param callbacks.'set_next_input' {function}
255 * @param {object} [options]
255 * @param {object} [options]
256 * @param [options.silent=false] {Boolean}
256 * @param [options.silent=false] {Boolean}
257 * @param [options.user_expressions=empty_dict] {Dict}
257 * @param [options.user_expressions=empty_dict] {Dict}
258 * @param [options.user_variables=empty_list] {List od Strings}
258 * @param [options.user_variables=empty_list] {List od Strings}
259 * @param [options.allow_stdin=false] {Boolean} true|false
259 * @param [options.allow_stdin=false] {Boolean} true|false
260 *
260 *
261 * @example
261 * @example
262 *
262 *
263 * The options object should contain the options for the execute call. Its default
263 * The options object should contain the options for the execute call. Its default
264 * values are:
264 * values are:
265 *
265 *
266 * options = {
266 * options = {
267 * silent : true,
267 * silent : true,
268 * user_variables : [],
268 * user_variables : [],
269 * user_expressions : {},
269 * user_expressions : {},
270 * allow_stdin : false
270 * allow_stdin : false
271 * }
271 * }
272 *
272 *
273 * When calling this method pass a callbacks structure of the form:
273 * When calling this method pass a callbacks structure of the form:
274 *
274 *
275 * callbacks = {
275 * callbacks = {
276 * 'execute_reply': execute_reply_callback,
276 * 'execute_reply': execute_reply_callback,
277 * 'output': output_callback,
277 * 'output': output_callback,
278 * 'clear_output': clear_output_callback,
278 * 'clear_output': clear_output_callback,
279 * 'set_next_input': set_next_input_callback
279 * 'set_next_input': set_next_input_callback
280 * }
280 * }
281 *
281 *
282 * The `execute_reply_callback` will be passed the content and metadata
282 * The `execute_reply_callback` will be passed the content and metadata
283 * objects of the `execute_reply` message documented
283 * objects of the `execute_reply` message documented
284 * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#execute)
284 * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#execute)
285 *
285 *
286 * The `output_callback` will be passed `msg_type` ('stream','display_data','pyout','pyerr')
286 * The `output_callback` will be passed `msg_type` ('stream','display_data','pyout','pyerr')
287 * of the output and the content and metadata objects of the PUB/SUB channel that contains the
287 * of the output and the content and metadata objects of the PUB/SUB channel that contains the
288 * output:
288 * output:
289 *
289 *
290 * http://ipython.org/ipython-doc/dev/development/messaging.html#messages-on-the-pub-sub-socket
290 * http://ipython.org/ipython-doc/dev/development/messaging.html#messages-on-the-pub-sub-socket
291 *
291 *
292 * The `clear_output_callback` will be passed a content object that contains
292 * The `clear_output_callback` will be passed a content object that contains
293 * stdout, stderr and other fields that are booleans, as well as the metadata object.
293 * stdout, stderr and other fields that are booleans, as well as the metadata object.
294 *
294 *
295 * The `set_next_input_callback` will be passed the text that should become the next
295 * The `set_next_input_callback` will be passed the text that should become the next
296 * input cell.
296 * input cell.
297 */
297 */
298 Kernel.prototype.execute = function (code, callbacks, options) {
298 Kernel.prototype.execute = function (code, callbacks, options) {
299
299
300 var content = {
300 var content = {
301 code : code,
301 code : code,
302 silent : true,
302 silent : true,
303 store_history : false,
303 user_variables : [],
304 user_variables : [],
304 user_expressions : {},
305 user_expressions : {},
305 allow_stdin : false
306 allow_stdin : false
306 };
307 };
307 callbacks = callbacks || {};
308 callbacks = callbacks || {};
308 if (callbacks.input_request !== undefined) {
309 if (callbacks.input_request !== undefined) {
309 content.allow_stdin = true;
310 content.allow_stdin = true;
310 }
311 }
311 $.extend(true, content, options)
312 $.extend(true, content, options)
312 $([IPython.events]).trigger('execution_request.Kernel', {kernel: this, content:content});
313 $([IPython.events]).trigger('execution_request.Kernel', {kernel: this, content:content});
313 var msg = this._get_msg("execute_request", content);
314 var msg = this._get_msg("execute_request", content);
314 this.shell_channel.send(JSON.stringify(msg));
315 this.shell_channel.send(JSON.stringify(msg));
315 this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
316 this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
316 return msg.header.msg_id;
317 return msg.header.msg_id;
317 };
318 };
318
319
319 /**
320 /**
320 * When calling this method pass a callbacks structure of the form:
321 * When calling this method pass a callbacks structure of the form:
321 *
322 *
322 * callbacks = {
323 * callbacks = {
323 * 'complete_reply': complete_reply_callback
324 * 'complete_reply': complete_reply_callback
324 * }
325 * }
325 *
326 *
326 * The `complete_reply_callback` will be passed the content object of the
327 * The `complete_reply_callback` will be passed the content object of the
327 * `complete_reply` message documented
328 * `complete_reply` message documented
328 * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#complete)
329 * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#complete)
329 *
330 *
330 * @method complete
331 * @method complete
331 * @param line {integer}
332 * @param line {integer}
332 * @param cursor_pos {integer}
333 * @param cursor_pos {integer}
333 * @param {dict} callbacks
334 * @param {dict} callbacks
334 * @param callbacks.complete_reply {function} `complete_reply_callback`
335 * @param callbacks.complete_reply {function} `complete_reply_callback`
335 *
336 *
336 */
337 */
337 Kernel.prototype.complete = function (line, cursor_pos, callbacks) {
338 Kernel.prototype.complete = function (line, cursor_pos, callbacks) {
338 callbacks = callbacks || {};
339 callbacks = callbacks || {};
339 var content = {
340 var content = {
340 text : '',
341 text : '',
341 line : line,
342 line : line,
342 block : null,
343 block : null,
343 cursor_pos : cursor_pos
344 cursor_pos : cursor_pos
344 };
345 };
345 var msg = this._get_msg("complete_request", content);
346 var msg = this._get_msg("complete_request", content);
346 this.shell_channel.send(JSON.stringify(msg));
347 this.shell_channel.send(JSON.stringify(msg));
347 this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
348 this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
348 return msg.header.msg_id;
349 return msg.header.msg_id;
349 };
350 };
350
351
351
352
352 Kernel.prototype.interrupt = function () {
353 Kernel.prototype.interrupt = function () {
353 if (this.running) {
354 if (this.running) {
354 $([IPython.events]).trigger('status_interrupting.Kernel', {kernel: this});
355 $([IPython.events]).trigger('status_interrupting.Kernel', {kernel: this});
355 $.post(this.kernel_url + "/interrupt");
356 $.post(this.kernel_url + "/interrupt");
356 };
357 };
357 };
358 };
358
359
359
360
360 Kernel.prototype.kill = function () {
361 Kernel.prototype.kill = function () {
361 if (this.running) {
362 if (this.running) {
362 this.running = false;
363 this.running = false;
363 var settings = {
364 var settings = {
364 cache : false,
365 cache : false,
365 type : "DELETE"
366 type : "DELETE"
366 };
367 };
367 $.ajax(this.kernel_url, settings);
368 $.ajax(this.kernel_url, settings);
368 };
369 };
369 };
370 };
370
371
371 Kernel.prototype.send_input_reply = function (input) {
372 Kernel.prototype.send_input_reply = function (input) {
372 var content = {
373 var content = {
373 value : input,
374 value : input,
374 };
375 };
375 $([IPython.events]).trigger('input_reply.Kernel', {kernel: this, content:content});
376 $([IPython.events]).trigger('input_reply.Kernel', {kernel: this, content:content});
376 var msg = this._get_msg("input_reply", content);
377 var msg = this._get_msg("input_reply", content);
377 this.stdin_channel.send(JSON.stringify(msg));
378 this.stdin_channel.send(JSON.stringify(msg));
378 return msg.header.msg_id;
379 return msg.header.msg_id;
379 };
380 };
380
381
381
382
382 // Reply handlers
383 // Reply handlers
383
384
384 Kernel.prototype.get_callbacks_for_msg = function (msg_id) {
385 Kernel.prototype.get_callbacks_for_msg = function (msg_id) {
385 var callbacks = this._msg_callbacks[msg_id];
386 var callbacks = this._msg_callbacks[msg_id];
386 return callbacks;
387 return callbacks;
387 };
388 };
388
389
389
390
390 Kernel.prototype.set_callbacks_for_msg = function (msg_id, callbacks) {
391 Kernel.prototype.set_callbacks_for_msg = function (msg_id, callbacks) {
391 this._msg_callbacks[msg_id] = callbacks || {};
392 this._msg_callbacks[msg_id] = callbacks || {};
392 }
393 }
393
394
394
395
395 Kernel.prototype._handle_shell_reply = function (e) {
396 Kernel.prototype._handle_shell_reply = function (e) {
396 var reply = $.parseJSON(e.data);
397 var reply = $.parseJSON(e.data);
397 $([IPython.events]).trigger('shell_reply.Kernel', {kernel: this, reply:reply});
398 $([IPython.events]).trigger('shell_reply.Kernel', {kernel: this, reply:reply});
398 var header = reply.header;
399 var header = reply.header;
399 var content = reply.content;
400 var content = reply.content;
400 var metadata = reply.metadata;
401 var metadata = reply.metadata;
401 var msg_type = header.msg_type;
402 var msg_type = header.msg_type;
402 var callbacks = this.get_callbacks_for_msg(reply.parent_header.msg_id);
403 var callbacks = this.get_callbacks_for_msg(reply.parent_header.msg_id);
403 if (callbacks !== undefined) {
404 if (callbacks !== undefined) {
404 var cb = callbacks[msg_type];
405 var cb = callbacks[msg_type];
405 if (cb !== undefined) {
406 if (cb !== undefined) {
406 cb(content, metadata);
407 cb(content, metadata);
407 }
408 }
408 };
409 };
409
410
410 if (content.payload !== undefined) {
411 if (content.payload !== undefined) {
411 var payload = content.payload || [];
412 var payload = content.payload || [];
412 this._handle_payload(callbacks, payload);
413 this._handle_payload(callbacks, payload);
413 }
414 }
414 };
415 };
415
416
416
417
417 Kernel.prototype._handle_payload = function (callbacks, payload) {
418 Kernel.prototype._handle_payload = function (callbacks, payload) {
418 var l = payload.length;
419 var l = payload.length;
419 // Payloads are handled by triggering events because we don't want the Kernel
420 // Payloads are handled by triggering events because we don't want the Kernel
420 // to depend on the Notebook or Pager classes.
421 // to depend on the Notebook or Pager classes.
421 for (var i=0; i<l; i++) {
422 for (var i=0; i<l; i++) {
422 if (payload[i].source === 'page') {
423 if (payload[i].source === 'page') {
423 var data = {'text':payload[i].text}
424 var data = {'text':payload[i].text}
424 $([IPython.events]).trigger('open_with_text.Pager', data);
425 $([IPython.events]).trigger('open_with_text.Pager', data);
425 } else if (payload[i].source === 'set_next_input') {
426 } else if (payload[i].source === 'set_next_input') {
426 if (callbacks.set_next_input !== undefined) {
427 if (callbacks.set_next_input !== undefined) {
427 callbacks.set_next_input(payload[i].text)
428 callbacks.set_next_input(payload[i].text)
428 }
429 }
429 }
430 }
430 };
431 };
431 };
432 };
432
433
433
434
434 Kernel.prototype._handle_iopub_reply = function (e) {
435 Kernel.prototype._handle_iopub_reply = function (e) {
435 var reply = $.parseJSON(e.data);
436 var reply = $.parseJSON(e.data);
436 var content = reply.content;
437 var content = reply.content;
437 var msg_type = reply.header.msg_type;
438 var msg_type = reply.header.msg_type;
438 var metadata = reply.metadata;
439 var metadata = reply.metadata;
439 var callbacks = this.get_callbacks_for_msg(reply.parent_header.msg_id);
440 var callbacks = this.get_callbacks_for_msg(reply.parent_header.msg_id);
440 if (msg_type !== 'status' && callbacks === undefined) {
441 if (msg_type !== 'status' && callbacks === undefined) {
441 // Message not from one of this notebook's cells and there are no
442 // Message not from one of this notebook's cells and there are no
442 // callbacks to handle it.
443 // callbacks to handle it.
443 return;
444 return;
444 }
445 }
445 var output_types = ['stream','display_data','pyout','pyerr'];
446 var output_types = ['stream','display_data','pyout','pyerr'];
446 if (output_types.indexOf(msg_type) >= 0) {
447 if (output_types.indexOf(msg_type) >= 0) {
447 var cb = callbacks['output'];
448 var cb = callbacks['output'];
448 if (cb !== undefined) {
449 if (cb !== undefined) {
449 cb(msg_type, content, metadata);
450 cb(msg_type, content, metadata);
450 }
451 }
451 } else if (msg_type === 'status') {
452 } else if (msg_type === 'status') {
452 if (content.execution_state === 'busy') {
453 if (content.execution_state === 'busy') {
453 $([IPython.events]).trigger('status_busy.Kernel', {kernel: this});
454 $([IPython.events]).trigger('status_busy.Kernel', {kernel: this});
454 } else if (content.execution_state === 'idle') {
455 } else if (content.execution_state === 'idle') {
455 $([IPython.events]).trigger('status_idle.Kernel', {kernel: this});
456 $([IPython.events]).trigger('status_idle.Kernel', {kernel: this});
456 } else if (content.execution_state === 'restarting') {
457 } else if (content.execution_state === 'restarting') {
457 // autorestarting is distinct from restarting,
458 // autorestarting is distinct from restarting,
458 // in that it means the kernel died and the server is restarting it.
459 // in that it means the kernel died and the server is restarting it.
459 // status_restarting sets the notification widget,
460 // status_restarting sets the notification widget,
460 // autorestart shows the more prominent dialog.
461 // autorestart shows the more prominent dialog.
461 $([IPython.events]).trigger('status_autorestarting.Kernel', {kernel: this});
462 $([IPython.events]).trigger('status_autorestarting.Kernel', {kernel: this});
462 $([IPython.events]).trigger('status_restarting.Kernel', {kernel: this});
463 $([IPython.events]).trigger('status_restarting.Kernel', {kernel: this});
463 } else if (content.execution_state === 'dead') {
464 } else if (content.execution_state === 'dead') {
464 this.stop_channels();
465 this.stop_channels();
465 $([IPython.events]).trigger('status_dead.Kernel', {kernel: this});
466 $([IPython.events]).trigger('status_dead.Kernel', {kernel: this});
466 };
467 };
467 } else if (msg_type === 'clear_output') {
468 } else if (msg_type === 'clear_output') {
468 var cb = callbacks['clear_output'];
469 var cb = callbacks['clear_output'];
469 if (cb !== undefined) {
470 if (cb !== undefined) {
470 cb(content, metadata);
471 cb(content, metadata);
471 }
472 }
472 };
473 };
473 };
474 };
474
475
475
476
476 Kernel.prototype._handle_input_request = function (e) {
477 Kernel.prototype._handle_input_request = function (e) {
477 var request = $.parseJSON(e.data);
478 var request = $.parseJSON(e.data);
478 var header = request.header;
479 var header = request.header;
479 var content = request.content;
480 var content = request.content;
480 var metadata = request.metadata;
481 var metadata = request.metadata;
481 var msg_type = header.msg_type;
482 var msg_type = header.msg_type;
482 if (msg_type !== 'input_request') {
483 if (msg_type !== 'input_request') {
483 console.log("Invalid input request!", request);
484 console.log("Invalid input request!", request);
484 return;
485 return;
485 }
486 }
486 var callbacks = this.get_callbacks_for_msg(request.parent_header.msg_id);
487 var callbacks = this.get_callbacks_for_msg(request.parent_header.msg_id);
487 if (callbacks !== undefined) {
488 if (callbacks !== undefined) {
488 var cb = callbacks[msg_type];
489 var cb = callbacks[msg_type];
489 if (cb !== undefined) {
490 if (cb !== undefined) {
490 cb(content, metadata);
491 cb(content, metadata);
491 }
492 }
492 };
493 };
493 };
494 };
494
495
495
496
496 IPython.Kernel = Kernel;
497 IPython.Kernel = Kernel;
497
498
498 return IPython;
499 return IPython;
499
500
500 }(IPython));
501 }(IPython));
501
502
General Comments 0
You need to be logged in to leave comments. Login now