##// END OF EJS Templates
monkey patch codemirror with new functionality...
Matthias BUSSONNIER -
Show More
@@ -1,384 +1,410 b''
1 1 //----------------------------------------------------------------------------
2 2 // Copyright (C) 2008-2011 The IPython Development Team
3 3 //
4 4 // Distributed under the terms of the BSD License. The full license is in
5 5 // the file COPYING, distributed as part of this software.
6 6 //----------------------------------------------------------------------------
7 7
8 8 //============================================================================
9 9 // CodeCell
10 10 //============================================================================
11 11 /**
12 12 * An extendable module that provide base functionnality to create cell for notebook.
13 13 * @module IPython
14 14 * @namespace IPython
15 15 * @submodule CodeCell
16 16 */
17 17
18
19 /* local util for codemirror */
20 var posEq = function(a, b) {return a.line == b.line && a.ch == b.ch;}
21
22 /**
23 *
24 * function to delete until previous non blanking space character
25 * or first multiple of 4 tabstop.
26 * @private
27 */
28 CodeMirror.commands.delSpaceToPrevTabStop = function(cm){
29 var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
30 if (!posEq(from, to)) {cm.replaceRange("", from, to); return}
31 var cur = cm.getCursor(), line = cm.getLine(cur.line);
32 var tabsize = cm.getOption('tabSize');
33 var chToPrevTabStop = cur.ch-(Math.ceil(cur.ch/tabsize)-1)*tabsize;
34 var from = {ch:cur.ch-chToPrevTabStop,line:cur.line}
35 var select = cm.getRange(from,cur)
36 if( select.match(/^\ +$/) != null){
37 cm.replaceRange("",from,cur)
38 } else {
39 cm.deleteH(-1,"char")
40 }
41 };
42
43
18 44 var IPython = (function (IPython) {
19 45 "use strict";
20 46
21 47 var utils = IPython.utils;
22 48 var key = IPython.utils.keycodes;
23 49 CodeMirror.modeURL = "/static/codemirror/mode/%N/%N.js";
24 50
25 51 /**
26 52 * A Cell conceived to write code.
27 53 *
28 54 * The kernel doesn't have to be set at creation time, in that case
29 55 * it will be null and set_kernel has to be called later.
30 56 * @class CodeCell
31 57 * @extends IPython.Cell
32 58 *
33 59 * @constructor
34 60 * @param {Object|null} kernel
35 61 */
36 62 var CodeCell = function (kernel) {
37 63 this.kernel = kernel || null;
38 64 this.code_mirror = null;
39 65 this.input_prompt_number = null;
40 66 this.collapsed = false;
41 67 this.default_mode = 'python';
42 68 IPython.Cell.apply(this, arguments);
43 69
44 70 var that = this;
45 71 this.element.focusout(
46 72 function() { that.auto_highlight(); }
47 73 );
48 74 };
49 75
50 76 CodeCell.prototype = new IPython.Cell();
51 77
52 78 /**
53 79 * @method auto_highlight
54 80 */
55 81 CodeCell.prototype.auto_highlight = function () {
56 82 this._auto_highlight(IPython.config.cell_magic_highlight)
57 83 };
58 84
59 85 /** @method create_element */
60 86 CodeCell.prototype.create_element = function () {
61 87 IPython.Cell.prototype.create_element.apply(this, arguments);
62 88
63 89 var cell = $('<div></div>').addClass('cell border-box-sizing code_cell vbox');
64 90 cell.attr('tabindex','2');
65 91
66 92 this.celltoolbar = new IPython.CellToolbar(this);
67 93 cell.append(this.celltoolbar.element);
68 94
69 95 var input = $('<div></div>').addClass('input hbox');
70 96 input.append($('<div/>').addClass('prompt input_prompt'));
71 97 var input_area = $('<div/>').addClass('input_area box-flex1');
72 98 this.code_mirror = CodeMirror(input_area.get(0), {
73 99 indentUnit : 4,
74 100 mode: 'python',
75 101 theme: 'ipython',
76 102 readOnly: this.read_only,
77 103 extraKeys: {"Tab": "indentMore","Shift-Tab" : "indentLess",'Backspace':"delSpaceToPrevTabStop"},
78 104 onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this),
79 105 matchBrackets: true
80 106 });
81 107 input.append(input_area);
82 108 var output = $('<div></div>');
83 109 cell.append(input).append(output);
84 110 this.element = cell;
85 111 this.output_area = new IPython.OutputArea(output, true);
86 112
87 113 // construct a completer only if class exist
88 114 // otherwise no print view
89 115 if (IPython.Completer !== undefined)
90 116 {
91 117 this.completer = new IPython.Completer(this);
92 118 }
93 119 };
94 120
95 121 /**
96 122 * This method gets called in CodeMirror's onKeyDown/onKeyPress
97 123 * handlers and is used to provide custom key handling. Its return
98 124 * value is used to determine if CodeMirror should ignore the event:
99 125 * true = ignore, false = don't ignore.
100 126 * @method handle_codemirror_keyevent
101 127 */
102 128 CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) {
103 129
104 130 if (this.read_only){
105 131 return false;
106 132 }
107 133
108 134 var that = this;
109 135 // whatever key is pressed, first, cancel the tooltip request before
110 136 // they are sent, and remove tooltip if any, except for tab again
111 137 if (event.type === 'keydown' && event.which != key.TAB ) {
112 138 IPython.tooltip.remove_and_cancel_tooltip();
113 139 };
114 140
115 141 var cur = editor.getCursor();
116 142 if (event.keyCode === key.ENTER){
117 143 this.auto_highlight();
118 144 }
119 145
120 146 if (event.keyCode === key.ENTER && (event.shiftKey || event.ctrlKey)) {
121 147 // Always ignore shift-enter in CodeMirror as we handle it.
122 148 return true;
123 149 } else if (event.which === 40 && event.type === 'keypress' && IPython.tooltip.time_before_tooltip >= 0) {
124 150 // triger on keypress (!) otherwise inconsistent event.which depending on plateform
125 151 // browser and keyboard layout !
126 152 // Pressing '(' , request tooltip, don't forget to reappend it
127 153 IPython.tooltip.pending(that);
128 154 } else if (event.which === key.UPARROW && event.type === 'keydown') {
129 155 // If we are not at the top, let CM handle the up arrow and
130 156 // prevent the global keydown handler from handling it.
131 157 if (!that.at_top()) {
132 158 event.stop();
133 159 return false;
134 160 } else {
135 161 return true;
136 162 };
137 163 } else if (event.which === key.ESC) {
138 164 IPython.tooltip.remove_and_cancel_tooltip(true);
139 165 return true;
140 166 } else if (event.which === key.DOWNARROW && event.type === 'keydown') {
141 167 // If we are not at the bottom, let CM handle the down arrow and
142 168 // prevent the global keydown handler from handling it.
143 169 if (!that.at_bottom()) {
144 170 event.stop();
145 171 return false;
146 172 } else {
147 173 return true;
148 174 };
149 175 } else if (event.keyCode === key.TAB && event.type == 'keydown' && event.shiftKey) {
150 176 if (editor.somethingSelected()){
151 177 var anchor = editor.getCursor("anchor");
152 178 var head = editor.getCursor("head");
153 179 if( anchor.line != head.line){
154 180 return false;
155 181 }
156 182 }
157 183 IPython.tooltip.request(that);
158 184 event.stop();
159 185 return true;
160 186 } else if (event.keyCode === key.TAB && event.type == 'keydown') {
161 187 // Tab completion.
162 188 //Do not trim here because of tooltip
163 189 if (editor.somethingSelected()){return false}
164 190 var pre_cursor = editor.getRange({line:cur.line,ch:0},cur);
165 191 if (pre_cursor.trim() === "") {
166 192 // Don't autocomplete if the part of the line before the cursor
167 193 // is empty. In this case, let CodeMirror handle indentation.
168 194 return false;
169 195 } else if ((pre_cursor.substr(-1) === "("|| pre_cursor.substr(-1) === " ") && IPython.config.tooltip_on_tab ) {
170 196 IPython.tooltip.request(that);
171 197 // Prevent the event from bubbling up.
172 198 event.stop();
173 199 // Prevent CodeMirror from handling the tab.
174 200 return true;
175 201 } else {
176 202 event.stop();
177 203 this.completer.startCompletion();
178 204 return true;
179 205 };
180 206 } else {
181 207 // keypress/keyup also trigger on TAB press, and we don't want to
182 208 // use those to disable tab completion.
183 209 return false;
184 210 };
185 211 return false;
186 212 };
187 213
188 214
189 215 // Kernel related calls.
190 216
191 217 CodeCell.prototype.set_kernel = function (kernel) {
192 218 this.kernel = kernel;
193 219 }
194 220
195 221 /**
196 222 * Execute current code cell to the kernel
197 223 * @method execute
198 224 */
199 225 CodeCell.prototype.execute = function () {
200 226 this.output_area.clear_output(true, true, true);
201 227 this.set_input_prompt('*');
202 228 this.element.addClass("running");
203 229 var callbacks = {
204 230 'execute_reply': $.proxy(this._handle_execute_reply, this),
205 231 'output': $.proxy(this.output_area.handle_output, this.output_area),
206 232 'clear_output': $.proxy(this.output_area.handle_clear_output, this.output_area),
207 233 'set_next_input': $.proxy(this._handle_set_next_input, this)
208 234 };
209 235 var msg_id = this.kernel.execute(this.get_text(), callbacks, {silent: false});
210 236 };
211 237
212 238 /**
213 239 * @method _handle_execute_reply
214 240 * @private
215 241 */
216 242 CodeCell.prototype._handle_execute_reply = function (content) {
217 243 this.set_input_prompt(content.execution_count);
218 244 this.element.removeClass("running");
219 245 $([IPython.events]).trigger('set_dirty.Notebook', {'value': true});
220 246 }
221 247
222 248 CodeCell.prototype._handle_set_next_input = function (text) {
223 249 var data = {'cell': this, 'text': text}
224 250 $([IPython.events]).trigger('set_next_input.Notebook', data);
225 251 }
226 252
227 253 // Basic cell manipulation.
228 254
229 255 CodeCell.prototype.select = function () {
230 256 IPython.Cell.prototype.select.apply(this);
231 257 this.code_mirror.refresh();
232 258 this.code_mirror.focus();
233 259 this.auto_highlight();
234 260 // We used to need an additional refresh() after the focus, but
235 261 // it appears that this has been fixed in CM. This bug would show
236 262 // up on FF when a newly loaded markdown cell was edited.
237 263 };
238 264
239 265
240 266 CodeCell.prototype.select_all = function () {
241 267 var start = {line: 0, ch: 0};
242 268 var nlines = this.code_mirror.lineCount();
243 269 var last_line = this.code_mirror.getLine(nlines-1);
244 270 var end = {line: nlines-1, ch: last_line.length};
245 271 this.code_mirror.setSelection(start, end);
246 272 };
247 273
248 274
249 275 CodeCell.prototype.collapse = function () {
250 276 this.collapsed = true;
251 277 this.output_area.collapse();
252 278 };
253 279
254 280
255 281 CodeCell.prototype.expand = function () {
256 282 this.collapsed = false;
257 283 this.output_area.expand();
258 284 };
259 285
260 286
261 287 CodeCell.prototype.toggle_output = function () {
262 288 this.collapsed = Boolean(1 - this.collapsed);
263 289 this.output_area.toggle_output();
264 290 };
265 291
266 292
267 293 CodeCell.prototype.toggle_output_scroll = function () {
268 294 this.output_area.toggle_scroll();
269 295 };
270 296
271 297
272 298 CodeCell.input_prompt_classical = function (prompt_value, lines_number) {
273 299 var ns = prompt_value || "&nbsp;";
274 300 return 'In&nbsp;[' + ns + ']:'
275 301 };
276 302
277 303 CodeCell.input_prompt_continuation = function (prompt_value, lines_number) {
278 304 var html = [CodeCell.input_prompt_classical(prompt_value, lines_number)];
279 305 for(var i=1; i < lines_number; i++){html.push(['...:'])};
280 306 return html.join('</br>')
281 307 };
282 308
283 309 CodeCell.input_prompt_function = CodeCell.input_prompt_classical;
284 310
285 311
286 312 CodeCell.prototype.set_input_prompt = function (number) {
287 313 var nline = 1
288 314 if( this.code_mirror != undefined) {
289 315 nline = this.code_mirror.lineCount();
290 316 }
291 317 this.input_prompt_number = number;
292 318 var prompt_html = CodeCell.input_prompt_function(this.input_prompt_number, nline);
293 319 this.element.find('div.input_prompt').html(prompt_html);
294 320 };
295 321
296 322
297 323 CodeCell.prototype.clear_input = function () {
298 324 this.code_mirror.setValue('');
299 325 };
300 326
301 327
302 328 CodeCell.prototype.get_text = function () {
303 329 return this.code_mirror.getValue();
304 330 };
305 331
306 332
307 333 CodeCell.prototype.set_text = function (code) {
308 334 return this.code_mirror.setValue(code);
309 335 };
310 336
311 337
312 338 CodeCell.prototype.at_top = function () {
313 339 var cursor = this.code_mirror.getCursor();
314 340 if (cursor.line === 0 && cursor.ch === 0) {
315 341 return true;
316 342 } else {
317 343 return false;
318 344 }
319 345 };
320 346
321 347
322 348 CodeCell.prototype.at_bottom = function () {
323 349 var cursor = this.code_mirror.getCursor();
324 350 if (cursor.line === (this.code_mirror.lineCount()-1) && cursor.ch === this.code_mirror.getLine(cursor.line).length) {
325 351 return true;
326 352 } else {
327 353 return false;
328 354 }
329 355 };
330 356
331 357
332 358 CodeCell.prototype.clear_output = function (stdout, stderr, other) {
333 359 this.output_area.clear_output(stdout, stderr, other);
334 360 };
335 361
336 362
337 363 // JSON serialization
338 364
339 365 CodeCell.prototype.fromJSON = function (data) {
340 366 IPython.Cell.prototype.fromJSON.apply(this, arguments);
341 367 if (data.cell_type === 'code') {
342 368 if (data.input !== undefined) {
343 369 this.set_text(data.input);
344 370 // make this value the starting point, so that we can only undo
345 371 // to this state, instead of a blank cell
346 372 this.code_mirror.clearHistory();
347 373 this.auto_highlight();
348 374 }
349 375 if (data.prompt_number !== undefined) {
350 376 this.set_input_prompt(data.prompt_number);
351 377 } else {
352 378 this.set_input_prompt();
353 379 };
354 380 this.output_area.fromJSON(data.outputs);
355 381 if (data.collapsed !== undefined) {
356 382 if (data.collapsed) {
357 383 this.collapse();
358 384 } else {
359 385 this.expand();
360 386 };
361 387 };
362 388 };
363 389 };
364 390
365 391
366 392 CodeCell.prototype.toJSON = function () {
367 393 var data = IPython.Cell.prototype.toJSON.apply(this);
368 394 data.input = this.get_text();
369 395 data.cell_type = 'code';
370 396 if (this.input_prompt_number) {
371 397 data.prompt_number = this.input_prompt_number;
372 398 };
373 399 var outputs = this.output_area.toJSON();
374 400 data.outputs = outputs;
375 401 data.language = 'python';
376 402 data.collapsed = this.collapsed;
377 403 return data;
378 404 };
379 405
380 406
381 407 IPython.CodeCell = CodeCell;
382 408
383 409 return IPython;
384 410 }(IPython));
General Comments 0
You need to be logged in to leave comments. Login now