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 { Linkifier
} from './Linkifier';
23 import { SelectionManager
} from './SelectionManager';
24 import { CharMeasure
} from './utils/CharMeasure';
25 import * as Browser
from './utils/Browser';
26 import * as Mouse
from './utils/Mouse';
27 import { CHARSETS
} from './Charsets';
30 * Terminal Emulation References:
32 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
33 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
34 * http://invisible-island.net/vttest/
35 * http://www.inwap.com/pdp10/ansicode.txt
36 * http://linux.die.net/man/4/console_codes
37 * http://linux.die.net/man/7/urxvt
40 // Let it work inside Node.js for automated testing purposes.
41 var document
= (typeof window
!= 'undefined') ? window
.document
: null;
44 * The amount of write requests to queue before sending an XOFF signal to the
45 * pty process. This number must be small in order for ^C and similar sequences
48 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
51 * The number of writes to perform in a single batch before allowing the
52 * renderer to catch up with a 0ms setTimeout.
54 var WRITE_BATCH_SIZE
= 300;
57 * The time between cursor blinks. This is driven by JS rather than a CSS
58 * animation due to a bug in Chromium that causes it to use excessive CPU time.
59 * See https://github.com/Microsoft/vscode/issues/22900
61 var CURSOR_BLINK_INTERVAL
= 600;
68 * Creates a new `Terminal` object.
70 * @param {object} options An object containing a set of options, the available options are:
71 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
72 * - `cols` (number): The number of columns of the terminal (horizontal size)
73 * - `rows` (number): The number of rows of the terminal (vertical size)
77 * @alias module:xterm/src/xterm
79 function Terminal(options
) {
82 if (!(this instanceof Terminal
)) {
83 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
86 self
.browser
= Browser
;
87 self
.cancel
= Terminal
.cancel
;
89 EventEmitter
.call(this);
91 if (typeof options
=== 'number') {
99 options
= options
|| {};
102 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
103 if (options
[key
] == null) {
104 options
[key
] = Terminal
.options
[key
];
106 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
107 options
[key
] = Terminal
[key
];
110 self
[key
] = options
[key
];
113 if (options
.colors
.length
=== 8) {
114 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
115 } else if (options
.colors
.length
=== 16) {
116 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
117 } else if (options
.colors
.length
=== 10) {
118 options
.colors
= options
.colors
.slice(0, -2).concat(
119 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
120 } else if (options
.colors
.length
=== 18) {
121 options
.colors
= options
.colors
.concat(
122 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
124 this.colors
= options
.colors
;
126 this.options
= options
;
128 // this.context = options.context || window;
129 // this.document = options.document || document;
130 this.parent
= options
.body
|| options
.parent
|| (
131 document
? document
.getElementsByTagName('body')[0] : null
134 this.cols
= options
.cols
|| options
.geometry
[0];
135 this.rows
= options
.rows
|| options
.geometry
[1];
136 this.geometry
= [this.cols
, this.rows
];
138 if (options
.handler
) {
139 this.on('data', options
.handler
);
143 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
149 * The scroll position of the viewport
154 * The cursor's x position after ybase
159 * The cursor's y position after ybase
163 this.cursorState
= 0;
164 this.cursorHidden
= false;
168 this.scrollBottom
= this.rows
- 1;
169 this.customKeydownHandler
= null;
170 this.cursorBlinkInterval
= null;
173 this.applicationKeypad
= false;
174 this.applicationCursor
= false;
175 this.originMode
= false;
176 this.insertMode
= false;
177 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
182 this.gcharset
= null;
184 this.charsets
= [null];
208 this.readable
= true;
209 this.writable
= true;
211 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
212 this.curAttr
= this.defAttr
;
215 this.currentParam
= 0;
219 this.inputHandler
= new InputHandler(this);
220 this.parser
= new Parser(this.inputHandler
, this);
221 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
222 this.renderer
= this.renderer
|| null;
223 this.selectionManager
= this.selectionManager
|| null;
224 this.linkifier
= this.linkifier
|| new Linkifier();
227 this.writeBuffer
= [];
228 this.writeInProgress
= false;
231 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
232 * This is a distinct state from writeStopped so that if the user requested
233 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
236 this.xoffSentToCatchUp
= false;
238 /** Whether writing has been stopped as a result of XOFF */
239 this.writeStopped
= false;
241 // leftover surrogate high from previous write invocation
242 this.surrogate_high
= '';
245 * An array of all lines in the entire buffer, including the prompt. The lines are array of
246 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
248 this.lines
= new CircularList(this.scrollback
);
251 this.lines
.push(this.blankLine());
257 // Store if user went browsing history in scrollback
258 this.userScrolling
= false;
261 inherits(Terminal
, EventEmitter
);
264 * back_color_erase feature for xterm.
266 Terminal
.prototype.eraseAttr = function() {
267 // if (this.is('screen')) return this.defAttr;
268 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
276 Terminal
.tangoColors
= [
297 // Colors 0-15 + 16-255
298 // Much thanks to TooTallNate for writing this.
299 Terminal
.colors
= (function() {
300 var colors
= Terminal
.tangoColors
.slice()
301 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
306 for (; i
< 216; i
++) {
307 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
312 for (; i
< 24; i
++) {
317 function out(r
, g
, b
) {
318 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
323 return c
.length
< 2 ? '0' + c
: c
;
329 Terminal
._colors
= Terminal
.colors
.slice();
331 Terminal
.vcolors
= (function() {
333 , colors
= Terminal
.colors
337 for (; i
< 256; i
++) {
338 color
= parseInt(colors
[i
].substring(1), 16);
340 (color
>> 16) & 0xff,
353 Terminal
.defaults
= {
354 colors
: Terminal
.colors
,
360 cursorStyle
: 'block',
368 useFlowControl
: false,
370 // programFeatures: false,
374 Terminal
.options
= {};
376 Terminal
.focus
= null;
378 each(keys(Terminal
.defaults
), function(key
) {
379 Terminal
[key
] = Terminal
.defaults
[key
];
380 Terminal
.options
[key
] = Terminal
.defaults
[key
];
384 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
386 Terminal
.prototype.focus = function() {
387 return this.textarea
.focus();
391 * Retrieves an option's value from the terminal.
392 * @param {string} key The option key.
394 Terminal
.prototype.getOption = function(key
, value
) {
395 if (!(key
in Terminal
.defaults
)) {
396 throw new Error('No option with key "' + key
+ '"');
399 if (typeof this.options
[key
] !== 'undefined') {
400 return this.options
[key
];
407 * Sets an option on the terminal.
408 * @param {string} key The option key.
409 * @param {string} value The option value.
411 Terminal
.prototype.setOption = function(key
, value
) {
412 if (!(key
in Terminal
.defaults
)) {
413 throw new Error('No option with key "' + key
+ '"');
417 if (this.options
[key
] !== value
) {
418 if (this.lines
.length
> value
) {
419 const amountToTrim
= this.lines
.length
- value
;
420 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
421 this.lines
.trimStart(amountToTrim
);
422 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
423 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
425 this.refresh(0, this.rows
- 1);
428 this.lines
.maxLength
= value
;
429 this.viewport
.syncScrollArea();
434 this.options
[key
] = value
;
436 case 'cursorBlink': this.setCursorBlinking(value
); break;
438 // Style 'block' applies with no class
439 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
440 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
442 case 'tabStopWidth': this.setupStops(); break;
446 Terminal
.prototype.restartCursorBlinking = function () {
447 this.setCursorBlinking(this.options
.cursorBlink
);
450 Terminal
.prototype.setCursorBlinking = function (enabled
) {
451 this.element
.classList
.toggle('xterm-cursor-blink', enabled
);
452 this.clearCursorBlinkingInterval();
455 this.cursorBlinkInterval
= setInterval(function () {
456 self
.element
.classList
.toggle('xterm-cursor-blink-on');
457 }, CURSOR_BLINK_INTERVAL
);
461 Terminal
.prototype.clearCursorBlinkingInterval = function () {
462 this.element
.classList
.remove('xterm-cursor-blink-on');
463 if (this.cursorBlinkInterval
) {
464 clearInterval(this.cursorBlinkInterval
);
465 this.cursorBlinkInterval
= null;
470 * Binds the desired focus behavior on a given terminal object.
474 Terminal
.bindFocus = function (term
) {
475 on(term
.textarea
, 'focus', function (ev
) {
476 if (term
.sendFocus
) {
477 term
.send(C0
.ESC
+ '[I');
479 term
.element
.classList
.add('focus');
481 term
.restartCursorBlinking
.apply(term
);
482 Terminal
.focus
= term
;
483 term
.emit('focus', {terminal
: term
});
488 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
490 Terminal
.prototype.blur = function() {
491 return this.textarea
.blur();
495 * Binds the desired blur behavior on a given terminal object.
499 Terminal
.bindBlur = function (term
) {
500 on(term
.textarea
, 'blur', function (ev
) {
501 term
.refresh(term
.y
, term
.y
);
502 if (term
.sendFocus
) {
503 term
.send(C0
.ESC
+ '[O');
505 term
.element
.classList
.remove('focus');
506 term
.clearCursorBlinkingInterval
.apply(term
);
507 Terminal
.focus
= null;
508 term
.emit('blur', {terminal
: term
});
513 * Initialize default behavior
515 Terminal
.prototype.initGlobal = function() {
518 Terminal
.bindKeys(this);
519 Terminal
.bindFocus(this);
520 Terminal
.bindBlur(this);
522 // Bind clipboard functionality
523 on(this.element
, 'copy', function (ev
) {
524 copyHandler
.call(this, ev
, term
, term
.selectionManager
);
526 on(this.textarea
, 'paste', function (ev
) {
527 pasteHandler
.call(this, ev
, term
);
529 on(this.element
, 'paste', function (ev
) {
530 pasteHandler
.call(this, ev
, term
);
533 function rightClickHandlerWrapper (ev
) {
534 rightClickHandler
.call(this, ev
, term
);
537 if (term
.browser
.isFirefox
) {
538 on(this.element
, 'mousedown', function (ev
) {
539 if (ev
.button
== 2) {
540 rightClickHandlerWrapper(ev
);
544 on(this.element
, 'contextmenu', rightClickHandlerWrapper
);
549 * Apply key handling to the terminal
551 Terminal
.bindKeys = function(term
) {
552 on(term
.element
, 'keydown', function(ev
) {
553 if (document
.activeElement
!= this) {
559 on(term
.element
, 'keypress', function(ev
) {
560 if (document
.activeElement
!= this) {
566 on(term
.element
, 'keyup', function(ev
) {
567 if (!wasMondifierKeyOnlyEvent(ev
)) {
572 on(term
.textarea
, 'keydown', function(ev
) {
576 on(term
.textarea
, 'keypress', function(ev
) {
578 // Truncate the textarea's value, since it is not needed
582 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
583 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
584 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
585 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
586 term
.on('refresh', function (data
) {
587 term
.queueLinkification(data
.start
, data
.end
)
593 * Insert the given row to the terminal or produce a new one
594 * if no row argument is passed. Return the inserted row.
595 * @param {HTMLElement} row (optional) The row to append to the terminal.
597 Terminal
.prototype.insertRow = function (row
) {
598 if (typeof row
!= 'object') {
599 row
= document
.createElement('div');
602 this.rowContainer
.appendChild(row
);
603 this.children
.push(row
);
609 * Opens the terminal within an element.
611 * @param {HTMLElement} parent The element to create the terminal within.
612 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
614 Terminal
.prototype.open = function(parent
, focus
) {
615 var self
=this, i
=0, div
;
617 this.parent
= parent
|| this.parent
;
620 throw new Error('Terminal requires a parent element.');
623 // Grab global elements
624 this.context
= this.parent
.ownerDocument
.defaultView
;
625 this.document
= this.parent
.ownerDocument
;
626 this.body
= this.document
.getElementsByTagName('body')[0];
628 //Create main element container
629 this.element
= this.document
.createElement('div');
630 this.element
.classList
.add('terminal');
631 this.element
.classList
.add('xterm');
632 this.element
.classList
.add('xterm-theme-' + this.theme
);
633 this.setCursorBlinking(this.options
.cursorBlink
);
635 this.element
.style
.height
;
636 this.element
.setAttribute('tabindex', 0);
638 this.viewportElement
= document
.createElement('div');
639 this.viewportElement
.classList
.add('xterm-viewport');
640 this.element
.appendChild(this.viewportElement
);
641 this.viewportScrollArea
= document
.createElement('div');
642 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
643 this.viewportElement
.appendChild(this.viewportScrollArea
);
645 // Create the selection container. This needs to be added before the
646 // rowContainer as the selection must be below the text.
647 this.selectionContainer
= document
.createElement('div');
648 this.selectionContainer
.classList
.add('xterm-selection');
649 this.element
.appendChild(this.selectionContainer
);
651 // Create the container that will hold the lines of the terminal and then
652 // produce the lines the lines.
653 this.rowContainer
= document
.createElement('div');
654 this.rowContainer
.classList
.add('xterm-rows');
655 this.element
.appendChild(this.rowContainer
);
657 this.linkifier
.attachToDom(document
, this.children
);
659 // Create the container that will hold helpers like the textarea for
660 // capturing DOM Events. Then produce the helpers.
661 this.helperContainer
= document
.createElement('div');
662 this.helperContainer
.classList
.add('xterm-helpers');
663 // TODO: This should probably be inserted once it's filled to prevent an additional layout
664 this.element
.appendChild(this.helperContainer
);
665 this.textarea
= document
.createElement('textarea');
666 this.textarea
.classList
.add('xterm-helper-textarea');
667 this.textarea
.setAttribute('autocorrect', 'off');
668 this.textarea
.setAttribute('autocapitalize', 'off');
669 this.textarea
.setAttribute('spellcheck', 'false');
670 this.textarea
.tabIndex
= 0;
671 this.textarea
.addEventListener('focus', function() {
672 self
.emit('focus', {terminal
: self
});
674 this.textarea
.addEventListener('blur', function() {
675 self
.emit('blur', {terminal
: self
});
677 this.helperContainer
.appendChild(this.textarea
);
679 this.compositionView
= document
.createElement('div');
680 this.compositionView
.classList
.add('composition-view');
681 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
682 this.helperContainer
.appendChild(this.compositionView
);
684 this.charSizeStyleElement
= document
.createElement('style');
685 this.helperContainer
.appendChild(this.charSizeStyleElement
);
687 for (; i
< this.rows
; i
++) {
690 this.parent
.appendChild(this.element
);
692 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
693 this.charMeasure
.on('charsizechanged', function () {
694 self
.updateCharSizeCSS();
696 this.charMeasure
.measure();
698 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
699 this.renderer
= new Renderer(this);
700 this.selectionManager
= new SelectionManager(this, this.lines
, this.rowContainer
, this.selectionContainer
, this.charMeasure
);
701 this.selectionManager
.on('refresh', data
=> this.renderer
.refreshSelection(data
.start
, data
.end
));
702 this.on('scroll', () => this.selectionManager
.refresh());
703 this.viewportElement
.addEventListener('scroll', () => this.selectionManager
.refresh());
705 // Setup loop that draws to screen
706 this.refresh(0, this.rows
- 1);
708 // Initialize global actions that
709 // need to be taken on the document.
713 * Automatic focus functionality.
714 * TODO: Default to `false` starting with xterm.js 3.0.
716 if (typeof focus
== 'undefined') {
717 let message
= 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
719 message
+= 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
720 message
+= 'it will default to `false`.';
722 console
.warn(message
);
730 on(this.element
, 'click', function() {
731 var selection
= document
.getSelection(),
732 collapsed
= selection
.isCollapsed
,
733 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
739 // Listen for mouse events and translate
740 // them into terminal mouse protocols.
744 * This event is emitted when terminal has completed opening.
753 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
754 * @param {string} addon The name of the addon to load
757 Terminal
.loadAddon = function(addon
, callback
) {
758 if (typeof exports
=== 'object' && typeof module
=== 'object') {
760 return require('./addons/' + addon
+ '/' + addon
);
761 } else if (typeof define
== 'function') {
763 return require(['./addons/' + addon
+ '/' + addon
], callback
);
765 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
771 * Updates the helper CSS class with any changes necessary after the terminal's
772 * character width has been changed.
774 Terminal
.prototype.updateCharSizeCSS = function() {
775 this.charSizeStyleElement
.textContent
=
776 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
777 `.xterm-normal-char{width:${this.charMeasure.width}px;}`
782 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
783 * To better understand these
784 * the xterm code is very helpful:
786 * button.c, charproc.c, misc.c
787 * Relevant functions in xterm/button.c:
788 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
790 Terminal
.prototype.bindMouse = function() {
791 var el
= this.element
, self
= this, pressed
= 32;
793 // mouseup, mousedown, wheel
794 // left click: ^[[M 3<^[[M#3<
796 function sendButton(ev
) {
800 // get the xterm-style button
801 button
= getButton(ev
);
803 // get mouse coordinates
804 pos
= Mouse
.getCoords(ev
, self
.rowContainer
, self
.charMeasure
);
807 // Temp fix until getcoords PR is pushed
810 if (pos
.x
< 0) pos
.x
= 0;
811 if (pos
.x
> self
.cols
) pos
.x
= self
.cols
;
812 if (pos
.y
< 0) pos
.y
= 0;
813 if (pos
.y
> self
.rows
) pos
.y
= self
.rows
;
817 sendEvent(button
, pos
);
819 switch (ev
.overrideType
|| ev
.type
) {
824 // keep it at the left
825 // button, just in case.
836 // motion example of a left click:
837 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
838 function sendMove(ev
) {
842 pos
= Mouse
.getCoords(ev
, self
.rowContainer
, self
.charMeasure
);
845 // Temp fix until getcoords PR is pushed
848 if (pos
.x
< 0) pos
.x
= 0;
849 if (pos
.x
> self
.cols
) pos
.x
= self
.cols
;
850 if (pos
.y
< 0) pos
.y
= 0;
851 if (pos
.y
> self
.rows
) pos
.y
= self
.rows
;
855 // buttons marked as motions
856 // are incremented by 32
859 sendEvent(button
, pos
);
863 // position to characters
864 function encode(data
, ch
) {
865 if (!self
.utfMouse
) {
866 if (ch
=== 255) return data
.push(0);
867 if (ch
> 127) ch
= 127;
870 if (ch
=== 2047) return data
.push(0);
874 if (ch
> 2047) ch
= 2047;
875 data
.push(0xC0 | (ch
>> 6));
876 data
.push(0x80 | (ch
& 0x3F));
881 // send a mouse event:
882 // regular/utf8: ^[[M Cb Cx Cy
883 // urxvt: ^[[ Cb ; Cx ; Cy M
884 // sgr: ^[[ Cb ; Cx ; Cy M/m
885 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
886 // locator: CSI P e ; P b ; P r ; P c ; P p & w
887 function sendEvent(button
, pos
) {
888 // self.emit('mouse', {
894 if (self
.vt300Mouse
) {
896 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
900 var data
= C0
.ESC
+ '[24';
901 if (button
=== 0) data
+= '1';
902 else if (button
=== 1) data
+= '3';
903 else if (button
=== 2) data
+= '5';
904 else if (button
=== 3) return;
906 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
911 if (self
.decLocator
) {
916 if (button
=== 0) button
= 2;
917 else if (button
=== 1) button
= 4;
918 else if (button
=== 2) button
= 6;
919 else if (button
=== 3) button
= 3;
920 self
.send(C0
.ESC
+ '['
923 + (button
=== 3 ? 4 : 0)
934 if (self
.urxvtMouse
) {
939 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
946 self
.send(C0
.ESC
+ '[<'
947 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
952 + ((button
& 3) === 3 ? 'm' : 'M'));
958 encode(data
, button
);
962 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
965 function getButton(ev
) {
978 // 1, and 2 - with 64 added
979 switch (ev
.overrideType
|| ev
.type
) {
981 button
= ev
.button
!= null
987 if (self
.browser
.isMSIE
) {
988 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
994 case 'DOMMouseScroll':
995 button
= ev
.detail
< 0
1000 button
= ev
.wheelDeltaY
> 0
1006 // next three bits are the modifiers:
1007 // 4 = shift, 8 = meta, 16 = control
1008 shift
= ev
.shiftKey
? 4 : 0;
1009 meta
= ev
.metaKey
? 8 : 0;
1010 ctrl
= ev
.ctrlKey
? 16 : 0;
1011 mod
= shift
| meta
| ctrl
;
1014 if (self
.vt200Mouse
) {
1017 } else if (!self
.normalMouse
) {
1022 button
= (32 + (mod
<< 2)) + button
;
1027 // mouse coordinates measured in cols/rows
1028 // function getCoords(ev) {
1029 // var x, y, w, h, el;
1031 // // ignore browsers without pageX for now
1032 // if (ev.pageX == null) return;
1036 // el = self.rowContainer;
1038 // // should probably check offsetParent
1039 // // but this is more portable
1040 // while (el && el !== self.document.documentElement) {
1041 // x -= el.offsetLeft;
1042 // y -= el.offsetTop;
1043 // el = 'offsetParent' in el
1044 // ? el.offsetParent
1048 // // convert to cols/rows
1049 // x = Math.ceil(x / self.charMeasure.width);
1050 // y = Math.ceil(y / self.charMeasure.height);
1052 // // be sure to avoid sending
1053 // // bad positions to the program
1054 // if (x < 0) x = 0;
1055 // if (x > self.cols) x = self.cols;
1056 // if (y < 0) y = 0;
1057 // if (y > self.rows) y = self.rows;
1059 // // xterm sends raw bytes and
1060 // // starts at 32 (SP) for each.
1071 on(el
, 'mousedown', function(ev
) {
1072 if (!self
.mouseEvents
) return;
1081 //if (self.vt200Mouse && !self.normalMouse) {
1082 if (self
.vt200Mouse
) {
1083 ev
.overrideType
= 'mouseup';
1085 return self
.cancel(ev
);
1089 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1091 // x10 compatibility mode can't send button releases
1092 if (!self
.x10Mouse
) {
1093 on(self
.document
, 'mouseup', function up(ev
) {
1095 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1096 off(self
.document
, 'mouseup', up
);
1097 return self
.cancel(ev
);
1101 return self
.cancel(ev
);
1104 //if (self.normalMouse) {
1105 // on(self.document, 'mousemove', sendMove);
1108 on(el
, 'wheel', function(ev
) {
1109 if (!self
.mouseEvents
) return;
1112 || self
.decLocator
) return;
1114 return self
.cancel(ev
);
1117 // allow wheel scrolling in
1118 // the shell for example
1119 on(el
, 'wheel', function(ev
) {
1120 if (self
.mouseEvents
) return;
1121 self
.viewport
.onWheel(ev
);
1122 return self
.cancel(ev
);
1127 * Destroys the terminal.
1129 Terminal
.prototype.destroy = function() {
1130 this.readable
= false;
1131 this.writable
= false;
1133 this.handler = function() {};
1134 this.write = function() {};
1135 if (this.element
&& this.element
.parentNode
) {
1136 this.element
.parentNode
.removeChild(this.element
);
1138 //this.emit('close');
1142 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1144 * @param {number} start The row to start from (between 0 and this.rows - 1).
1145 * @param {number} end The row to end at (between start and this.rows - 1).
1147 Terminal
.prototype.refresh = function(start
, end
) {
1148 if (this.renderer
) {
1149 this.renderer
.queueRefresh(start
, end
);
1154 * Queues linkification for the specified rows.
1155 * @param {number} start The row to start from (between 0 and this.rows - 1).
1156 * @param {number} end The row to end at (between start and this.rows - 1).
1158 Terminal
.prototype.queueLinkification = function(start
, end
) {
1159 if (this.linkifier
) {
1160 for (let i
= start
; i
<= end
; i
++) {
1161 this.linkifier
.linkifyRow(i
);
1167 * Display the cursor element
1169 Terminal
.prototype.showCursor = function() {
1170 if (!this.cursorState
) {
1171 this.cursorState
= 1;
1172 this.refresh(this.y
, this.y
);
1177 * Scroll the terminal down 1 row, creating a blank line.
1179 Terminal
.prototype.scroll = function() {
1182 // Make room for the new row in lines
1183 if (this.lines
.length
=== this.lines
.maxLength
) {
1184 this.lines
.trimStart(1);
1186 if (this.ydisp
!== 0) {
1193 // TODO: Why is this done twice?
1194 if (!this.userScrolling
) {
1195 this.ydisp
= this.ybase
;
1199 row
= this.ybase
+ this.rows
- 1;
1201 // subtract the bottom scroll region
1202 row
-= this.rows
- 1 - this.scrollBottom
;
1204 if (row
=== this.lines
.length
) {
1205 // Optimization: pushing is faster than splicing when they amount to the same behavior
1206 this.lines
.push(this.blankLine());
1209 this.lines
.splice(row
, 0, this.blankLine());
1212 if (this.scrollTop
!== 0) {
1213 if (this.ybase
!== 0) {
1215 if (!this.userScrolling
) {
1216 this.ydisp
= this.ybase
;
1219 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1223 this.updateRange(this.scrollTop
);
1224 this.updateRange(this.scrollBottom
);
1227 * This event is emitted whenever the terminal is scrolled.
1228 * The one parameter passed is the new y display position.
1232 this.emit('scroll', this.ydisp
);
1236 * Scroll the display of the terminal
1237 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1238 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1239 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1240 * viewport originally.
1242 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1244 this.userScrolling
= true;
1245 } else if (disp
+ this.ydisp
>= this.ybase
) {
1246 this.userScrolling
= false;
1251 if (this.ydisp
> this.ybase
) {
1252 this.ydisp
= this.ybase
;
1253 } else if (this.ydisp
< 0) {
1257 if (!suppressScrollEvent
) {
1258 this.emit('scroll', this.ydisp
);
1261 this.refresh(0, this.rows
- 1);
1265 * Scroll the display of the terminal by a number of pages.
1266 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1268 Terminal
.prototype.scrollPages = function(pageCount
) {
1269 this.scrollDisp(pageCount
* (this.rows
- 1));
1273 * Scrolls the display of the terminal to the top.
1275 Terminal
.prototype.scrollToTop = function() {
1276 this.scrollDisp(-this.ydisp
);
1280 * Scrolls the display of the terminal to the bottom.
1282 Terminal
.prototype.scrollToBottom = function() {
1283 this.scrollDisp(this.ybase
- this.ydisp
);
1287 * Writes text to the terminal.
1288 * @param {string} text The text to write to the terminal.
1290 Terminal
.prototype.write = function(data
) {
1291 this.writeBuffer
.push(data
);
1293 // Send XOFF to pause the pty process if the write buffer becomes too large so
1294 // xterm.js can catch up before more data is sent. This is necessary in order
1295 // to keep signals such as ^C responsive.
1296 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1297 // XOFF - stop pty pipe
1298 // XON will be triggered by emulator before processing data chunk
1300 this.xoffSentToCatchUp
= true;
1303 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1304 // Kick off a write which will write all data in sequence recursively
1305 this.writeInProgress
= true;
1306 // Kick off an async innerWrite so more writes can come in while processing data
1308 setTimeout(function () {
1314 Terminal
.prototype.innerWrite = function() {
1315 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1316 while (writeBatch
.length
> 0) {
1317 var data
= writeBatch
.shift();
1318 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1320 // If XOFF was sent in order to catch up with the pty process, resume it if
1321 // the writeBuffer is empty to allow more data to come in.
1322 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1324 this.xoffSentToCatchUp
= false;
1327 this.refreshStart
= this.y
;
1328 this.refreshEnd
= this.y
;
1330 this.parser
.parse(data
);
1332 this.updateRange(this.y
);
1333 this.refresh(this.refreshStart
, this.refreshEnd
);
1335 if (this.writeBuffer
.length
> 0) {
1336 // Allow renderer to catch up before processing the next batch
1338 setTimeout(function () {
1342 this.writeInProgress
= false;
1347 * Writes text to the terminal, followed by a break line character (\n).
1348 * @param {string} text The text to write to the terminal.
1350 Terminal
.prototype.writeln = function(data
) {
1351 this.write(data
+ '\r\n');
1355 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1356 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1358 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1359 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1360 * the default action. The function returns whether the event should be processed by xterm.js.
1362 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1363 this.customKeydownHandler
= customKeydownHandler
;
1367 * Attaches a http(s) link handler, forcing web links to behave differently to
1368 * regular <a> tags. This will trigger a refresh as links potentially need to be
1369 * reconstructed. Calling this with null will remove the handler.
1370 * @param {LinkHandler} handler The handler callback function.
1372 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1373 if (!this.linkifier
) {
1374 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1376 this.linkifier
.setHypertextLinkHandler(handler
);
1377 // Refresh to force links to refresh
1378 this.refresh(0, this.rows
- 1);
1382 * Attaches a validation callback for hypertext links. This is useful to use
1383 * validation logic or to do something with the link's element and url.
1384 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1385 * be cleared with null.
1387 Terminal
.prototype.setHypertextValidationCallback = function(handler
) {
1388 if (!this.linkifier
) {
1389 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1391 this.linkifier
.setHypertextValidationCallback(handler
);
1392 // Refresh to force links to refresh
1393 this.refresh(0, this.rows
- 1);
1397 * Registers a link matcher, allowing custom link patterns to be matched and
1399 * @param {RegExp} regex The regular expression to search for, specifically
1400 * this searches the textContent of the rows. You will want to use \s to match
1401 * a space ' ' character for example.
1402 * @param {LinkHandler} handler The callback when the link is called.
1403 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1404 * @return {number} The ID of the new matcher, this can be used to deregister.
1406 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1407 if (this.linkifier
) {
1408 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1409 this.refresh(0, this.rows
- 1);
1415 * Deregisters a link matcher if it has been registered.
1416 * @param {number} matcherId The link matcher's ID (returned after register)
1418 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1419 if (this.linkifier
) {
1420 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1421 this.refresh(0, this.rows
- 1);
1427 * Handle a keydown event
1429 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1430 * @param {KeyboardEvent} ev The keydown event to be handled.
1432 Terminal
.prototype.keyDown = function(ev
) {
1433 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1437 this.restartCursorBlinking();
1439 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1440 if (this.ybase
!== this.ydisp
) {
1441 this.scrollToBottom();
1447 var result
= this.evaluateKeyEscapeSequence(ev
);
1449 if (result
.key
=== C0
.DC3
) { // XOFF
1450 this.writeStopped
= true;
1451 } else if (result
.key
=== C0
.DC1
) { // XON
1452 this.writeStopped
= false;
1455 if (result
.scrollDisp
) {
1456 this.scrollDisp(result
.scrollDisp
);
1457 return this.cancel(ev
, true);
1460 if (isThirdLevelShift(this, ev
)) {
1464 if (result
.cancel
) {
1465 // The event is canceled at the end already, is this necessary?
1466 this.cancel(ev
, true);
1473 this.emit('keydown', ev
);
1474 this.emit('key', result
.key
, ev
);
1476 this.handler(result
.key
);
1478 return this.cancel(ev
, true);
1482 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1483 * returned value is the new key code to pass to the PTY.
1485 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1486 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1488 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1490 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1491 // canceled at the end of keyDown
1493 // The new key even to emit
1495 // The number of characters to scroll, if this is defined it will cancel the event
1496 scrollDisp
: undefined
1498 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1499 switch (ev
.keyCode
) {
1503 result
.key
= C0
.BS
; // ^H
1506 result
.key
= C0
.DEL
; // ^?
1511 result
.key
= C0
.ESC
+ '[Z';
1515 result
.cancel
= true;
1520 result
.cancel
= true;
1524 result
.key
= C0
.ESC
;
1525 result
.cancel
= true;
1530 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1531 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1532 // http://unix.stackexchange.com/a/108106
1533 // macOS uses different escape sequences than linux
1534 if (result
.key
== C0
.ESC
+ '[1;3D') {
1535 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1537 } else if (this.applicationCursor
) {
1538 result
.key
= C0
.ESC
+ 'OD';
1540 result
.key
= C0
.ESC
+ '[D';
1546 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1547 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1548 // http://unix.stackexchange.com/a/108106
1549 // macOS uses different escape sequences than linux
1550 if (result
.key
== C0
.ESC
+ '[1;3C') {
1551 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1553 } else if (this.applicationCursor
) {
1554 result
.key
= C0
.ESC
+ 'OC';
1556 result
.key
= C0
.ESC
+ '[C';
1562 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1563 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1564 // http://unix.stackexchange.com/a/108106
1565 if (result
.key
== C0
.ESC
+ '[1;3A') {
1566 result
.key
= C0
.ESC
+ '[1;5A';
1568 } else if (this.applicationCursor
) {
1569 result
.key
= C0
.ESC
+ 'OA';
1571 result
.key
= C0
.ESC
+ '[A';
1577 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1578 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1579 // http://unix.stackexchange.com/a/108106
1580 if (result
.key
== C0
.ESC
+ '[1;3B') {
1581 result
.key
= C0
.ESC
+ '[1;5B';
1583 } else if (this.applicationCursor
) {
1584 result
.key
= C0
.ESC
+ 'OB';
1586 result
.key
= C0
.ESC
+ '[B';
1591 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1592 // <Ctrl> or <Shift> + <Insert> are used to
1593 // copy-paste on some systems.
1594 result
.key
= C0
.ESC
+ '[2~';
1600 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1602 result
.key
= C0
.ESC
+ '[3~';
1608 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1609 else if (this.applicationCursor
)
1610 result
.key
= C0
.ESC
+ 'OH';
1612 result
.key
= C0
.ESC
+ '[H';
1617 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1618 else if (this.applicationCursor
)
1619 result
.key
= C0
.ESC
+ 'OF';
1621 result
.key
= C0
.ESC
+ '[F';
1626 result
.scrollDisp
= -(this.rows
- 1);
1628 result
.key
= C0
.ESC
+ '[5~';
1634 result
.scrollDisp
= this.rows
- 1;
1636 result
.key
= C0
.ESC
+ '[6~';
1642 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1644 result
.key
= C0
.ESC
+ 'OP';
1649 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1651 result
.key
= C0
.ESC
+ 'OQ';
1656 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1658 result
.key
= C0
.ESC
+ 'OR';
1663 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1665 result
.key
= C0
.ESC
+ 'OS';
1670 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1672 result
.key
= C0
.ESC
+ '[15~';
1677 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1679 result
.key
= C0
.ESC
+ '[17~';
1684 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1686 result
.key
= C0
.ESC
+ '[18~';
1691 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1693 result
.key
= C0
.ESC
+ '[19~';
1698 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1700 result
.key
= C0
.ESC
+ '[20~';
1705 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1707 result
.key
= C0
.ESC
+ '[21~';
1712 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1714 result
.key
= C0
.ESC
+ '[23~';
1719 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1721 result
.key
= C0
.ESC
+ '[24~';
1726 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1727 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1728 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1729 } else if (ev
.keyCode
=== 32) {
1731 result
.key
= String
.fromCharCode(0);
1732 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1733 // escape, file sep, group sep, record sep, unit sep
1734 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1735 } else if (ev
.keyCode
=== 56) {
1737 result
.key
= String
.fromCharCode(127);
1738 } else if (ev
.keyCode
=== 219) {
1739 // ^[ - Control Sequence Introducer (CSI)
1740 result
.key
= String
.fromCharCode(27);
1741 } else if (ev
.keyCode
=== 220) {
1742 // ^\ - String Terminator (ST)
1743 result
.key
= String
.fromCharCode(28);
1744 } else if (ev
.keyCode
=== 221) {
1745 // ^] - Operating System Command (OSC)
1746 result
.key
= String
.fromCharCode(29);
1748 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1749 // On Mac this is a third level shift. Use <Esc> instead.
1750 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1751 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1752 } else if (ev
.keyCode
=== 192) {
1753 result
.key
= C0
.ESC
+ '`';
1754 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1755 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1765 * Set the G level of the terminal
1768 Terminal
.prototype.setgLevel = function(g
) {
1770 this.charset
= this.charsets
[g
];
1774 * Set the charset for the given G level of the terminal
1778 Terminal
.prototype.setgCharset = function(g
, charset
) {
1779 this.charsets
[g
] = charset
;
1780 if (this.glevel
=== g
) {
1781 this.charset
= charset
;
1786 * Handle a keypress event.
1788 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1789 * @param {KeyboardEvent} ev The keypress event to be handled.
1791 Terminal
.prototype.keyPress = function(ev
) {
1798 } else if (ev
.which
== null) {
1800 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1807 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1812 key
= String
.fromCharCode(key
);
1814 this.emit('keypress', key
, ev
);
1815 this.emit('key', key
, ev
);
1823 * Send data for handling to the terminal
1824 * @param {string} data
1826 Terminal
.prototype.send = function(data
) {
1830 setTimeout(function() {
1831 self
.handler(self
.queue
);
1841 * Note: We could do sweet things with webaudio here
1843 Terminal
.prototype.bell = function() {
1844 if (!this.visualBell
) return;
1846 this.element
.style
.borderColor
= 'white';
1847 setTimeout(function() {
1848 self
.element
.style
.borderColor
= '';
1850 if (this.popOnBell
) this.focus();
1854 * Log the current state to the console.
1856 Terminal
.prototype.log = function() {
1857 if (!this.debug
) return;
1858 if (!this.context
.console
|| !this.context
.console
.log
) return;
1859 var args
= Array
.prototype.slice
.call(arguments
);
1860 this.context
.console
.log
.apply(this.context
.console
, args
);
1864 * Log the current state as error to the console.
1866 Terminal
.prototype.error = function() {
1867 if (!this.debug
) return;
1868 if (!this.context
.console
|| !this.context
.console
.error
) return;
1869 var args
= Array
.prototype.slice
.call(arguments
);
1870 this.context
.console
.error
.apply(this.context
.console
, args
);
1874 * Resizes the terminal.
1876 * @param {number} x The number of columns to resize to.
1877 * @param {number} y The number of rows to resize to.
1879 Terminal
.prototype.resize = function(x
, y
) {
1880 if (isNaN(x
) || isNaN(y
)) {
1891 if (x
=== this.cols
&& y
=== this.rows
) {
1901 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1902 i
= this.lines
.length
;
1904 while (this.lines
.get(i
).length
< x
) {
1905 this.lines
.get(i
).push(ch
);
1911 this.setupStops(this.cols
);
1919 // y is rows, not this.y
1920 if (this.lines
.length
< y
+ this.ybase
) {
1921 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
1922 // There is room above the buffer and there are no empty elements below the line,
1926 if (this.ydisp
> 0) {
1927 // Viewport is at the top of the buffer, must increase downwards
1931 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1932 // are blank lines after the cursor
1933 this.lines
.push(this.blankLine());
1936 if (this.children
.length
< y
) {
1942 if (this.lines
.length
> y
+ this.ybase
) {
1943 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
1944 // The line is a blank line below the cursor, remove it
1947 // The line is the cursor, scroll down
1952 if (this.children
.length
> y
) {
1953 el
= this.children
.shift();
1955 el
.parentNode
.removeChild(el
);
1961 // Make sure that the cursor stays on screen
1974 this.scrollBottom
= y
- 1;
1976 this.charMeasure
.measure();
1978 this.refresh(0, this.rows
- 1);
1982 this.geometry
= [this.cols
, this.rows
];
1983 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
1987 * Updates the range of rows to refresh
1988 * @param {number} y The number of rows to refresh next.
1990 Terminal
.prototype.updateRange = function(y
) {
1991 if (y
< this.refreshStart
) this.refreshStart
= y
;
1992 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
1993 // if (y > this.refreshEnd) {
1994 // this.refreshEnd = y;
1995 // if (y > this.rows - 1) {
1996 // this.refreshEnd = this.rows - 1;
2002 * Set the range of refreshing to the maximum value
2004 Terminal
.prototype.maxRange = function() {
2005 this.refreshStart
= 0;
2006 this.refreshEnd
= this.rows
- 1;
2012 * Setup the tab stops.
2015 Terminal
.prototype.setupStops = function(i
) {
2017 if (!this.tabs
[i
]) {
2018 i
= this.prevStop(i
);
2025 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
2026 this.tabs
[i
] = true;
2032 * Move the cursor to the previous tab stop from the given position (default is current).
2033 * @param {number} x The position to move the cursor to the previous tab stop.
2035 Terminal
.prototype.prevStop = function(x
) {
2036 if (x
== null) x
= this.x
;
2037 while (!this.tabs
[--x
] && x
> 0);
2038 return x
>= this.cols
2045 * Move the cursor one tab stop forward from the given position (default is current).
2046 * @param {number} x The position to move the cursor one tab stop forward.
2048 Terminal
.prototype.nextStop = function(x
) {
2049 if (x
== null) x
= this.x
;
2050 while (!this.tabs
[++x
] && x
< this.cols
);
2051 return x
>= this.cols
2058 * Erase in the identified line everything from "x" to the end of the line (right).
2059 * @param {number} x The column from which to start erasing to the end of the line.
2060 * @param {number} y The line in which to operate.
2062 Terminal
.prototype.eraseRight = function(x
, y
) {
2063 var line
= this.lines
.get(this.ybase
+ y
);
2067 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2068 for (; x
< this.cols
; x
++) {
2071 this.updateRange(y
);
2077 * Erase in the identified line everything from "x" to the start of the line (left).
2078 * @param {number} x The column from which to start erasing to the start of the line.
2079 * @param {number} y The line in which to operate.
2081 Terminal
.prototype.eraseLeft = function(x
, y
) {
2082 var line
= this.lines
.get(this.ybase
+ y
);
2086 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2091 this.updateRange(y
);
2095 * Clears the entire buffer, making the prompt line the new first line.
2097 Terminal
.prototype.clear = function() {
2098 if (this.ybase
=== 0 && this.y
=== 0) {
2099 // Don't clear if it's already clear
2102 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2103 this.lines
.length
= 1;
2107 for (var i
= 1; i
< this.rows
; i
++) {
2108 this.lines
.push(this.blankLine());
2110 this.refresh(0, this.rows
- 1);
2111 this.emit('scroll', this.ydisp
);
2115 * Erase all content in the given line
2116 * @param {number} y The line to erase all of its contents.
2118 Terminal
.prototype.eraseLine = function(y
) {
2119 this.eraseRight(0, y
);
2124 * Return the data array of a blank line
2125 * @param {number} cur First bunch of data for each "blank" character.
2127 Terminal
.prototype.blankLine = function(cur
) {
2132 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2136 for (; i
< this.cols
; i
++) {
2145 * If cur return the back color xterm feature attribute. Else return defAttr.
2146 * @param {object} cur
2148 Terminal
.prototype.ch = function(cur
) {
2150 ? [this.eraseAttr(), ' ', 1]
2151 : [this.defAttr
, ' ', 1];
2156 * Evaluate if the current erminal is the given argument.
2157 * @param {object} term The terminal to evaluate
2159 Terminal
.prototype.is = function(term
) {
2160 var name
= this.termName
;
2161 return (name
+ '').indexOf(term
) === 0;
2166 * Emit the 'data' event and populate the given data.
2167 * @param {string} data The data to populate in the event.
2169 Terminal
.prototype.handler = function(data
) {
2170 // Prevents all events to pty process if stdin is disabled
2171 if (this.options
.disableStdin
) {
2175 // Input is being sent to the terminal, the terminal should focus the prompt.
2176 if (this.ybase
!== this.ydisp
) {
2177 this.scrollToBottom();
2179 this.emit('data', data
);
2184 * Emit the 'title' event and populate the given title.
2185 * @param {string} title The title to populate in the event.
2187 Terminal
.prototype.handleTitle = function(title
) {
2189 * This event is emitted when the title of the terminal is changed
2190 * from inside the terminal. The parameter is the new title.
2194 this.emit('title', title
);
2203 * ESC D Index (IND is 0x84).
2205 Terminal
.prototype.index = function() {
2207 if (this.y
> this.scrollBottom
) {
2211 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2212 if (this.x
>= this.cols
) {
2219 * ESC M Reverse Index (RI is 0x8d).
2221 * Move the cursor up one row, inserting a new blank line if necessary.
2223 Terminal
.prototype.reverseIndex = function() {
2225 if (this.y
=== this.scrollTop
) {
2226 // possibly move the code below to term.reverseScroll();
2227 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2228 // blankLine(true) is xterm/linux behavior
2229 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2230 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2231 this.updateRange(this.scrollTop
);
2232 this.updateRange(this.scrollBottom
);
2240 * ESC c Full Reset (RIS).
2242 Terminal
.prototype.reset = function() {
2243 this.options
.rows
= this.rows
;
2244 this.options
.cols
= this.cols
;
2245 var customKeydownHandler
= this.customKeydownHandler
;
2246 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2247 Terminal
.call(this, this.options
);
2248 this.customKeydownHandler
= customKeydownHandler
;
2249 this.cursorBlinkInterval
= cursorBlinkInterval
;
2250 this.refresh(0, this.rows
- 1);
2251 this.viewport
.syncScrollArea();
2256 * ESC H Tab Set (HTS is 0x88).
2258 Terminal
.prototype.tabSet = function() {
2259 this.tabs
[this.x
] = true;
2266 function on(el
, type
, handler
, capture
) {
2267 if (!Array
.isArray(el
)) {
2270 el
.forEach(function (element
) {
2271 element
.addEventListener(type
, handler
, capture
|| false);
2275 function off(el
, type
, handler
, capture
) {
2276 el
.removeEventListener(type
, handler
, capture
|| false);
2279 function cancel(ev
, force
) {
2280 if (!this.cancelEvents
&& !force
) {
2283 ev
.preventDefault();
2284 ev
.stopPropagation();
2288 function inherits(child
, parent
) {
2290 this.constructor = child
;
2292 f
.prototype = parent
.prototype;
2293 child
.prototype = new f
;
2296 function indexOf(obj
, el
) {
2299 if (obj
[i
] === el
) return i
;
2304 function isThirdLevelShift(term
, ev
) {
2306 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2307 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2309 if (ev
.type
== 'keypress') {
2310 return thirdLevelKey
;
2313 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2314 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2317 // Expose to InputHandler (temporary)
2318 Terminal
.prototype.matchColor
= matchColor
;
2320 function matchColor(r1
, g1
, b1
) {
2321 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2323 if (matchColor
._cache
[hash
] != null) {
2324 return matchColor
._cache
[hash
];
2327 var ldiff
= Infinity
2336 for (; i
< Terminal
.vcolors
.length
; i
++) {
2337 c
= Terminal
.vcolors
[i
];
2342 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2355 return matchColor
._cache
[hash
] = li
;
2358 matchColor
._cache
= {};
2360 // http://stackoverflow.com/questions/1633828
2361 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2362 return Math
.pow(30 * (r1
- r2
), 2)
2363 + Math
.pow(59 * (g1
- g2
), 2)
2364 + Math
.pow(11 * (b1
- b2
), 2);
2367 function each(obj
, iter
, con
) {
2368 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2369 for (var i
= 0; i
< obj
.length
; i
++) {
2370 iter
.call(con
, obj
[i
], i
, obj
);
2374 function wasMondifierKeyOnlyEvent(ev
) {
2375 return ev
.keyCode
=== 16 || // Shift
2376 ev
.keyCode
=== 17 || // Ctrl
2377 ev
.keyCode
=== 18; // Alt
2380 function keys(obj
) {
2381 if (Object
.keys
) return Object
.keys(obj
);
2384 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2395 Terminal
.EventEmitter
= EventEmitter
;
2396 Terminal
.inherits
= inherits
;
2399 * Adds an event listener to the terminal.
2401 * @param {string} event The name of the event. TODO: Document all event types
2402 * @param {function} callback The function to call when the event is triggered.
2406 Terminal
.cancel
= cancel
;
2408 module
.exports
= Terminal
;