##// END OF EJS Templates
Backport PR #4064: Store default codemirror mode in only 1 place...
MinRK -
Show More
@@ -1,335 +1,340 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 // Cell
9 // Cell
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 Cell
15 * @submodule Cell
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 /**
22 /**
23 * The Base `Cell` class from which to inherit
23 * The Base `Cell` class from which to inherit
24 * @class Cell
24 * @class Cell
25 **/
25 **/
26
26
27 /*
27 /*
28 * @constructor
28 * @constructor
29 *
29 *
30 * @param {object|undefined} [options]
30 * @param {object|undefined} [options]
31 * @param [options.cm_config] {object} config to pass to CodeMirror, will extend default parameters
31 * @param [options.cm_config] {object} config to pass to CodeMirror, will extend default parameters
32 */
32 */
33 var Cell = function (options) {
33 var Cell = function (options) {
34
34
35 options = this.mergeopt(Cell, options)
35 options = this.mergeopt(Cell, options)
36 // superclass default overwrite our default
36 // superclass default overwrite our default
37
37
38 this.placeholder = options.placeholder || '';
38 this.placeholder = options.placeholder || '';
39 this.read_only = options.cm_config.readOnly;
39 this.read_only = options.cm_config.readOnly;
40 this.selected = false;
40 this.selected = false;
41 this.element = null;
41 this.element = null;
42 this.metadata = {};
42 this.metadata = {};
43 // load this from metadata later ?
43 // load this from metadata later ?
44 this.user_highlight = 'auto';
44 this.user_highlight = 'auto';
45 this.cm_config = options.cm_config;
45 this.cm_config = options.cm_config;
46 this.create_element();
46 this.create_element();
47 if (this.element !== null) {
47 if (this.element !== null) {
48 this.element.data("cell", this);
48 this.element.data("cell", this);
49 this.bind_events();
49 this.bind_events();
50 }
50 }
51 this.cell_id = utils.uuid();
51 this.cell_id = utils.uuid();
52 this._options = options;
52 this._options = options;
53 };
53 };
54
54
55 Cell.options_default = {
55 Cell.options_default = {
56 cm_config : {
56 cm_config : {
57 indentUnit : 4,
57 indentUnit : 4,
58 readOnly: false,
58 readOnly: false,
59 theme: "default"
59 theme: "default"
60 }
60 }
61 };
61 };
62
62
63 // FIXME: Workaround CM Bug #332 (Safari segfault on drag)
63 // FIXME: Workaround CM Bug #332 (Safari segfault on drag)
64 // by disabling drag/drop altogether on Safari
64 // by disabling drag/drop altogether on Safari
65 // https://github.com/marijnh/CodeMirror/issues/332
65 // https://github.com/marijnh/CodeMirror/issues/332
66
66
67 if (utils.browser[0] == "Safari") {
67 if (utils.browser[0] == "Safari") {
68 Cell.options_default.cm_config.dragDrop = false;
68 Cell.options_default.cm_config.dragDrop = false;
69 }
69 }
70
70
71 Cell.prototype.mergeopt = function(_class, options, overwrite){
71 Cell.prototype.mergeopt = function(_class, options, overwrite){
72 overwrite = overwrite || {};
72 overwrite = overwrite || {};
73 return $.extend(true, {}, _class.options_default, options, overwrite)
73 return $.extend(true, {}, _class.options_default, options, overwrite)
74
74
75 }
75 }
76
76
77
77
78
78
79 /**
79 /**
80 * Empty. Subclasses must implement create_element.
80 * Empty. Subclasses must implement create_element.
81 * This should contain all the code to create the DOM element in notebook
81 * This should contain all the code to create the DOM element in notebook
82 * and will be called by Base Class constructor.
82 * and will be called by Base Class constructor.
83 * @method create_element
83 * @method create_element
84 */
84 */
85 Cell.prototype.create_element = function () {
85 Cell.prototype.create_element = function () {
86 };
86 };
87
87
88
88
89 /**
89 /**
90 * Subclasses can implement override bind_events.
90 * Subclasses can implement override bind_events.
91 * Be carefull to call the parent method when overwriting as it fires event.
91 * Be carefull to call the parent method when overwriting as it fires event.
92 * this will be triggerd after create_element in constructor.
92 * this will be triggerd after create_element in constructor.
93 * @method bind_events
93 * @method bind_events
94 */
94 */
95 Cell.prototype.bind_events = function () {
95 Cell.prototype.bind_events = function () {
96 var that = this;
96 var that = this;
97 // We trigger events so that Cell doesn't have to depend on Notebook.
97 // We trigger events so that Cell doesn't have to depend on Notebook.
98 that.element.click(function (event) {
98 that.element.click(function (event) {
99 if (that.selected === false) {
99 if (that.selected === false) {
100 $([IPython.events]).trigger('select.Cell', {'cell':that});
100 $([IPython.events]).trigger('select.Cell', {'cell':that});
101 }
101 }
102 });
102 });
103 that.element.focusin(function (event) {
103 that.element.focusin(function (event) {
104 if (that.selected === false) {
104 if (that.selected === false) {
105 $([IPython.events]).trigger('select.Cell', {'cell':that});
105 $([IPython.events]).trigger('select.Cell', {'cell':that});
106 }
106 }
107 });
107 });
108 if (this.code_mirror) {
108 if (this.code_mirror) {
109 this.code_mirror.on("change", function(cm, change) {
109 this.code_mirror.on("change", function(cm, change) {
110 $([IPython.events]).trigger("set_dirty.Notebook", {value: true});
110 $([IPython.events]).trigger("set_dirty.Notebook", {value: true});
111 });
111 });
112 }
112 }
113 };
113 };
114
114
115 /**
115 /**
116 * Triger typsetting of math by mathjax on current cell element
116 * Triger typsetting of math by mathjax on current cell element
117 * @method typeset
117 * @method typeset
118 */
118 */
119 Cell.prototype.typeset = function () {
119 Cell.prototype.typeset = function () {
120 if (window.MathJax){
120 if (window.MathJax){
121 var cell_math = this.element.get(0);
121 var cell_math = this.element.get(0);
122 MathJax.Hub.Queue(["Typeset", MathJax.Hub, cell_math]);
122 MathJax.Hub.Queue(["Typeset", MathJax.Hub, cell_math]);
123 }
123 }
124 };
124 };
125
125
126 /**
126 /**
127 * should be triggerd when cell is selected
127 * should be triggerd when cell is selected
128 * @method select
128 * @method select
129 */
129 */
130 Cell.prototype.select = function () {
130 Cell.prototype.select = function () {
131 this.element.addClass('selected');
131 this.element.addClass('selected');
132 this.selected = true;
132 this.selected = true;
133 };
133 };
134
134
135
135
136 /**
136 /**
137 * should be triggerd when cell is unselected
137 * should be triggerd when cell is unselected
138 * @method unselect
138 * @method unselect
139 */
139 */
140 Cell.prototype.unselect = function () {
140 Cell.prototype.unselect = function () {
141 this.element.removeClass('selected');
141 this.element.removeClass('selected');
142 this.selected = false;
142 this.selected = false;
143 };
143 };
144
144
145 /**
145 /**
146 * should be overritten by subclass
146 * should be overritten by subclass
147 * @method get_text
147 * @method get_text
148 */
148 */
149 Cell.prototype.get_text = function () {
149 Cell.prototype.get_text = function () {
150 };
150 };
151
151
152 /**
152 /**
153 * should be overritten by subclass
153 * should be overritten by subclass
154 * @method set_text
154 * @method set_text
155 * @param {string} text
155 * @param {string} text
156 */
156 */
157 Cell.prototype.set_text = function (text) {
157 Cell.prototype.set_text = function (text) {
158 };
158 };
159
159
160 /**
160 /**
161 * Refresh codemirror instance
161 * Refresh codemirror instance
162 * @method refresh
162 * @method refresh
163 */
163 */
164 Cell.prototype.refresh = function () {
164 Cell.prototype.refresh = function () {
165 this.code_mirror.refresh();
165 this.code_mirror.refresh();
166 };
166 };
167
167
168
168
169 /**
169 /**
170 * should be overritten by subclass
170 * should be overritten by subclass
171 * @method edit
171 * @method edit
172 **/
172 **/
173 Cell.prototype.edit = function () {
173 Cell.prototype.edit = function () {
174 };
174 };
175
175
176
176
177 /**
177 /**
178 * should be overritten by subclass
178 * should be overritten by subclass
179 * @method render
179 * @method render
180 **/
180 **/
181 Cell.prototype.render = function () {
181 Cell.prototype.render = function () {
182 };
182 };
183
183
184 /**
184 /**
185 * should be overritten by subclass
185 * should be overritten by subclass
186 * serialise cell to json.
186 * serialise cell to json.
187 * @method toJSON
187 * @method toJSON
188 **/
188 **/
189 Cell.prototype.toJSON = function () {
189 Cell.prototype.toJSON = function () {
190 var data = {};
190 var data = {};
191 data.metadata = this.metadata;
191 data.metadata = this.metadata;
192 return data;
192 return data;
193 };
193 };
194
194
195
195
196 /**
196 /**
197 * should be overritten by subclass
197 * should be overritten by subclass
198 * @method fromJSON
198 * @method fromJSON
199 **/
199 **/
200 Cell.prototype.fromJSON = function (data) {
200 Cell.prototype.fromJSON = function (data) {
201 if (data.metadata !== undefined) {
201 if (data.metadata !== undefined) {
202 this.metadata = data.metadata;
202 this.metadata = data.metadata;
203 }
203 }
204 this.celltoolbar.rebuild();
204 this.celltoolbar.rebuild();
205 };
205 };
206
206
207
207
208 /**
208 /**
209 * can the cell be splitted in 2 cells.
209 * can the cell be splitted in 2 cells.
210 * @method is_splittable
210 * @method is_splittable
211 **/
211 **/
212 Cell.prototype.is_splittable = function () {
212 Cell.prototype.is_splittable = function () {
213 return true;
213 return true;
214 };
214 };
215
215
216
216
217 /**
217 /**
218 * @return {String} - the text before the cursor
218 * @return {String} - the text before the cursor
219 * @method get_pre_cursor
219 * @method get_pre_cursor
220 **/
220 **/
221 Cell.prototype.get_pre_cursor = function () {
221 Cell.prototype.get_pre_cursor = function () {
222 var cursor = this.code_mirror.getCursor();
222 var cursor = this.code_mirror.getCursor();
223 var text = this.code_mirror.getRange({line:0, ch:0}, cursor);
223 var text = this.code_mirror.getRange({line:0, ch:0}, cursor);
224 text = text.replace(/^\n+/, '').replace(/\n+$/, '');
224 text = text.replace(/^\n+/, '').replace(/\n+$/, '');
225 return text;
225 return text;
226 }
226 }
227
227
228
228
229 /**
229 /**
230 * @return {String} - the text after the cursor
230 * @return {String} - the text after the cursor
231 * @method get_post_cursor
231 * @method get_post_cursor
232 **/
232 **/
233 Cell.prototype.get_post_cursor = function () {
233 Cell.prototype.get_post_cursor = function () {
234 var cursor = this.code_mirror.getCursor();
234 var cursor = this.code_mirror.getCursor();
235 var last_line_num = this.code_mirror.lineCount()-1;
235 var last_line_num = this.code_mirror.lineCount()-1;
236 var last_line_len = this.code_mirror.getLine(last_line_num).length;
236 var last_line_len = this.code_mirror.getLine(last_line_num).length;
237 var end = {line:last_line_num, ch:last_line_len}
237 var end = {line:last_line_num, ch:last_line_len}
238 var text = this.code_mirror.getRange(cursor, end);
238 var text = this.code_mirror.getRange(cursor, end);
239 text = text.replace(/^\n+/, '').replace(/\n+$/, '');
239 text = text.replace(/^\n+/, '').replace(/\n+$/, '');
240 return text;
240 return text;
241 };
241 };
242
242
243 /**
243 /**
244 * Show/Hide CodeMirror LineNumber
244 * Show/Hide CodeMirror LineNumber
245 * @method show_line_numbers
245 * @method show_line_numbers
246 *
246 *
247 * @param value {Bool} show (true), or hide (false) the line number in CodeMirror
247 * @param value {Bool} show (true), or hide (false) the line number in CodeMirror
248 **/
248 **/
249 Cell.prototype.show_line_numbers = function (value) {
249 Cell.prototype.show_line_numbers = function (value) {
250 this.code_mirror.setOption('lineNumbers', value);
250 this.code_mirror.setOption('lineNumbers', value);
251 this.code_mirror.refresh();
251 this.code_mirror.refresh();
252 };
252 };
253
253
254 /**
254 /**
255 * Toggle CodeMirror LineNumber
255 * Toggle CodeMirror LineNumber
256 * @method toggle_line_numbers
256 * @method toggle_line_numbers
257 **/
257 **/
258 Cell.prototype.toggle_line_numbers = function () {
258 Cell.prototype.toggle_line_numbers = function () {
259 var val = this.code_mirror.getOption('lineNumbers');
259 var val = this.code_mirror.getOption('lineNumbers');
260 this.show_line_numbers(!val);
260 this.show_line_numbers(!val);
261 };
261 };
262
262
263 /**
263 /**
264 * Force codemirror highlight mode
264 * Force codemirror highlight mode
265 * @method force_highlight
265 * @method force_highlight
266 * @param {object} - CodeMirror mode
266 * @param {object} - CodeMirror mode
267 **/
267 **/
268 Cell.prototype.force_highlight = function(mode) {
268 Cell.prototype.force_highlight = function(mode) {
269 this.user_highlight = mode;
269 this.user_highlight = mode;
270 this.auto_highlight();
270 this.auto_highlight();
271 };
271 };
272
272
273 /**
273 /**
274 * Try to autodetect cell highlight mode, or use selected mode
274 * Try to autodetect cell highlight mode, or use selected mode
275 * @methods _auto_highlight
275 * @methods _auto_highlight
276 * @private
276 * @private
277 * @param {String|object|undefined} - CodeMirror mode | 'auto'
277 * @param {String|object|undefined} - CodeMirror mode | 'auto'
278 **/
278 **/
279 Cell.prototype._auto_highlight = function (modes) {
279 Cell.prototype._auto_highlight = function (modes) {
280 //Here we handle manually selected modes
280 //Here we handle manually selected modes
281 if( this.user_highlight != undefined && this.user_highlight != 'auto' )
281 if( this.user_highlight != undefined && this.user_highlight != 'auto' )
282 {
282 {
283 var mode = this.user_highlight;
283 var mode = this.user_highlight;
284 CodeMirror.autoLoadMode(this.code_mirror, mode);
284 CodeMirror.autoLoadMode(this.code_mirror, mode);
285 this.code_mirror.setOption('mode', mode);
285 this.code_mirror.setOption('mode', mode);
286 return;
286 return;
287 }
287 }
288 var first_line = this.code_mirror.getLine(0);
288 var first_line = this.code_mirror.getLine(0);
289 // loop on every pairs
289 // loop on every pairs
290 for( var mode in modes) {
290 for( var mode in modes) {
291 var regs = modes[mode]['reg'];
291 var regs = modes[mode]['reg'];
292 // only one key every time but regexp can't be keys...
292 // only one key every time but regexp can't be keys...
293 for(var reg in regs ) {
293 for(var reg in regs ) {
294 // here we handle non magic_modes
294 // here we handle non magic_modes
295 if(first_line.match(regs[reg]) != null) {
295 if(first_line.match(regs[reg]) != null) {
296 if (mode.search('magic_') != 0) {
296 if (mode.search('magic_') != 0) {
297 this.code_mirror.setOption('mode', mode);
297 this.code_mirror.setOption('mode', mode);
298 CodeMirror.autoLoadMode(this.code_mirror, mode);
298 CodeMirror.autoLoadMode(this.code_mirror, mode);
299 return;
299 return;
300 }
300 }
301 var open = modes[mode]['open']|| "%%";
301 var open = modes[mode]['open']|| "%%";
302 var close = modes[mode]['close']|| "%%end";
302 var close = modes[mode]['close']|| "%%end";
303 var mmode = mode;
303 var mmode = mode;
304 mode = mmode.substr(6);
304 mode = mmode.substr(6);
305 CodeMirror.autoLoadMode(this.code_mirror, mode);
305 CodeMirror.autoLoadMode(this.code_mirror, mode);
306 // create on the fly a mode that swhitch between
306 // create on the fly a mode that swhitch between
307 // plain/text and smth else otherwise `%%` is
307 // plain/text and smth else otherwise `%%` is
308 // source of some highlight issues.
308 // source of some highlight issues.
309 // we use patchedGetMode to circumvent a bug in CM
309 // we use patchedGetMode to circumvent a bug in CM
310 CodeMirror.defineMode(mmode , function(config) {
310 CodeMirror.defineMode(mmode , function(config) {
311 return CodeMirror.multiplexingMode(
311 return CodeMirror.multiplexingMode(
312 CodeMirror.patchedGetMode(config, 'text/plain'),
312 CodeMirror.patchedGetMode(config, 'text/plain'),
313 // always set someting on close
313 // always set someting on close
314 {open: open, close: close,
314 {open: open, close: close,
315 mode: CodeMirror.patchedGetMode(config, mode),
315 mode: CodeMirror.patchedGetMode(config, mode),
316 delimStyle: "delimit"
316 delimStyle: "delimit"
317 }
317 }
318 );
318 );
319 });
319 });
320 this.code_mirror.setOption('mode', mmode);
320 this.code_mirror.setOption('mode', mmode);
321 return;
321 return;
322 }
322 }
323 }
323 }
324 }
324 }
325 // fallback on default (python)
325 // fallback on default
326 var default_mode = this.default_mode || 'text/plain';
326 var default_mode
327 try {
328 default_mode = this._options.cm_config.mode;
329 } catch(e) {
330 default_mode = 'text/plain';
331 }
327 this.code_mirror.setOption('mode', default_mode);
332 this.code_mirror.setOption('mode', default_mode);
328 };
333 };
329
334
330 IPython.Cell = Cell;
335 IPython.Cell = Cell;
331
336
332 return IPython;
337 return IPython;
333
338
334 }(IPython));
339 }(IPython));
335
340
@@ -1,443 +1,442 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';
69 this.cell_type = "code";
68 this.cell_type = "code";
70
69
71
70
72 var cm_overwrite_options = {
71 var cm_overwrite_options = {
73 onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this)
72 onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this)
74 };
73 };
75
74
76 options = this.mergeopt(CodeCell, options, {cm_config:cm_overwrite_options});
75 options = this.mergeopt(CodeCell, options, {cm_config:cm_overwrite_options});
77
76
78 IPython.Cell.apply(this,[options]);
77 IPython.Cell.apply(this,[options]);
79
78
80 var that = this;
79 var that = this;
81 this.element.focusout(
80 this.element.focusout(
82 function() { that.auto_highlight(); }
81 function() { that.auto_highlight(); }
83 );
82 );
84 };
83 };
85
84
86 CodeCell.options_default = {
85 CodeCell.options_default = {
87 cm_config : {
86 cm_config : {
88 extraKeys: {
87 extraKeys: {
89 "Tab" : "indentMore",
88 "Tab" : "indentMore",
90 "Shift-Tab" : "indentLess",
89 "Shift-Tab" : "indentLess",
91 "Backspace" : "delSpaceToPrevTabStop",
90 "Backspace" : "delSpaceToPrevTabStop",
92 "Cmd-/" : "toggleComment",
91 "Cmd-/" : "toggleComment",
93 "Ctrl-/" : "toggleComment"
92 "Ctrl-/" : "toggleComment"
94 },
93 },
95 mode: 'ipython',
94 mode: 'ipython',
96 theme: 'ipython',
95 theme: 'ipython',
97 matchBrackets: true
96 matchBrackets: true
98 }
97 }
99 };
98 };
100
99
101
100
102 CodeCell.prototype = new IPython.Cell();
101 CodeCell.prototype = new IPython.Cell();
103
102
104 /**
103 /**
105 * @method auto_highlight
104 * @method auto_highlight
106 */
105 */
107 CodeCell.prototype.auto_highlight = function () {
106 CodeCell.prototype.auto_highlight = function () {
108 this._auto_highlight(IPython.config.cell_magic_highlight)
107 this._auto_highlight(IPython.config.cell_magic_highlight)
109 };
108 };
110
109
111 /** @method create_element */
110 /** @method create_element */
112 CodeCell.prototype.create_element = function () {
111 CodeCell.prototype.create_element = function () {
113 IPython.Cell.prototype.create_element.apply(this, arguments);
112 IPython.Cell.prototype.create_element.apply(this, arguments);
114
113
115 var cell = $('<div></div>').addClass('cell border-box-sizing code_cell');
114 var cell = $('<div></div>').addClass('cell border-box-sizing code_cell');
116 cell.attr('tabindex','2');
115 cell.attr('tabindex','2');
117
116
118 this.celltoolbar = new IPython.CellToolbar(this);
117 this.celltoolbar = new IPython.CellToolbar(this);
119
118
120 var input = $('<div></div>').addClass('input');
119 var input = $('<div></div>').addClass('input');
121 var vbox = $('<div/>').addClass('vbox box-flex1')
120 var vbox = $('<div/>').addClass('vbox box-flex1')
122 input.append($('<div/>').addClass('prompt input_prompt'));
121 input.append($('<div/>').addClass('prompt input_prompt'));
123 vbox.append(this.celltoolbar.element);
122 vbox.append(this.celltoolbar.element);
124 var input_area = $('<div/>').addClass('input_area');
123 var input_area = $('<div/>').addClass('input_area');
125 this.code_mirror = CodeMirror(input_area.get(0), this.cm_config);
124 this.code_mirror = CodeMirror(input_area.get(0), this.cm_config);
126 $(this.code_mirror.getInputField()).attr("spellcheck", "false");
125 $(this.code_mirror.getInputField()).attr("spellcheck", "false");
127 vbox.append(input_area);
126 vbox.append(input_area);
128 input.append(vbox);
127 input.append(vbox);
129 var output = $('<div></div>');
128 var output = $('<div></div>');
130 cell.append(input).append(output);
129 cell.append(input).append(output);
131 this.element = cell;
130 this.element = cell;
132 this.output_area = new IPython.OutputArea(output, true);
131 this.output_area = new IPython.OutputArea(output, true);
133
132
134 // construct a completer only if class exist
133 // construct a completer only if class exist
135 // otherwise no print view
134 // otherwise no print view
136 if (IPython.Completer !== undefined)
135 if (IPython.Completer !== undefined)
137 {
136 {
138 this.completer = new IPython.Completer(this);
137 this.completer = new IPython.Completer(this);
139 }
138 }
140 };
139 };
141
140
142 /**
141 /**
143 * This method gets called in CodeMirror's onKeyDown/onKeyPress
142 * This method gets called in CodeMirror's onKeyDown/onKeyPress
144 * handlers and is used to provide custom key handling. Its return
143 * handlers and is used to provide custom key handling. Its return
145 * value is used to determine if CodeMirror should ignore the event:
144 * value is used to determine if CodeMirror should ignore the event:
146 * true = ignore, false = don't ignore.
145 * true = ignore, false = don't ignore.
147 * @method handle_codemirror_keyevent
146 * @method handle_codemirror_keyevent
148 */
147 */
149 CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) {
148 CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) {
150
149
151 var that = this;
150 var that = this;
152 // whatever key is pressed, first, cancel the tooltip request before
151 // whatever key is pressed, first, cancel the tooltip request before
153 // they are sent, and remove tooltip if any, except for tab again
152 // they are sent, and remove tooltip if any, except for tab again
154 if (event.type === 'keydown' && event.which != key.TAB ) {
153 if (event.type === 'keydown' && event.which != key.TAB ) {
155 IPython.tooltip.remove_and_cancel_tooltip();
154 IPython.tooltip.remove_and_cancel_tooltip();
156 };
155 };
157
156
158 var cur = editor.getCursor();
157 var cur = editor.getCursor();
159 if (event.keyCode === key.ENTER){
158 if (event.keyCode === key.ENTER){
160 this.auto_highlight();
159 this.auto_highlight();
161 }
160 }
162
161
163 if (event.keyCode === key.ENTER && (event.shiftKey || event.ctrlKey)) {
162 if (event.keyCode === key.ENTER && (event.shiftKey || event.ctrlKey)) {
164 // Always ignore shift-enter in CodeMirror as we handle it.
163 // Always ignore shift-enter in CodeMirror as we handle it.
165 return true;
164 return true;
166 } else if (event.which === 40 && event.type === 'keypress' && IPython.tooltip.time_before_tooltip >= 0) {
165 } 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
166 // triger on keypress (!) otherwise inconsistent event.which depending on plateform
168 // browser and keyboard layout !
167 // browser and keyboard layout !
169 // Pressing '(' , request tooltip, don't forget to reappend it
168 // Pressing '(' , request tooltip, don't forget to reappend it
170 // The second argument says to hide the tooltip if the docstring
169 // The second argument says to hide the tooltip if the docstring
171 // is actually empty
170 // is actually empty
172 IPython.tooltip.pending(that, true);
171 IPython.tooltip.pending(that, true);
173 } else if (event.which === key.UPARROW && event.type === 'keydown') {
172 } else if (event.which === key.UPARROW && event.type === 'keydown') {
174 // If we are not at the top, let CM handle the up arrow and
173 // If we are not at the top, let CM handle the up arrow and
175 // prevent the global keydown handler from handling it.
174 // prevent the global keydown handler from handling it.
176 if (!that.at_top()) {
175 if (!that.at_top()) {
177 event.stop();
176 event.stop();
178 return false;
177 return false;
179 } else {
178 } else {
180 return true;
179 return true;
181 };
180 };
182 } else if (event.which === key.ESC) {
181 } else if (event.which === key.ESC) {
183 IPython.tooltip.remove_and_cancel_tooltip(true);
182 IPython.tooltip.remove_and_cancel_tooltip(true);
184 return true;
183 return true;
185 } else if (event.which === key.DOWNARROW && event.type === 'keydown') {
184 } else if (event.which === key.DOWNARROW && event.type === 'keydown') {
186 // If we are not at the bottom, let CM handle the down arrow and
185 // If we are not at the bottom, let CM handle the down arrow and
187 // prevent the global keydown handler from handling it.
186 // prevent the global keydown handler from handling it.
188 if (!that.at_bottom()) {
187 if (!that.at_bottom()) {
189 event.stop();
188 event.stop();
190 return false;
189 return false;
191 } else {
190 } else {
192 return true;
191 return true;
193 };
192 };
194 } else if (event.keyCode === key.TAB && event.type == 'keydown' && event.shiftKey) {
193 } else if (event.keyCode === key.TAB && event.type == 'keydown' && event.shiftKey) {
195 if (editor.somethingSelected()){
194 if (editor.somethingSelected()){
196 var anchor = editor.getCursor("anchor");
195 var anchor = editor.getCursor("anchor");
197 var head = editor.getCursor("head");
196 var head = editor.getCursor("head");
198 if( anchor.line != head.line){
197 if( anchor.line != head.line){
199 return false;
198 return false;
200 }
199 }
201 }
200 }
202 IPython.tooltip.request(that);
201 IPython.tooltip.request(that);
203 event.stop();
202 event.stop();
204 return true;
203 return true;
205 } else if (event.keyCode === key.TAB && event.type == 'keydown') {
204 } else if (event.keyCode === key.TAB && event.type == 'keydown') {
206 // Tab completion.
205 // Tab completion.
207 //Do not trim here because of tooltip
206 //Do not trim here because of tooltip
208 if (editor.somethingSelected()){return false}
207 if (editor.somethingSelected()){return false}
209 var pre_cursor = editor.getRange({line:cur.line,ch:0},cur);
208 var pre_cursor = editor.getRange({line:cur.line,ch:0},cur);
210 if (pre_cursor.trim() === "") {
209 if (pre_cursor.trim() === "") {
211 // Don't autocomplete if the part of the line before the cursor
210 // Don't autocomplete if the part of the line before the cursor
212 // is empty. In this case, let CodeMirror handle indentation.
211 // is empty. In this case, let CodeMirror handle indentation.
213 return false;
212 return false;
214 } else if ((pre_cursor.substr(-1) === "("|| pre_cursor.substr(-1) === " ") && IPython.config.tooltip_on_tab ) {
213 } else if ((pre_cursor.substr(-1) === "("|| pre_cursor.substr(-1) === " ") && IPython.config.tooltip_on_tab ) {
215 IPython.tooltip.request(that);
214 IPython.tooltip.request(that);
216 // Prevent the event from bubbling up.
215 // Prevent the event from bubbling up.
217 event.stop();
216 event.stop();
218 // Prevent CodeMirror from handling the tab.
217 // Prevent CodeMirror from handling the tab.
219 return true;
218 return true;
220 } else {
219 } else {
221 event.stop();
220 event.stop();
222 this.completer.startCompletion();
221 this.completer.startCompletion();
223 return true;
222 return true;
224 };
223 };
225 } else {
224 } else {
226 // keypress/keyup also trigger on TAB press, and we don't want to
225 // keypress/keyup also trigger on TAB press, and we don't want to
227 // use those to disable tab completion.
226 // use those to disable tab completion.
228 return false;
227 return false;
229 };
228 };
230 return false;
229 return false;
231 };
230 };
232
231
233
232
234 // Kernel related calls.
233 // Kernel related calls.
235
234
236 CodeCell.prototype.set_kernel = function (kernel) {
235 CodeCell.prototype.set_kernel = function (kernel) {
237 this.kernel = kernel;
236 this.kernel = kernel;
238 }
237 }
239
238
240 /**
239 /**
241 * Execute current code cell to the kernel
240 * Execute current code cell to the kernel
242 * @method execute
241 * @method execute
243 */
242 */
244 CodeCell.prototype.execute = function () {
243 CodeCell.prototype.execute = function () {
245 this.output_area.clear_output(true, true, true);
244 this.output_area.clear_output(true, true, true);
246 this.set_input_prompt('*');
245 this.set_input_prompt('*');
247 this.element.addClass("running");
246 this.element.addClass("running");
248 var callbacks = {
247 var callbacks = {
249 'execute_reply': $.proxy(this._handle_execute_reply, this),
248 'execute_reply': $.proxy(this._handle_execute_reply, this),
250 'output': $.proxy(this.output_area.handle_output, this.output_area),
249 'output': $.proxy(this.output_area.handle_output, this.output_area),
251 'clear_output': $.proxy(this.output_area.handle_clear_output, this.output_area),
250 'clear_output': $.proxy(this.output_area.handle_clear_output, this.output_area),
252 'set_next_input': $.proxy(this._handle_set_next_input, this),
251 'set_next_input': $.proxy(this._handle_set_next_input, this),
253 'input_request': $.proxy(this._handle_input_request, this)
252 'input_request': $.proxy(this._handle_input_request, this)
254 };
253 };
255 var msg_id = this.kernel.execute(this.get_text(), callbacks, {silent: false, store_history: true});
254 var msg_id = this.kernel.execute(this.get_text(), callbacks, {silent: false, store_history: true});
256 };
255 };
257
256
258 /**
257 /**
259 * @method _handle_execute_reply
258 * @method _handle_execute_reply
260 * @private
259 * @private
261 */
260 */
262 CodeCell.prototype._handle_execute_reply = function (content) {
261 CodeCell.prototype._handle_execute_reply = function (content) {
263 this.set_input_prompt(content.execution_count);
262 this.set_input_prompt(content.execution_count);
264 this.element.removeClass("running");
263 this.element.removeClass("running");
265 $([IPython.events]).trigger('set_dirty.Notebook', {value: true});
264 $([IPython.events]).trigger('set_dirty.Notebook', {value: true});
266 }
265 }
267
266
268 /**
267 /**
269 * @method _handle_set_next_input
268 * @method _handle_set_next_input
270 * @private
269 * @private
271 */
270 */
272 CodeCell.prototype._handle_set_next_input = function (text) {
271 CodeCell.prototype._handle_set_next_input = function (text) {
273 var data = {'cell': this, 'text': text}
272 var data = {'cell': this, 'text': text}
274 $([IPython.events]).trigger('set_next_input.Notebook', data);
273 $([IPython.events]).trigger('set_next_input.Notebook', data);
275 }
274 }
276
275
277 /**
276 /**
278 * @method _handle_input_request
277 * @method _handle_input_request
279 * @private
278 * @private
280 */
279 */
281 CodeCell.prototype._handle_input_request = function (content) {
280 CodeCell.prototype._handle_input_request = function (content) {
282 this.output_area.append_raw_input(content);
281 this.output_area.append_raw_input(content);
283 }
282 }
284
283
285
284
286 // Basic cell manipulation.
285 // Basic cell manipulation.
287
286
288 CodeCell.prototype.select = function () {
287 CodeCell.prototype.select = function () {
289 IPython.Cell.prototype.select.apply(this);
288 IPython.Cell.prototype.select.apply(this);
290 this.code_mirror.refresh();
289 this.code_mirror.refresh();
291 this.code_mirror.focus();
290 this.code_mirror.focus();
292 this.auto_highlight();
291 this.auto_highlight();
293 // We used to need an additional refresh() after the focus, but
292 // 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
293 // 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.
294 // up on FF when a newly loaded markdown cell was edited.
296 };
295 };
297
296
298
297
299 CodeCell.prototype.select_all = function () {
298 CodeCell.prototype.select_all = function () {
300 var start = {line: 0, ch: 0};
299 var start = {line: 0, ch: 0};
301 var nlines = this.code_mirror.lineCount();
300 var nlines = this.code_mirror.lineCount();
302 var last_line = this.code_mirror.getLine(nlines-1);
301 var last_line = this.code_mirror.getLine(nlines-1);
303 var end = {line: nlines-1, ch: last_line.length};
302 var end = {line: nlines-1, ch: last_line.length};
304 this.code_mirror.setSelection(start, end);
303 this.code_mirror.setSelection(start, end);
305 };
304 };
306
305
307
306
308 CodeCell.prototype.collapse = function () {
307 CodeCell.prototype.collapse = function () {
309 this.collapsed = true;
308 this.collapsed = true;
310 this.output_area.collapse();
309 this.output_area.collapse();
311 };
310 };
312
311
313
312
314 CodeCell.prototype.expand = function () {
313 CodeCell.prototype.expand = function () {
315 this.collapsed = false;
314 this.collapsed = false;
316 this.output_area.expand();
315 this.output_area.expand();
317 };
316 };
318
317
319
318
320 CodeCell.prototype.toggle_output = function () {
319 CodeCell.prototype.toggle_output = function () {
321 this.collapsed = Boolean(1 - this.collapsed);
320 this.collapsed = Boolean(1 - this.collapsed);
322 this.output_area.toggle_output();
321 this.output_area.toggle_output();
323 };
322 };
324
323
325
324
326 CodeCell.prototype.toggle_output_scroll = function () {
325 CodeCell.prototype.toggle_output_scroll = function () {
327 this.output_area.toggle_scroll();
326 this.output_area.toggle_scroll();
328 };
327 };
329
328
330
329
331 CodeCell.input_prompt_classical = function (prompt_value, lines_number) {
330 CodeCell.input_prompt_classical = function (prompt_value, lines_number) {
332 var ns = prompt_value || "&nbsp;";
331 var ns = prompt_value || "&nbsp;";
333 return 'In&nbsp;[' + ns + ']:'
332 return 'In&nbsp;[' + ns + ']:'
334 };
333 };
335
334
336 CodeCell.input_prompt_continuation = function (prompt_value, lines_number) {
335 CodeCell.input_prompt_continuation = function (prompt_value, lines_number) {
337 var html = [CodeCell.input_prompt_classical(prompt_value, lines_number)];
336 var html = [CodeCell.input_prompt_classical(prompt_value, lines_number)];
338 for(var i=1; i < lines_number; i++){html.push(['...:'])};
337 for(var i=1; i < lines_number; i++){html.push(['...:'])};
339 return html.join('</br>')
338 return html.join('</br>')
340 };
339 };
341
340
342 CodeCell.input_prompt_function = CodeCell.input_prompt_classical;
341 CodeCell.input_prompt_function = CodeCell.input_prompt_classical;
343
342
344
343
345 CodeCell.prototype.set_input_prompt = function (number) {
344 CodeCell.prototype.set_input_prompt = function (number) {
346 var nline = 1
345 var nline = 1
347 if( this.code_mirror != undefined) {
346 if( this.code_mirror != undefined) {
348 nline = this.code_mirror.lineCount();
347 nline = this.code_mirror.lineCount();
349 }
348 }
350 this.input_prompt_number = number;
349 this.input_prompt_number = number;
351 var prompt_html = CodeCell.input_prompt_function(this.input_prompt_number, nline);
350 var prompt_html = CodeCell.input_prompt_function(this.input_prompt_number, nline);
352 this.element.find('div.input_prompt').html(prompt_html);
351 this.element.find('div.input_prompt').html(prompt_html);
353 };
352 };
354
353
355
354
356 CodeCell.prototype.clear_input = function () {
355 CodeCell.prototype.clear_input = function () {
357 this.code_mirror.setValue('');
356 this.code_mirror.setValue('');
358 };
357 };
359
358
360
359
361 CodeCell.prototype.get_text = function () {
360 CodeCell.prototype.get_text = function () {
362 return this.code_mirror.getValue();
361 return this.code_mirror.getValue();
363 };
362 };
364
363
365
364
366 CodeCell.prototype.set_text = function (code) {
365 CodeCell.prototype.set_text = function (code) {
367 return this.code_mirror.setValue(code);
366 return this.code_mirror.setValue(code);
368 };
367 };
369
368
370
369
371 CodeCell.prototype.at_top = function () {
370 CodeCell.prototype.at_top = function () {
372 var cursor = this.code_mirror.getCursor();
371 var cursor = this.code_mirror.getCursor();
373 if (cursor.line === 0 && cursor.ch === 0) {
372 if (cursor.line === 0 && cursor.ch === 0) {
374 return true;
373 return true;
375 } else {
374 } else {
376 return false;
375 return false;
377 }
376 }
378 };
377 };
379
378
380
379
381 CodeCell.prototype.at_bottom = function () {
380 CodeCell.prototype.at_bottom = function () {
382 var cursor = this.code_mirror.getCursor();
381 var cursor = this.code_mirror.getCursor();
383 if (cursor.line === (this.code_mirror.lineCount()-1) && cursor.ch === this.code_mirror.getLine(cursor.line).length) {
382 if (cursor.line === (this.code_mirror.lineCount()-1) && cursor.ch === this.code_mirror.getLine(cursor.line).length) {
384 return true;
383 return true;
385 } else {
384 } else {
386 return false;
385 return false;
387 }
386 }
388 };
387 };
389
388
390
389
391 CodeCell.prototype.clear_output = function (stdout, stderr, other) {
390 CodeCell.prototype.clear_output = function (stdout, stderr, other) {
392 this.output_area.clear_output(stdout, stderr, other);
391 this.output_area.clear_output(stdout, stderr, other);
393 };
392 };
394
393
395
394
396 // JSON serialization
395 // JSON serialization
397
396
398 CodeCell.prototype.fromJSON = function (data) {
397 CodeCell.prototype.fromJSON = function (data) {
399 IPython.Cell.prototype.fromJSON.apply(this, arguments);
398 IPython.Cell.prototype.fromJSON.apply(this, arguments);
400 if (data.cell_type === 'code') {
399 if (data.cell_type === 'code') {
401 if (data.input !== undefined) {
400 if (data.input !== undefined) {
402 this.set_text(data.input);
401 this.set_text(data.input);
403 // make this value the starting point, so that we can only undo
402 // make this value the starting point, so that we can only undo
404 // to this state, instead of a blank cell
403 // to this state, instead of a blank cell
405 this.code_mirror.clearHistory();
404 this.code_mirror.clearHistory();
406 this.auto_highlight();
405 this.auto_highlight();
407 }
406 }
408 if (data.prompt_number !== undefined) {
407 if (data.prompt_number !== undefined) {
409 this.set_input_prompt(data.prompt_number);
408 this.set_input_prompt(data.prompt_number);
410 } else {
409 } else {
411 this.set_input_prompt();
410 this.set_input_prompt();
412 };
411 };
413 this.output_area.fromJSON(data.outputs);
412 this.output_area.fromJSON(data.outputs);
414 if (data.collapsed !== undefined) {
413 if (data.collapsed !== undefined) {
415 if (data.collapsed) {
414 if (data.collapsed) {
416 this.collapse();
415 this.collapse();
417 } else {
416 } else {
418 this.expand();
417 this.expand();
419 };
418 };
420 };
419 };
421 };
420 };
422 };
421 };
423
422
424
423
425 CodeCell.prototype.toJSON = function () {
424 CodeCell.prototype.toJSON = function () {
426 var data = IPython.Cell.prototype.toJSON.apply(this);
425 var data = IPython.Cell.prototype.toJSON.apply(this);
427 data.input = this.get_text();
426 data.input = this.get_text();
428 data.cell_type = 'code';
427 data.cell_type = 'code';
429 if (this.input_prompt_number) {
428 if (this.input_prompt_number) {
430 data.prompt_number = this.input_prompt_number;
429 data.prompt_number = this.input_prompt_number;
431 };
430 };
432 var outputs = this.output_area.toJSON();
431 var outputs = this.output_area.toJSON();
433 data.outputs = outputs;
432 data.outputs = outputs;
434 data.language = 'python';
433 data.language = 'python';
435 data.collapsed = this.collapsed;
434 data.collapsed = this.collapsed;
436 return data;
435 return data;
437 };
436 };
438
437
439
438
440 IPython.CodeCell = CodeCell;
439 IPython.CodeCell = CodeCell;
441
440
442 return IPython;
441 return IPython;
443 }(IPython));
442 }(IPython));
General Comments 0
You need to be logged in to leave comments. Login now