2 * xterm.js: xterm, in the browser
3 * Originally forked from (with the author's permission):
4 * Fabrice Bellard's javascript vt100 for jslinux:
5 * http://bellard.org/jslinux/
6 * Copyright (c) 2011 Fabrice Bellard
7 * The original design remains. The terminal itself
8 * has been extended to include xterm CSI codes, among
13 import { CompositionHelper
} from './CompositionHelper';
14 import { EventEmitter
} from './EventEmitter';
15 import { Viewport
} from './Viewport';
16 import { rightClickHandler
, pasteHandler
, copyHandler
} from './handlers/Clipboard';
17 import { CircularList
} from './utils/CircularList';
18 import { C0
} from './EscapeSequences';
19 import { InputHandler
} from './InputHandler';
20 import { Parser
} from './Parser';
21 import { Renderer
} from './Renderer';
22 import { CharMeasure
} from './utils/CharMeasure';
23 import * as Browser
from './utils/Browser';
24 import * as Keyboard
from './utils/Keyboard';
25 import { CHARSETS
} from './Charsets';
28 * Terminal Emulation References:
30 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
31 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
32 * http://invisible-island.net/vttest/
33 * http://www.inwap.com/pdp10/ansicode.txt
34 * http://linux.die.net/man/4/console_codes
35 * http://linux.die.net/man/7/urxvt
38 // Let it work inside Node.js for automated testing purposes.
39 var document
= (typeof window
!= 'undefined') ? window
.document
: null;
42 * The amount of write requests to queue before sending an XOFF signal to the
43 * pty process. This number must be small in order for ^C and similar sequences
46 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
49 * The number of writes to perform in a single batch before allowing the
50 * renderer to catch up with a 0ms setTimeout.
52 var WRITE_BATCH_SIZE
= 300;
59 * Creates a new `Terminal` object.
61 * @param {object} options An object containing a set of options, the available options are:
62 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
63 * - `cols` (number): The number of columns of the terminal (horizontal size)
64 * - `rows` (number): The number of rows of the terminal (vertical size)
68 * @alias module:xterm/src/xterm
70 function Terminal(options
) {
73 if (!(this instanceof Terminal
)) {
74 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
77 self
.browser
= Browser
;
78 self
.cancel
= Terminal
.cancel
;
80 EventEmitter
.call(this);
82 if (typeof options
=== 'number') {
90 options
= options
|| {};
93 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
94 if (options
[key
] == null) {
95 options
[key
] = Terminal
.options
[key
];
97 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
98 options
[key
] = Terminal
[key
];
101 self
[key
] = options
[key
];
104 if (options
.colors
.length
=== 8) {
105 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
106 } else if (options
.colors
.length
=== 16) {
107 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
108 } else if (options
.colors
.length
=== 10) {
109 options
.colors
= options
.colors
.slice(0, -2).concat(
110 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
111 } else if (options
.colors
.length
=== 18) {
112 options
.colors
= options
.colors
.concat(
113 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
115 this.colors
= options
.colors
;
117 this.options
= options
;
119 // this.context = options.context || window;
120 // this.document = options.document || document;
121 this.parent
= options
.body
|| options
.parent
|| (
122 document
? document
.getElementsByTagName('body')[0] : null
125 this.cols
= options
.cols
|| options
.geometry
[0];
126 this.rows
= options
.rows
|| options
.geometry
[1];
127 this.geometry
= [this.cols
, this.rows
];
129 if (options
.handler
) {
130 this.on('data', options
.handler
);
134 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
140 * The scroll position of the viewport
145 * The cursor's x position after ybase
150 * The cursor's y position after ybase
154 this.cursorState
= 0;
155 this.cursorHidden
= false;
159 this.scrollBottom
= this.rows
- 1;
160 this.customKeydownHandler
= null;
163 this.applicationKeypad
= false;
164 this.applicationCursor
= false;
165 this.originMode
= false;
166 this.insertMode
= false;
167 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
172 this.gcharset
= null;
174 this.charsets
= [null];
198 this.readable
= true;
199 this.writable
= true;
201 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
202 this.curAttr
= this.defAttr
;
205 this.currentParam
= 0;
209 this.inputHandler
= new InputHandler(this);
210 this.parser
= new Parser(this.inputHandler
, this);
211 this.renderer
= null;
214 this.writeBuffer
= [];
215 this.writeInProgress
= false;
218 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
219 * This is a distinct state from writeStopped so that if the user requested
220 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
223 this.xoffSentToCatchUp
= false;
225 /** Whether writing has been stopped as a result of XOFF */
226 this.writeStopped
= false;
228 // leftover surrogate high from previous write invocation
229 this.surrogate_high
= '';
232 * An array of all lines in the entire buffer, including the prompt. The lines are array of
233 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
235 this.lines
= new CircularList(this.scrollback
);
238 this.lines
.push(this.blankLine());
244 // Store if user went browsing history in scrollback
245 this.userScrolling
= false;
248 inherits(Terminal
, EventEmitter
);
251 * back_color_erase feature for xterm.
253 Terminal
.prototype.eraseAttr = function() {
254 // if (this.is('screen')) return this.defAttr;
255 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
263 Terminal
.tangoColors
= [
284 // Colors 0-15 + 16-255
285 // Much thanks to TooTallNate for writing this.
286 Terminal
.colors
= (function() {
287 var colors
= Terminal
.tangoColors
.slice()
288 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
293 for (; i
< 216; i
++) {
294 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
299 for (; i
< 24; i
++) {
304 function out(r
, g
, b
) {
305 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
310 return c
.length
< 2 ? '0' + c
: c
;
316 Terminal
._colors
= Terminal
.colors
.slice();
318 Terminal
.vcolors
= (function() {
320 , colors
= Terminal
.colors
324 for (; i
< 256; i
++) {
325 color
= parseInt(colors
[i
].substring(1), 16);
327 (color
>> 16) & 0xff,
340 Terminal
.defaults
= {
341 colors
: Terminal
.colors
,
347 cursorStyle
: 'block',
355 useFlowControl
: false,
357 // programFeatures: false,
361 Terminal
.options
= {};
363 Terminal
.focus
= null;
365 each(keys(Terminal
.defaults
), function(key
) {
366 Terminal
[key
] = Terminal
.defaults
[key
];
367 Terminal
.options
[key
] = Terminal
.defaults
[key
];
371 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
373 Terminal
.prototype.focus = function() {
374 return this.textarea
.focus();
378 * Retrieves an option's value from the terminal.
379 * @param {string} key The option key.
381 Terminal
.prototype.getOption = function(key
, value
) {
382 if (!(key
in Terminal
.defaults
)) {
383 throw new Error('No option with key "' + key
+ '"');
386 if (typeof this.options
[key
] !== 'undefined') {
387 return this.options
[key
];
394 * Sets an option on the terminal.
395 * @param {string} key The option key.
396 * @param {string} value The option value.
398 Terminal
.prototype.setOption = function(key
, value
) {
399 if (!(key
in Terminal
.defaults
)) {
400 throw new Error('No option with key "' + key
+ '"');
404 if (this.options
[key
] !== value
) {
405 if (this.lines
.length
> value
) {
406 const amountToTrim
= this.lines
.length
- value
;
407 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
408 this.lines
.trimStart(amountToTrim
);
409 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
410 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
412 this.refresh(0, this.rows
- 1);
415 this.lines
.maxLength
= value
;
416 this.viewport
.syncScrollArea();
421 this.options
[key
] = value
;
423 case 'cursorBlink': this.element
.classList
.toggle('xterm-cursor-blink', value
); break;
425 // Style 'block' applies with no class
426 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
427 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
429 case 'tabStopWidth': this.setupStops(); break;
434 * Binds the desired focus behavior on a given terminal object.
438 Terminal
.bindFocus = function (term
) {
439 on(term
.textarea
, 'focus', function (ev
) {
440 if (term
.sendFocus
) {
441 term
.send(C0
.ESC
+ '[I');
443 term
.element
.classList
.add('focus');
445 Terminal
.focus
= term
;
446 term
.emit('focus', {terminal
: term
});
451 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
453 Terminal
.prototype.blur = function() {
454 return this.textarea
.blur();
458 * Binds the desired blur behavior on a given terminal object.
462 Terminal
.bindBlur = function (term
) {
463 on(term
.textarea
, 'blur', function (ev
) {
464 term
.refresh(term
.y
, term
.y
);
465 if (term
.sendFocus
) {
466 term
.send(C0
.ESC
+ '[O');
468 term
.element
.classList
.remove('focus');
469 Terminal
.focus
= null;
470 term
.emit('blur', {terminal
: term
});
475 * Initialize default behavior
477 Terminal
.prototype.initGlobal = function() {
480 Terminal
.bindKeys(this);
481 Terminal
.bindFocus(this);
482 Terminal
.bindBlur(this);
484 // Bind clipboard functionality
485 on(this.element
, 'copy', function (ev
) {
486 copyHandler
.call(this, ev
, term
);
488 on(this.textarea
, 'paste', function (ev
) {
489 pasteHandler
.call(this, ev
, term
);
491 on(this.element
, 'paste', function (ev
) {
492 pasteHandler
.call(this, ev
, term
);
495 function rightClickHandlerWrapper (ev
) {
496 rightClickHandler
.call(this, ev
, term
);
499 if (term
.browser
.isFirefox
) {
500 on(this.element
, 'mousedown', function (ev
) {
501 if (ev
.button
== 2) {
502 rightClickHandlerWrapper(ev
);
506 on(this.element
, 'contextmenu', rightClickHandlerWrapper
);
511 * Apply key handling to the terminal
513 Terminal
.bindKeys = function(term
) {
514 on(term
.element
, 'keydown', function(ev
) {
515 if (document
.activeElement
!= this) {
521 on(term
.element
, 'keypress', function(ev
) {
522 if (document
.activeElement
!= this) {
528 on(term
.element
, 'keyup', function(ev
) {
529 if (!wasMondifierKeyOnlyEvent(ev
)) {
534 on(term
.textarea
, 'keydown', function(ev
) {
538 on(term
.textarea
, 'keypress', function(ev
) {
540 // Truncate the textarea's value, since it is not needed
544 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
545 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
546 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
547 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
552 * Insert the given row to the terminal or produce a new one
553 * if no row argument is passed. Return the inserted row.
554 * @param {HTMLElement} row (optional) The row to append to the terminal.
556 Terminal
.prototype.insertRow = function (row
) {
557 if (typeof row
!= 'object') {
558 row
= document
.createElement('div');
561 this.rowContainer
.appendChild(row
);
562 this.children
.push(row
);
568 * Opens the terminal within an element.
570 * @param {HTMLElement} parent The element to create the terminal within.
572 Terminal
.prototype.open = function(parent
) {
573 var self
=this, i
=0, div
;
575 this.parent
= parent
|| this.parent
;
578 throw new Error('Terminal requires a parent element.');
581 // Grab global elements
582 this.context
= this.parent
.ownerDocument
.defaultView
;
583 this.document
= this.parent
.ownerDocument
;
584 this.body
= this.document
.getElementsByTagName('body')[0];
586 //Create main element container
587 this.element
= this.document
.createElement('div');
588 this.element
.classList
.add('terminal');
589 this.element
.classList
.add('xterm');
590 this.element
.classList
.add('xterm-theme-' + this.theme
);
591 this.element
.classList
.toggle('xterm-cursor-blink', this.options
.cursorBlink
);
593 this.element
.style
.height
594 this.element
.setAttribute('tabindex', 0);
596 this.viewportElement
= document
.createElement('div');
597 this.viewportElement
.classList
.add('xterm-viewport');
598 this.element
.appendChild(this.viewportElement
);
599 this.viewportScrollArea
= document
.createElement('div');
600 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
601 this.viewportElement
.appendChild(this.viewportScrollArea
);
603 // Create the container that will hold the lines of the terminal and then
604 // produce the lines the lines.
605 this.rowContainer
= document
.createElement('div');
606 this.rowContainer
.classList
.add('xterm-rows');
607 this.element
.appendChild(this.rowContainer
);
610 // Create the container that will hold helpers like the textarea for
611 // capturing DOM Events. Then produce the helpers.
612 this.helperContainer
= document
.createElement('div');
613 this.helperContainer
.classList
.add('xterm-helpers');
614 // TODO: This should probably be inserted once it's filled to prevent an additional layout
615 this.element
.appendChild(this.helperContainer
);
616 this.textarea
= document
.createElement('textarea');
617 this.textarea
.classList
.add('xterm-helper-textarea');
618 this.textarea
.setAttribute('autocorrect', 'off');
619 this.textarea
.setAttribute('autocapitalize', 'off');
620 this.textarea
.setAttribute('spellcheck', 'false');
621 this.textarea
.tabIndex
= 0;
622 this.textarea
.addEventListener('focus', function() {
623 self
.emit('focus', {terminal
: self
});
625 this.textarea
.addEventListener('blur', function() {
626 self
.emit('blur', {terminal
: self
});
628 this.helperContainer
.appendChild(this.textarea
);
630 this.compositionView
= document
.createElement('div');
631 this.compositionView
.classList
.add('composition-view');
632 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
633 this.helperContainer
.appendChild(this.compositionView
);
635 this.charSizeStyleElement
= document
.createElement('style');
636 this.helperContainer
.appendChild(this.charSizeStyleElement
);
638 for (; i
< this.rows
; i
++) {
641 this.parent
.appendChild(this.element
);
643 this.charMeasure
= new CharMeasure(this.helperContainer
);
644 this.charMeasure
.on('charsizechanged', function () {
645 self
.updateCharSizeCSS();
647 this.charMeasure
.measure();
649 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
650 this.renderer
= new Renderer(this);
652 // Setup loop that draws to screen
653 this.refresh(0, this.rows
- 1);
655 // Initialize global actions that
656 // need to be taken on the document.
659 // Ensure there is a Terminal.focus.
662 on(this.element
, 'click', function() {
663 var selection
= document
.getSelection(),
664 collapsed
= selection
.isCollapsed
,
665 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
671 // Listen for mouse events and translate
672 // them into terminal mouse protocols.
676 * This event is emitted when terminal has completed opening.
685 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
686 * @param {string} addon The name of the addon to load
689 Terminal
.loadAddon = function(addon
, callback
) {
690 if (typeof exports
=== 'object' && typeof module
=== 'object') {
692 return require('./addons/' + addon
+ '/' + addon
);
693 } else if (typeof define
== 'function') {
695 return require(['./addons/' + addon
+ '/' + addon
], callback
);
697 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
703 * Updates the helper CSS class with any changes necessary after the terminal's
704 * character width has been changed.
706 Terminal
.prototype.updateCharSizeCSS = function() {
707 this.charSizeStyleElement
.textContent
= '.xterm-wide-char{width:' + (this.charMeasure
.width
* 2) + 'px;}';
712 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
713 * To better understand these
714 * the xterm code is very helpful:
716 * button.c, charproc.c, misc.c
717 * Relevant functions in xterm/button.c:
718 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
720 Terminal
.prototype.bindMouse = function() {
721 var el
= this.element
, self
= this, pressed
= 32;
723 // mouseup, mousedown, wheel
724 // left click: ^[[M 3<^[[M#3<
726 function sendButton(ev
) {
730 // get the xterm-style button
731 button
= getButton(ev
);
733 // get mouse coordinates
737 sendEvent(button
, pos
);
739 switch (ev
.overrideType
|| ev
.type
) {
744 // keep it at the left
745 // button, just in case.
756 // motion example of a left click:
757 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
758 function sendMove(ev
) {
765 // buttons marked as motions
766 // are incremented by 32
769 sendEvent(button
, pos
);
773 // position to characters
774 function encode(data
, ch
) {
775 if (!self
.utfMouse
) {
776 if (ch
=== 255) return data
.push(0);
777 if (ch
> 127) ch
= 127;
780 if (ch
=== 2047) return data
.push(0);
784 if (ch
> 2047) ch
= 2047;
785 data
.push(0xC0 | (ch
>> 6));
786 data
.push(0x80 | (ch
& 0x3F));
791 // send a mouse event:
792 // regular/utf8: ^[[M Cb Cx Cy
793 // urxvt: ^[[ Cb ; Cx ; Cy M
794 // sgr: ^[[ Cb ; Cx ; Cy M/m
795 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
796 // locator: CSI P e ; P b ; P r ; P c ; P p & w
797 function sendEvent(button
, pos
) {
798 // self.emit('mouse', {
804 if (self
.vt300Mouse
) {
806 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
810 var data
= C0
.ESC
+ '[24';
811 if (button
=== 0) data
+= '1';
812 else if (button
=== 1) data
+= '3';
813 else if (button
=== 2) data
+= '5';
814 else if (button
=== 3) return;
816 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
821 if (self
.decLocator
) {
826 if (button
=== 0) button
= 2;
827 else if (button
=== 1) button
= 4;
828 else if (button
=== 2) button
= 6;
829 else if (button
=== 3) button
= 3;
830 self
.send(C0
.ESC
+ '['
833 + (button
=== 3 ? 4 : 0)
844 if (self
.urxvtMouse
) {
849 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
856 self
.send(C0
.ESC
+ '[<'
857 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
862 + ((button
& 3) === 3 ? 'm' : 'M'));
868 encode(data
, button
);
872 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
875 function getButton(ev
) {
888 // 1, and 2 - with 64 added
889 switch (ev
.overrideType
|| ev
.type
) {
891 button
= ev
.button
!= null
897 if (self
.browser
.isMSIE
) {
898 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
904 case 'DOMMouseScroll':
905 button
= ev
.detail
< 0
910 button
= ev
.wheelDeltaY
> 0
916 // next three bits are the modifiers:
917 // 4 = shift, 8 = meta, 16 = control
918 shift
= ev
.shiftKey
? 4 : 0;
919 meta
= ev
.metaKey
? 8 : 0;
920 ctrl
= ev
.ctrlKey
? 16 : 0;
921 mod
= shift
| meta
| ctrl
;
924 if (self
.vt200Mouse
) {
927 } else if (!self
.normalMouse
) {
932 button
= (32 + (mod
<< 2)) + button
;
937 // mouse coordinates measured in cols/rows
938 function getCoords(ev
) {
941 // ignore browsers without pageX for now
942 if (ev
.pageX
== null) return;
948 // should probably check offsetParent
949 // but this is more portable
950 while (el
&& el
!== self
.document
.documentElement
) {
953 el
= 'offsetParent' in el
958 // convert to cols/rows
959 w
= self
.element
.clientWidth
;
960 h
= self
.element
.clientHeight
;
961 x
= Math
.ceil((x
/ w
) * self
.cols
);
962 y
= Math
.ceil((y
/ h
) * self
.rows
);
964 // be sure to avoid sending
965 // bad positions to the program
967 if (x
> self
.cols
) x
= self
.cols
;
969 if (y
> self
.rows
) y
= self
.rows
;
971 // xterm sends raw bytes and
972 // starts at 32 (SP) for each.
983 on(el
, 'mousedown', function(ev
) {
984 if (!self
.mouseEvents
) return;
993 //if (self.vt200Mouse && !self.normalMouse) {
994 if (self
.vt200Mouse
) {
995 ev
.overrideType
= 'mouseup';
997 return self
.cancel(ev
);
1001 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1003 // x10 compatibility mode can't send button releases
1004 if (!self
.x10Mouse
) {
1005 on(self
.document
, 'mouseup', function up(ev
) {
1007 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1008 off(self
.document
, 'mouseup', up
);
1009 return self
.cancel(ev
);
1013 return self
.cancel(ev
);
1016 //if (self.normalMouse) {
1017 // on(self.document, 'mousemove', sendMove);
1020 on(el
, 'wheel', function(ev
) {
1021 if (!self
.mouseEvents
) return;
1024 || self
.decLocator
) return;
1026 return self
.cancel(ev
);
1029 // allow wheel scrolling in
1030 // the shell for example
1031 on(el
, 'wheel', function(ev
) {
1032 if (self
.mouseEvents
) return;
1033 self
.viewport
.onWheel(ev
);
1034 return self
.cancel(ev
);
1039 * Destroys the terminal.
1041 Terminal
.prototype.destroy = function() {
1042 this.readable
= false;
1043 this.writable
= false;
1045 this.handler = function() {};
1046 this.write = function() {};
1047 if (this.element
.parentNode
) {
1048 this.element
.parentNode
.removeChild(this.element
);
1050 //this.emit('close');
1054 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1056 * @param {number} start The row to start from (between 0 and terminal's height terminal - 1)
1057 * @param {number} end The row to end at (between fromRow and terminal's height terminal - 1)
1059 Terminal
.prototype.refresh = function(start
, end
) {
1060 if (this.renderer
) {
1061 this.renderer
.queueRefresh(start
, end
);
1066 * Display the cursor element
1068 Terminal
.prototype.showCursor = function() {
1069 if (!this.cursorState
) {
1070 this.cursorState
= 1;
1071 this.refresh(this.y
, this.y
);
1076 * Scroll the terminal down 1 row, creating a blank line.
1078 Terminal
.prototype.scroll = function() {
1081 // Make room for the new row in lines
1082 if (this.lines
.length
=== this.lines
.maxLength
) {
1083 this.lines
.trimStart(1);
1085 if (this.ydisp
!== 0) {
1092 // TODO: Why is this done twice?
1093 if (!this.userScrolling
) {
1094 this.ydisp
= this.ybase
;
1098 row
= this.ybase
+ this.rows
- 1;
1100 // subtract the bottom scroll region
1101 row
-= this.rows
- 1 - this.scrollBottom
;
1103 if (row
=== this.lines
.length
) {
1104 // Optimization: pushing is faster than splicing when they amount to the same behavior
1105 this.lines
.push(this.blankLine());
1108 this.lines
.splice(row
, 0, this.blankLine());
1111 if (this.scrollTop
!== 0) {
1112 if (this.ybase
!== 0) {
1114 if (!this.userScrolling
) {
1115 this.ydisp
= this.ybase
;
1118 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1122 this.updateRange(this.scrollTop
);
1123 this.updateRange(this.scrollBottom
);
1126 * This event is emitted whenever the terminal is scrolled.
1127 * The one parameter passed is the new y display position.
1131 this.emit('scroll', this.ydisp
);
1135 * Scroll the display of the terminal
1136 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1137 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1138 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1139 * viewport originally.
1141 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1143 this.userScrolling
= true;
1144 } else if (disp
+ this.ydisp
>= this.ybase
) {
1145 this.userScrolling
= false;
1150 if (this.ydisp
> this.ybase
) {
1151 this.ydisp
= this.ybase
;
1152 } else if (this.ydisp
< 0) {
1156 if (!suppressScrollEvent
) {
1157 this.emit('scroll', this.ydisp
);
1160 this.refresh(0, this.rows
- 1);
1164 * Scroll the display of the terminal by a number of pages.
1165 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1167 Terminal
.prototype.scrollPages = function(pageCount
) {
1168 this.scrollDisp(pageCount
* (this.rows
- 1));
1172 * Scrolls the display of the terminal to the top.
1174 Terminal
.prototype.scrollToTop = function() {
1175 this.scrollDisp(-this.ydisp
);
1179 * Scrolls the display of the terminal to the bottom.
1181 Terminal
.prototype.scrollToBottom = function() {
1182 this.scrollDisp(this.ybase
- this.ydisp
);
1186 * Writes text to the terminal.
1187 * @param {string} text The text to write to the terminal.
1189 Terminal
.prototype.write = function(data
) {
1190 this.writeBuffer
.push(data
);
1192 // Send XOFF to pause the pty process if the write buffer becomes too large so
1193 // xterm.js can catch up before more data is sent. This is necessary in order
1194 // to keep signals such as ^C responsive.
1195 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1196 // XOFF - stop pty pipe
1197 // XON will be triggered by emulator before processing data chunk
1199 this.xoffSentToCatchUp
= true;
1202 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1203 // Kick off a write which will write all data in sequence recursively
1204 this.writeInProgress
= true;
1205 // Kick off an async innerWrite so more writes can come in while processing data
1207 setTimeout(function () {
1213 Terminal
.prototype.innerWrite = function() {
1214 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1215 while (writeBatch
.length
> 0) {
1216 var data
= writeBatch
.shift();
1217 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1219 // If XOFF was sent in order to catch up with the pty process, resume it if
1220 // the writeBuffer is empty to allow more data to come in.
1221 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1223 this.xoffSentToCatchUp
= false;
1226 this.refreshStart
= this.y
;
1227 this.refreshEnd
= this.y
;
1229 this.parser
.parse(data
);
1231 this.updateRange(this.y
);
1232 this.refresh(this.refreshStart
, this.refreshEnd
);
1234 if (this.writeBuffer
.length
> 0) {
1235 // Allow renderer to catch up before processing the next batch
1237 setTimeout(function () {
1241 this.writeInProgress
= false;
1246 * Writes text to the terminal, followed by a break line character (\n).
1247 * @param {string} text The text to write to the terminal.
1249 Terminal
.prototype.writeln = function(data
) {
1250 this.write(data
+ '\r\n');
1254 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1255 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1257 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1258 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1259 * the default action. The function returns whether the event should be processed by xterm.js.
1261 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1262 this.customKeydownHandler
= customKeydownHandler
;
1266 * Handle a keydown event
1268 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1269 * @param {KeyboardEvent} ev The keydown event to be handled.
1271 Terminal
.prototype.keyDown = function(ev
) {
1272 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1276 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1277 if (this.ybase
!== this.ydisp
) {
1278 this.scrollToBottom();
1284 var result
= this.evaluateKeyEscapeSequence(ev
);
1286 if (result
.key
=== C0
.DC3
) { // XOFF
1287 this.writeStopped
= true;
1288 } else if (result
.key
=== C0
.DC1
) { // XON
1289 this.writeStopped
= false;
1292 if (result
.scrollDisp
) {
1293 this.scrollDisp(result
.scrollDisp
);
1294 return this.cancel(ev
, true);
1297 if (isThirdLevelShift(this, ev
)) {
1301 if (result
.cancel
) {
1302 // The event is canceled at the end already, is this necessary?
1303 this.cancel(ev
, true);
1310 this.emit('keydown', ev
);
1311 this.emit('key', result
.key
, ev
);
1313 this.handler(result
.key
);
1315 return this.cancel(ev
, true);
1319 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1320 * returned value is the new key code to pass to the PTY.
1322 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1323 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1325 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1327 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1328 // canceled at the end of keyDown
1330 // The new key even to emit
1332 // The number of characters to scroll, if this is defined it will cancel the event
1333 scrollDisp
: undefined
1335 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1336 switch (ev
.keyCode
) {
1340 result
.key
= C0
.BS
; // ^H
1343 result
.key
= C0
.DEL
; // ^?
1348 result
.key
= C0
.ESC
+ '[Z';
1352 result
.cancel
= true;
1357 result
.cancel
= true;
1361 result
.key
= C0
.ESC
;
1362 result
.cancel
= true;
1367 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1368 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1369 // http://unix.stackexchange.com/a/108106
1370 // macOS uses different escape sequences than linux
1371 if (result
.key
== C0
.ESC
+ '[1;3D') {
1372 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1374 } else if (this.applicationCursor
) {
1375 result
.key
= C0
.ESC
+ 'OD';
1377 result
.key
= C0
.ESC
+ '[D';
1383 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1384 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1385 // http://unix.stackexchange.com/a/108106
1386 // macOS uses different escape sequences than linux
1387 if (result
.key
== C0
.ESC
+ '[1;3C') {
1388 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1390 } else if (this.applicationCursor
) {
1391 result
.key
= C0
.ESC
+ 'OC';
1393 result
.key
= C0
.ESC
+ '[C';
1399 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1400 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1401 // http://unix.stackexchange.com/a/108106
1402 if (result
.key
== C0
.ESC
+ '[1;3A') {
1403 result
.key
= C0
.ESC
+ '[1;5A';
1405 } else if (this.applicationCursor
) {
1406 result
.key
= C0
.ESC
+ 'OA';
1408 result
.key
= C0
.ESC
+ '[A';
1414 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1415 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1416 // http://unix.stackexchange.com/a/108106
1417 if (result
.key
== C0
.ESC
+ '[1;3B') {
1418 result
.key
= C0
.ESC
+ '[1;5B';
1420 } else if (this.applicationCursor
) {
1421 result
.key
= C0
.ESC
+ 'OB';
1423 result
.key
= C0
.ESC
+ '[B';
1428 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1429 // <Ctrl> or <Shift> + <Insert> are used to
1430 // copy-paste on some systems.
1431 result
.key
= C0
.ESC
+ '[2~';
1437 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1439 result
.key
= C0
.ESC
+ '[3~';
1445 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1446 else if (this.applicationCursor
)
1447 result
.key
= C0
.ESC
+ 'OH';
1449 result
.key
= C0
.ESC
+ '[H';
1454 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1455 else if (this.applicationCursor
)
1456 result
.key
= C0
.ESC
+ 'OF';
1458 result
.key
= C0
.ESC
+ '[F';
1463 result
.scrollDisp
= -(this.rows
- 1);
1465 result
.key
= C0
.ESC
+ '[5~';
1471 result
.scrollDisp
= this.rows
- 1;
1473 result
.key
= C0
.ESC
+ '[6~';
1479 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1481 result
.key
= C0
.ESC
+ 'OP';
1486 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1488 result
.key
= C0
.ESC
+ 'OQ';
1493 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1495 result
.key
= C0
.ESC
+ 'OR';
1500 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1502 result
.key
= C0
.ESC
+ 'OS';
1507 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1509 result
.key
= C0
.ESC
+ '[15~';
1514 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1516 result
.key
= C0
.ESC
+ '[17~';
1521 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1523 result
.key
= C0
.ESC
+ '[18~';
1528 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1530 result
.key
= C0
.ESC
+ '[19~';
1535 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1537 result
.key
= C0
.ESC
+ '[20~';
1542 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1544 result
.key
= C0
.ESC
+ '[21~';
1549 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1551 result
.key
= C0
.ESC
+ '[23~';
1556 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1558 result
.key
= C0
.ESC
+ '[24~';
1563 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1564 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1565 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1566 } else if (ev
.keyCode
=== 32) {
1568 result
.key
= String
.fromCharCode(0);
1569 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1570 // escape, file sep, group sep, record sep, unit sep
1571 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1572 } else if (ev
.keyCode
=== 56) {
1574 result
.key
= String
.fromCharCode(127);
1575 } else if (ev
.keyCode
=== 219) {
1576 // ^[ - Control Sequence Introducer (CSI)
1577 result
.key
= String
.fromCharCode(27);
1578 } else if (ev
.keyCode
=== 220) {
1579 // ^\ - String Terminator (ST)
1580 result
.key
= String
.fromCharCode(28);
1581 } else if (ev
.keyCode
=== 221) {
1582 // ^] - Operating System Command (OSC)
1583 result
.key
= String
.fromCharCode(29);
1585 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1586 // On Mac this is a third level shift. Use <Esc> instead.
1587 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1588 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1589 } else if (ev
.keyCode
=== 192) {
1590 result
.key
= C0
.ESC
+ '`';
1591 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1592 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1602 * Set the G level of the terminal
1605 Terminal
.prototype.setgLevel = function(g
) {
1607 this.charset
= this.charsets
[g
];
1611 * Set the charset for the given G level of the terminal
1615 Terminal
.prototype.setgCharset = function(g
, charset
) {
1616 this.charsets
[g
] = charset
;
1617 if (this.glevel
=== g
) {
1618 this.charset
= charset
;
1623 * Handle a keypress event.
1625 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1626 * @param {KeyboardEvent} ev The keypress event to be handled.
1628 Terminal
.prototype.keyPress = function(ev
) {
1635 } else if (ev
.which
== null) {
1637 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1644 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1649 key
= String
.fromCharCode(key
);
1651 this.emit('keypress', key
, ev
);
1652 this.emit('key', key
, ev
);
1660 * Send data for handling to the terminal
1661 * @param {string} data
1663 Terminal
.prototype.send = function(data
) {
1667 setTimeout(function() {
1668 self
.handler(self
.queue
);
1678 * Note: We could do sweet things with webaudio here
1680 Terminal
.prototype.bell = function() {
1681 if (!this.visualBell
) return;
1683 this.element
.style
.borderColor
= 'white';
1684 setTimeout(function() {
1685 self
.element
.style
.borderColor
= '';
1687 if (this.popOnBell
) this.focus();
1691 * Log the current state to the console.
1693 Terminal
.prototype.log = function() {
1694 if (!this.debug
) return;
1695 if (!this.context
.console
|| !this.context
.console
.log
) return;
1696 var args
= Array
.prototype.slice
.call(arguments
);
1697 this.context
.console
.log
.apply(this.context
.console
, args
);
1701 * Log the current state as error to the console.
1703 Terminal
.prototype.error = function() {
1704 if (!this.debug
) return;
1705 if (!this.context
.console
|| !this.context
.console
.error
) return;
1706 var args
= Array
.prototype.slice
.call(arguments
);
1707 this.context
.console
.error
.apply(this.context
.console
, args
);
1711 * Resizes the terminal.
1713 * @param {number} x The number of columns to resize to.
1714 * @param {number} y The number of rows to resize to.
1716 Terminal
.prototype.resize = function(x
, y
) {
1724 if (x
=== this.cols
&& y
=== this.rows
) {
1734 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1735 i
= this.lines
.length
;
1737 while (this.lines
.get(i
).length
< x
) {
1738 this.lines
.get(i
).push(ch
);
1742 i
= this.lines
.length
;
1744 while (this.lines
.get(i
).length
> x
) {
1745 this.lines
.get(i
).pop();
1750 this.setupStops(this.cols
);
1758 // y is rows, not this.y
1759 if (this.lines
.length
< y
+ this.ybase
) {
1760 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
1761 // There is room above the buffer and there are no empty elements below the line,
1765 if (this.ydisp
> 0) {
1766 // Viewport is at the top of the buffer, must increase downwards
1770 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1771 // are blank lines after the cursor
1772 this.lines
.push(this.blankLine());
1775 if (this.children
.length
< y
) {
1781 if (this.lines
.length
> y
+ this.ybase
) {
1782 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
1783 // The line is a blank line below the cursor, remove it
1786 // The line is the cursor, scroll down
1791 if (this.children
.length
> y
) {
1792 el
= this.children
.shift();
1794 el
.parentNode
.removeChild(el
);
1800 // Make sure that the cursor stays on screen
1813 this.scrollBottom
= y
- 1;
1815 this.charMeasure
.measure();
1817 this.refresh(0, this.rows
- 1);
1821 this.geometry
= [this.cols
, this.rows
];
1822 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
1826 * Updates the range of rows to refresh
1827 * @param {number} y The number of rows to refresh next.
1829 Terminal
.prototype.updateRange = function(y
) {
1830 if (y
< this.refreshStart
) this.refreshStart
= y
;
1831 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
1832 // if (y > this.refreshEnd) {
1833 // this.refreshEnd = y;
1834 // if (y > this.rows - 1) {
1835 // this.refreshEnd = this.rows - 1;
1841 * Set the range of refreshing to the maximum value
1843 Terminal
.prototype.maxRange = function() {
1844 this.refreshStart
= 0;
1845 this.refreshEnd
= this.rows
- 1;
1851 * Setup the tab stops.
1854 Terminal
.prototype.setupStops = function(i
) {
1856 if (!this.tabs
[i
]) {
1857 i
= this.prevStop(i
);
1864 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
1865 this.tabs
[i
] = true;
1871 * Move the cursor to the previous tab stop from the given position (default is current).
1872 * @param {number} x The position to move the cursor to the previous tab stop.
1874 Terminal
.prototype.prevStop = function(x
) {
1875 if (x
== null) x
= this.x
;
1876 while (!this.tabs
[--x
] && x
> 0);
1877 return x
>= this.cols
1884 * Move the cursor one tab stop forward from the given position (default is current).
1885 * @param {number} x The position to move the cursor one tab stop forward.
1887 Terminal
.prototype.nextStop = function(x
) {
1888 if (x
== null) x
= this.x
;
1889 while (!this.tabs
[++x
] && x
< this.cols
);
1890 return x
>= this.cols
1897 * Erase in the identified line everything from "x" to the end of the line (right).
1898 * @param {number} x The column from which to start erasing to the end of the line.
1899 * @param {number} y The line in which to operate.
1901 Terminal
.prototype.eraseRight = function(x
, y
) {
1902 var line
= this.lines
.get(this.ybase
+ y
);
1906 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
1907 for (; x
< this.cols
; x
++) {
1910 this.updateRange(y
);
1916 * Erase in the identified line everything from "x" to the start of the line (left).
1917 * @param {number} x The column from which to start erasing to the start of the line.
1918 * @param {number} y The line in which to operate.
1920 Terminal
.prototype.eraseLeft = function(x
, y
) {
1921 var line
= this.lines
.get(this.ybase
+ y
);
1925 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
1930 this.updateRange(y
);
1934 * Clears the entire buffer, making the prompt line the new first line.
1936 Terminal
.prototype.clear = function() {
1937 if (this.ybase
=== 0 && this.y
=== 0) {
1938 // Don't clear if it's already clear
1941 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
1942 this.lines
.length
= 1;
1946 for (var i
= 1; i
< this.rows
; i
++) {
1947 this.lines
.push(this.blankLine());
1949 this.refresh(0, this.rows
- 1);
1950 this.emit('scroll', this.ydisp
);
1954 * Erase all content in the given line
1955 * @param {number} y The line to erase all of its contents.
1957 Terminal
.prototype.eraseLine = function(y
) {
1958 this.eraseRight(0, y
);
1963 * Return the data array of a blank line
1964 * @param {number} cur First bunch of data for each "blank" character.
1966 Terminal
.prototype.blankLine = function(cur
) {
1971 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
1975 for (; i
< this.cols
; i
++) {
1984 * If cur return the back color xterm feature attribute. Else return defAttr.
1985 * @param {object} cur
1987 Terminal
.prototype.ch = function(cur
) {
1989 ? [this.eraseAttr(), ' ', 1]
1990 : [this.defAttr
, ' ', 1];
1995 * Evaluate if the current erminal is the given argument.
1996 * @param {object} term The terminal to evaluate
1998 Terminal
.prototype.is = function(term
) {
1999 var name
= this.termName
;
2000 return (name
+ '').indexOf(term
) === 0;
2005 * Emit the 'data' event and populate the given data.
2006 * @param {string} data The data to populate in the event.
2008 Terminal
.prototype.handler = function(data
) {
2009 // Prevents all events to pty process if stdin is disabled
2010 if (this.options
.disableStdin
) {
2014 // Input is being sent to the terminal, the terminal should focus the prompt.
2015 if (this.ybase
!== this.ydisp
) {
2016 this.scrollToBottom();
2018 this.emit('data', data
);
2023 * Emit the 'title' event and populate the given title.
2024 * @param {string} title The title to populate in the event.
2026 Terminal
.prototype.handleTitle = function(title
) {
2028 * This event is emitted when the title of the terminal is changed
2029 * from inside the terminal. The parameter is the new title.
2033 this.emit('title', title
);
2042 * ESC D Index (IND is 0x84).
2044 Terminal
.prototype.index = function() {
2046 if (this.y
> this.scrollBottom
) {
2050 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2051 if (this.x
>= this.cols
) {
2058 * ESC M Reverse Index (RI is 0x8d).
2060 * Move the cursor up one row, inserting a new blank line if necessary.
2062 Terminal
.prototype.reverseIndex = function() {
2064 if (this.y
=== this.scrollTop
) {
2065 // possibly move the code below to term.reverseScroll();
2066 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2067 // blankLine(true) is xterm/linux behavior
2068 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2069 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2070 this.updateRange(this.scrollTop
);
2071 this.updateRange(this.scrollBottom
);
2079 * ESC c Full Reset (RIS).
2081 Terminal
.prototype.reset = function() {
2082 this.options
.rows
= this.rows
;
2083 this.options
.cols
= this.cols
;
2084 var customKeydownHandler
= this.customKeydownHandler
;
2085 Terminal
.call(this, this.options
);
2086 this.customKeydownHandler
= customKeydownHandler
;
2087 this.refresh(0, this.rows
- 1);
2088 this.viewport
.syncScrollArea();
2093 * ESC H Tab Set (HTS is 0x88).
2095 Terminal
.prototype.tabSet = function() {
2096 this.tabs
[this.x
] = true;
2103 function on(el
, type
, handler
, capture
) {
2104 if (!Array
.isArray(el
)) {
2107 el
.forEach(function (element
) {
2108 element
.addEventListener(type
, handler
, capture
|| false);
2112 function off(el
, type
, handler
, capture
) {
2113 el
.removeEventListener(type
, handler
, capture
|| false);
2116 function cancel(ev
, force
) {
2117 if (!this.cancelEvents
&& !force
) {
2120 ev
.preventDefault();
2121 ev
.stopPropagation();
2125 function inherits(child
, parent
) {
2127 this.constructor = child
;
2129 f
.prototype = parent
.prototype;
2130 child
.prototype = new f
;
2133 function indexOf(obj
, el
) {
2136 if (obj
[i
] === el
) return i
;
2141 function isThirdLevelShift(term
, ev
) {
2143 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2144 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2146 if (ev
.type
== 'keypress') {
2147 return thirdLevelKey
;
2150 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2151 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2154 // Expose to InputHandler (temporary)
2155 Terminal
.prototype.matchColor
= matchColor
;
2157 function matchColor(r1
, g1
, b1
) {
2158 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2160 if (matchColor
._cache
[hash
] != null) {
2161 return matchColor
._cache
[hash
];
2164 var ldiff
= Infinity
2173 for (; i
< Terminal
.vcolors
.length
; i
++) {
2174 c
= Terminal
.vcolors
[i
];
2179 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2192 return matchColor
._cache
[hash
] = li
;
2195 matchColor
._cache
= {};
2197 // http://stackoverflow.com/questions/1633828
2198 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2199 return Math
.pow(30 * (r1
- r2
), 2)
2200 + Math
.pow(59 * (g1
- g2
), 2)
2201 + Math
.pow(11 * (b1
- b2
), 2);
2204 function each(obj
, iter
, con
) {
2205 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2206 for (var i
= 0; i
< obj
.length
; i
++) {
2207 iter
.call(con
, obj
[i
], i
, obj
);
2211 function wasMondifierKeyOnlyEvent(ev
) {
2212 return ev
.keyCode
=== 16 || // Shift
2213 ev
.keyCode
=== 17 || // Ctrl
2214 ev
.keyCode
=== 18; // Alt
2217 function keys(obj
) {
2218 if (Object
.keys
) return Object
.keys(obj
);
2221 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2232 Terminal
.EventEmitter
= EventEmitter
;
2233 Terminal
.inherits
= inherits
;
2236 * Adds an event listener to the terminal.
2238 * @param {string} event The name of the event. TODO: Document all event types
2239 * @param {function} callback The function to call when the event is triggered.
2243 Terminal
.cancel
= cancel
;
2245 module
.exports
= Terminal
;