]> git.proxmox.com Git - mirror_xterm.js.git/blame - src/xterm.js
jsdoc and tidy up
[mirror_xterm.js.git] / src / xterm.js
CommitLineData
8bc844c0 1/**
5af18f8e
PK
2 * xterm.js: xterm, in the browser
3 * Copyright (c) 2014, sourceLair Limited (www.sourcelair.com (MIT License)
6cc8b3cd
CJ
4 * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
5 * https://github.com/chjj/term.js
8bc844c0
CJ
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 *
25 * Originally forked from (with the author's permission):
26 * Fabrice Bellard's javascript vt100 for jslinux:
27 * http://bellard.org/jslinux/
28 * Copyright (c) 2011 Fabrice Bellard
29 * The original design remains. The terminal itself
30 * has been extended to include xterm CSI codes, among
31 * other features.
32 */
33
3f455f90 34(function (xterm) {
6a87253d
AO
35 if (typeof exports === 'object' && typeof module === 'object') {
36 /*
bd215861 37 * CommonJS environment
6a87253d
AO
38 */
39 module.exports = xterm.call(this);
40 } else if (typeof define == 'function') {
3f455f90
PK
41 /*
42 * Require.js is available
43 */
87979aee 44 define([], xterm.bind(window));
3f455f90
PK
45 } else {
46 /*
47 * Plain browser environment
987f09d8 48 */
3f455f90
PK
49 this.Xterm = xterm.call(this);
50 this.Terminal = this.Xterm; /* Backwards compatibility with term.js */
51 }
52})(function() {
53 /**
54 * Terminal Emulation References:
55 * http://vt100.net/
56 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
57 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
58 * http://invisible-island.net/vttest/
59 * http://www.inwap.com/pdp10/ansicode.txt
60 * http://linux.die.net/man/4/console_codes
61 * http://linux.die.net/man/7/urxvt
62 */
63
64 'use strict';
65
66 /**
67 * Shared
68 */
69
70 var window = this, document = this.document;
71
72 /**
73 * EventEmitter
74 */
75
76 function EventEmitter() {
77 this._events = this._events || {};
78 }
8bc844c0 79
3f455f90
PK
80 EventEmitter.prototype.addListener = function(type, listener) {
81 this._events[type] = this._events[type] || [];
82 this._events[type].push(listener);
83 };
8bc844c0 84
3f455f90 85 EventEmitter.prototype.on = EventEmitter.prototype.addListener;
8bc844c0 86
3f455f90
PK
87 EventEmitter.prototype.removeListener = function(type, listener) {
88 if (!this._events[type]) return;
8bc844c0 89
3f455f90
PK
90 var obj = this._events[type]
91 , i = obj.length;
8bc844c0 92
3f455f90
PK
93 while (i--) {
94 if (obj[i] === listener || obj[i].listener === listener) {
95 obj.splice(i, 1);
96 return;
97 }
98 }
99 };
100
101 EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
8bc844c0 102
3f455f90
PK
103 EventEmitter.prototype.removeAllListeners = function(type) {
104 if (this._events[type]) delete this._events[type];
105 };
8bc844c0 106
3f455f90 107 EventEmitter.prototype.once = function(type, listener) {
6406a88d 108 var self = this;
3f455f90
PK
109 function on() {
110 var args = Array.prototype.slice.call(arguments);
fc7b22dc
DI
111 this.removeListener(type, on);
112 return listener.apply(this, args);
3f455f90
PK
113 }
114 on.listener = listener;
115 return this.on(type, on);
116 };
8bc844c0 117
3f455f90
PK
118 EventEmitter.prototype.emit = function(type) {
119 if (!this._events[type]) return;
8bc844c0 120
3f455f90
PK
121 var args = Array.prototype.slice.call(arguments, 1)
122 , obj = this._events[type]
123 , l = obj.length
124 , i = 0;
8bc844c0 125
3f455f90
PK
126 for (; i < l; i++) {
127 obj[i].apply(this, args);
128 }
129 };
8bc844c0 130
3f455f90
PK
131 EventEmitter.prototype.listeners = function(type) {
132 return this._events[type] = this._events[type] || [];
133 };
8bc844c0 134
8bc844c0 135
cab79c47
DI
136 /**
137 * Encapsulates the logic for handling compositionstart, compositionupdate and compositionend
138 * events, displaying the in-progress composition to the UI and forwarding the final composition
139 * to the handler.
140 * @param {HTMLTextAreaElement} textarea The textarea that xterm uses for input.
141 * @param {HTMLElement} compositionView The element to display the in-progress composition in.
142 * @param {Terminal} terminal The Terminal to forward the finished composition to.
143 */
29000fb7
DI
144 function CompositionHelper(textarea, compositionView, terminal) {
145 this.textarea = textarea;
146 this.compositionView = compositionView;
147 this.terminal = terminal;
148
149 // Whether input composition is currently happening, eg. via a mobile keyboard, speech input
150 // or IME. This variable determines whether the compositionText should be displayed on the UI.
151 this.isComposing = false;
152
153 // The input currently being composed, eg. via a mobile keyboard, speech input or IME.
154 this.compositionText = null;
155
156 // The position within the input textarea's value of the current composition.
157 this.compositionPosition = { start: null, end: null };
c656ed04 158
cab79c47
DI
159 // Whether a composition is in the process of being sent, setting this to false will cancel
160 // any in-progress composition.
c656ed04 161 this.isSendingComposition = false;
29000fb7
DI
162 }
163
cab79c47
DI
164 /**
165 * Handles the compositionstart event, activating the composition view.
166 */
c656ed04 167 CompositionHelper.prototype.compositionstart = function() {
29000fb7
DI
168 this.isComposing = true;
169 this.compositionPosition.start = this.textarea.value.length;
170 this.compositionView.textContent = '';
171 this.compositionView.classList.add('active');
172 };
173
cab79c47
DI
174 /**
175 * Handles the compositionupdate event, updating the composition view.
176 * @param {CompositionEvent} ev The event.
177 */
29000fb7 178 CompositionHelper.prototype.compositionupdate = function(ev) {
29000fb7 179 this.compositionView.textContent = ev.data;
cab79c47 180 this.updateCompositionViewPosition();
c656ed04
DI
181 var self = this;
182 setTimeout(function() {
183 self.compositionPosition.end = self.textarea.value.length;
c656ed04 184 }, 0);
29000fb7
DI
185 };
186
cab79c47
DI
187 /**
188 * Handles the compositionend event, hiding the composition view and sending the composition to
189 * the handler.
190 */
c656ed04
DI
191 CompositionHelper.prototype.compositionend = function() {
192 this.finalizeComposition(true);
193 };
194
195 /**
196 * Finalizes the composition, resuming regular input actions. This is called when a composition
197 * is ending.
198 * @param {boolean} waitForPropogation Whether to wait for events to propogate before sending
199 * the input. This should be false if a non-composition keystroke is entered before the
200 * compositionend event is triggered, such as enter, so that the composition is send before
201 * the command is executed.
202 */
203 CompositionHelper.prototype.finalizeComposition = function(waitForPropogation) {
29000fb7
DI
204 this.compositionView.classList.remove('active');
205 this.isComposing = false;
c656ed04
DI
206
207 if (!waitForPropogation) {
208 // Cancel any delayed composition send requests and send the input immediately.
209 this.isSendingComposition = false;
210 var input = this.textarea.value.substring(this.compositionPosition.start, this.compositionPosition.end);
211 this.terminal.handler(input);
212 } else {
213 // Make a deep copy of the composition position here as a new compositionstart event may
214 // fire before the setTimeout executes.
215 var currentCompositionPosition = {
216 start: this.compositionPosition.start,
217 end: this.compositionPosition.end,
218 }
219
220 // Since composition* events happen before the changes take place in the textarea on most
221 // browsers, use a setTimeout with 0ms time to allow the native compositionend event to
222 // complete. This ensures the correct character is retrieved, this solution was used
223 // because:
224 // - The compositionend event's data property is unreliable, at least on Chromium
225 // - The last compositionupdate event's data property does not always accurately describe
226 // the character, a counter example being Korean where an ending consonsant can move to
227 // the following character if the following input is a vowel.
228 var self = this;
229 this.isSendingComposition = true;
230 setTimeout(function () {
231 // Ensure that the input has not already been sent
232 if (self.isSendingComposition) {
233 console.log('send input ' + input + ' delayed');
234 self.isSendingComposition = false;
235 var input = self.textarea.value.substring(currentCompositionPosition.start, currentCompositionPosition.end);
236 self.terminal.handler(input);
237 }
238 }, 0);
239 }
240 }
29000fb7 241
cab79c47
DI
242 /**
243 * Updates the composition view's position.
244 */
245 CompositionHelper.prototype.updateCompositionViewPosition = function() {
29000fb7
DI
246 var cursor = document.querySelector('.terminal-cursor');
247 term.compositionView.style.left = cursor.offsetLeft + 'px';
248 term.compositionView.style.top = cursor.offsetTop + 'px';
249 };
250
251
3f455f90
PK
252 /**
253 * States
254 */
255 var normal = 0, escaped = 1, csi = 2, osc = 3, charset = 4, dcs = 5, ignore = 6;
8bc844c0 256
3f455f90
PK
257 /**
258 * Terminal
259 */
8bc844c0 260
fd5be55d
DI
261 /**
262 * Creates a new `Terminal` object.
263 *
264 * @param {object} options An object containing a set of options, the available options are:
265 * - cursorBlink (boolean): Whether the terminal cursor blinks
266 *
267 * @public
107d1a14
PK
268 * @class Xterm Xterm
269 * @alias module:xterm/src/xterm
fd5be55d 270 */
3f455f90
PK
271 function Terminal(options) {
272 var self = this;
8bc844c0 273
3f455f90
PK
274 if (!(this instanceof Terminal)) {
275 return new Terminal(arguments[0], arguments[1], arguments[2]);
276 }
8bc844c0 277
3f455f90 278 self.cancel = Terminal.cancel;
8bc844c0 279
3f455f90 280 EventEmitter.call(this);
8bc844c0 281
3f455f90
PK
282 if (typeof options === 'number') {
283 options = {
284 cols: arguments[0],
285 rows: arguments[1],
286 handler: arguments[2]
287 };
288 }
5fd1948b 289
3f455f90 290 options = options || {};
8bc844c0 291
8bc844c0 292
3f455f90
PK
293 Object.keys(Terminal.defaults).forEach(function(key) {
294 if (options[key] == null) {
295 options[key] = Terminal.options[key];
86dad1b0 296
3f455f90
PK
297 if (Terminal[key] !== Terminal.defaults[key]) {
298 options[key] = Terminal[key];
299 }
300 }
301 self[key] = options[key];
302 });
91273161 303
3f455f90
PK
304 if (options.colors.length === 8) {
305 options.colors = options.colors.concat(Terminal._colors.slice(8));
306 } else if (options.colors.length === 16) {
307 options.colors = options.colors.concat(Terminal._colors.slice(16));
308 } else if (options.colors.length === 10) {
309 options.colors = options.colors.slice(0, -2).concat(
310 Terminal._colors.slice(8, -2), options.colors.slice(-2));
311 } else if (options.colors.length === 18) {
312 options.colors = options.colors.concat(
313 Terminal._colors.slice(16, -2), options.colors.slice(-2));
314 }
315 this.colors = options.colors;
8bc844c0 316
3f455f90 317 this.options = options;
91273161 318
3f455f90
PK
319 // this.context = options.context || window;
320 // this.document = options.document || document;
321 this.parent = options.body || options.parent
322 || (document ? document.getElementsByTagName('body')[0] : null);
5fd1948b 323
3f455f90
PK
324 this.cols = options.cols || options.geometry[0];
325 this.rows = options.rows || options.geometry[1];
326
327 if (options.handler) {
328 this.on('data', options.handler);
329 }
330
df268ad5
DI
331 /**
332 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
87c9370e 333 * buffer
df268ad5 334 */
3f455f90 335 this.ybase = 0;
df268ad5
DI
336
337 /**
338 * The scroll position of the viewport
339 */
3f455f90 340 this.ydisp = 0;
df268ad5
DI
341
342 /**
343 * The cursor's x position after ybase
344 */
3f455f90 345 this.x = 0;
df268ad5
DI
346
347 /**
348 * The cursor's y position after ybase
349 */
3f455f90 350 this.y = 0;
df268ad5 351
af29effb
DI
352 /**
353 * Used to debounce the refresh function
354 */
355 this.isRefreshing = false;
356
357 /**
358 * Whether there is a full terminal refresh queued
359 */
af29effb 360
3f455f90
PK
361 this.cursorState = 0;
362 this.cursorHidden = false;
363 this.convertEol;
364 this.state = 0;
365 this.queue = '';
366 this.scrollTop = 0;
367 this.scrollBottom = this.rows - 1;
368
369 // modes
370 this.applicationKeypad = false;
371 this.applicationCursor = false;
372 this.originMode = false;
373 this.insertMode = false;
4afa08da 374 this.wraparoundMode = true; // defaults: xterm - true, vt100 - false
3f455f90
PK
375 this.normal = null;
376
377 // charset
378 this.charset = null;
379 this.gcharset = null;
380 this.glevel = 0;
381 this.charsets = [null];
382
383 // mouse properties
384 this.decLocator;
385 this.x10Mouse;
386 this.vt200Mouse;
387 this.vt300Mouse;
388 this.normalMouse;
389 this.mouseEvents;
390 this.sendFocus;
391 this.utfMouse;
392 this.sgrMouse;
393 this.urxvtMouse;
394
395 // misc
396 this.element;
397 this.children;
398 this.refreshStart;
399 this.refreshEnd;
400 this.savedX;
401 this.savedY;
402 this.savedCols;
403
404 // stream
405 this.readable = true;
406 this.writable = true;
407
408 this.defAttr = (0 << 18) | (257 << 9) | (256 << 0);
409 this.curAttr = this.defAttr;
410
411 this.params = [];
412 this.currentParam = 0;
413 this.prefix = '';
414 this.postfix = '';
415
e3126ba3
JB
416 // leftover surrogate high from previous write invocation
417 this.surrogate_high = '';
874ba72f 418
df268ad5
DI
419 /**
420 * An array of all lines in the entire buffer, including the prompt. The lines are array of
421 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
422 */
3f455f90
PK
423 this.lines = [];
424 var i = this.rows;
425 while (i--) {
426 this.lines.push(this.blankLine());
86dad1b0 427 }
3f455f90
PK
428
429 this.tabs;
430 this.setupStops();
86dad1b0 431 }
8bc844c0 432
3f455f90 433 inherits(Terminal, EventEmitter);
8bc844c0 434
107d1a14
PK
435 /**
436 *
437 * back_color_erase feature for xterm.
107d1a14 438 */
3f455f90
PK
439 Terminal.prototype.eraseAttr = function() {
440 // if (this.is('screen')) return this.defAttr;
441 return (this.defAttr & ~0x1ff) | (this.curAttr & 0x1ff);
442 };
a68c8336 443
3f455f90
PK
444 /**
445 * Colors
446 */
447
448 // Colors 0-15
449 Terminal.tangoColors = [
450 // dark:
451 '#2e3436',
452 '#cc0000',
453 '#4e9a06',
454 '#c4a000',
455 '#3465a4',
456 '#75507b',
457 '#06989a',
458 '#d3d7cf',
459 // bright:
460 '#555753',
461 '#ef2929',
462 '#8ae234',
463 '#fce94f',
464 '#729fcf',
465 '#ad7fa8',
466 '#34e2e2',
467 '#eeeeec'
468 ];
469
470 // Colors 0-15 + 16-255
471 // Much thanks to TooTallNate for writing this.
472 Terminal.colors = (function() {
473 var colors = Terminal.tangoColors.slice()
474 , r = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
475 , i;
476
477 // 16-231
478 i = 0;
479 for (; i < 216; i++) {
480 out(r[(i / 36) % 6 | 0], r[(i / 6) % 6 | 0], r[i % 6]);
481 }
8bc844c0 482
3f455f90
PK
483 // 232-255 (grey)
484 i = 0;
485 for (; i < 24; i++) {
486 r = 8 + i * 10;
487 out(r, r, r);
488 }
8bc844c0 489
3f455f90
PK
490 function out(r, g, b) {
491 colors.push('#' + hex(r) + hex(g) + hex(b));
492 }
8bc844c0 493
3f455f90
PK
494 function hex(c) {
495 c = c.toString(16);
496 return c.length < 2 ? '0' + c : c;
497 }
8bc844c0 498
3f455f90
PK
499 return colors;
500 })();
3b322929 501
3f455f90 502 Terminal._colors = Terminal.colors.slice();
31161ffe 503
3f455f90
PK
504 Terminal.vcolors = (function() {
505 var out = []
506 , colors = Terminal.colors
507 , i = 0
508 , color;
8bc844c0 509
3f455f90
PK
510 for (; i < 256; i++) {
511 color = parseInt(colors[i].substring(1), 16);
512 out.push([
513 (color >> 16) & 0xff,
514 (color >> 8) & 0xff,
515 color & 0xff
516 ]);
517 }
5fd1948b 518
3f455f90
PK
519 return out;
520 })();
521
522 /**
523 * Options
524 */
525
526 Terminal.defaults = {
527 colors: Terminal.colors,
528 theme: 'default',
529 convertEol: false,
530 termName: 'xterm',
531 geometry: [80, 24],
532 cursorBlink: false,
533 visualBell: false,
534 popOnBell: false,
535 scrollback: 1000,
536 screenKeys: false,
537 debug: false,
538 cancelEvents: false
539 // programFeatures: false,
540 // focusKeys: false,
541 };
cc7f4d0d 542
3f455f90 543 Terminal.options = {};
cd956bca 544
7988f634
SS
545 Terminal.focus = null;
546
3f455f90
PK
547 each(keys(Terminal.defaults), function(key) {
548 Terminal[key] = Terminal.defaults[key];
549 Terminal.options[key] = Terminal.defaults[key];
550 });
551
552 /**
a6e85ad5 553 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
3f455f90
PK
554 */
555 Terminal.prototype.focus = function() {
fc7b22dc
DI
556 if (document.activeElement === this.textarea) {
557 return;
558 }
559
560 if (this.sendFocus) {
561 this.send('\x1b[I');
562 }
563
aaedcfc7 564 this.element.classList.add('focus');
fc7b22dc
DI
565 this.showCursor();
566 this.textarea.focus();
567 Terminal.focus = this;
a6e85ad5 568 };
8bc844c0 569
a6e85ad5
PK
570 /**
571 * Binds the desired focus behavior on a given terminal object.
572 *
573 * @static
574 */
575 Terminal.bindFocus = function (term) {
576 on(term.element, 'focus', function (ev) {
577 if (term.sendFocus) {
578 term.send('\x1b[I');
579 }
8bc844c0 580
a6e85ad5
PK
581 term.showCursor();
582 Terminal.focus = term;
583 term.emit('focus', {terminal: term});
584 });
3f455f90 585 };
8bc844c0 586
a6e85ad5
PK
587 /**
588 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
a6e85ad5 589 */
3f455f90 590 Terminal.prototype.blur = function() {
fc7b22dc
DI
591 if (Terminal.focus !== this) {
592 return;
593 }
594
aaedcfc7 595 this.element.classList.remove('focus');
fc7b22dc
DI
596 this.cursorState = 0;
597 this.refresh(this.y, this.y);
598 this.textarea.blur();
599 if (this.sendFocus) {
600 this.send('\x1b[0]');
601 }
602 Terminal.focus = null;
a6e85ad5 603 };
8bc844c0 604
a6e85ad5
PK
605 /**
606 * Binds the desired blur behavior on a given terminal object.
607 *
608 * @static
609 */
610 Terminal.bindBlur = function (term) {
611 on(term.element, 'blur', function (ev) {
612 if (term.sendFocus) {
613 term.send('\x1b[O');
614 }
615 Terminal.focus = null;
616 term.emit('blur', {terminal: term});
617 });
3f455f90 618 };
8bc844c0 619
3f455f90
PK
620 /**
621 * Initialize default behavior
622 */
3f455f90 623 Terminal.prototype.initGlobal = function() {
c02cc844 624 Terminal.bindPaste(this);
fc7b22dc 625 Terminal.bindKeys(this);
3f455f90
PK
626 Terminal.bindCopy(this);
627 };
8bc844c0 628
3f455f90 629 /**
64721687
PK
630 * Bind to paste event and allow both keyboard and right-click pasting, without having the
631 * contentEditable value set to true.
3f455f90
PK
632 */
633 Terminal.bindPaste = function(term) {
fc7b22dc
DI
634 on([term.textarea, term.element], 'paste', function(ev) {
635 ev.stopPropagation();
3f455f90
PK
636 if (ev.clipboardData) {
637 var text = ev.clipboardData.getData('text/plain');
638 term.handler(text);
fc7b22dc
DI
639 term.textarea.value = '';
640 return term.cancel(ev);
3f455f90 641 }
3f455f90 642 });
3f455f90 643 };
8bc844c0 644
00f4232e
PK
645 /**
646 * Prepares text copied from terminal selection, to be saved in the clipboard by:
647 * 1. stripping all trailing white spaces
648 * 2. converting all non-breaking spaces to regular spaces
649 * @param {string} text The copied text that needs processing for storing in clipboard
fed92ac5 650 * @returns {string}
00f4232e
PK
651 * @static
652 */
653 Terminal.prepareCopiedTextForClipboard = function (text) {
654 var space = String.fromCharCode(32),
655 nonBreakingSpace = String.fromCharCode(160),
656 allNonBreakingSpaces = new RegExp(nonBreakingSpace, 'g'),
657 processedText = text.split('\n').map(function (line) {
658 /**
659 * Strip all trailing white spaces and convert all non-breaking spaces to regular
660 * spaces.
661 */
662 var processedLine = line.replace(/\s+$/g, '').replace(allNonBreakingSpaces, space);
663
664 return processedLine;
665 }).join('\n');
666
667 return processedText;
668 };
8bc844c0 669
c02cc844 670 /**
fc7b22dc 671 * Apply key handling to the terminal
3f455f90 672 */
fc7b22dc
DI
673 Terminal.bindKeys = function(term) {
674 on(term.element, 'keydown', function(ev) {
675 if (document.activeElement != this) {
676 return;
677 }
678 term.keyDown(ev);
679 }, true);
00f4232e 680
fc7b22dc
DI
681 on(term.element, 'keypress', function(ev) {
682 if (document.activeElement != this) {
683 return;
684 }
685 term.keyPress(ev);
686 }, true);
8bc844c0 687
fc7b22dc 688 on(term.element, 'keyup', term.focus.bind(term));
8bc844c0 689
fc7b22dc
DI
690 on(term.textarea, 'keydown', function(ev) {
691 term.keyDown(ev);
692 }, true);
8bc844c0 693
fc7b22dc
DI
694 on(term.textarea, 'keypress', function(ev) {
695 term.keyPress(ev);
696 // Truncate the textarea's value, since it is not needed
697 this.value = '';
698 }, true);
a52b7e7a
DI
699
700 on(term.textarea, 'compositionstart', function(ev) {
29000fb7 701 term.compositionHelper.compositionstart.bind(term.compositionHelper, ev)();
a52b7e7a
DI
702 });
703 on(term.textarea, 'compositionupdate', function(ev) {
29000fb7 704 term.compositionHelper.compositionupdate.bind(term.compositionHelper, ev)();
a52b7e7a
DI
705 });
706 on(term.textarea, 'compositionend', function(ev) {
29000fb7 707 term.compositionHelper.compositionend.bind(term.compositionHelper, ev)();
a52b7e7a 708 });
3f455f90 709 };
8bc844c0 710
fc7b22dc
DI
711 /**
712 * Binds copy functionality to the given terminal.
713 * @static
714 */
715 Terminal.bindCopy = function(term) {
716 on(term.element, 'copy', function(ev) {
717 return; // temporary
8bc844c0 718 });
3f455f90 719 };
8bc844c0 720
8bc844c0 721
107d1a14 722 /**
3f455f90
PK
723 * Insert the given row to the terminal or produce a new one
724 * if no row argument is passed. Return the inserted row.
107d1a14 725 * @param {HTMLElement} row (optional) The row to append to the terminal.
3f455f90
PK
726 */
727 Terminal.prototype.insertRow = function (row) {
728 if (typeof row != 'object') {
729 row = document.createElement('div');
730 }
8bc844c0 731
3f455f90
PK
732 this.rowContainer.appendChild(row);
733 this.children.push(row);
734
735 return row;
f3bd6145 736 };
8bc844c0 737
8bc844c0 738
fd5be55d
DI
739 /**
740 * Opens the terminal within an element.
741 *
742 * @param {HTMLElement} parent The element to create the terminal within.
3f455f90
PK
743 */
744 Terminal.prototype.open = function(parent) {
745 var self=this, i=0, div;
8bc844c0 746
3f455f90 747 this.parent = parent || this.parent;
8bc844c0 748
3f455f90
PK
749 if (!this.parent) {
750 throw new Error('Terminal requires a parent element.');
751 }
8bc844c0 752
3f455f90
PK
753 /*
754 * Grab global elements
755 */
756 this.context = this.parent.ownerDocument.defaultView;
757 this.document = this.parent.ownerDocument;
758 this.body = this.document.getElementsByTagName('body')[0];
759
760 /*
761 * Parse User-Agent
762 */
763 if (this.context.navigator && this.context.navigator.userAgent) {
3f455f90
PK
764 this.isMSIE = !!~this.context.navigator.userAgent.indexOf('MSIE');
765 }
8bc844c0 766
b01165c1 767 /*
768 * Find the users platform. We use this to interpret the meta key
769 * and ISO third level shifts.
770 * http://stackoverflow.com/questions/19877924/what-is-the-list-of-possible-values-for-navigator-platform-as-of-today
771 */
772 if (this.context.navigator && this.context.navigator.platform) {
773 this.isMac = contains(
774 this.context.navigator.platform,
775 ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K']
776 );
777 this.isIpad = this.context.navigator.platform === 'iPad';
778 this.isIphone = this.context.navigator.platform === 'iPhone';
779 this.isMSWindows = contains(
780 this.context.navigator.platform,
781 ['Windows', 'Win16', 'Win32', 'WinCE']
782 );
783 }
784
3f455f90
PK
785 /*
786 * Create main element container
787 */
788 this.element = this.document.createElement('div');
a523803d
AK
789 this.element.classList.add('terminal');
790 this.element.classList.add('xterm');
791 this.element.classList.add('xterm-theme-' + this.theme);
3f455f90
PK
792 this.element.setAttribute('tabindex', 0);
793
794 /*
795 * Create the container that will hold the lines of the terminal and then
796 * produce the lines the lines.
797 */
798 this.rowContainer = document.createElement('div');
799 this.rowContainer.classList.add('xterm-rows');
800 this.element.appendChild(this.rowContainer);
801 this.children = [];
802
fc7b22dc
DI
803 /*
804 * Create the container that will hold helpers like the textarea for
805 * capturing DOM Events. Then produce the helpers.
806 */
807 this.helperContainer = document.createElement('div');
808 this.helperContainer.classList.add('xterm-helpers');
26af6ffd 809 // TODO: This should probably be inserted once it's filled to prevent an additional layout
fc7b22dc
DI
810 this.element.appendChild(this.helperContainer);
811 this.textarea = document.createElement('textarea');
812 this.textarea.classList.add('xterm-helper-textarea');
813 this.textarea.setAttribute('autocorrect', 'off');
814 this.textarea.setAttribute('autocapitalize', 'off');
815 this.textarea.setAttribute('spellcheck', 'false');
816 this.textarea.tabIndex = 0;
817 this.textarea.onfocus = function() {
818 self.emit('focus', {terminal: self});
819 }
820 this.textarea.onblur = function() {
821 self.emit('blur', {terminal: self});
822 }
823 this.helperContainer.appendChild(this.textarea);
29000fb7 824
26af6ffd
DI
825 this.compositionView = document.createElement('div');
826 this.compositionView.classList.add('composition-view');
29000fb7 827 this.compositionHelper = new CompositionHelper(this.textarea, this.compositionView, this);
26af6ffd 828 this.helperContainer.appendChild(this.compositionView);
fc7b22dc 829
3f455f90
PK
830 for (; i < this.rows; i++) {
831 this.insertRow();
832 }
833 this.parent.appendChild(this.element);
8bc844c0 834
26af6ffd 835
3f455f90
PK
836 // Draw the screen.
837 this.refresh(0, this.rows - 1);
8bc844c0 838
3f455f90
PK
839 // Initialize global actions that
840 // need to be taken on the document.
841 this.initGlobal();
15f68335 842
3f455f90
PK
843 // Ensure there is a Terminal.focus.
844 this.focus();
15f68335 845
3f455f90 846 on(this.element, 'mouseup', function() {
f53f5735
TD
847 var selection = document.getSelection(),
848 collapsed = selection.isCollapsed,
849 isRange = typeof collapsed == 'boolean' ? !collapsed : selection.type == 'Range';
850 if (!isRange) {
3f455f90
PK
851 self.focus();
852 }
853 });
8bc844c0 854
3f455f90
PK
855 // Listen for mouse events and translate
856 // them into terminal mouse protocols.
857 this.bindMouse();
8bc844c0 858
3f455f90
PK
859 // Figure out whether boldness affects
860 // the character width of monospace fonts.
861 if (Terminal.brokenBold == null) {
862 Terminal.brokenBold = isBoldBroken(this.document);
8bc844c0
CJ
863 }
864
3f455f90
PK
865 this.emit('open');
866 };
8bc844c0 867
57300f51
PK
868
869 /**
870 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
871 * @param {string} addon The name of the addon to load
872 * @static
873 */
874 Terminal.loadAddon = function(addon, callback) {
875 if (typeof exports === 'object' && typeof module === 'object') {
876 // CommonJS
877 return require(__dirname + '/../addons/' + addon);
878 } else if (typeof define == 'function') {
879 // RequireJS
880 return require(['../addons/' + addon + '/' + addon], callback);
881 } else {
882 console.error('Cannot load a module without a CommonJS or RequireJS environment.');
883 return false;
884 }
885 };
886
887
107d1a14
PK
888 /**
889 * XTerm mouse events
890 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
891 * To better understand these
892 * the xterm code is very helpful:
893 * Relevant files:
894 * button.c, charproc.c, misc.c
895 * Relevant functions in xterm/button.c:
896 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
897 */
3f455f90 898 Terminal.prototype.bindMouse = function() {
107d1a14
PK
899 var el = this.element, self = this, pressed = 32;
900 var wheelEvent = ('onmousewheel' in this.context) ? 'mousewheel' : 'DOMMouseScroll';
8bc844c0 901
3f455f90
PK
902 // mouseup, mousedown, mousewheel
903 // left click: ^[[M 3<^[[M#3<
904 // mousewheel up: ^[[M`3>
905 function sendButton(ev) {
906 var button
907 , pos;
8bc844c0 908
3f455f90
PK
909 // get the xterm-style button
910 button = getButton(ev);
8bc844c0 911
3f455f90
PK
912 // get mouse coordinates
913 pos = getCoords(ev);
914 if (!pos) return;
8bc844c0 915
3f455f90 916 sendEvent(button, pos);
8bc844c0 917
59b79e9b 918 switch (ev.overrideType || ev.type) {
3f455f90
PK
919 case 'mousedown':
920 pressed = button;
8bc844c0 921 break;
3f455f90
PK
922 case 'mouseup':
923 // keep it at the left
924 // button, just in case.
925 pressed = 32;
8bc844c0 926 break;
3f455f90
PK
927 case wheelEvent:
928 // nothing. don't
929 // interfere with
930 // `pressed`.
8bc844c0 931 break;
3f455f90
PK
932 }
933 }
8bc844c0 934
3f455f90
PK
935 // motion example of a left click:
936 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
937 function sendMove(ev) {
938 var button = pressed
939 , pos;
8bc844c0 940
3f455f90
PK
941 pos = getCoords(ev);
942 if (!pos) return;
a7f50531 943
3f455f90
PK
944 // buttons marked as motions
945 // are incremented by 32
946 button += 32;
a7f50531 947
3f455f90
PK
948 sendEvent(button, pos);
949 }
efa0e3c1 950
3f455f90
PK
951 // encode button and
952 // position to characters
953 function encode(data, ch) {
954 if (!self.utfMouse) {
955 if (ch === 255) return data.push(0);
956 if (ch > 127) ch = 127;
957 data.push(ch);
958 } else {
959 if (ch === 2047) return data.push(0);
960 if (ch < 127) {
961 data.push(ch);
962 } else {
963 if (ch > 2047) ch = 2047;
964 data.push(0xC0 | (ch >> 6));
965 data.push(0x80 | (ch & 0x3F));
966 }
8bc844c0 967 }
3f455f90 968 }
8bc844c0 969
3f455f90
PK
970 // send a mouse event:
971 // regular/utf8: ^[[M Cb Cx Cy
972 // urxvt: ^[[ Cb ; Cx ; Cy M
973 // sgr: ^[[ Cb ; Cx ; Cy M/m
974 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
975 // locator: CSI P e ; P b ; P r ; P c ; P p & w
976 function sendEvent(button, pos) {
977 // self.emit('mouse', {
978 // x: pos.x - 32,
979 // y: pos.x - 32,
980 // button: button
981 // });
982
983 if (self.vt300Mouse) {
984 // NOTE: Unstable.
985 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
986 button &= 3;
987 pos.x -= 32;
988 pos.y -= 32;
989 var data = '\x1b[24';
990 if (button === 0) data += '1';
991 else if (button === 1) data += '3';
992 else if (button === 2) data += '5';
993 else if (button === 3) return;
994 else data += '0';
995 data += '~[' + pos.x + ',' + pos.y + ']\r';
996 self.send(data);
997 return;
998 }
8bc844c0 999
3f455f90
PK
1000 if (self.decLocator) {
1001 // NOTE: Unstable.
1002 button &= 3;
1003 pos.x -= 32;
1004 pos.y -= 32;
1005 if (button === 0) button = 2;
1006 else if (button === 1) button = 4;
1007 else if (button === 2) button = 6;
1008 else if (button === 3) button = 3;
1009 self.send('\x1b['
1010 + button
1011 + ';'
1012 + (button === 3 ? 4 : 0)
1013 + ';'
1014 + pos.y
1015 + ';'
1016 + pos.x
1017 + ';'
1018 + (pos.page || 0)
1019 + '&w');
1020 return;
1021 }
8bc844c0 1022
3f455f90
PK
1023 if (self.urxvtMouse) {
1024 pos.x -= 32;
1025 pos.y -= 32;
1026 pos.x++;
1027 pos.y++;
1028 self.send('\x1b[' + button + ';' + pos.x + ';' + pos.y + 'M');
1029 return;
1030 }
8bc844c0 1031
3f455f90
PK
1032 if (self.sgrMouse) {
1033 pos.x -= 32;
1034 pos.y -= 32;
1035 self.send('\x1b[<'
1036 + ((button & 3) === 3 ? button & ~3 : button)
1037 + ';'
1038 + pos.x
1039 + ';'
1040 + pos.y
1041 + ((button & 3) === 3 ? 'm' : 'M'));
1042 return;
1043 }
8bc844c0 1044
3f455f90 1045 var data = [];
8bc844c0 1046
3f455f90
PK
1047 encode(data, button);
1048 encode(data, pos.x);
1049 encode(data, pos.y);
8bc844c0 1050
3f455f90
PK
1051 self.send('\x1b[M' + String.fromCharCode.apply(String, data));
1052 }
8bc844c0 1053
3f455f90
PK
1054 function getButton(ev) {
1055 var button
1056 , shift
1057 , meta
1058 , ctrl
1059 , mod;
1060
1061 // two low bits:
1062 // 0 = left
1063 // 1 = middle
1064 // 2 = right
1065 // 3 = release
1066 // wheel up/down:
1067 // 1, and 2 - with 64 added
59b79e9b 1068 switch (ev.overrideType || ev.type) {
3f455f90
PK
1069 case 'mousedown':
1070 button = ev.button != null
1071 ? +ev.button
1072 : ev.which != null
1073 ? ev.which - 1
1074 : null;
1075
1076 if (self.isMSIE) {
1077 button = button === 1 ? 0 : button === 4 ? 1 : button;
8bc844c0 1078 }
8bc844c0 1079 break;
3f455f90
PK
1080 case 'mouseup':
1081 button = 3;
8bc844c0 1082 break;
3f455f90
PK
1083 case 'DOMMouseScroll':
1084 button = ev.detail < 0
1085 ? 64
1086 : 65;
8bc844c0 1087 break;
3f455f90
PK
1088 case 'mousewheel':
1089 button = ev.wheelDeltaY > 0
1090 ? 64
1091 : 65;
8bc844c0 1092 break;
3f455f90 1093 }
8bc844c0 1094
3f455f90
PK
1095 // next three bits are the modifiers:
1096 // 4 = shift, 8 = meta, 16 = control
1097 shift = ev.shiftKey ? 4 : 0;
1098 meta = ev.metaKey ? 8 : 0;
1099 ctrl = ev.ctrlKey ? 16 : 0;
1100 mod = shift | meta | ctrl;
1101
1102 // no mods
1103 if (self.vt200Mouse) {
1104 // ctrl only
1105 mod &= ctrl;
1106 } else if (!self.normalMouse) {
1107 mod = 0;
1108 }
8bc844c0 1109
3f455f90
PK
1110 // increment to SP
1111 button = (32 + (mod << 2)) + button;
8bc844c0 1112
3f455f90
PK
1113 return button;
1114 }
8bc844c0 1115
3f455f90
PK
1116 // mouse coordinates measured in cols/rows
1117 function getCoords(ev) {
1118 var x, y, w, h, el;
1119
1120 // ignore browsers without pageX for now
1121 if (ev.pageX == null) return;
1122
1123 x = ev.pageX;
1124 y = ev.pageY;
1125 el = self.element;
1126
1127 // should probably check offsetParent
1128 // but this is more portable
1129 while (el && el !== self.document.documentElement) {
1130 x -= el.offsetLeft;
1131 y -= el.offsetTop;
1132 el = 'offsetParent' in el
1133 ? el.offsetParent
1134 : el.parentNode;
1135 }
8bc844c0 1136
3f455f90
PK
1137 // convert to cols/rows
1138 w = self.element.clientWidth;
1139 h = self.element.clientHeight;
1140 x = Math.round((x / w) * self.cols);
1141 y = Math.round((y / h) * self.rows);
1142
1143 // be sure to avoid sending
1144 // bad positions to the program
1145 if (x < 0) x = 0;
1146 if (x > self.cols) x = self.cols;
1147 if (y < 0) y = 0;
1148 if (y > self.rows) y = self.rows;
1149
1150 // xterm sends raw bytes and
1151 // starts at 32 (SP) for each.
1152 x += 32;
1153 y += 32;
1154
1155 return {
1156 x: x,
1157 y: y,
59b79e9b 1158 type: (ev.overrideType || ev.type) === wheelEvent
3f455f90 1159 ? 'mousewheel'
59b79e9b 1160 : (ev.overrideType || ev.type)
3f455f90
PK
1161 };
1162 }
8bc844c0 1163
3f455f90
PK
1164 on(el, 'mousedown', function(ev) {
1165 if (!self.mouseEvents) return;
8bc844c0 1166
3f455f90
PK
1167 // send the button
1168 sendButton(ev);
1169
1170 // ensure focus
1171 self.focus();
1172
1173 // fix for odd bug
1174 //if (self.vt200Mouse && !self.normalMouse) {
1175 if (self.vt200Mouse) {
59b79e9b
BF
1176 ev.overrideType = 'mouseup';
1177 sendButton(ev);
3f455f90 1178 return self.cancel(ev);
8bc844c0 1179 }
8bc844c0 1180
3f455f90
PK
1181 // bind events
1182 if (self.normalMouse) on(self.document, 'mousemove', sendMove);
1183
1184 // x10 compatibility mode can't send button releases
1185 if (!self.x10Mouse) {
1186 on(self.document, 'mouseup', function up(ev) {
1187 sendButton(ev);
1188 if (self.normalMouse) off(self.document, 'mousemove', sendMove);
1189 off(self.document, 'mouseup', up);
1190 return self.cancel(ev);
1191 });
8bc844c0 1192 }
3f455f90
PK
1193
1194 return self.cancel(ev);
1195 });
1196
1197 //if (self.normalMouse) {
1198 // on(self.document, 'mousemove', sendMove);
1199 //}
1200
1201 on(el, wheelEvent, function(ev) {
1202 if (!self.mouseEvents) return;
1203 if (self.x10Mouse
1204 || self.vt300Mouse
1205 || self.decLocator) return;
1206 sendButton(ev);
1207 return self.cancel(ev);
1208 });
1209
1210 // allow mousewheel scrolling in
1211 // the shell for example
1212 on(el, wheelEvent, function(ev) {
1213 if (self.mouseEvents) return;
1214 if (self.applicationKeypad) return;
1215 if (ev.type === 'DOMMouseScroll') {
1216 self.scrollDisp(ev.detail < 0 ? -1 : 1);
1217 } else {
1218 self.scrollDisp(ev.wheelDeltaY > 0 ? -1 : 1);
1219 }
1220 return self.cancel(ev);
1221 });
1222 };
1223
1224 /**
fd5be55d 1225 * Destroys the terminal.
3f455f90 1226 */
3f455f90
PK
1227 Terminal.prototype.destroy = function() {
1228 this.readable = false;
1229 this.writable = false;
1230 this._events = {};
1231 this.handler = function() {};
1232 this.write = function() {};
1233 if (this.element.parentNode) {
1234 this.element.parentNode.removeChild(this.element);
1235 }
1236 //this.emit('close');
1237 };
1238
1239
1a384616
PK
1240 /**
1241 * Flags used to render terminal text properly
1242 */
1243 Terminal.flags = {
5a56849d
PK
1244 BOLD: 1,
1245 UNDERLINE: 2,
1246 BLINK: 4,
1247 INVERSE: 8,
1248 INVISIBLE: 16
1a384616
PK
1249 }
1250
fd5be55d 1251 /**
1aeb5620
PK
1252 * Refreshes (re-renders) terminal content within two rows (inclusive)
1253 *
1254 * Rendering Engine:
1255 *
1256 * In the screen buffer, each character is stored as a an array with a character
1257 * and a 32-bit integer:
1258 * - First value: a utf-16 character.
1259 * - Second value:
1260 * - Next 9 bits: background color (0-511).
1261 * - Next 9 bits: foreground color (0-511).
1262 * - Next 14 bits: a mask for misc. flags:
1263 * - 1=bold
1264 * - 2=underline
1265 * - 4=blink
1266 * - 8=inverse
1267 * - 16=invisible
fd5be55d
DI
1268 *
1269 * @param {number} start The row to start from (between 0 and terminal's height terminal - 1)
1270 * @param {number} end The row to end at (between fromRow and terminal's height terminal - 1)
a6e85ad5 1271 * @param {boolean} queue Whether the refresh should ran right now or be queued
fd5be55d 1272 */
a6e85ad5
PK
1273 Terminal.prototype.refresh = function(start, end, queue) {
1274 var self = this;
1275
1276 // queue defaults to true
1277 queue = (typeof queue == 'undefined') ? true : queue;
3f455f90 1278
a6e85ad5
PK
1279 /**
1280 * The refresh queue allows refresh to execute only approximately 30 times a second. For
1281 * commands that pass a significant amount of output to the write function, this prevents the
1282 * terminal from maxing out the CPU and making the UI unresponsive. While commands can still
1283 * run beyond what they do on the terminal, it is far better with a debounce in place as
1284 * every single terminal manipulation does not need to be constructed in the DOM.
1285 *
1286 * A side-effect of this is that it makes ^C to interrupt a process seem more responsive.
1287 */
1288 if (queue) {
1289 // If refresh should be queued, order the refresh and return.
1290 if (this._refreshIsQueued) {
1291 // If a refresh has already been queued, just order a full refresh next
1292 this._fullRefreshNext = true;
1293 } else {
1294 setTimeout(function () {
1295 self.refresh(start, end, false);
1296 }, 34)
1297 this._refreshIsQueued = true;
1298 }
af29effb
DI
1299 return;
1300 }
a6e85ad5
PK
1301
1302 // If refresh should be run right now (not be queued), release the lock
1303 this._refreshIsQueued = false;
1304
1305 // If multiple refreshes were requested, make a full refresh.
1306 if (this._fullRefreshNext) {
1307 start = 0;
1308 end = this.rows - 1;
1309 this._fullRefreshNext = false // reset lock
1310 }
1311
874ba72f 1312 var x, y, i, line, out, ch, ch_width, width, data, attr, bg, fg, flags, row, parent, focused = document.activeElement;
af29effb 1313
af7588ef 1314 // If this is a big refresh, remove the terminal rows from the DOM for faster calculations
3f455f90
PK
1315 if (end - start >= this.rows / 2) {
1316 parent = this.element.parentNode;
af7588ef
PK
1317 if (parent) {
1318 this.element.removeChild(this.rowContainer);
1319 }
3f455f90
PK
1320 }
1321
1322 width = this.cols;
1323 y = start;
1324
edf89718 1325 if (end >= this.rows.length) {
3f455f90 1326 this.log('`end` is too large. Most likely a bad CSR.');
edf89718 1327 end = this.rows.length - 1;
3f455f90
PK
1328 }
1329
1330 for (; y <= end; y++) {
1331 row = y + this.ydisp;
1332
1333 line = this.lines[row];
1334 out = '';
1335
da9f86f1 1336 if (this.y === y - (this.ybase - this.ydisp)
3f455f90 1337 && this.cursorState
3f455f90
PK
1338 && !this.cursorHidden) {
1339 x = this.x;
1340 } else {
1341 x = -1;
1342 }
1343
1344 attr = this.defAttr;
1345 i = 0;
1346
1347 for (; i < width; i++) {
1348 data = line[i][0];
1349 ch = line[i][1];
f951abb7 1350 ch_width = line[i][2];
874ba72f
JB
1351 if (!ch_width)
1352 continue;
3f455f90
PK
1353
1354 if (i === x) data = -1;
1355
1356 if (data !== attr) {
1357 if (attr !== this.defAttr) {
1358 out += '</span>';
1359 }
1360 if (data !== this.defAttr) {
1361 if (data === -1) {
0d803ac8
DI
1362 out += '<span class="reverse-video terminal-cursor';
1363 if (this.cursorBlink) {
1364 out += ' blinking';
1365 }
1366 out += '">';
3f455f90 1367 } else {
ae0f9637 1368 var classNames = [];
3f455f90
PK
1369
1370 bg = data & 0x1ff;
1371 fg = (data >> 9) & 0x1ff;
1372 flags = data >> 18;
1373
1a384616 1374 if (flags & Terminal.flags.BOLD) {
3f455f90 1375 if (!Terminal.brokenBold) {
ae0f9637 1376 classNames.push('xterm-bold');
3f455f90
PK
1377 }
1378 // See: XTerm*boldColors
1379 if (fg < 8) fg += 8;
1380 }
1381
1a384616 1382 if (flags & Terminal.flags.UNDERLINE) {
ae0f9637 1383 classNames.push('xterm-underline');
3f455f90
PK
1384 }
1385
1a384616 1386 if (flags & Terminal.flags.BLINK) {
ae0f9637 1387 classNames.push('xterm-blink');
3f455f90
PK
1388 }
1389
1a384616
PK
1390 /**
1391 * If inverse flag is on, then swap the foreground and background variables.
1392 */
1393 if (flags & Terminal.flags.INVERSE) {
1394 /* One-line variable swap in JavaScript: http://stackoverflow.com/a/16201730 */
1395 bg = [fg, fg = bg][0];
1396 // Should inverse just be before the
1397 // above boldColors effect instead?
1398 if ((flags & 1) && fg < 8) fg += 8;
3f455f90
PK
1399 }
1400
1a384616 1401 if (flags & Terminal.flags.INVISIBLE) {
ae0f9637 1402 classNames.push('xterm-hidden');
3f455f90
PK
1403 }
1404
1a384616
PK
1405 /**
1406 * Weird situation: Invert flag used black foreground and white background results
1407 * in invalid background color, positioned at the 256 index of the 256 terminal
1408 * color map. Pin the colors manually in such a case.
1409 *
1410 * Source: https://github.com/sourcelair/xterm.js/issues/57
1411 */
1412 if (flags & Terminal.flags.INVERSE) {
1413 if (bg == 257) {
1414 bg = 15;
1415 }
1416 if (fg == 256) {
1417 fg = 0;
1418 }
1419 }
1420
1421 if (bg < 256) {
ae0f9637 1422 classNames.push('xterm-bg-color-' + bg);
3f455f90
PK
1423 }
1424
1a384616 1425 if (fg < 256) {
ae0f9637 1426 classNames.push('xterm-color-' + fg);
3f455f90
PK
1427 }
1428
ae0f9637
DI
1429 out += '<span';
1430 if (classNames.length) {
1431 out += ' class="' + classNames.join(' ') + '"';
1432 }
1433 out += '>';
8bc844c0 1434 }
3f455f90
PK
1435 }
1436 }
1437
1438 switch (ch) {
1439 case '&':
1440 out += '&amp;';
8bc844c0 1441 break;
3f455f90
PK
1442 case '<':
1443 out += '&lt;';
8bc844c0 1444 break;
3f455f90
PK
1445 case '>':
1446 out += '&gt;';
8bc844c0 1447 break;
3f455f90
PK
1448 default:
1449 if (ch <= ' ') {
1450 out += '&nbsp;';
1451 } else {
3f455f90
PK
1452 out += ch;
1453 }
8bc844c0
CJ
1454 break;
1455 }
1456
3f455f90 1457 attr = data;
8bc844c0 1458 }
8bc844c0 1459
3f455f90
PK
1460 if (attr !== this.defAttr) {
1461 out += '</span>';
8bc844c0
CJ
1462 }
1463
3f455f90
PK
1464 this.children[y].innerHTML = out;
1465 }
8bc844c0 1466
3f455f90 1467 if (parent) {
af7588ef 1468 this.element.appendChild(this.rowContainer);
3f455f90
PK
1469 }
1470
29000fb7 1471 // TODO: Attach to refresh event instead?
cab79c47 1472 term.compositionHelper.updateCompositionViewPosition();
26af6ffd 1473
3f455f90
PK
1474 this.emit('refresh', {element: this.element, start: start, end: end});
1475 };
1476
107d1a14
PK
1477 /**
1478 * Display the cursor element
1479 */
3f455f90
PK
1480 Terminal.prototype.showCursor = function() {
1481 if (!this.cursorState) {
1482 this.cursorState = 1;
1483 this.refresh(this.y, this.y);
3f455f90
PK
1484 }
1485 };
1486
107d1a14
PK
1487 /**
1488 * Scroll the terminal
1489 */
3f455f90
PK
1490 Terminal.prototype.scroll = function() {
1491 var row;
1492
1493 if (++this.ybase === this.scrollback) {
1494 this.ybase = this.ybase / 2 | 0;
1495 this.lines = this.lines.slice(-(this.ybase + this.rows) + 1);
1496 }
1497
1498 this.ydisp = this.ybase;
1499
1500 // last line
1501 row = this.ybase + this.rows - 1;
1502
1503 // subtract the bottom scroll region
1504 row -= this.rows - 1 - this.scrollBottom;
1505
1506 if (row === this.lines.length) {
1507 // potential optimization:
1508 // pushing is faster than splicing
1509 // when they amount to the same
1510 // behavior.
1511 this.lines.push(this.blankLine());
1512 } else {
1513 // add our new line
1514 this.lines.splice(row, 0, this.blankLine());
1515 }
1516
1517 if (this.scrollTop !== 0) {
1518 if (this.ybase !== 0) {
1519 this.ybase--;
1520 this.ydisp = this.ybase;
8bc844c0 1521 }
3f455f90
PK
1522 this.lines.splice(this.ybase + this.scrollTop, 1);
1523 }
8bc844c0 1524
3f455f90
PK
1525 // this.maxRange();
1526 this.updateRange(this.scrollTop);
1527 this.updateRange(this.scrollBottom);
1528 };
8bc844c0 1529
107d1a14
PK
1530 /**
1531 * Scroll the display of the terminal
f3cf646b 1532 * @param {number} disp The number of lines to scroll down (negatives scroll up).
107d1a14 1533 */
3f455f90
PK
1534 Terminal.prototype.scrollDisp = function(disp) {
1535 this.ydisp += disp;
8bc844c0 1536
3f455f90
PK
1537 if (this.ydisp > this.ybase) {
1538 this.ydisp = this.ybase;
1539 } else if (this.ydisp < 0) {
1540 this.ydisp = 0;
1541 }
8bc844c0 1542
3f455f90
PK
1543 this.refresh(0, this.rows - 1);
1544 };
8bc844c0 1545
fd5be55d
DI
1546 /**
1547 * Writes text to the terminal.
fd5be55d 1548 * @param {string} text The text to write to the terminal.
fd5be55d 1549 */
3f455f90 1550 Terminal.prototype.write = function(data) {
4afa08da 1551 var l = data.length, i = 0, j, cs, ch, code, low, ch_width, row;
8bc844c0 1552
3f455f90
PK
1553 this.refreshStart = this.y;
1554 this.refreshEnd = this.y;
8bc844c0 1555
3f455f90
PK
1556 if (this.ybase !== this.ydisp) {
1557 this.ydisp = this.ybase;
1558 this.maxRange();
1559 }
8bc844c0 1560
e3126ba3
JB
1561 // apply leftover surrogate high from last write
1562 if (this.surrogate_high) {
1563 data = this.surrogate_high + data;
1564 this.surrogate_high = '';
1565 }
874ba72f 1566
3f455f90
PK
1567 for (; i < l; i++) {
1568 ch = data[i];
874ba72f 1569
e3126ba3
JB
1570 // FIXME: higher chars than 0xa0 are not allowed in escape sequences
1571 // --> maybe move to default
874ba72f 1572 code = data.charCodeAt(i);
874ba72f 1573 if (0xD800 <= code && code <= 0xDBFF) {
e3126ba3
JB
1574 // we got a surrogate high
1575 // get surrogate low (next 2 bytes)
1576 low = data.charCodeAt(i+1);
1577 if (isNaN(low)) {
1578 // end of data stream, save surrogate high
1579 this.surrogate_high = ch;
1580 continue;
1581 }
1582 code = ((code - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
1583 ch += data.charAt(i+1);
874ba72f
JB
1584 }
1585 // surrogate low - already handled above
1586 if (0xDC00 <= code && code <= 0xDFFF)
e3126ba3 1587 continue;
874ba72f 1588
3f455f90
PK
1589 switch (this.state) {
1590 case normal:
1591 switch (ch) {
1592 case '\x07':
1593 this.bell();
1594 break;
8bc844c0 1595
3f455f90
PK
1596 // '\n', '\v', '\f'
1597 case '\n':
1598 case '\x0b':
1599 case '\x0c':
1600 if (this.convertEol) {
1601 this.x = 0;
1602 }
1603 this.y++;
1604 if (this.y > this.scrollBottom) {
1605 this.y--;
1606 this.scroll();
1607 }
1608 break;
8bc844c0 1609
3f455f90
PK
1610 // '\r'
1611 case '\r':
1612 this.x = 0;
1613 break;
8bc844c0 1614
3f455f90
PK
1615 // '\b'
1616 case '\x08':
1617 if (this.x > 0) {
1618 this.x--;
1619 }
1620 break;
1621
1622 // '\t'
1623 case '\t':
1624 this.x = this.nextStop();
1625 break;
8bc844c0 1626
3f455f90
PK
1627 // shift out
1628 case '\x0e':
1629 this.setgLevel(1);
1630 break;
1631
1632 // shift in
1633 case '\x0f':
1634 this.setgLevel(0);
1635 break;
1636
1637 // '\e'
1638 case '\x1b':
1639 this.state = escaped;
1640 break;
1641
1642 default:
1643 // ' '
e3126ba3
JB
1644 // calculate print space
1645 // expensive call, therefore we save width in line buffer
1646 ch_width = wcwidth(code);
f951abb7 1647
3f455f90
PK
1648 if (ch >= ' ') {
1649 if (this.charset && this.charset[ch]) {
1650 ch = this.charset[ch];
1651 }
1652
4afa08da
JB
1653 row = this.y + this.ybase;
1654
e3126ba3 1655 // insert combining char in last cell
c3bc59b5 1656 // FIXME: needs handling after cursor jumps
874ba72f 1657 if (!ch_width && this.x) {
0b018fd4 1658
c3bc59b5 1659 // dont overflow left
4afa08da
JB
1660 if (this.lines[row][this.x-1]) {
1661 if (!this.lines[row][this.x-1][2]) {
c3bc59b5
JB
1662
1663 // found empty cell after fullwidth, need to go 2 cells back
4afa08da
JB
1664 if (this.lines[row][this.x-2])
1665 this.lines[row][this.x-2][1] += ch;
c3bc59b5
JB
1666
1667 } else {
4afa08da 1668 this.lines[row][this.x-1][1] += ch;
c3bc59b5
JB
1669 }
1670 this.updateRange(this.y);
1671 }
874ba72f
JB
1672 break;
1673 }
1674
e3126ba3
JB
1675 // goto next line if ch would overflow
1676 // TODO: needs a global min terminal width of 2
1677 if (this.x+ch_width-1 >= this.cols) {
4afa08da
JB
1678 // autowrap - DECAWM
1679 if (this.wraparoundMode) {
1680 this.x = 0;
1681 this.y++;
1682 if (this.y > this.scrollBottom) {
1683 this.y--;
1684 this.scroll();
1685 }
1686 } else {
1687 this.x = this.cols-1;
1688 if(ch_width===2) // FIXME: check for xterm behavior
1689 continue;
1690 }
1691 }
1692 row = this.y + this.ybase;
1693
1694 // insert mode: move characters to right
1695 if (this.insertMode) {
1696 // do this twice for a fullwidth char
1697 for (var moves=0; moves<ch_width; ++moves) {
1698 // remove last cell, if it's width is 0
1699 // we have to adjust the second last cell as well
1700 var removed = this.lines[this.y + this.ybase].pop();
1701 if (removed[2]===0
1702 && this.lines[row][this.cols-2]
1703 && this.lines[row][this.cols-2][2]===2)
1704 this.lines[row][this.cols-2] = [this.curAttr, ' ', 1];
1705
1706 // insert empty cell at cursor
1707 this.lines[row].splice(this.x, 0, [this.curAttr, ' ', 1]);
3f455f90
PK
1708 }
1709 }
1710
4afa08da 1711 this.lines[row][this.x] = [this.curAttr, ch, ch_width];
3f455f90
PK
1712 this.x++;
1713 this.updateRange(this.y);
1714
e3126ba3 1715 // fullwidth char - set next cell width to zero and advance cursor
4afa08da
JB
1716 if (ch_width===2) {
1717 this.lines[row][this.x] = [this.curAttr, '', 0];
3f455f90
PK
1718 this.x++;
1719 }
1720 }
1721 break;
a4607f90 1722 }
8bc844c0 1723 break;
3f455f90
PK
1724 case escaped:
1725 switch (ch) {
1726 // ESC [ Control Sequence Introducer ( CSI is 0x9b).
1727 case '[':
1728 this.params = [];
1729 this.currentParam = 0;
1730 this.state = csi;
1731 break;
8bc844c0 1732
3f455f90
PK
1733 // ESC ] Operating System Command ( OSC is 0x9d).
1734 case ']':
1735 this.params = [];
1736 this.currentParam = 0;
1737 this.state = osc;
1738 break;
8bc844c0 1739
3f455f90
PK
1740 // ESC P Device Control String ( DCS is 0x90).
1741 case 'P':
1742 this.params = [];
1743 this.currentParam = 0;
1744 this.state = dcs;
1745 break;
8bc844c0 1746
3f455f90
PK
1747 // ESC _ Application Program Command ( APC is 0x9f).
1748 case '_':
1749 this.state = ignore;
1750 break;
8bc844c0 1751
3f455f90
PK
1752 // ESC ^ Privacy Message ( PM is 0x9e).
1753 case '^':
1754 this.state = ignore;
1755 break;
8bc844c0 1756
3f455f90
PK
1757 // ESC c Full Reset (RIS).
1758 case 'c':
1759 this.reset();
1760 break;
8bc844c0 1761
3f455f90
PK
1762 // ESC E Next Line ( NEL is 0x85).
1763 // ESC D Index ( IND is 0x84).
1764 case 'E':
1765 this.x = 0;
1766 ;
1767 case 'D':
1768 this.index();
1769 break;
8bc844c0 1770
3f455f90
PK
1771 // ESC M Reverse Index ( RI is 0x8d).
1772 case 'M':
1773 this.reverseIndex();
1774 break;
8bc844c0 1775
3f455f90
PK
1776 // ESC % Select default/utf-8 character set.
1777 // @ = default, G = utf-8
1778 case '%':
1779 //this.charset = null;
1780 this.setgLevel(0);
1781 this.setgCharset(0, Terminal.charsets.US);
1782 this.state = normal;
1783 i++;
1784 break;
8bc844c0 1785
3f455f90
PK
1786 // ESC (,),*,+,-,. Designate G0-G2 Character Set.
1787 case '(': // <-- this seems to get all the attention
1788 case ')':
1789 case '*':
1790 case '+':
1791 case '-':
1792 case '.':
1793 switch (ch) {
1794 case '(':
1795 this.gcharset = 0;
1796 break;
1797 case ')':
1798 this.gcharset = 1;
1799 break;
1800 case '*':
1801 this.gcharset = 2;
1802 break;
1803 case '+':
1804 this.gcharset = 3;
1805 break;
1806 case '-':
1807 this.gcharset = 1;
1808 break;
1809 case '.':
1810 this.gcharset = 2;
1811 break;
1812 }
1813 this.state = charset;
1814 break;
8bc844c0 1815
3f455f90
PK
1816 // Designate G3 Character Set (VT300).
1817 // A = ISO Latin-1 Supplemental.
1818 // Not implemented.
1819 case '/':
1820 this.gcharset = 3;
1821 this.state = charset;
1822 i--;
1823 break;
8bc844c0 1824
3f455f90
PK
1825 // ESC N
1826 // Single Shift Select of G2 Character Set
1827 // ( SS2 is 0x8e). This affects next character only.
1828 case 'N':
1829 break;
1830 // ESC O
1831 // Single Shift Select of G3 Character Set
1832 // ( SS3 is 0x8f). This affects next character only.
1833 case 'O':
1834 break;
1835 // ESC n
1836 // Invoke the G2 Character Set as GL (LS2).
1837 case 'n':
1838 this.setgLevel(2);
1839 break;
1840 // ESC o
1841 // Invoke the G3 Character Set as GL (LS3).
1842 case 'o':
1843 this.setgLevel(3);
1844 break;
1845 // ESC |
1846 // Invoke the G3 Character Set as GR (LS3R).
1847 case '|':
1848 this.setgLevel(3);
1849 break;
1850 // ESC }
1851 // Invoke the G2 Character Set as GR (LS2R).
1852 case '}':
1853 this.setgLevel(2);
1854 break;
1855 // ESC ~
1856 // Invoke the G1 Character Set as GR (LS1R).
1857 case '~':
1858 this.setgLevel(1);
1859 break;
8bc844c0 1860
3f455f90
PK
1861 // ESC 7 Save Cursor (DECSC).
1862 case '7':
1863 this.saveCursor();
1864 this.state = normal;
1865 break;
8bc844c0 1866
3f455f90
PK
1867 // ESC 8 Restore Cursor (DECRC).
1868 case '8':
1869 this.restoreCursor();
1870 this.state = normal;
1871 break;
8bc844c0 1872
3f455f90
PK
1873 // ESC # 3 DEC line height/width
1874 case '#':
1875 this.state = normal;
1876 i++;
1877 break;
8bc844c0 1878
3f455f90
PK
1879 // ESC H Tab Set (HTS is 0x88).
1880 case 'H':
1881 this.tabSet();
1882 break;
8bc844c0 1883
3f455f90
PK
1884 // ESC = Application Keypad (DECPAM).
1885 case '=':
1886 this.log('Serial port requested application keypad.');
1887 this.applicationKeypad = true;
1888 this.state = normal;
1889 break;
8bc844c0 1890
3f455f90
PK
1891 // ESC > Normal Keypad (DECPNM).
1892 case '>':
1893 this.log('Switching back to normal keypad.');
1894 this.applicationKeypad = false;
1895 this.state = normal;
1896 break;
8bc844c0 1897
3f455f90
PK
1898 default:
1899 this.state = normal;
1900 this.error('Unknown ESC control: %s.', ch);
1901 break;
1902 }
8bc844c0
CJ
1903 break;
1904
3f455f90
PK
1905 case charset:
1906 switch (ch) {
1907 case '0': // DEC Special Character and Line Drawing Set.
1908 cs = Terminal.charsets.SCLD;
1909 break;
1910 case 'A': // UK
1911 cs = Terminal.charsets.UK;
1912 break;
1913 case 'B': // United States (USASCII).
1914 cs = Terminal.charsets.US;
1915 break;
1916 case '4': // Dutch
1917 cs = Terminal.charsets.Dutch;
1918 break;
1919 case 'C': // Finnish
1920 case '5':
1921 cs = Terminal.charsets.Finnish;
1922 break;
1923 case 'R': // French
1924 cs = Terminal.charsets.French;
1925 break;
1926 case 'Q': // FrenchCanadian
1927 cs = Terminal.charsets.FrenchCanadian;
1928 break;
1929 case 'K': // German
1930 cs = Terminal.charsets.German;
1931 break;
1932 case 'Y': // Italian
1933 cs = Terminal.charsets.Italian;
1934 break;
1935 case 'E': // NorwegianDanish
1936 case '6':
1937 cs = Terminal.charsets.NorwegianDanish;
1938 break;
1939 case 'Z': // Spanish
1940 cs = Terminal.charsets.Spanish;
1941 break;
1942 case 'H': // Swedish
1943 case '7':
1944 cs = Terminal.charsets.Swedish;
1945 break;
1946 case '=': // Swiss
1947 cs = Terminal.charsets.Swiss;
1948 break;
1949 case '/': // ISOLatin (actually /A)
1950 cs = Terminal.charsets.ISOLatin;
1951 i++;
1952 break;
1953 default: // Default
1954 cs = Terminal.charsets.US;
1955 break;
1956 }
1957 this.setgCharset(this.gcharset, cs);
1958 this.gcharset = null;
1959 this.state = normal;
8bc844c0
CJ
1960 break;
1961
3f455f90
PK
1962 case osc:
1963 // OSC Ps ; Pt ST
1964 // OSC Ps ; Pt BEL
1965 // Set Text Parameters.
1966 if (ch === '\x1b' || ch === '\x07') {
1967 if (ch === '\x1b') i++;
8bc844c0 1968
3f455f90 1969 this.params.push(this.currentParam);
8bc844c0 1970
3f455f90
PK
1971 switch (this.params[0]) {
1972 case 0:
1973 case 1:
1974 case 2:
1975 if (this.params[1]) {
1976 this.title = this.params[1];
1977 this.handleTitle(this.title);
1978 }
1979 break;
1980 case 3:
1981 // set X property
1982 break;
1983 case 4:
1984 case 5:
1985 // change dynamic colors
1986 break;
1987 case 10:
1988 case 11:
1989 case 12:
1990 case 13:
1991 case 14:
1992 case 15:
1993 case 16:
1994 case 17:
1995 case 18:
1996 case 19:
1997 // change dynamic ui colors
1998 break;
1999 case 46:
2000 // change log file
2001 break;
2002 case 50:
2003 // dynamic font
2004 break;
2005 case 51:
2006 // emacs shell
2007 break;
2008 case 52:
2009 // manipulate selection data
2010 break;
2011 case 104:
2012 case 105:
2013 case 110:
2014 case 111:
2015 case 112:
2016 case 113:
2017 case 114:
2018 case 115:
2019 case 116:
2020 case 117:
2021 case 118:
2022 // reset colors
2023 break;
2024 }
8bc844c0 2025
3f455f90
PK
2026 this.params = [];
2027 this.currentParam = 0;
2028 this.state = normal;
2029 } else {
2030 if (!this.params.length) {
2031 if (ch >= '0' && ch <= '9') {
2032 this.currentParam =
2033 this.currentParam * 10 + ch.charCodeAt(0) - 48;
2034 } else if (ch === ';') {
2035 this.params.push(this.currentParam);
2036 this.currentParam = '';
2037 }
2038 } else {
2039 this.currentParam += ch;
2040 }
2041 }
8bc844c0
CJ
2042 break;
2043
3f455f90
PK
2044 case csi:
2045 // '?', '>', '!'
2046 if (ch === '?' || ch === '>' || ch === '!') {
2047 this.prefix = ch;
2048 break;
8bc844c0 2049 }
8bc844c0 2050
3f455f90
PK
2051 // 0 - 9
2052 if (ch >= '0' && ch <= '9') {
2053 this.currentParam = this.currentParam * 10 + ch.charCodeAt(0) - 48;
2054 break;
2055 }
8bc844c0 2056
3f455f90
PK
2057 // '$', '"', ' ', '\''
2058 if (ch === '$' || ch === '"' || ch === ' ' || ch === '\'') {
2059 this.postfix = ch;
2060 break;
2061 }
2062
2063 this.params.push(this.currentParam);
2064 this.currentParam = 0;
2065
2066 // ';'
2067 if (ch === ';') break;
2068
2069 this.state = normal;
2070
2071 switch (ch) {
2072 // CSI Ps A
2073 // Cursor Up Ps Times (default = 1) (CUU).
2074 case 'A':
2075 this.cursorUp(this.params);
2076 break;
2077
2078 // CSI Ps B
2079 // Cursor Down Ps Times (default = 1) (CUD).
2080 case 'B':
2081 this.cursorDown(this.params);
2082 break;
2083
2084 // CSI Ps C
2085 // Cursor Forward Ps Times (default = 1) (CUF).
2086 case 'C':
2087 this.cursorForward(this.params);
2088 break;
2089
2090 // CSI Ps D
2091 // Cursor Backward Ps Times (default = 1) (CUB).
2092 case 'D':
2093 this.cursorBackward(this.params);
2094 break;
2095
2096 // CSI Ps ; Ps H
2097 // Cursor Position [row;column] (default = [1,1]) (CUP).
2098 case 'H':
2099 this.cursorPos(this.params);
2100 break;
2101
2102 // CSI Ps J Erase in Display (ED).
2103 case 'J':
2104 this.eraseInDisplay(this.params);
2105 break;
2106
2107 // CSI Ps K Erase in Line (EL).
2108 case 'K':
2109 this.eraseInLine(this.params);
2110 break;
2111
2112 // CSI Pm m Character Attributes (SGR).
2113 case 'm':
2114 if (!this.prefix) {
2115 this.charAttributes(this.params);
2116 }
2117 break;
2118
2119 // CSI Ps n Device Status Report (DSR).
2120 case 'n':
2121 if (!this.prefix) {
2122 this.deviceStatus(this.params);
2123 }
2124 break;
2125
2126 /**
2127 * Additions
2128 */
2129
2130 // CSI Ps @
2131 // Insert Ps (Blank) Character(s) (default = 1) (ICH).
2132 case '@':
2133 this.insertChars(this.params);
2134 break;
2135
2136 // CSI Ps E
2137 // Cursor Next Line Ps Times (default = 1) (CNL).
2138 case 'E':
2139 this.cursorNextLine(this.params);
2140 break;
2141
2142 // CSI Ps F
2143 // Cursor Preceding Line Ps Times (default = 1) (CNL).
2144 case 'F':
2145 this.cursorPrecedingLine(this.params);
2146 break;
2147
2148 // CSI Ps G
2149 // Cursor Character Absolute [column] (default = [row,1]) (CHA).
2150 case 'G':
2151 this.cursorCharAbsolute(this.params);
2152 break;
2153
2154 // CSI Ps L
2155 // Insert Ps Line(s) (default = 1) (IL).
2156 case 'L':
2157 this.insertLines(this.params);
2158 break;
2159
2160 // CSI Ps M
2161 // Delete Ps Line(s) (default = 1) (DL).
2162 case 'M':
2163 this.deleteLines(this.params);
2164 break;
2165
2166 // CSI Ps P
2167 // Delete Ps Character(s) (default = 1) (DCH).
2168 case 'P':
2169 this.deleteChars(this.params);
2170 break;
2171
2172 // CSI Ps X
2173 // Erase Ps Character(s) (default = 1) (ECH).
2174 case 'X':
2175 this.eraseChars(this.params);
2176 break;
2177
2178 // CSI Pm ` Character Position Absolute
2179 // [column] (default = [row,1]) (HPA).
2180 case '`':
2181 this.charPosAbsolute(this.params);
2182 break;
2183
2184 // 141 61 a * HPR -
2185 // Horizontal Position Relative
2186 case 'a':
2187 this.HPositionRelative(this.params);
2188 break;
2189
2190 // CSI P s c
2191 // Send Device Attributes (Primary DA).
2192 // CSI > P s c
2193 // Send Device Attributes (Secondary DA)
2194 case 'c':
2195 this.sendDeviceAttributes(this.params);
2196 break;
2197
2198 // CSI Pm d
2199 // Line Position Absolute [row] (default = [1,column]) (VPA).
2200 case 'd':
2201 this.linePosAbsolute(this.params);
2202 break;
2203
2204 // 145 65 e * VPR - Vertical Position Relative
2205 case 'e':
2206 this.VPositionRelative(this.params);
2207 break;
2208
2209 // CSI Ps ; Ps f
2210 // Horizontal and Vertical Position [row;column] (default =
2211 // [1,1]) (HVP).
2212 case 'f':
2213 this.HVPosition(this.params);
2214 break;
2215
2216 // CSI Pm h Set Mode (SM).
2217 // CSI ? Pm h - mouse escape codes, cursor escape codes
2218 case 'h':
2219 this.setMode(this.params);
2220 break;
2221
2222 // CSI Pm l Reset Mode (RM).
2223 // CSI ? Pm l
2224 case 'l':
2225 this.resetMode(this.params);
2226 break;
2227
2228 // CSI Ps ; Ps r
2229 // Set Scrolling Region [top;bottom] (default = full size of win-
2230 // dow) (DECSTBM).
2231 // CSI ? Pm r
2232 case 'r':
2233 this.setScrollRegion(this.params);
2234 break;
2235
2236 // CSI s
2237 // Save cursor (ANSI.SYS).
2238 case 's':
2239 this.saveCursor(this.params);
2240 break;
2241
2242 // CSI u
2243 // Restore cursor (ANSI.SYS).
2244 case 'u':
2245 this.restoreCursor(this.params);
2246 break;
2247
2248 /**
2249 * Lesser Used
2250 */
2251
2252 // CSI Ps I
2253 // Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
2254 case 'I':
2255 this.cursorForwardTab(this.params);
2256 break;
2257
2258 // CSI Ps S Scroll up Ps lines (default = 1) (SU).
2259 case 'S':
2260 this.scrollUp(this.params);
2261 break;
2262
2263 // CSI Ps T Scroll down Ps lines (default = 1) (SD).
2264 // CSI Ps ; Ps ; Ps ; Ps ; Ps T
2265 // CSI > Ps; Ps T
2266 case 'T':
2267 // if (this.prefix === '>') {
2268 // this.resetTitleModes(this.params);
2269 // break;
2270 // }
2271 // if (this.params.length > 2) {
2272 // this.initMouseTracking(this.params);
2273 // break;
2274 // }
2275 if (this.params.length < 2 && !this.prefix) {
2276 this.scrollDown(this.params);
2277 }
2278 break;
2279
2280 // CSI Ps Z
2281 // Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
2282 case 'Z':
2283 this.cursorBackwardTab(this.params);
2284 break;
2285
2286 // CSI Ps b Repeat the preceding graphic character Ps times (REP).
2287 case 'b':
2288 this.repeatPrecedingCharacter(this.params);
2289 break;
2290
2291 // CSI Ps g Tab Clear (TBC).
2292 case 'g':
2293 this.tabClear(this.params);
2294 break;
2295
2296 // CSI Pm i Media Copy (MC).
2297 // CSI ? Pm i
2298 // case 'i':
2299 // this.mediaCopy(this.params);
2300 // break;
2301
2302 // CSI Pm m Character Attributes (SGR).
2303 // CSI > Ps; Ps m
2304 // case 'm': // duplicate
2305 // if (this.prefix === '>') {
2306 // this.setResources(this.params);
2307 // } else {
2308 // this.charAttributes(this.params);
2309 // }
2310 // break;
2311
2312 // CSI Ps n Device Status Report (DSR).
2313 // CSI > Ps n
2314 // case 'n': // duplicate
2315 // if (this.prefix === '>') {
2316 // this.disableModifiers(this.params);
2317 // } else {
2318 // this.deviceStatus(this.params);
2319 // }
2320 // break;
2321
2322 // CSI > Ps p Set pointer mode.
2323 // CSI ! p Soft terminal reset (DECSTR).
2324 // CSI Ps$ p
2325 // Request ANSI mode (DECRQM).
2326 // CSI ? Ps$ p
2327 // Request DEC private mode (DECRQM).
2328 // CSI Ps ; Ps " p
2329 case 'p':
2330 switch (this.prefix) {
2331 // case '>':
2332 // this.setPointerMode(this.params);
2333 // break;
2334 case '!':
2335 this.softReset(this.params);
2336 break;
2337 // case '?':
2338 // if (this.postfix === '$') {
2339 // this.requestPrivateMode(this.params);
2340 // }
2341 // break;
2342 // default:
2343 // if (this.postfix === '"') {
2344 // this.setConformanceLevel(this.params);
2345 // } else if (this.postfix === '$') {
2346 // this.requestAnsiMode(this.params);
2347 // }
2348 // break;
2349 }
2350 break;
2351
2352 // CSI Ps q Load LEDs (DECLL).
2353 // CSI Ps SP q
2354 // CSI Ps " q
2355 // case 'q':
2356 // if (this.postfix === ' ') {
2357 // this.setCursorStyle(this.params);
2358 // break;
2359 // }
2360 // if (this.postfix === '"') {
2361 // this.setCharProtectionAttr(this.params);
2362 // break;
2363 // }
2364 // this.loadLEDs(this.params);
2365 // break;
2366
2367 // CSI Ps ; Ps r
2368 // Set Scrolling Region [top;bottom] (default = full size of win-
2369 // dow) (DECSTBM).
2370 // CSI ? Pm r
2371 // CSI Pt; Pl; Pb; Pr; Ps$ r
2372 // case 'r': // duplicate
2373 // if (this.prefix === '?') {
2374 // this.restorePrivateValues(this.params);
2375 // } else if (this.postfix === '$') {
2376 // this.setAttrInRectangle(this.params);
2377 // } else {
2378 // this.setScrollRegion(this.params);
2379 // }
2380 // break;
2381
2382 // CSI s Save cursor (ANSI.SYS).
2383 // CSI ? Pm s
2384 // case 's': // duplicate
2385 // if (this.prefix === '?') {
2386 // this.savePrivateValues(this.params);
2387 // } else {
2388 // this.saveCursor(this.params);
2389 // }
2390 // break;
2391
2392 // CSI Ps ; Ps ; Ps t
2393 // CSI Pt; Pl; Pb; Pr; Ps$ t
2394 // CSI > Ps; Ps t
2395 // CSI Ps SP t
2396 // case 't':
2397 // if (this.postfix === '$') {
2398 // this.reverseAttrInRectangle(this.params);
2399 // } else if (this.postfix === ' ') {
2400 // this.setWarningBellVolume(this.params);
2401 // } else {
2402 // if (this.prefix === '>') {
2403 // this.setTitleModeFeature(this.params);
2404 // } else {
2405 // this.manipulateWindow(this.params);
2406 // }
2407 // }
2408 // break;
2409
2410 // CSI u Restore cursor (ANSI.SYS).
2411 // CSI Ps SP u
2412 // case 'u': // duplicate
2413 // if (this.postfix === ' ') {
2414 // this.setMarginBellVolume(this.params);
2415 // } else {
2416 // this.restoreCursor(this.params);
2417 // }
2418 // break;
2419
2420 // CSI Pt; Pl; Pb; Pr; Pp; Pt; Pl; Pp$ v
2421 // case 'v':
2422 // if (this.postfix === '$') {
2423 // this.copyRectagle(this.params);
2424 // }
2425 // break;
2426
2427 // CSI Pt ; Pl ; Pb ; Pr ' w
2428 // case 'w':
2429 // if (this.postfix === '\'') {
2430 // this.enableFilterRectangle(this.params);
2431 // }
2432 // break;
2433
2434 // CSI Ps x Request Terminal Parameters (DECREQTPARM).
2435 // CSI Ps x Select Attribute Change Extent (DECSACE).
2436 // CSI Pc; Pt; Pl; Pb; Pr$ x
2437 // case 'x':
2438 // if (this.postfix === '$') {
2439 // this.fillRectangle(this.params);
2440 // } else {
2441 // this.requestParameters(this.params);
2442 // //this.__(this.params);
2443 // }
2444 // break;
2445
2446 // CSI Ps ; Pu ' z
2447 // CSI Pt; Pl; Pb; Pr$ z
2448 // case 'z':
2449 // if (this.postfix === '\'') {
2450 // this.enableLocatorReporting(this.params);
2451 // } else if (this.postfix === '$') {
2452 // this.eraseRectangle(this.params);
2453 // }
2454 // break;
2455
2456 // CSI Pm ' {
2457 // CSI Pt; Pl; Pb; Pr$ {
2458 // case '{':
2459 // if (this.postfix === '\'') {
2460 // this.setLocatorEvents(this.params);
2461 // } else if (this.postfix === '$') {
2462 // this.selectiveEraseRectangle(this.params);
2463 // }
2464 // break;
2465
2466 // CSI Ps ' |
2467 // case '|':
2468 // if (this.postfix === '\'') {
2469 // this.requestLocatorPosition(this.params);
2470 // }
2471 // break;
2472
2473 // CSI P m SP }
2474 // Insert P s Column(s) (default = 1) (DECIC), VT420 and up.
2475 // case '}':
2476 // if (this.postfix === ' ') {
2477 // this.insertColumns(this.params);
2478 // }
2479 // break;
2480
2481 // CSI P m SP ~
2482 // Delete P s Column(s) (default = 1) (DECDC), VT420 and up
2483 // case '~':
2484 // if (this.postfix === ' ') {
2485 // this.deleteColumns(this.params);
2486 // }
2487 // break;
2488
2489 default:
2490 this.error('Unknown CSI code: %s.', ch);
2491 break;
2492 }
2493
2494 this.prefix = '';
2495 this.postfix = '';
2496 break;
2497
2498 case dcs:
2499 if (ch === '\x1b' || ch === '\x07') {
2500 if (ch === '\x1b') i++;
2501
2502 switch (this.prefix) {
2503 // User-Defined Keys (DECUDK).
2504 case '':
2505 break;
2506
2507 // Request Status String (DECRQSS).
2508 // test: echo -e '\eP$q"p\e\\'
2509 case '$q':
2510 var pt = this.currentParam
2511 , valid = false;
2512
2513 switch (pt) {
2514 // DECSCA
2515 case '"q':
2516 pt = '0"q';
2517 break;
2518
2519 // DECSCL
2520 case '"p':
2521 pt = '61"p';
2522 break;
2523
2524 // DECSTBM
2525 case 'r':
2526 pt = ''
2527 + (this.scrollTop + 1)
2528 + ';'
2529 + (this.scrollBottom + 1)
2530 + 'r';
2531 break;
2532
2533 // SGR
2534 case 'm':
2535 pt = '0m';
2536 break;
2537
2538 default:
2539 this.error('Unknown DCS Pt: %s.', pt);
2540 pt = '';
2541 break;
2542 }
2543
2544 this.send('\x1bP' + +valid + '$r' + pt + '\x1b\\');
2545 break;
2546
2547 // Set Termcap/Terminfo Data (xterm, experimental).
2548 case '+p':
2549 break;
2550
2551 // Request Termcap/Terminfo String (xterm, experimental)
2552 // Regular xterm does not even respond to this sequence.
2553 // This can cause a small glitch in vim.
2554 // test: echo -ne '\eP+q6b64\e\\'
2555 case '+q':
2556 var pt = this.currentParam
2557 , valid = false;
2558
2559 this.send('\x1bP' + +valid + '+r' + pt + '\x1b\\');
2560 break;
2561
2562 default:
2563 this.error('Unknown DCS prefix: %s.', this.prefix);
2564 break;
2565 }
2566
2567 this.currentParam = 0;
2568 this.prefix = '';
2569 this.state = normal;
2570 } else if (!this.currentParam) {
2571 if (!this.prefix && ch !== '$' && ch !== '+') {
2572 this.currentParam = ch;
2573 } else if (this.prefix.length === 2) {
2574 this.currentParam = ch;
2575 } else {
2576 this.prefix += ch;
2577 }
2578 } else {
2579 this.currentParam += ch;
2580 }
2581 break;
2582
2583 case ignore:
2584 // For PM and APC.
2585 if (ch === '\x1b' || ch === '\x07') {
2586 if (ch === '\x1b') i++;
2587 this.state = normal;
2588 }
2589 break;
2590 }
2591 }
2592
2593 this.updateRange(this.y);
2594 this.refresh(this.refreshStart, this.refreshEnd);
2595 };
2596
107d1a14
PK
2597 /**
2598 * Writes text to the terminal, followed by a break line character (\n).
2599 * @param {string} text The text to write to the terminal.
2600 */
3f455f90
PK
2601 Terminal.prototype.writeln = function(data) {
2602 this.write(data + '\r\n');
2603 };
2604
107d1a14
PK
2605 /**
2606 * Handle a keydown event
2607 * Key Resources:
2608 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
2609 * @param {KeyboardEvent} ev The keydown event to be handled.
2610 */
3f455f90 2611 Terminal.prototype.keyDown = function(ev) {
c656ed04
DI
2612 if (this.compositionHelper.isComposing || this.compositionHelper.isSendingComposition) {
2613 if (ev.keyCode === 229) {
2614 // Continue composing
2615 return;
2616 } else {
2617 // Finish composition immediately
2618 this.compositionHelper.finalizeComposition(null);
2619 }
26af6ffd 2620 }
a52b7e7a 2621
3a866cf2
DI
2622 var self = this;
2623 var result = this.evaluateKeyEscapeSequence(ev);
2624
2625 if (result.scrollDisp) {
2626 this.scrollDisp(result.scrollDisp);
2627 return this.cancel(ev);
2628 }
2629
b01165c1 2630 if (isThirdLevelShift(this, ev)) {
2631 return true;
2632 }
2633
2634 if (result.cancel ) {
3a866cf2
DI
2635 // The event is canceled at the end already, is this necessary?
2636 this.cancel(ev, true);
2637 }
2638
b01165c1 2639 if (!result.key) {
3a866cf2
DI
2640 return true;
2641 }
2642
2643 this.emit('keydown', ev);
2644 this.emit('key', result.key, ev);
2645 this.showCursor();
2646 this.handler(result.key);
2647
2648 return this.cancel(ev, true);
2649 };
3f455f90 2650
0535f942
DI
2651 /**
2652 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
2653 * returned value is the new key code to pass to the PTY.
2654 *
2655 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
107d1a14 2656 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
0535f942 2657 */
3a866cf2
DI
2658 Terminal.prototype.evaluateKeyEscapeSequence = function(ev) {
2659 var result = {
2660 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
2661 // canceled at the end of keyDown
2662 cancel: false,
2663 // The new key even to emit
2664 key: undefined,
2665 // The number of characters to scroll, if this is defined it will cancel the event
2666 scrollDisp: undefined
2667 };
3f455f90
PK
2668 switch (ev.keyCode) {
2669 // backspace
2670 case 8:
2671 if (ev.shiftKey) {
3a866cf2 2672 result.key = '\x08'; // ^H
3f455f90
PK
2673 break;
2674 }
3a866cf2 2675 result.key = '\x7f'; // ^?
3f455f90
PK
2676 break;
2677 // tab
2678 case 9:
2679 if (ev.shiftKey) {
3a866cf2 2680 result.key = '\x1b[Z';
3f455f90
PK
2681 break;
2682 }
3a866cf2
DI
2683 result.key = '\t';
2684 result.cancel = true;
3f455f90
PK
2685 break;
2686 // return/enter
2687 case 13:
3a866cf2
DI
2688 result.key = '\r';
2689 result.cancel = true;
3f455f90
PK
2690 break;
2691 // escape
2692 case 27:
3a866cf2
DI
2693 result.key = '\x1b';
2694 result.cancel = true;
3f455f90
PK
2695 break;
2696 // left-arrow
2697 case 37:
72ed03ad 2698 if (ev.altKey) {
3a866cf2
DI
2699 result.key = '\x1bb' // Jump a word back
2700 result.cancel = true;
72ed03ad 2701 break;
e2aaa8d3
DI
2702 }
2703 if (ev.ctrlKey) {
3a866cf2 2704 result.key = '\x1b[5D'; // Jump a word back
e2aaa8d3
DI
2705 break;
2706 }
2707 if (this.applicationCursor) {
3a866cf2 2708 result.key = '\x1bOD'; // SS3 as ^[O for 7-bit
3f455f90
PK
2709 break;
2710 }
3a866cf2 2711 result.key = '\x1b[D';
3f455f90
PK
2712 break;
2713 // right-arrow
2714 case 39:
72ed03ad 2715 if (ev.altKey) {
3a866cf2
DI
2716 result.key = '\x1bf' // Jump a word forward
2717 result.cancel = true;
72ed03ad 2718 break;
e2aaa8d3
DI
2719 }
2720 if (ev.ctrlKey) {
3a866cf2 2721 result.key = '\x1b[5C'; // Jump a word forward
e2aaa8d3
DI
2722 break;
2723 }
2724 if (this.applicationCursor) {
3a866cf2 2725 result.key = '\x1bOC';
3f455f90
PK
2726 break;
2727 }
3a866cf2 2728 result.key = '\x1b[C';
3f455f90
PK
2729 break;
2730 // up-arrow
2731 case 38:
2732 if (this.applicationCursor) {
3a866cf2 2733 result.key = '\x1bOA';
3f455f90
PK
2734 break;
2735 }
2736 if (ev.ctrlKey) {
3a866cf2 2737 result.scrollDisp = -1;
3f455f90 2738 } else {
3a866cf2 2739 result.key = '\x1b[A';
3f455f90
PK
2740 }
2741 break;
2742 // down-arrow
2743 case 40:
2744 if (this.applicationCursor) {
3a866cf2 2745 result.key = '\x1bOB';
3f455f90
PK
2746 break;
2747 }
2748 if (ev.ctrlKey) {
3a866cf2 2749 result.scrollDisp = 1;
3f455f90 2750 } else {
3a866cf2 2751 result.key = '\x1b[B';
3f455f90
PK
2752 }
2753 break;
3f455f90
PK
2754 // insert
2755 case 45:
524db022 2756 if (!ev.shiftKey && !ev.ctrlKey) {
2757 // <Ctrl> or <Shift> + <Insert> are used to
2758 // copy-paste on some systems.
740ae96f 2759 result.key = '\x1b[2~';
524db022 2760 }
3f455f90 2761 break;
0535f942
DI
2762 // delete
2763 case 46: result.key = '\x1b[3~'; break;
3f455f90
PK
2764 // home
2765 case 36:
2766 if (this.applicationKeypad) {
3a866cf2 2767 result.key = '\x1bOH';
3f455f90
PK
2768 break;
2769 }
3a866cf2 2770 result.key = '\x1bOH';
3f455f90
PK
2771 break;
2772 // end
2773 case 35:
2774 if (this.applicationKeypad) {
3a866cf2 2775 result.key = '\x1bOF';
3f455f90
PK
2776 break;
2777 }
3a866cf2 2778 result.key = '\x1bOF';
3f455f90
PK
2779 break;
2780 // page up
2781 case 33:
2782 if (ev.shiftKey) {
3a866cf2 2783 result.scrollDisp = -(this.rows - 1);
3f455f90 2784 } else {
3a866cf2 2785 result.key = '\x1b[5~';
3f455f90
PK
2786 }
2787 break;
2788 // page down
2789 case 34:
2790 if (ev.shiftKey) {
3a866cf2 2791 result.scrollDisp = this.rows - 1;
3f455f90 2792 } else {
3a866cf2 2793 result.key = '\x1b[6~';
3f455f90
PK
2794 }
2795 break;
3a866cf2
DI
2796 // F1-F12
2797 case 112: result.key = '\x1bOP'; break;
2798 case 113: result.key = '\x1bOQ'; break;
2799 case 114: result.key = '\x1bOR'; break;
2800 case 115: result.key = '\x1bOS'; break;
2801 case 116: result.key = '\x1b[15~'; break;
2802 case 117: result.key = '\x1b[17~'; break;
2803 case 118: result.key = '\x1b[18~'; break;
2804 case 119: result.key = '\x1b[19~'; break;
2805 case 120: result.key = '\x1b[20~'; break;
2806 case 121: result.key = '\x1b[21~'; break;
2807 case 122: result.key = '\x1b[23~'; break;
2808 case 123: result.key = '\x1b[24~'; break;
3f455f90
PK
2809 default:
2810 // a-z and space
369e1f4c 2811 if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
3f455f90 2812 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
3a866cf2 2813 result.key = String.fromCharCode(ev.keyCode - 64);
3f455f90
PK
2814 } else if (ev.keyCode === 32) {
2815 // NUL
3a866cf2 2816 result.key = String.fromCharCode(0);
3f455f90
PK
2817 } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
2818 // escape, file sep, group sep, record sep, unit sep
3a866cf2 2819 result.key = String.fromCharCode(ev.keyCode - 51 + 27);
3f455f90
PK
2820 } else if (ev.keyCode === 56) {
2821 // delete
3a866cf2 2822 result.key = String.fromCharCode(127);
3f455f90
PK
2823 } else if (ev.keyCode === 219) {
2824 // ^[ - escape
3a866cf2 2825 result.key = String.fromCharCode(27);
3f455f90
PK
2826 } else if (ev.keyCode === 221) {
2827 // ^] - group sep
3a866cf2 2828 result.key = String.fromCharCode(29);
3f455f90 2829 }
b01165c1 2830 } else if (!this.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
2831 // On Mac this is a third level shift. Use <Esc> instead.
3f455f90 2832 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
3a866cf2 2833 result.key = '\x1b' + String.fromCharCode(ev.keyCode + 32);
3f455f90 2834 } else if (ev.keyCode === 192) {
3a866cf2 2835 result.key = '\x1b`';
3f455f90 2836 } else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
3a866cf2 2837 result.key = '\x1b' + (ev.keyCode - 48);
3f455f90
PK
2838 }
2839 }
2840 break;
2841 }
3a866cf2 2842 return result;
3f455f90
PK
2843 };
2844
107d1a14
PK
2845 /**
2846 * Set the G level of the terminal
2847 * @param g
2848 */
3f455f90
PK
2849 Terminal.prototype.setgLevel = function(g) {
2850 this.glevel = g;
2851 this.charset = this.charsets[g];
2852 };
2853
107d1a14
PK
2854 /**
2855 * Set the charset for the given G level of the terminal
2856 * @param g
2857 * @param charset
2858 */
3f455f90
PK
2859 Terminal.prototype.setgCharset = function(g, charset) {
2860 this.charsets[g] = charset;
2861 if (this.glevel === g) {
2862 this.charset = charset;
2863 }
2864 };
2865
107d1a14
PK
2866 /**
2867 * Handle a keypress event.
2868 * Key Resources:
2869 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
2870 * @param {KeyboardEvent} ev The keypress event to be handled.
2871 */
3f455f90
PK
2872 Terminal.prototype.keyPress = function(ev) {
2873 var key;
2874
fc7b22dc
DI
2875 this.cancel(ev);
2876
3f455f90
PK
2877 if (ev.charCode) {
2878 key = ev.charCode;
2879 } else if (ev.which == null) {
2880 key = ev.keyCode;
2881 } else if (ev.which !== 0 && ev.charCode !== 0) {
2882 key = ev.which;
2883 } else {
2884 return false;
2885 }
2886
b01165c1 2887 if (!key || (
2888 (ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
2889 )) {
3f455f90
PK
2890 return false;
2891 }
2892
2893 key = String.fromCharCode(key);
2894
2895 this.emit('keypress', key, ev);
2896 this.emit('key', key, ev);
2897 this.showCursor();
2898 this.handler(key);
2899
2900 return false;
2901 };
2902
107d1a14
PK
2903 /**
2904 * Send data for handling to the terminal
2905 * @param {string} data
2906 */
3f455f90
PK
2907 Terminal.prototype.send = function(data) {
2908 var self = this;
2909
2910 if (!this.queue) {
2911 setTimeout(function() {
2912 self.handler(self.queue);
2913 self.queue = '';
2914 }, 1);
2915 }
2916
2917 this.queue += data;
2918 };
2919
107d1a14
PK
2920 /**
2921 * Ring the bell.
2922 * Note: We could do sweet things with webaudio here
2923 */
3f455f90
PK
2924 Terminal.prototype.bell = function() {
2925 if (!this.visualBell) return;
2926 var self = this;
2927 this.element.style.borderColor = 'white';
2928 setTimeout(function() {
2929 self.element.style.borderColor = '';
2930 }, 10);
2931 if (this.popOnBell) this.focus();
2932 };
2933
107d1a14
PK
2934 /**
2935 * Log the current state to the console.
2936 */
3f455f90
PK
2937 Terminal.prototype.log = function() {
2938 if (!this.debug) return;
2939 if (!this.context.console || !this.context.console.log) return;
2940 var args = Array.prototype.slice.call(arguments);
2941 this.context.console.log.apply(this.context.console, args);
2942 };
2943
107d1a14
PK
2944 /**
2945 * Log the current state as error to the console.
2946 */
3f455f90
PK
2947 Terminal.prototype.error = function() {
2948 if (!this.debug) return;
2949 if (!this.context.console || !this.context.console.error) return;
2950 var args = Array.prototype.slice.call(arguments);
2951 this.context.console.error.apply(this.context.console, args);
2952 };
2953
fd5be55d
DI
2954 /**
2955 * Resizes the terminal.
2956 *
2957 * @param {number} x The number of columns to resize to.
2958 * @param {number} y The number of rows to resize to.
fd5be55d 2959 */
3f455f90
PK
2960 Terminal.prototype.resize = function(x, y) {
2961 var line
2962 , el
2963 , i
2964 , j
eee99f62
DI
2965 , ch
2966 , addToY;
3f455f90 2967
e721bdc9
DI
2968 if (x === this.cols && y === this.rows) {
2969 return;
2970 }
2971
3f455f90
PK
2972 if (x < 1) x = 1;
2973 if (y < 1) y = 1;
2974
2975 // resize cols
2976 j = this.cols;
2977 if (j < x) {
838c11b6 2978 ch = [this.defAttr, ' ', 1]; // does xterm use the default attr?
3f455f90
PK
2979 i = this.lines.length;
2980 while (i--) {
2981 while (this.lines[i].length < x) {
2982 this.lines[i].push(ch);
2983 }
2984 }
e721bdc9 2985 } else { // (j > x)
3f455f90
PK
2986 i = this.lines.length;
2987 while (i--) {
2988 while (this.lines[i].length > x) {
2989 this.lines[i].pop();
2990 }
2991 }
2992 }
2993 this.setupStops(j);
2994 this.cols = x;
2995
2996 // resize rows
2997 j = this.rows;
eee99f62 2998 addToY = 0;
3f455f90
PK
2999 if (j < y) {
3000 el = this.element;
3001 while (j++ < y) {
eee99f62 3002 // y is rows, not this.y
3f455f90 3003 if (this.lines.length < y + this.ybase) {
eee99f62
DI
3004 if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
3005 // There is room above the buffer and there are no empty elements below the line,
3006 // scroll up
3007 this.ybase--;
eee99f62 3008 addToY++
05041722
DI
3009 if (this.ydisp > 0) {
3010 // Viewport is at the top of the buffer, must increase downwards
87c9370e
DI
3011 this.ydisp--;
3012 }
eee99f62
DI
3013 } else {
3014 // Add a blank line if there is no buffer left at the top to scroll to, or if there
3015 // are blank lines after the cursor
3016 this.lines.push(this.blankLine());
3017 }
3f455f90
PK
3018 }
3019 if (this.children.length < y) {
3020 this.insertRow();
3021 }
3022 }
e721bdc9 3023 } else { // (j > y)
3f455f90
PK
3024 while (j-- > y) {
3025 if (this.lines.length > y + this.ybase) {
eee99f62
DI
3026 if (this.lines.length > this.ybase + this.y + 1) {
3027 // The line is a blank line below the cursor, remove it
df268ad5
DI
3028 this.lines.pop();
3029 } else {
eee99f62 3030 // The line is the cursor, scroll down
df268ad5
DI
3031 this.ybase++;
3032 this.ydisp++;
3033 }
3f455f90
PK
3034 }
3035 if (this.children.length > y) {
685bc54b 3036 el = this.children.shift();
3f455f90
PK
3037 if (!el) continue;
3038 el.parentNode.removeChild(el);
3039 }
3040 }
3041 }
3042 this.rows = y;
3043
3044 /*
3045 * Make sure that the cursor stays on screen
3046 */
3047 if (this.y >= y) {
3048 this.y = y - 1;
3049 }
eee99f62
DI
3050 if (addToY) {
3051 this.y += addToY;
3052 }
3f455f90
PK
3053
3054 if (this.x >= x) {
3055 this.x = x - 1;
3056 }
3057
3058 this.scrollTop = 0;
3059 this.scrollBottom = y - 1;
3060
3061 this.refresh(0, this.rows - 1);
3062
3063 this.normal = null;
3064
3065 this.emit('resize', {terminal: this, cols: x, rows: y});
3066 };
3067
1aeb5620
PK
3068 /**
3069 * Updates the range of rows to refresh
3070 * @param {number} y The number of rows to refresh next.
3071 */
3f455f90
PK
3072 Terminal.prototype.updateRange = function(y) {
3073 if (y < this.refreshStart) this.refreshStart = y;
3074 if (y > this.refreshEnd) this.refreshEnd = y;
3075 // if (y > this.refreshEnd) {
3076 // this.refreshEnd = y;
3077 // if (y > this.rows - 1) {
3078 // this.refreshEnd = this.rows - 1;
3079 // }
3080 // }
3081 };
3082
1aeb5620
PK
3083 /**
3084 * Set the range of refreshing to the maximyum value
3085 */
3f455f90
PK
3086 Terminal.prototype.maxRange = function() {
3087 this.refreshStart = 0;
3088 this.refreshEnd = this.rows - 1;
3089 };
3090
3091 Terminal.prototype.setupStops = function(i) {
3092 if (i != null) {
3093 if (!this.tabs[i]) {
3094 i = this.prevStop(i);
3095 }
3096 } else {
3097 this.tabs = {};
3098 i = 0;
3099 }
3100
3101 for (; i < this.cols; i += 8) {
3102 this.tabs[i] = true;
3103 }
3104 };
3105
3106 Terminal.prototype.prevStop = function(x) {
3107 if (x == null) x = this.x;
3108 while (!this.tabs[--x] && x > 0);
3109 return x >= this.cols
3110 ? this.cols - 1
3111 : x < 0 ? 0 : x;
3112 };
3113
3114 Terminal.prototype.nextStop = function(x) {
3115 if (x == null) x = this.x;
3116 while (!this.tabs[++x] && x < this.cols);
3117 return x >= this.cols
3118 ? this.cols - 1
3119 : x < 0 ? 0 : x;
3120 };
3121
3122 Terminal.prototype.eraseRight = function(x, y) {
3123 var line = this.lines[this.ybase + y]
874ba72f 3124 , ch = [this.eraseAttr(), ' ', 1]; // xterm
3f455f90
PK
3125
3126
3127 for (; x < this.cols; x++) {
3128 line[x] = ch;
3129 }
3130
3131 this.updateRange(y);
3132 };
3133
3134 Terminal.prototype.eraseLeft = function(x, y) {
3135 var line = this.lines[this.ybase + y]
874ba72f 3136 , ch = [this.eraseAttr(), ' ', 1]; // xterm
3f455f90
PK
3137
3138 x++;
3139 while (x--) line[x] = ch;
3140
3141 this.updateRange(y);
3142 };
3143
3144 Terminal.prototype.eraseLine = function(y) {
3145 this.eraseRight(0, y);
3146 };
3147
3148 Terminal.prototype.blankLine = function(cur) {
3149 var attr = cur
3150 ? this.eraseAttr()
3151 : this.defAttr;
3152
874ba72f 3153 var ch = [attr, ' ', 1] // width defaults to 1 halfwidth character
3f455f90
PK
3154 , line = []
3155 , i = 0;
3156
3157 for (; i < this.cols; i++) {
3158 line[i] = ch;
3159 }
3160
3161 return line;
3162 };
3163
3164 Terminal.prototype.ch = function(cur) {
3165 return cur
874ba72f
JB
3166 ? [this.eraseAttr(), ' ', 1]
3167 : [this.defAttr, ' ', 1];
3f455f90
PK
3168 };
3169
3170 Terminal.prototype.is = function(term) {
3171 var name = this.termName;
3172 return (name + '').indexOf(term) === 0;
3173 };
3174
3175 Terminal.prototype.handler = function(data) {
3176 this.emit('data', data);
3177 };
3178
3179 Terminal.prototype.handleTitle = function(title) {
3180 this.emit('title', title);
3181 };
3182
3183 /**
3184 * ESC
3185 */
3186
3187 // ESC D Index (IND is 0x84).
3188 Terminal.prototype.index = function() {
3189 this.y++;
3190 if (this.y > this.scrollBottom) {
3191 this.y--;
3192 this.scroll();
3193 }
3194 this.state = normal;
3195 };
3196
3197 // ESC M Reverse Index (RI is 0x8d).
3198 Terminal.prototype.reverseIndex = function() {
3199 var j;
3200 this.y--;
3201 if (this.y < this.scrollTop) {
3202 this.y++;
3203 // possibly move the code below to term.reverseScroll();
3204 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
3205 // blankLine(true) is xterm/linux behavior
3206 this.lines.splice(this.y + this.ybase, 0, this.blankLine(true));
3207 j = this.rows - 1 - this.scrollBottom;
3208 this.lines.splice(this.rows - 1 + this.ybase - j + 1, 1);
3209 // this.maxRange();
3210 this.updateRange(this.scrollTop);
3211 this.updateRange(this.scrollBottom);
3212 }
3213 this.state = normal;
3214 };
3215
3216 // ESC c Full Reset (RIS).
3217 Terminal.prototype.reset = function() {
3218 this.options.rows = this.rows;
3219 this.options.cols = this.cols;
3220 Terminal.call(this, this.options);
3221 this.refresh(0, this.rows - 1);
3222 };
3223
3224 // ESC H Tab Set (HTS is 0x88).
3225 Terminal.prototype.tabSet = function() {
3226 this.tabs[this.x] = true;
3227 this.state = normal;
3228 };
3229
3230 /**
3231 * CSI
3232 */
3233
3234 // CSI Ps A
3235 // Cursor Up Ps Times (default = 1) (CUU).
3236 Terminal.prototype.cursorUp = function(params) {
3237 var param = params[0];
3238 if (param < 1) param = 1;
3239 this.y -= param;
3240 if (this.y < 0) this.y = 0;
3241 };
3242
3243 // CSI Ps B
3244 // Cursor Down Ps Times (default = 1) (CUD).
3245 Terminal.prototype.cursorDown = function(params) {
3246 var param = params[0];
3247 if (param < 1) param = 1;
3248 this.y += param;
3249 if (this.y >= this.rows) {
3250 this.y = this.rows - 1;
3251 }
3252 };
3253
3254 // CSI Ps C
3255 // Cursor Forward Ps Times (default = 1) (CUF).
3256 Terminal.prototype.cursorForward = function(params) {
3257 var param = params[0];
3258 if (param < 1) param = 1;
3259 this.x += param;
3260 if (this.x >= this.cols) {
3261 this.x = this.cols - 1;
3262 }
3263 };
3264
3265 // CSI Ps D
3266 // Cursor Backward Ps Times (default = 1) (CUB).
3267 Terminal.prototype.cursorBackward = function(params) {
3268 var param = params[0];
3269 if (param < 1) param = 1;
3270 this.x -= param;
3271 if (this.x < 0) this.x = 0;
3272 };
3273
3274 // CSI Ps ; Ps H
3275 // Cursor Position [row;column] (default = [1,1]) (CUP).
3276 Terminal.prototype.cursorPos = function(params) {
3277 var row, col;
3278
3279 row = params[0] - 1;
3280
3281 if (params.length >= 2) {
3282 col = params[1] - 1;
3283 } else {
3284 col = 0;
3285 }
3286
3287 if (row < 0) {
3288 row = 0;
3289 } else if (row >= this.rows) {
3290 row = this.rows - 1;
3291 }
3292
3293 if (col < 0) {
3294 col = 0;
3295 } else if (col >= this.cols) {
3296 col = this.cols - 1;
3297 }
3298
3299 this.x = col;
3300 this.y = row;
3301 };
3302
3303 // CSI Ps J Erase in Display (ED).
3304 // Ps = 0 -> Erase Below (default).
3305 // Ps = 1 -> Erase Above.
3306 // Ps = 2 -> Erase All.
3307 // Ps = 3 -> Erase Saved Lines (xterm).
3308 // CSI ? Ps J
3309 // Erase in Display (DECSED).
3310 // Ps = 0 -> Selective Erase Below (default).
3311 // Ps = 1 -> Selective Erase Above.
3312 // Ps = 2 -> Selective Erase All.
3313 Terminal.prototype.eraseInDisplay = function(params) {
3314 var j;
3315 switch (params[0]) {
3316 case 0:
3317 this.eraseRight(this.x, this.y);
3318 j = this.y + 1;
3319 for (; j < this.rows; j++) {
3320 this.eraseLine(j);
3321 }
3322 break;
3323 case 1:
3324 this.eraseLeft(this.x, this.y);
3325 j = this.y;
3326 while (j--) {
3327 this.eraseLine(j);
3328 }
3329 break;
3330 case 2:
3331 j = this.rows;
3332 while (j--) this.eraseLine(j);
3333 break;
3334 case 3:
3335 ; // no saved lines
3336 break;
3337 }
3338 };
3339
3340 // CSI Ps K Erase in Line (EL).
3341 // Ps = 0 -> Erase to Right (default).
3342 // Ps = 1 -> Erase to Left.
3343 // Ps = 2 -> Erase All.
3344 // CSI ? Ps K
3345 // Erase in Line (DECSEL).
3346 // Ps = 0 -> Selective Erase to Right (default).
3347 // Ps = 1 -> Selective Erase to Left.
3348 // Ps = 2 -> Selective Erase All.
3349 Terminal.prototype.eraseInLine = function(params) {
3350 switch (params[0]) {
3351 case 0:
3352 this.eraseRight(this.x, this.y);
3353 break;
3354 case 1:
3355 this.eraseLeft(this.x, this.y);
3356 break;
3357 case 2:
3358 this.eraseLine(this.y);
3359 break;
3360 }
3361 };
3362
3363 // CSI Pm m Character Attributes (SGR).
3364 // Ps = 0 -> Normal (default).
3365 // Ps = 1 -> Bold.
3366 // Ps = 4 -> Underlined.
3367 // Ps = 5 -> Blink (appears as Bold).
3368 // Ps = 7 -> Inverse.
3369 // Ps = 8 -> Invisible, i.e., hidden (VT300).
3370 // Ps = 2 2 -> Normal (neither bold nor faint).
3371 // Ps = 2 4 -> Not underlined.
3372 // Ps = 2 5 -> Steady (not blinking).
3373 // Ps = 2 7 -> Positive (not inverse).
3374 // Ps = 2 8 -> Visible, i.e., not hidden (VT300).
3375 // Ps = 3 0 -> Set foreground color to Black.
3376 // Ps = 3 1 -> Set foreground color to Red.
3377 // Ps = 3 2 -> Set foreground color to Green.
3378 // Ps = 3 3 -> Set foreground color to Yellow.
3379 // Ps = 3 4 -> Set foreground color to Blue.
3380 // Ps = 3 5 -> Set foreground color to Magenta.
3381 // Ps = 3 6 -> Set foreground color to Cyan.
3382 // Ps = 3 7 -> Set foreground color to White.
3383 // Ps = 3 9 -> Set foreground color to default (original).
3384 // Ps = 4 0 -> Set background color to Black.
3385 // Ps = 4 1 -> Set background color to Red.
3386 // Ps = 4 2 -> Set background color to Green.
3387 // Ps = 4 3 -> Set background color to Yellow.
3388 // Ps = 4 4 -> Set background color to Blue.
3389 // Ps = 4 5 -> Set background color to Magenta.
3390 // Ps = 4 6 -> Set background color to Cyan.
3391 // Ps = 4 7 -> Set background color to White.
3392 // Ps = 4 9 -> Set background color to default (original).
3393
3394 // If 16-color support is compiled, the following apply. Assume
3395 // that xterm's resources are set so that the ISO color codes are
3396 // the first 8 of a set of 16. Then the aixterm colors are the
3397 // bright versions of the ISO colors:
3398 // Ps = 9 0 -> Set foreground color to Black.
3399 // Ps = 9 1 -> Set foreground color to Red.
3400 // Ps = 9 2 -> Set foreground color to Green.
3401 // Ps = 9 3 -> Set foreground color to Yellow.
3402 // Ps = 9 4 -> Set foreground color to Blue.
3403 // Ps = 9 5 -> Set foreground color to Magenta.
3404 // Ps = 9 6 -> Set foreground color to Cyan.
3405 // Ps = 9 7 -> Set foreground color to White.
3406 // Ps = 1 0 0 -> Set background color to Black.
3407 // Ps = 1 0 1 -> Set background color to Red.
3408 // Ps = 1 0 2 -> Set background color to Green.
3409 // Ps = 1 0 3 -> Set background color to Yellow.
3410 // Ps = 1 0 4 -> Set background color to Blue.
3411 // Ps = 1 0 5 -> Set background color to Magenta.
3412 // Ps = 1 0 6 -> Set background color to Cyan.
3413 // Ps = 1 0 7 -> Set background color to White.
3414
3415 // If xterm is compiled with the 16-color support disabled, it
3416 // supports the following, from rxvt:
3417 // Ps = 1 0 0 -> Set foreground and background color to
3418 // default.
3419
3420 // If 88- or 256-color support is compiled, the following apply.
3421 // Ps = 3 8 ; 5 ; Ps -> Set foreground color to the second
3422 // Ps.
3423 // Ps = 4 8 ; 5 ; Ps -> Set background color to the second
3424 // Ps.
3425 Terminal.prototype.charAttributes = function(params) {
3426 // Optimize a single SGR0.
3427 if (params.length === 1 && params[0] === 0) {
3428 this.curAttr = this.defAttr;
3429 return;
3430 }
3431
3432 var l = params.length
3433 , i = 0
3434 , flags = this.curAttr >> 18
3435 , fg = (this.curAttr >> 9) & 0x1ff
3436 , bg = this.curAttr & 0x1ff
3437 , p;
3438
3439 for (; i < l; i++) {
3440 p = params[i];
3441 if (p >= 30 && p <= 37) {
3442 // fg color 8
3443 fg = p - 30;
3444 } else if (p >= 40 && p <= 47) {
3445 // bg color 8
3446 bg = p - 40;
3447 } else if (p >= 90 && p <= 97) {
3448 // fg color 16
3449 p += 8;
3450 fg = p - 90;
3451 } else if (p >= 100 && p <= 107) {
3452 // bg color 16
3453 p += 8;
3454 bg = p - 100;
3455 } else if (p === 0) {
3456 // default
3457 flags = this.defAttr >> 18;
3458 fg = (this.defAttr >> 9) & 0x1ff;
3459 bg = this.defAttr & 0x1ff;
3460 // flags = 0;
3461 // fg = 0x1ff;
3462 // bg = 0x1ff;
3463 } else if (p === 1) {
3464 // bold text
3465 flags |= 1;
3466 } else if (p === 4) {
3467 // underlined text
3468 flags |= 2;
3469 } else if (p === 5) {
3470 // blink
3471 flags |= 4;
3472 } else if (p === 7) {
3473 // inverse and positive
3474 // test with: echo -e '\e[31m\e[42mhello\e[7mworld\e[27mhi\e[m'
3475 flags |= 8;
3476 } else if (p === 8) {
3477 // invisible
3478 flags |= 16;
3479 } else if (p === 22) {
3480 // not bold
3481 flags &= ~1;
3482 } else if (p === 24) {
3483 // not underlined
3484 flags &= ~2;
3485 } else if (p === 25) {
3486 // not blink
3487 flags &= ~4;
3488 } else if (p === 27) {
3489 // not inverse
3490 flags &= ~8;
3491 } else if (p === 28) {
3492 // not invisible
3493 flags &= ~16;
3494 } else if (p === 39) {
3495 // reset fg
3496 fg = (this.defAttr >> 9) & 0x1ff;
3497 } else if (p === 49) {
3498 // reset bg
3499 bg = this.defAttr & 0x1ff;
3500 } else if (p === 38) {
3501 // fg color 256
3502 if (params[i + 1] === 2) {
3503 i += 2;
3504 fg = matchColor(
3505 params[i] & 0xff,
3506 params[i + 1] & 0xff,
3507 params[i + 2] & 0xff);
3508 if (fg === -1) fg = 0x1ff;
3509 i += 2;
3510 } else if (params[i + 1] === 5) {
3511 i += 2;
3512 p = params[i] & 0xff;
3513 fg = p;
3514 }
3515 } else if (p === 48) {
3516 // bg color 256
3517 if (params[i + 1] === 2) {
3518 i += 2;
3519 bg = matchColor(
3520 params[i] & 0xff,
3521 params[i + 1] & 0xff,
3522 params[i + 2] & 0xff);
3523 if (bg === -1) bg = 0x1ff;
3524 i += 2;
3525 } else if (params[i + 1] === 5) {
3526 i += 2;
3527 p = params[i] & 0xff;
3528 bg = p;
3529 }
3530 } else if (p === 100) {
3531 // reset fg/bg
3532 fg = (this.defAttr >> 9) & 0x1ff;
3533 bg = this.defAttr & 0x1ff;
3534 } else {
3535 this.error('Unknown SGR attribute: %d.', p);
3536 }
3537 }
3538
3539 this.curAttr = (flags << 18) | (fg << 9) | bg;
3540 };
3541
3542 // CSI Ps n Device Status Report (DSR).
3543 // Ps = 5 -> Status Report. Result (``OK'') is
3544 // CSI 0 n
3545 // Ps = 6 -> Report Cursor Position (CPR) [row;column].
3546 // Result is
3547 // CSI r ; c R
3548 // CSI ? Ps n
3549 // Device Status Report (DSR, DEC-specific).
3550 // Ps = 6 -> Report Cursor Position (CPR) [row;column] as CSI
3551 // ? r ; c R (assumes page is zero).
3552 // Ps = 1 5 -> Report Printer status as CSI ? 1 0 n (ready).
3553 // or CSI ? 1 1 n (not ready).
3554 // Ps = 2 5 -> Report UDK status as CSI ? 2 0 n (unlocked)
3555 // or CSI ? 2 1 n (locked).
3556 // Ps = 2 6 -> Report Keyboard status as
3557 // CSI ? 2 7 ; 1 ; 0 ; 0 n (North American).
3558 // The last two parameters apply to VT400 & up, and denote key-
3559 // board ready and LK01 respectively.
3560 // Ps = 5 3 -> Report Locator status as
3561 // CSI ? 5 3 n Locator available, if compiled-in, or
3562 // CSI ? 5 0 n No Locator, if not.
3563 Terminal.prototype.deviceStatus = function(params) {
3564 if (!this.prefix) {
3565 switch (params[0]) {
3566 case 5:
3567 // status report
3568 this.send('\x1b[0n');
3569 break;
3570 case 6:
3571 // cursor position
3572 this.send('\x1b['
3573 + (this.y + 1)
3574 + ';'
3575 + (this.x + 1)
3576 + 'R');
3577 break;
3578 }
3579 } else if (this.prefix === '?') {
3580 // modern xterm doesnt seem to
3581 // respond to any of these except ?6, 6, and 5
3582 switch (params[0]) {
3583 case 6:
3584 // cursor position
3585 this.send('\x1b[?'
3586 + (this.y + 1)
3587 + ';'
3588 + (this.x + 1)
3589 + 'R');
3590 break;
3591 case 15:
3592 // no printer
3593 // this.send('\x1b[?11n');
3594 break;
3595 case 25:
3596 // dont support user defined keys
3597 // this.send('\x1b[?21n');
3598 break;
3599 case 26:
3600 // north american keyboard
3601 // this.send('\x1b[?27;1;0;0n');
3602 break;
3603 case 53:
3604 // no dec locator/mouse
3605 // this.send('\x1b[?50n');
3606 break;
3607 }
3608 }
3609 };
3610
3611 /**
3612 * Additions
3613 */
3614
3615 // CSI Ps @
3616 // Insert Ps (Blank) Character(s) (default = 1) (ICH).
3617 Terminal.prototype.insertChars = function(params) {
3618 var param, row, j, ch;
3619
3620 param = params[0];
3621 if (param < 1) param = 1;
3622
3623 row = this.y + this.ybase;
3624 j = this.x;
4afa08da 3625 ch = [this.eraseAttr(), ' ', 1]; // xterm
3f455f90
PK
3626
3627 while (param-- && j < this.cols) {
3628 this.lines[row].splice(j++, 0, ch);
3629 this.lines[row].pop();
3630 }
3631 };
3632
3633 // CSI Ps E
3634 // Cursor Next Line Ps Times (default = 1) (CNL).
3635 // same as CSI Ps B ?
3636 Terminal.prototype.cursorNextLine = function(params) {
3637 var param = params[0];
3638 if (param < 1) param = 1;
3639 this.y += param;
3640 if (this.y >= this.rows) {
3641 this.y = this.rows - 1;
3642 }
3643 this.x = 0;
3644 };
3645
3646 // CSI Ps F
3647 // Cursor Preceding Line Ps Times (default = 1) (CNL).
3648 // reuse CSI Ps A ?
3649 Terminal.prototype.cursorPrecedingLine = function(params) {
3650 var param = params[0];
3651 if (param < 1) param = 1;
3652 this.y -= param;
3653 if (this.y < 0) this.y = 0;
3654 this.x = 0;
3655 };
3656
3657 // CSI Ps G
3658 // Cursor Character Absolute [column] (default = [row,1]) (CHA).
3659 Terminal.prototype.cursorCharAbsolute = function(params) {
3660 var param = params[0];
3661 if (param < 1) param = 1;
3662 this.x = param - 1;
3663 };
3664
3665 // CSI Ps L
3666 // Insert Ps Line(s) (default = 1) (IL).
3667 Terminal.prototype.insertLines = function(params) {
3668 var param, row, j;
3669
3670 param = params[0];
3671 if (param < 1) param = 1;
3672 row = this.y + this.ybase;
3673
3674 j = this.rows - 1 - this.scrollBottom;
3675 j = this.rows - 1 + this.ybase - j + 1;
3676
3677 while (param--) {
3678 // test: echo -e '\e[44m\e[1L\e[0m'
3679 // blankLine(true) - xterm/linux behavior
3680 this.lines.splice(row, 0, this.blankLine(true));
3681 this.lines.splice(j, 1);
3682 }
3683
3684 // this.maxRange();
3685 this.updateRange(this.y);
3686 this.updateRange(this.scrollBottom);
3687 };
3688
3689 // CSI Ps M
3690 // Delete Ps Line(s) (default = 1) (DL).
3691 Terminal.prototype.deleteLines = function(params) {
3692 var param, row, j;
3693
3694 param = params[0];
3695 if (param < 1) param = 1;
3696 row = this.y + this.ybase;
3697
3698 j = this.rows - 1 - this.scrollBottom;
3699 j = this.rows - 1 + this.ybase - j;
3700
3701 while (param--) {
3702 // test: echo -e '\e[44m\e[1M\e[0m'
3703 // blankLine(true) - xterm/linux behavior
3704 this.lines.splice(j + 1, 0, this.blankLine(true));
3705 this.lines.splice(row, 1);
3706 }
3707
3708 // this.maxRange();
3709 this.updateRange(this.y);
3710 this.updateRange(this.scrollBottom);
3711 };
3712
3713 // CSI Ps P
3714 // Delete Ps Character(s) (default = 1) (DCH).
3715 Terminal.prototype.deleteChars = function(params) {
3716 var param, row, ch;
3717
3718 param = params[0];
3719 if (param < 1) param = 1;
3720
3721 row = this.y + this.ybase;
4afa08da 3722 ch = [this.eraseAttr(), ' ', 1]; // xterm
3f455f90
PK
3723
3724 while (param--) {
3725 this.lines[row].splice(this.x, 1);
3726 this.lines[row].push(ch);
3727 }
3728 };
3729
3730 // CSI Ps X
3731 // Erase Ps Character(s) (default = 1) (ECH).
3732 Terminal.prototype.eraseChars = function(params) {
3733 var param, row, j, ch;
3734
3735 param = params[0];
3736 if (param < 1) param = 1;
3737
3738 row = this.y + this.ybase;
3739 j = this.x;
4afa08da 3740 ch = [this.eraseAttr(), ' ', 1]; // xterm
3f455f90
PK
3741
3742 while (param-- && j < this.cols) {
3743 this.lines[row][j++] = ch;
3744 }
3745 };
3746
3747 // CSI Pm ` Character Position Absolute
3748 // [column] (default = [row,1]) (HPA).
3749 Terminal.prototype.charPosAbsolute = function(params) {
3750 var param = params[0];
3751 if (param < 1) param = 1;
3752 this.x = param - 1;
3753 if (this.x >= this.cols) {
3754 this.x = this.cols - 1;
3755 }
3756 };
3757
3758 // 141 61 a * HPR -
3759 // Horizontal Position Relative
3760 // reuse CSI Ps C ?
3761 Terminal.prototype.HPositionRelative = function(params) {
3762 var param = params[0];
3763 if (param < 1) param = 1;
3764 this.x += param;
3765 if (this.x >= this.cols) {
3766 this.x = this.cols - 1;
3767 }
3768 };
3769
3770 // CSI Ps c Send Device Attributes (Primary DA).
3771 // Ps = 0 or omitted -> request attributes from terminal. The
3772 // response depends on the decTerminalID resource setting.
3773 // -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'')
3774 // -> CSI ? 1 ; 0 c (``VT101 with No Options'')
3775 // -> CSI ? 6 c (``VT102'')
3776 // -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'')
3777 // The VT100-style response parameters do not mean anything by
3778 // themselves. VT220 parameters do, telling the host what fea-
3779 // tures the terminal supports:
3780 // Ps = 1 -> 132-columns.
3781 // Ps = 2 -> Printer.
3782 // Ps = 6 -> Selective erase.
3783 // Ps = 8 -> User-defined keys.
3784 // Ps = 9 -> National replacement character sets.
3785 // Ps = 1 5 -> Technical characters.
3786 // Ps = 2 2 -> ANSI color, e.g., VT525.
3787 // Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode).
3788 // CSI > Ps c
3789 // Send Device Attributes (Secondary DA).
3790 // Ps = 0 or omitted -> request the terminal's identification
3791 // code. The response depends on the decTerminalID resource set-
3792 // ting. It should apply only to VT220 and up, but xterm extends
3793 // this to VT100.
3794 // -> CSI > Pp ; Pv ; Pc c
3795 // where Pp denotes the terminal type
3796 // Pp = 0 -> ``VT100''.
3797 // Pp = 1 -> ``VT220''.
3798 // and Pv is the firmware version (for xterm, this was originally
3799 // the XFree86 patch number, starting with 95). In a DEC termi-
3800 // nal, Pc indicates the ROM cartridge registration number and is
3801 // always zero.
3802 // More information:
3803 // xterm/charproc.c - line 2012, for more information.
3804 // vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)
3805 Terminal.prototype.sendDeviceAttributes = function(params) {
3806 if (params[0] > 0) return;
3807
3808 if (!this.prefix) {
3809 if (this.is('xterm')
3810 || this.is('rxvt-unicode')
3811 || this.is('screen')) {
3812 this.send('\x1b[?1;2c');
3813 } else if (this.is('linux')) {
3814 this.send('\x1b[?6c');
3815 }
3816 } else if (this.prefix === '>') {
3817 // xterm and urxvt
3818 // seem to spit this
3819 // out around ~370 times (?).
3820 if (this.is('xterm')) {
3821 this.send('\x1b[>0;276;0c');
3822 } else if (this.is('rxvt-unicode')) {
3823 this.send('\x1b[>85;95;0c');
3824 } else if (this.is('linux')) {
3825 // not supported by linux console.
3826 // linux console echoes parameters.
3827 this.send(params[0] + 'c');
3828 } else if (this.is('screen')) {
3829 this.send('\x1b[>83;40003;0c');
3830 }
3831 }
3832 };
3833
3834 // CSI Pm d
3835 // Line Position Absolute [row] (default = [1,column]) (VPA).
3836 Terminal.prototype.linePosAbsolute = function(params) {
3837 var param = params[0];
3838 if (param < 1) param = 1;
3839 this.y = param - 1;
3840 if (this.y >= this.rows) {
3841 this.y = this.rows - 1;
3842 }
3843 };
3844
3845 // 145 65 e * VPR - Vertical Position Relative
3846 // reuse CSI Ps B ?
3847 Terminal.prototype.VPositionRelative = function(params) {
3848 var param = params[0];
3849 if (param < 1) param = 1;
3850 this.y += param;
3851 if (this.y >= this.rows) {
3852 this.y = this.rows - 1;
3853 }
3854 };
3855
3856 // CSI Ps ; Ps f
3857 // Horizontal and Vertical Position [row;column] (default =
3858 // [1,1]) (HVP).
3859 Terminal.prototype.HVPosition = function(params) {
3860 if (params[0] < 1) params[0] = 1;
3861 if (params[1] < 1) params[1] = 1;
3862
3863 this.y = params[0] - 1;
3864 if (this.y >= this.rows) {
3865 this.y = this.rows - 1;
3866 }
3867
3868 this.x = params[1] - 1;
3869 if (this.x >= this.cols) {
3870 this.x = this.cols - 1;
3871 }
3872 };
3873
3874 // CSI Pm h Set Mode (SM).
3875 // Ps = 2 -> Keyboard Action Mode (AM).
3876 // Ps = 4 -> Insert Mode (IRM).
3877 // Ps = 1 2 -> Send/receive (SRM).
3878 // Ps = 2 0 -> Automatic Newline (LNM).
3879 // CSI ? Pm h
3880 // DEC Private Mode Set (DECSET).
3881 // Ps = 1 -> Application Cursor Keys (DECCKM).
3882 // Ps = 2 -> Designate USASCII for character sets G0-G3
3883 // (DECANM), and set VT100 mode.
3884 // Ps = 3 -> 132 Column Mode (DECCOLM).
3885 // Ps = 4 -> Smooth (Slow) Scroll (DECSCLM).
3886 // Ps = 5 -> Reverse Video (DECSCNM).
3887 // Ps = 6 -> Origin Mode (DECOM).
3888 // Ps = 7 -> Wraparound Mode (DECAWM).
3889 // Ps = 8 -> Auto-repeat Keys (DECARM).
3890 // Ps = 9 -> Send Mouse X & Y on button press. See the sec-
3891 // tion Mouse Tracking.
3892 // Ps = 1 0 -> Show toolbar (rxvt).
3893 // Ps = 1 2 -> Start Blinking Cursor (att610).
3894 // Ps = 1 8 -> Print form feed (DECPFF).
3895 // Ps = 1 9 -> Set print extent to full screen (DECPEX).
3896 // Ps = 2 5 -> Show Cursor (DECTCEM).
3897 // Ps = 3 0 -> Show scrollbar (rxvt).
3898 // Ps = 3 5 -> Enable font-shifting functions (rxvt).
3899 // Ps = 3 8 -> Enter Tektronix Mode (DECTEK).
3900 // Ps = 4 0 -> Allow 80 -> 132 Mode.
3901 // Ps = 4 1 -> more(1) fix (see curses resource).
3902 // Ps = 4 2 -> Enable Nation Replacement Character sets (DECN-
3903 // RCM).
3904 // Ps = 4 4 -> Turn On Margin Bell.
3905 // Ps = 4 5 -> Reverse-wraparound Mode.
3906 // Ps = 4 6 -> Start Logging. This is normally disabled by a
3907 // compile-time option.
3908 // Ps = 4 7 -> Use Alternate Screen Buffer. (This may be dis-
3909 // abled by the titeInhibit resource).
3910 // Ps = 6 6 -> Application keypad (DECNKM).
3911 // Ps = 6 7 -> Backarrow key sends backspace (DECBKM).
3912 // Ps = 1 0 0 0 -> Send Mouse X & Y on button press and
3913 // release. See the section Mouse Tracking.
3914 // Ps = 1 0 0 1 -> Use Hilite Mouse Tracking.
3915 // Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking.
3916 // Ps = 1 0 0 3 -> Use All Motion Mouse Tracking.
3917 // Ps = 1 0 0 4 -> Send FocusIn/FocusOut events.
3918 // Ps = 1 0 0 5 -> Enable Extended Mouse Mode.
3919 // Ps = 1 0 1 0 -> Scroll to bottom on tty output (rxvt).
3920 // Ps = 1 0 1 1 -> Scroll to bottom on key press (rxvt).
3921 // Ps = 1 0 3 4 -> Interpret "meta" key, sets eighth bit.
3922 // (enables the eightBitInput resource).
3923 // Ps = 1 0 3 5 -> Enable special modifiers for Alt and Num-
3924 // Lock keys. (This enables the numLock resource).
3925 // Ps = 1 0 3 6 -> Send ESC when Meta modifies a key. (This
3926 // enables the metaSendsEscape resource).
3927 // Ps = 1 0 3 7 -> Send DEL from the editing-keypad Delete
3928 // key.
3929 // Ps = 1 0 3 9 -> Send ESC when Alt modifies a key. (This
3930 // enables the altSendsEscape resource).
3931 // Ps = 1 0 4 0 -> Keep selection even if not highlighted.
3932 // (This enables the keepSelection resource).
3933 // Ps = 1 0 4 1 -> Use the CLIPBOARD selection. (This enables
3934 // the selectToClipboard resource).
3935 // Ps = 1 0 4 2 -> Enable Urgency window manager hint when
3936 // Control-G is received. (This enables the bellIsUrgent
3937 // resource).
3938 // Ps = 1 0 4 3 -> Enable raising of the window when Control-G
3939 // is received. (enables the popOnBell resource).
3940 // Ps = 1 0 4 7 -> Use Alternate Screen Buffer. (This may be
3941 // disabled by the titeInhibit resource).
3942 // Ps = 1 0 4 8 -> Save cursor as in DECSC. (This may be dis-
3943 // abled by the titeInhibit resource).
3944 // Ps = 1 0 4 9 -> Save cursor as in DECSC and use Alternate
3945 // Screen Buffer, clearing it first. (This may be disabled by
3946 // the titeInhibit resource). This combines the effects of the 1
3947 // 0 4 7 and 1 0 4 8 modes. Use this with terminfo-based
3948 // applications rather than the 4 7 mode.
3949 // Ps = 1 0 5 0 -> Set terminfo/termcap function-key mode.
3950 // Ps = 1 0 5 1 -> Set Sun function-key mode.
3951 // Ps = 1 0 5 2 -> Set HP function-key mode.
3952 // Ps = 1 0 5 3 -> Set SCO function-key mode.
3953 // Ps = 1 0 6 0 -> Set legacy keyboard emulation (X11R6).
3954 // Ps = 1 0 6 1 -> Set VT220 keyboard emulation.
3955 // Ps = 2 0 0 4 -> Set bracketed paste mode.
3956 // Modes:
3957 // http://vt100.net/docs/vt220-rm/chapter4.html
3958 Terminal.prototype.setMode = function(params) {
3959 if (typeof params === 'object') {
3960 var l = params.length
3961 , i = 0;
3962
3963 for (; i < l; i++) {
3964 this.setMode(params[i]);
3965 }
3966
3967 return;
3968 }
3969
3970 if (!this.prefix) {
3971 switch (params) {
3972 case 4:
3973 this.insertMode = true;
3974 break;
3975 case 20:
3976 //this.convertEol = true;
3977 break;
3978 }
3979 } else if (this.prefix === '?') {
3980 switch (params) {
3981 case 1:
3982 this.applicationCursor = true;
3983 break;
3984 case 2:
3985 this.setgCharset(0, Terminal.charsets.US);
3986 this.setgCharset(1, Terminal.charsets.US);
3987 this.setgCharset(2, Terminal.charsets.US);
3988 this.setgCharset(3, Terminal.charsets.US);
3989 // set VT100 mode here
3990 break;
3991 case 3: // 132 col mode
3992 this.savedCols = this.cols;
3993 this.resize(132, this.rows);
3994 break;
3995 case 6:
3996 this.originMode = true;
3997 break;
3998 case 7:
3999 this.wraparoundMode = true;
4000 break;
4001 case 12:
4002 // this.cursorBlink = true;
4003 break;
4004 case 66:
4005 this.log('Serial port requested application keypad.');
4006 this.applicationKeypad = true;
4007 break;
4008 case 9: // X10 Mouse
4009 // no release, no motion, no wheel, no modifiers.
4010 case 1000: // vt200 mouse
4011 // no motion.
4012 // no modifiers, except control on the wheel.
4013 case 1002: // button event mouse
4014 case 1003: // any event mouse
4015 // any event - sends motion events,
4016 // even if there is no button held down.
4017 this.x10Mouse = params === 9;
4018 this.vt200Mouse = params === 1000;
4019 this.normalMouse = params > 1000;
4020 this.mouseEvents = true;
4021 this.element.style.cursor = 'default';
4022 this.log('Binding to mouse events.');
4023 break;
4024 case 1004: // send focusin/focusout events
4025 // focusin: ^[[I
4026 // focusout: ^[[O
4027 this.sendFocus = true;
4028 break;
4029 case 1005: // utf8 ext mode mouse
4030 this.utfMouse = true;
4031 // for wide terminals
4032 // simply encodes large values as utf8 characters
4033 break;
4034 case 1006: // sgr ext mode mouse
4035 this.sgrMouse = true;
4036 // for wide terminals
4037 // does not add 32 to fields
4038 // press: ^[[<b;x;yM
4039 // release: ^[[<b;x;ym
4040 break;
4041 case 1015: // urxvt ext mode mouse
4042 this.urxvtMouse = true;
4043 // for wide terminals
4044 // numbers for fields
4045 // press: ^[[b;x;yM
4046 // motion: ^[[b;x;yT
4047 break;
4048 case 25: // show cursor
4049 this.cursorHidden = false;
4050 break;
4051 case 1049: // alt screen buffer cursor
4052 //this.saveCursor();
4053 ; // FALL-THROUGH
4054 case 47: // alt screen buffer
4055 case 1047: // alt screen buffer
4056 if (!this.normal) {
4057 var normal = {
4058 lines: this.lines,
4059 ybase: this.ybase,
4060 ydisp: this.ydisp,
4061 x: this.x,
4062 y: this.y,
4063 scrollTop: this.scrollTop,
4064 scrollBottom: this.scrollBottom,
4065 tabs: this.tabs
4066 // XXX save charset(s) here?
4067 // charset: this.charset,
4068 // glevel: this.glevel,
4069 // charsets: this.charsets
4070 };
4071 this.reset();
4072 this.normal = normal;
4073 this.showCursor();
4074 }
4075 break;
4076 }
4077 }
4078 };
4079
4080 // CSI Pm l Reset Mode (RM).
4081 // Ps = 2 -> Keyboard Action Mode (AM).
4082 // Ps = 4 -> Replace Mode (IRM).
4083 // Ps = 1 2 -> Send/receive (SRM).
4084 // Ps = 2 0 -> Normal Linefeed (LNM).
4085 // CSI ? Pm l
4086 // DEC Private Mode Reset (DECRST).
4087 // Ps = 1 -> Normal Cursor Keys (DECCKM).
4088 // Ps = 2 -> Designate VT52 mode (DECANM).
4089 // Ps = 3 -> 80 Column Mode (DECCOLM).
4090 // Ps = 4 -> Jump (Fast) Scroll (DECSCLM).
4091 // Ps = 5 -> Normal Video (DECSCNM).
4092 // Ps = 6 -> Normal Cursor Mode (DECOM).
4093 // Ps = 7 -> No Wraparound Mode (DECAWM).
4094 // Ps = 8 -> No Auto-repeat Keys (DECARM).
4095 // Ps = 9 -> Don't send Mouse X & Y on button press.
4096 // Ps = 1 0 -> Hide toolbar (rxvt).
4097 // Ps = 1 2 -> Stop Blinking Cursor (att610).
4098 // Ps = 1 8 -> Don't print form feed (DECPFF).
4099 // Ps = 1 9 -> Limit print to scrolling region (DECPEX).
4100 // Ps = 2 5 -> Hide Cursor (DECTCEM).
4101 // Ps = 3 0 -> Don't show scrollbar (rxvt).
4102 // Ps = 3 5 -> Disable font-shifting functions (rxvt).
4103 // Ps = 4 0 -> Disallow 80 -> 132 Mode.
4104 // Ps = 4 1 -> No more(1) fix (see curses resource).
4105 // Ps = 4 2 -> Disable Nation Replacement Character sets (DEC-
4106 // NRCM).
4107 // Ps = 4 4 -> Turn Off Margin Bell.
4108 // Ps = 4 5 -> No Reverse-wraparound Mode.
4109 // Ps = 4 6 -> Stop Logging. (This is normally disabled by a
4110 // compile-time option).
4111 // Ps = 4 7 -> Use Normal Screen Buffer.
4112 // Ps = 6 6 -> Numeric keypad (DECNKM).
4113 // Ps = 6 7 -> Backarrow key sends delete (DECBKM).
4114 // Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and
4115 // release. See the section Mouse Tracking.
4116 // Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking.
4117 // Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking.
4118 // Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking.
4119 // Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events.
4120 // Ps = 1 0 0 5 -> Disable Extended Mouse Mode.
4121 // Ps = 1 0 1 0 -> Don't scroll to bottom on tty output
4122 // (rxvt).
4123 // Ps = 1 0 1 1 -> Don't scroll to bottom on key press (rxvt).
4124 // Ps = 1 0 3 4 -> Don't interpret "meta" key. (This disables
4125 // the eightBitInput resource).
4126 // Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num-
4127 // Lock keys. (This disables the numLock resource).
4128 // Ps = 1 0 3 6 -> Don't send ESC when Meta modifies a key.
4129 // (This disables the metaSendsEscape resource).
4130 // Ps = 1 0 3 7 -> Send VT220 Remove from the editing-keypad
4131 // Delete key.
4132 // Ps = 1 0 3 9 -> Don't send ESC when Alt modifies a key.
4133 // (This disables the altSendsEscape resource).
4134 // Ps = 1 0 4 0 -> Do not keep selection when not highlighted.
4135 // (This disables the keepSelection resource).
4136 // Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables
4137 // the selectToClipboard resource).
4138 // Ps = 1 0 4 2 -> Disable Urgency window manager hint when
4139 // Control-G is received. (This disables the bellIsUrgent
4140 // resource).
4141 // Ps = 1 0 4 3 -> Disable raising of the window when Control-
4142 // G is received. (This disables the popOnBell resource).
4143 // Ps = 1 0 4 7 -> Use Normal Screen Buffer, clearing screen
4144 // first if in the Alternate Screen. (This may be disabled by
4145 // the titeInhibit resource).
4146 // Ps = 1 0 4 8 -> Restore cursor as in DECRC. (This may be
4147 // disabled by the titeInhibit resource).
4148 // Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor
4149 // as in DECRC. (This may be disabled by the titeInhibit
4150 // resource). This combines the effects of the 1 0 4 7 and 1 0
4151 // 4 8 modes. Use this with terminfo-based applications rather
4152 // than the 4 7 mode.
4153 // Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode.
4154 // Ps = 1 0 5 1 -> Reset Sun function-key mode.
4155 // Ps = 1 0 5 2 -> Reset HP function-key mode.
4156 // Ps = 1 0 5 3 -> Reset SCO function-key mode.
4157 // Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6).
4158 // Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style.
4159 // Ps = 2 0 0 4 -> Reset bracketed paste mode.
4160 Terminal.prototype.resetMode = function(params) {
4161 if (typeof params === 'object') {
4162 var l = params.length
4163 , i = 0;
4164
4165 for (; i < l; i++) {
4166 this.resetMode(params[i]);
4167 }
4168
4169 return;
4170 }
4171
4172 if (!this.prefix) {
4173 switch (params) {
4174 case 4:
4175 this.insertMode = false;
4176 break;
4177 case 20:
4178 //this.convertEol = false;
4179 break;
4180 }
4181 } else if (this.prefix === '?') {
4182 switch (params) {
4183 case 1:
4184 this.applicationCursor = false;
4185 break;
4186 case 3:
4187 if (this.cols === 132 && this.savedCols) {
4188 this.resize(this.savedCols, this.rows);
4189 }
4190 delete this.savedCols;
4191 break;
4192 case 6:
4193 this.originMode = false;
4194 break;
4195 case 7:
4196 this.wraparoundMode = false;
4197 break;
4198 case 12:
4199 // this.cursorBlink = false;
4200 break;
4201 case 66:
4202 this.log('Switching back to normal keypad.');
4203 this.applicationKeypad = false;
4204 break;
4205 case 9: // X10 Mouse
4206 case 1000: // vt200 mouse
4207 case 1002: // button event mouse
4208 case 1003: // any event mouse
4209 this.x10Mouse = false;
4210 this.vt200Mouse = false;
4211 this.normalMouse = false;
4212 this.mouseEvents = false;
4213 this.element.style.cursor = '';
4214 break;
4215 case 1004: // send focusin/focusout events
4216 this.sendFocus = false;
4217 break;
4218 case 1005: // utf8 ext mode mouse
4219 this.utfMouse = false;
4220 break;
4221 case 1006: // sgr ext mode mouse
4222 this.sgrMouse = false;
4223 break;
4224 case 1015: // urxvt ext mode mouse
4225 this.urxvtMouse = false;
4226 break;
4227 case 25: // hide cursor
4228 this.cursorHidden = true;
4229 break;
4230 case 1049: // alt screen buffer cursor
4231 ; // FALL-THROUGH
4232 case 47: // normal screen buffer
4233 case 1047: // normal screen buffer - clearing it first
4234 if (this.normal) {
4235 this.lines = this.normal.lines;
4236 this.ybase = this.normal.ybase;
4237 this.ydisp = this.normal.ydisp;
4238 this.x = this.normal.x;
4239 this.y = this.normal.y;
4240 this.scrollTop = this.normal.scrollTop;
4241 this.scrollBottom = this.normal.scrollBottom;
4242 this.tabs = this.normal.tabs;
4243 this.normal = null;
4244 // if (params === 1049) {
4245 // this.x = this.savedX;
4246 // this.y = this.savedY;
4247 // }
4248 this.refresh(0, this.rows - 1);
4249 this.showCursor();
4250 }
4251 break;
4252 }
4253 }
4254 };
4255
4256 // CSI Ps ; Ps r
4257 // Set Scrolling Region [top;bottom] (default = full size of win-
4258 // dow) (DECSTBM).
4259 // CSI ? Pm r
4260 Terminal.prototype.setScrollRegion = function(params) {
4261 if (this.prefix) return;
4262 this.scrollTop = (params[0] || 1) - 1;
4263 this.scrollBottom = (params[1] || this.rows) - 1;
4264 this.x = 0;
4265 this.y = 0;
4266 };
4267
4268 // CSI s
4269 // Save cursor (ANSI.SYS).
4270 Terminal.prototype.saveCursor = function(params) {
4271 this.savedX = this.x;
4272 this.savedY = this.y;
4273 };
4274
4275 // CSI u
4276 // Restore cursor (ANSI.SYS).
4277 Terminal.prototype.restoreCursor = function(params) {
4278 this.x = this.savedX || 0;
4279 this.y = this.savedY || 0;
4280 };
4281
4282 /**
4283 * Lesser Used
4284 */
4285
4286 // CSI Ps I
4287 // Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
4288 Terminal.prototype.cursorForwardTab = function(params) {
4289 var param = params[0] || 1;
4290 while (param--) {
4291 this.x = this.nextStop();
4292 }
4293 };
4294
4295 // CSI Ps S Scroll up Ps lines (default = 1) (SU).
4296 Terminal.prototype.scrollUp = function(params) {
4297 var param = params[0] || 1;
4298 while (param--) {
4299 this.lines.splice(this.ybase + this.scrollTop, 1);
4300 this.lines.splice(this.ybase + this.scrollBottom, 0, this.blankLine());
4301 }
4302 // this.maxRange();
4303 this.updateRange(this.scrollTop);
4304 this.updateRange(this.scrollBottom);
4305 };
4306
4307 // CSI Ps T Scroll down Ps lines (default = 1) (SD).
4308 Terminal.prototype.scrollDown = function(params) {
4309 var param = params[0] || 1;
4310 while (param--) {
4311 this.lines.splice(this.ybase + this.scrollBottom, 1);
4312 this.lines.splice(this.ybase + this.scrollTop, 0, this.blankLine());
4313 }
4314 // this.maxRange();
4315 this.updateRange(this.scrollTop);
4316 this.updateRange(this.scrollBottom);
4317 };
4318
4319 // CSI Ps ; Ps ; Ps ; Ps ; Ps T
4320 // Initiate highlight mouse tracking. Parameters are
4321 // [func;startx;starty;firstrow;lastrow]. See the section Mouse
4322 // Tracking.
4323 Terminal.prototype.initMouseTracking = function(params) {
4324 // Relevant: DECSET 1001
4325 };
4326
4327 // CSI > Ps; Ps T
4328 // Reset one or more features of the title modes to the default
4329 // value. Normally, "reset" disables the feature. It is possi-
4330 // ble to disable the ability to reset features by compiling a
4331 // different default for the title modes into xterm.
4332 // Ps = 0 -> Do not set window/icon labels using hexadecimal.
4333 // Ps = 1 -> Do not query window/icon labels using hexadeci-
4334 // mal.
4335 // Ps = 2 -> Do not set window/icon labels using UTF-8.
4336 // Ps = 3 -> Do not query window/icon labels using UTF-8.
4337 // (See discussion of "Title Modes").
4338 Terminal.prototype.resetTitleModes = function(params) {
4339 ;
4340 };
4341
4342 // CSI Ps Z Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
4343 Terminal.prototype.cursorBackwardTab = function(params) {
4344 var param = params[0] || 1;
4345 while (param--) {
4346 this.x = this.prevStop();
4347 }
4348 };
4349
4350 // CSI Ps b Repeat the preceding graphic character Ps times (REP).
4351 Terminal.prototype.repeatPrecedingCharacter = function(params) {
4352 var param = params[0] || 1
4353 , line = this.lines[this.ybase + this.y]
4afa08da 4354 , ch = line[this.x - 1] || [this.defAttr, ' ', 1];
3f455f90
PK
4355
4356 while (param--) line[this.x++] = ch;
4357 };
4358
4359 // CSI Ps g Tab Clear (TBC).
4360 // Ps = 0 -> Clear Current Column (default).
4361 // Ps = 3 -> Clear All.
4362 // Potentially:
4363 // Ps = 2 -> Clear Stops on Line.
4364 // http://vt100.net/annarbor/aaa-ug/section6.html
4365 Terminal.prototype.tabClear = function(params) {
4366 var param = params[0];
4367 if (param <= 0) {
4368 delete this.tabs[this.x];
4369 } else if (param === 3) {
4370 this.tabs = {};
4371 }
4372 };
4373
4374 // CSI Pm i Media Copy (MC).
4375 // Ps = 0 -> Print screen (default).
4376 // Ps = 4 -> Turn off printer controller mode.
4377 // Ps = 5 -> Turn on printer controller mode.
4378 // CSI ? Pm i
4379 // Media Copy (MC, DEC-specific).
4380 // Ps = 1 -> Print line containing cursor.
4381 // Ps = 4 -> Turn off autoprint mode.
4382 // Ps = 5 -> Turn on autoprint mode.
4383 // Ps = 1 0 -> Print composed display, ignores DECPEX.
4384 // Ps = 1 1 -> Print all pages.
4385 Terminal.prototype.mediaCopy = function(params) {
4386 ;
4387 };
4388
4389 // CSI > Ps; Ps m
4390 // Set or reset resource-values used by xterm to decide whether
4391 // to construct escape sequences holding information about the
4392 // modifiers pressed with a given key. The first parameter iden-
4393 // tifies the resource to set/reset. The second parameter is the
4394 // value to assign to the resource. If the second parameter is
4395 // omitted, the resource is reset to its initial value.
4396 // Ps = 1 -> modifyCursorKeys.
4397 // Ps = 2 -> modifyFunctionKeys.
4398 // Ps = 4 -> modifyOtherKeys.
4399 // If no parameters are given, all resources are reset to their
4400 // initial values.
4401 Terminal.prototype.setResources = function(params) {
4402 ;
4403 };
4404
4405 // CSI > Ps n
4406 // Disable modifiers which may be enabled via the CSI > Ps; Ps m
4407 // sequence. This corresponds to a resource value of "-1", which
4408 // cannot be set with the other sequence. The parameter identi-
4409 // fies the resource to be disabled:
4410 // Ps = 1 -> modifyCursorKeys.
4411 // Ps = 2 -> modifyFunctionKeys.
4412 // Ps = 4 -> modifyOtherKeys.
4413 // If the parameter is omitted, modifyFunctionKeys is disabled.
4414 // When modifyFunctionKeys is disabled, xterm uses the modifier
4415 // keys to make an extended sequence of functions rather than
4416 // adding a parameter to each function key to denote the modi-
4417 // fiers.
4418 Terminal.prototype.disableModifiers = function(params) {
4419 ;
4420 };
4421
4422 // CSI > Ps p
4423 // Set resource value pointerMode. This is used by xterm to
4424 // decide whether to hide the pointer cursor as the user types.
4425 // Valid values for the parameter:
4426 // Ps = 0 -> never hide the pointer.
4427 // Ps = 1 -> hide if the mouse tracking mode is not enabled.
4428 // Ps = 2 -> always hide the pointer. If no parameter is
4429 // given, xterm uses the default, which is 1 .
4430 Terminal.prototype.setPointerMode = function(params) {
4431 ;
4432 };
4433
4434 // CSI ! p Soft terminal reset (DECSTR).
4435 // http://vt100.net/docs/vt220-rm/table4-10.html
4436 Terminal.prototype.softReset = function(params) {
4437 this.cursorHidden = false;
4438 this.insertMode = false;
4439 this.originMode = false;
4440 this.wraparoundMode = false; // autowrap
4441 this.applicationKeypad = false; // ?
4442 this.applicationCursor = false;
4443 this.scrollTop = 0;
4444 this.scrollBottom = this.rows - 1;
4445 this.curAttr = this.defAttr;
4446 this.x = this.y = 0; // ?
4447 this.charset = null;
4448 this.glevel = 0; // ??
4449 this.charsets = [null]; // ??
4450 };
4451
4452 // CSI Ps$ p
4453 // Request ANSI mode (DECRQM). For VT300 and up, reply is
4454 // CSI Ps; Pm$ y
4455 // where Ps is the mode number as in RM, and Pm is the mode
4456 // value:
4457 // 0 - not recognized
4458 // 1 - set
4459 // 2 - reset
4460 // 3 - permanently set
4461 // 4 - permanently reset
4462 Terminal.prototype.requestAnsiMode = function(params) {
4463 ;
4464 };
4465
4466 // CSI ? Ps$ p
4467 // Request DEC private mode (DECRQM). For VT300 and up, reply is
4468 // CSI ? Ps; Pm$ p
4469 // where Ps is the mode number as in DECSET, Pm is the mode value
4470 // as in the ANSI DECRQM.
4471 Terminal.prototype.requestPrivateMode = function(params) {
4472 ;
4473 };
4474
4475 // CSI Ps ; Ps " p
4476 // Set conformance level (DECSCL). Valid values for the first
4477 // parameter:
4478 // Ps = 6 1 -> VT100.
4479 // Ps = 6 2 -> VT200.
4480 // Ps = 6 3 -> VT300.
4481 // Valid values for the second parameter:
4482 // Ps = 0 -> 8-bit controls.
4483 // Ps = 1 -> 7-bit controls (always set for VT100).
4484 // Ps = 2 -> 8-bit controls.
4485 Terminal.prototype.setConformanceLevel = function(params) {
4486 ;
4487 };
4488
4489 // CSI Ps q Load LEDs (DECLL).
4490 // Ps = 0 -> Clear all LEDS (default).
4491 // Ps = 1 -> Light Num Lock.
4492 // Ps = 2 -> Light Caps Lock.
4493 // Ps = 3 -> Light Scroll Lock.
4494 // Ps = 2 1 -> Extinguish Num Lock.
4495 // Ps = 2 2 -> Extinguish Caps Lock.
4496 // Ps = 2 3 -> Extinguish Scroll Lock.
4497 Terminal.prototype.loadLEDs = function(params) {
4498 ;
4499 };
4500
4501 // CSI Ps SP q
4502 // Set cursor style (DECSCUSR, VT520).
4503 // Ps = 0 -> blinking block.
4504 // Ps = 1 -> blinking block (default).
4505 // Ps = 2 -> steady block.
4506 // Ps = 3 -> blinking underline.
4507 // Ps = 4 -> steady underline.
4508 Terminal.prototype.setCursorStyle = function(params) {
4509 ;
4510 };
4511
4512 // CSI Ps " q
4513 // Select character protection attribute (DECSCA). Valid values
4514 // for the parameter:
4515 // Ps = 0 -> DECSED and DECSEL can erase (default).
4516 // Ps = 1 -> DECSED and DECSEL cannot erase.
4517 // Ps = 2 -> DECSED and DECSEL can erase.
4518 Terminal.prototype.setCharProtectionAttr = function(params) {
4519 ;
4520 };
4521
4522 // CSI ? Pm r
4523 // Restore DEC Private Mode Values. The value of Ps previously
4524 // saved is restored. Ps values are the same as for DECSET.
4525 Terminal.prototype.restorePrivateValues = function(params) {
4526 ;
4527 };
4528
4529 // CSI Pt; Pl; Pb; Pr; Ps$ r
4530 // Change Attributes in Rectangular Area (DECCARA), VT400 and up.
4531 // Pt; Pl; Pb; Pr denotes the rectangle.
4532 // Ps denotes the SGR attributes to change: 0, 1, 4, 5, 7.
4533 // NOTE: xterm doesn't enable this code by default.
4534 Terminal.prototype.setAttrInRectangle = function(params) {
4535 var t = params[0]
4536 , l = params[1]
4537 , b = params[2]
4538 , r = params[3]
4539 , attr = params[4];
4540
4541 var line
4542 , i;
4543
4544 for (; t < b + 1; t++) {
4545 line = this.lines[this.ybase + t];
4546 for (i = l; i < r; i++) {
4547 line[i] = [attr, line[i][1]];
4548 }
4549 }
4550
4551 // this.maxRange();
4552 this.updateRange(params[0]);
4553 this.updateRange(params[2]);
4554 };
4555
4556
4557 // CSI Pc; Pt; Pl; Pb; Pr$ x
4558 // Fill Rectangular Area (DECFRA), VT420 and up.
4559 // Pc is the character to use.
4560 // Pt; Pl; Pb; Pr denotes the rectangle.
4561 // NOTE: xterm doesn't enable this code by default.
4562 Terminal.prototype.fillRectangle = function(params) {
4563 var ch = params[0]
4564 , t = params[1]
4565 , l = params[2]
4566 , b = params[3]
4567 , r = params[4];
4568
4569 var line
4570 , i;
4571
4572 for (; t < b + 1; t++) {
4573 line = this.lines[this.ybase + t];
4574 for (i = l; i < r; i++) {
4575 line[i] = [line[i][0], String.fromCharCode(ch)];
4576 }
4577 }
4578
4579 // this.maxRange();
4580 this.updateRange(params[1]);
4581 this.updateRange(params[3]);
4582 };
4583
4584 // CSI Ps ; Pu ' z
4585 // Enable Locator Reporting (DECELR).
4586 // Valid values for the first parameter:
4587 // Ps = 0 -> Locator disabled (default).
4588 // Ps = 1 -> Locator enabled.
4589 // Ps = 2 -> Locator enabled for one report, then disabled.
4590 // The second parameter specifies the coordinate unit for locator
4591 // reports.
4592 // Valid values for the second parameter:
4593 // Pu = 0 <- or omitted -> default to character cells.
4594 // Pu = 1 <- device physical pixels.
4595 // Pu = 2 <- character cells.
4596 Terminal.prototype.enableLocatorReporting = function(params) {
4597 var val = params[0] > 0;
4598 //this.mouseEvents = val;
4599 //this.decLocator = val;
4600 };
4601
4602 // CSI Pt; Pl; Pb; Pr$ z
4603 // Erase Rectangular Area (DECERA), VT400 and up.
4604 // Pt; Pl; Pb; Pr denotes the rectangle.
4605 // NOTE: xterm doesn't enable this code by default.
4606 Terminal.prototype.eraseRectangle = function(params) {
4607 var t = params[0]
4608 , l = params[1]
4609 , b = params[2]
4610 , r = params[3];
4611
4612 var line
4613 , i
4614 , ch;
4615
4afa08da 4616 ch = [this.eraseAttr(), ' ', 1]; // xterm?
3f455f90
PK
4617
4618 for (; t < b + 1; t++) {
4619 line = this.lines[this.ybase + t];
4620 for (i = l; i < r; i++) {
4621 line[i] = ch;
4622 }
4623 }
4624
4625 // this.maxRange();
4626 this.updateRange(params[0]);
4627 this.updateRange(params[2]);
4628 };
8bc844c0 4629
8bc844c0 4630
3f455f90
PK
4631 // CSI P m SP }
4632 // Insert P s Column(s) (default = 1) (DECIC), VT420 and up.
4633 // NOTE: xterm doesn't enable this code by default.
4634 Terminal.prototype.insertColumns = function() {
4635 var param = params[0]
4636 , l = this.ybase + this.rows
4afa08da 4637 , ch = [this.eraseAttr(), ' ', 1] // xterm?
3f455f90 4638 , i;
8bc844c0 4639
3f455f90
PK
4640 while (param--) {
4641 for (i = this.ybase; i < l; i++) {
4642 this.lines[i].splice(this.x + 1, 0, ch);
4643 this.lines[i].pop();
8bc844c0 4644 }
3f455f90 4645 }
8bc844c0 4646
3f455f90
PK
4647 this.maxRange();
4648 };
8bc844c0 4649
178b611b 4650
3f455f90
PK
4651 // CSI P m SP ~
4652 // Delete P s Column(s) (default = 1) (DECDC), VT420 and up
4653 // NOTE: xterm doesn't enable this code by default.
4654 Terminal.prototype.deleteColumns = function() {
4655 var param = params[0]
4656 , l = this.ybase + this.rows
4afa08da 4657 , ch = [this.eraseAttr(), ' ', 1] // xterm?
3f455f90
PK
4658 , i;
4659
4660 while (param--) {
4661 for (i = this.ybase; i < l; i++) {
4662 this.lines[i].splice(this.x, 1);
4663 this.lines[i].push(ch);
4664 }
4665 }
8bc844c0 4666
3f455f90
PK
4667 this.maxRange();
4668 };
8bc844c0 4669
3f455f90
PK
4670 /**
4671 * Character Sets
4672 */
4673
4674 Terminal.charsets = {};
4675
4676 // DEC Special Character and Line Drawing Set.
4677 // http://vt100.net/docs/vt102-ug/table5-13.html
4678 // A lot of curses apps use this if they see TERM=xterm.
4679 // testing: echo -e '\e(0a\e(B'
4680 // The xterm output sometimes seems to conflict with the
4681 // reference above. xterm seems in line with the reference
4682 // when running vttest however.
4683 // The table below now uses xterm's output from vttest.
4684 Terminal.charsets.SCLD = { // (0
4685 '`': '\u25c6', // '◆'
4686 'a': '\u2592', // '▒'
4687 'b': '\u0009', // '\t'
4688 'c': '\u000c', // '\f'
4689 'd': '\u000d', // '\r'
4690 'e': '\u000a', // '\n'
4691 'f': '\u00b0', // '°'
4692 'g': '\u00b1', // '±'
4693 'h': '\u2424', // '\u2424' (NL)
4694 'i': '\u000b', // '\v'
4695 'j': '\u2518', // '┘'
4696 'k': '\u2510', // '┐'
4697 'l': '\u250c', // '┌'
4698 'm': '\u2514', // '└'
4699 'n': '\u253c', // '┼'
4700 'o': '\u23ba', // '⎺'
4701 'p': '\u23bb', // '⎻'
4702 'q': '\u2500', // '─'
4703 'r': '\u23bc', // '⎼'
4704 's': '\u23bd', // '⎽'
4705 't': '\u251c', // '├'
4706 'u': '\u2524', // '┤'
4707 'v': '\u2534', // '┴'
4708 'w': '\u252c', // '┬'
4709 'x': '\u2502', // '│'
4710 'y': '\u2264', // '≤'
4711 'z': '\u2265', // '≥'
4712 '{': '\u03c0', // 'π'
4713 '|': '\u2260', // '≠'
4714 '}': '\u00a3', // '£'
4715 '~': '\u00b7' // '·'
4716 };
4717
4718 Terminal.charsets.UK = null; // (A
4719 Terminal.charsets.US = null; // (B (USASCII)
4720 Terminal.charsets.Dutch = null; // (4
4721 Terminal.charsets.Finnish = null; // (C or (5
4722 Terminal.charsets.French = null; // (R
4723 Terminal.charsets.FrenchCanadian = null; // (Q
4724 Terminal.charsets.German = null; // (K
4725 Terminal.charsets.Italian = null; // (Y
4726 Terminal.charsets.NorwegianDanish = null; // (E or (6
4727 Terminal.charsets.Spanish = null; // (Z
4728 Terminal.charsets.Swedish = null; // (H or (7
4729 Terminal.charsets.Swiss = null; // (=
4730 Terminal.charsets.ISOLatin = null; // /A
4731
4732 /**
4733 * Helpers
4734 */
4735
b01165c1 4736 function contains(el, arr) {
4737 for (var i = 0; i < arr.length; i += 1) {
4738 if (el === arr[i]) {
4739 return true;
4740 }
4741 }
4742 return false;
4743 }
4744
3f455f90
PK
4745 function on(el, type, handler, capture) {
4746 if (!Array.isArray(el)) {
4747 el = [el];
9e6cb6b6 4748 }
3f455f90
PK
4749 el.forEach(function (element) {
4750 element.addEventListener(type, handler, capture || false);
4751 });
9e6cb6b6 4752 }
8bc844c0 4753
3f455f90
PK
4754 function off(el, type, handler, capture) {
4755 el.removeEventListener(type, handler, capture || false);
5d3f8786 4756 }
3f455f90
PK
4757
4758 function cancel(ev, force) {
4759 if (!this.cancelEvents && !force) {
4760 return;
9e6cb6b6 4761 }
3f455f90
PK
4762 ev.preventDefault();
4763 ev.stopPropagation();
4764 return false;
9e6cb6b6 4765 }
8bc844c0 4766
3f455f90
PK
4767 function inherits(child, parent) {
4768 function f() {
4769 this.constructor = child;
9e6cb6b6 4770 }
3f455f90
PK
4771 f.prototype = parent.prototype;
4772 child.prototype = new f;
4773 }
8bc844c0 4774
3f455f90
PK
4775 // if bold is broken, we can't
4776 // use it in the terminal.
4777 function isBoldBroken(document) {
4778 var body = document.getElementsByTagName('body')[0];
4779 var el = document.createElement('span');
4780 el.innerHTML = 'hello world';
4781 body.appendChild(el);
4782 var w1 = el.scrollWidth;
4783 el.style.fontWeight = 'bold';
4784 var w2 = el.scrollWidth;
4785 body.removeChild(el);
4786 return w1 !== w2;
4787 }
8bc844c0 4788
3f455f90
PK
4789 var String = this.String;
4790 var setTimeout = this.setTimeout;
4791 var setInterval = this.setInterval;
4792
4793 function indexOf(obj, el) {
4794 var i = obj.length;
4795 while (i--) {
4796 if (obj[i] === el) return i;
9e6cb6b6 4797 }
3f455f90 4798 return -1;
9e6cb6b6 4799 }
8bc844c0 4800
b01165c1 4801 function isThirdLevelShift(term, ev) {
4802 var thirdLevelKey =
4803 (term.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
4804 (term.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
4805
4806 // Don't invoke for arrows, pageDown, home, backspace, etc.
4807 return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
4808 }
4809
3f455f90
PK
4810 function matchColor(r1, g1, b1) {
4811 var hash = (r1 << 16) | (g1 << 8) | b1;
4812
4813 if (matchColor._cache[hash] != null) {
4814 return matchColor._cache[hash];
4815 }
8bc844c0 4816
3f455f90
PK
4817 var ldiff = Infinity
4818 , li = -1
4819 , i = 0
4820 , c
4821 , r2
4822 , g2
4823 , b2
4824 , diff;
4825
4826 for (; i < Terminal.vcolors.length; i++) {
4827 c = Terminal.vcolors[i];
4828 r2 = c[0];
4829 g2 = c[1];
4830 b2 = c[2];
4831
4832 diff = matchColor.distance(r1, g1, b1, r2, g2, b2);
4833
4834 if (diff === 0) {
4835 li = i;
4836 break;
4837 }
9e6cb6b6 4838
3f455f90
PK
4839 if (diff < ldiff) {
4840 ldiff = diff;
4841 li = i;
4842 }
4843 }
8bc844c0 4844
3f455f90
PK
4845 return matchColor._cache[hash] = li;
4846 }
8bc844c0 4847
3f455f90 4848 matchColor._cache = {};
8bc844c0 4849
3f455f90
PK
4850 // http://stackoverflow.com/questions/1633828
4851 matchColor.distance = function(r1, g1, b1, r2, g2, b2) {
4852 return Math.pow(30 * (r1 - r2), 2)
4853 + Math.pow(59 * (g1 - g2), 2)
4854 + Math.pow(11 * (b1 - b2), 2);
4855 };
8bc844c0 4856
3f455f90
PK
4857 function each(obj, iter, con) {
4858 if (obj.forEach) return obj.forEach(iter, con);
4859 for (var i = 0; i < obj.length; i++) {
4860 iter.call(con, obj[i], i, obj);
4861 }
a68c8336
CJ
4862 }
4863
3f455f90
PK
4864 function keys(obj) {
4865 if (Object.keys) return Object.keys(obj);
4866 var key, keys = [];
4867 for (key in obj) {
4868 if (Object.prototype.hasOwnProperty.call(obj, key)) {
4869 keys.push(key);
4870 }
4871 }
4872 return keys;
86dad1b0 4873 }
86dad1b0 4874
e3126ba3
JB
4875 var wcwidth = (function(opts) {
4876 // extracted from https://www.cl.cam.ac.uk/%7Emgk25/ucs/wcwidth.c
4877 // combining characters
4878 var COMBINING = [
4879 [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489],
4880 [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2],
4881 [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603],
4882 [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670],
4883 [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED],
4884 [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A],
4885 [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902],
4886 [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D],
4887 [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981],
4888 [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD],
4889 [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C],
4890 [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D],
4891 [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC],
4892 [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD],
4893 [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C],
4894 [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D],
4895 [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0],
4896 [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48],
4897 [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC],
4898 [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD],
4899 [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D],
4900 [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6],
4901 [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E],
4902 [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC],
4903 [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35],
4904 [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E],
4905 [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97],
4906 [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030],
4907 [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039],
4908 [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F],
4909 [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753],
4910 [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD],
4911 [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD],
4912 [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922],
4913 [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B],
4914 [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34],
4915 [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42],
4916 [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF],
4917 [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063],
4918 [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F],
4919 [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B],
4920 [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F],
4921 [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB],
4922 [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F],
4923 [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169],
4924 [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD],
4925 [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F],
4926 [0xE0100, 0xE01EF]
4927 ];
4928 // binary search
4929 function bisearch(ucs) {
4930 var min = 0;
4931 var max = COMBINING.length - 1;
4932 var mid;
4933 if (ucs < COMBINING[0][0] || ucs > COMBINING[max][1])
4934 return false;
4935 while (max >= min) {
4936 mid = Math.floor((min + max) / 2);
4937 if (ucs > COMBINING[mid][1])
4938 min = mid + 1;
4939 else if (ucs < COMBINING[mid][0])
4940 max = mid - 1;
4941 else
4942 return true;
4943 }
4944 return false;
4945 }
4946 function wcwidth(ucs) {
4947 // test for 8-bit control characters
4948 if (ucs === 0)
4949 return opts.nul;
4950 if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0))
4951 return opts.control;
4952 // binary search in table of non-spacing characters
4953 if (bisearch(ucs))
4954 return 0;
4955 // if we arrive here, ucs is not a combining or C0/C1 control character
4956 return 1 +
4957 (
4958 ucs >= 0x1100 &&
4959 (
4960 ucs <= 0x115f || // Hangul Jamo init. consonants
4961 ucs == 0x2329 ||
4962 ucs == 0x232a ||
4963 (ucs >= 0x2e80 && ucs <= 0xa4cf && ucs != 0x303f) || // CJK..Yi
4964 (ucs >= 0xac00 && ucs <= 0xd7a3) || // Hangul Syllables
4965 (ucs >= 0xf900 && ucs <= 0xfaff) || // CJK Compat Ideographs
4966 (ucs >= 0xfe10 && ucs <= 0xfe19) || // Vertical forms
4967 (ucs >= 0xfe30 && ucs <= 0xfe6f) || // CJK Compat Forms
4968 (ucs >= 0xff00 && ucs <= 0xff60) || // Fullwidth Forms
4969 (ucs >= 0xffe0 && ucs <= 0xffe6) ||
4970 (ucs >= 0x20000 && ucs <= 0x2fffd) ||
4971 (ucs >= 0x30000 && ucs <= 0x3fffd)
4972 )
4973 );
4974 }
4975 return wcwidth;
4976 })({nul: 0, control: 0}); // configurable options
4977
3f455f90
PK
4978 /**
4979 * Expose
4980 */
4981
4982 Terminal.EventEmitter = EventEmitter;
4983 Terminal.inherits = inherits;
fd5be55d
DI
4984
4985 /**
4986 * Adds an event listener to the terminal.
4987 *
4988 * @param {string} event The name of the event. TODO: Document all event types
4989 * @param {function} callback The function to call when the event is triggered.
fd5be55d 4990 */
3f455f90
PK
4991 Terminal.on = on;
4992 Terminal.off = off;
4993 Terminal.cancel = cancel;
8bc844c0 4994
107d1a14 4995
3f455f90 4996 return Terminal;
987f09d8 4997});