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 { BufferSet
} from './BufferSet';
14 import { CompositionHelper
} from './CompositionHelper';
15 import { EventEmitter
} from './EventEmitter';
16 import { Viewport
} from './Viewport';
17 import { rightClickHandler
, moveTextAreaUnderMouseCursor
, pasteHandler
, copyHandler
} from './handlers/Clipboard';
18 import { CircularList
} from './utils/CircularList';
19 import { C0
} from './EscapeSequences';
20 import { InputHandler
} from './InputHandler';
21 import { Parser
} from './Parser';
22 import { Renderer
} from './Renderer';
23 import { Linkifier
} from './Linkifier';
24 import { SelectionManager
} from './SelectionManager';
25 import { CharMeasure
} from './utils/CharMeasure';
26 import * as Browser
from './utils/Browser';
27 import * as Mouse
from './utils/Mouse';
28 import { CHARSETS
} from './Charsets';
29 import { getRawByteCoords
} from './utils/Mouse';
30 import { translateBufferLineToString
} from './utils/BufferLine';
33 * Terminal Emulation References:
35 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
36 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
37 * http://invisible-island.net/vttest/
38 * http://www.inwap.com/pdp10/ansicode.txt
39 * http://linux.die.net/man/4/console_codes
40 * http://linux.die.net/man/7/urxvt
43 // Let it work inside Node.js for automated testing purposes.
44 var document
= (typeof window
!= 'undefined') ? window
.document
: null;
47 * The amount of write requests to queue before sending an XOFF signal to the
48 * pty process. This number must be small in order for ^C and similar sequences
51 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
54 * The number of writes to perform in a single batch before allowing the
55 * renderer to catch up with a 0ms setTimeout.
57 var WRITE_BATCH_SIZE
= 300;
60 * The time between cursor blinks. This is driven by JS rather than a CSS
61 * animation due to a bug in Chromium that causes it to use excessive CPU time.
62 * See https://github.com/Microsoft/vscode/issues/22900
64 var CURSOR_BLINK_INTERVAL
= 600;
71 * Creates a new `Terminal` object.
73 * @param {object} options An object containing a set of options, the available options are:
74 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
75 * - `cols` (number): The number of columns of the terminal (horizontal size)
76 * - `rows` (number): The number of rows of the terminal (vertical size)
80 * @alias module:xterm/src/xterm
82 function Terminal(options
) {
85 if (!(this instanceof Terminal
)) {
86 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
89 self
.browser
= Browser
;
90 self
.cancel
= Terminal
.cancel
;
92 EventEmitter
.call(this);
94 if (typeof options
=== 'number') {
102 options
= options
|| {};
105 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
106 if (options
[key
] == null) {
107 options
[key
] = Terminal
.options
[key
];
109 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
110 options
[key
] = Terminal
[key
];
113 self
[key
] = options
[key
];
116 if (options
.colors
.length
=== 8) {
117 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
118 } else if (options
.colors
.length
=== 16) {
119 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
120 } else if (options
.colors
.length
=== 10) {
121 options
.colors
= options
.colors
.slice(0, -2).concat(
122 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
123 } else if (options
.colors
.length
=== 18) {
124 options
.colors
= options
.colors
.concat(
125 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
127 this.colors
= options
.colors
;
129 this.options
= options
;
131 // this.context = options.context || window;
132 // this.document = options.document || document;
133 this.parent
= options
.body
|| options
.parent
|| (
134 document
? document
.getElementsByTagName('body')[0] : null
137 this.cols
= options
.cols
|| options
.geometry
[0];
138 this.rows
= options
.rows
|| options
.geometry
[1];
139 this.geometry
= [this.cols
, this.rows
];
141 if (options
.handler
) {
142 this.on('data', options
.handler
);
145 this.cursorState
= 0;
146 this.cursorHidden
= false;
149 this.customKeyEventHandler
= null;
150 this.cursorBlinkInterval
= null;
153 this.applicationKeypad
= false;
154 this.applicationCursor
= false;
155 this.originMode
= false;
156 this.insertMode
= false;
157 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
161 this.gcharset
= null;
163 this.charsets
= [null];
187 this.readable
= true;
188 this.writable
= true;
190 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
191 this.curAttr
= this.defAttr
;
194 this.currentParam
= 0;
198 this.inputHandler
= new InputHandler(this);
199 this.parser
= new Parser(this.inputHandler
, this);
200 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
201 this.renderer
= this.renderer
|| null;
202 this.selectionManager
= this.selectionManager
|| null;
203 this.linkifier
= this.linkifier
|| new Linkifier();
206 this.writeBuffer
= [];
207 this.writeInProgress
= false;
210 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
211 * This is a distinct state from writeStopped so that if the user requested
212 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
215 this.xoffSentToCatchUp
= false;
217 /** Whether writing has been stopped as a result of XOFF */
218 this.writeStopped
= false;
220 // leftover surrogate high from previous write invocation
221 this.surrogate_high
= '';
223 // Create the terminal's buffers and set the current buffer
224 this.buffers
= new BufferSet(this);
225 this.buffer
= this.buffers
.active
; // Convenience shortcut;
226 this.buffers
.on('activate', function (buffer
) {
227 this._terminal
.buffer
= buffer
;
230 // Ensure the selection manager has the correct buffer
231 if (this.selectionManager
) {
232 this.selectionManager
.setBuffer(this.buffer
.lines
);
237 // Store if user went browsing history in scrollback
238 this.userScrolling
= false;
241 inherits(Terminal
, EventEmitter
);
244 * back_color_erase feature for xterm.
246 Terminal
.prototype.eraseAttr = function() {
247 // if (this.is('screen')) return this.defAttr;
248 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
256 Terminal
.tangoColors
= [
277 // Colors 0-15 + 16-255
278 // Much thanks to TooTallNate for writing this.
279 Terminal
.colors
= (function() {
280 var colors
= Terminal
.tangoColors
.slice()
281 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
286 for (; i
< 216; i
++) {
287 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
292 for (; i
< 24; i
++) {
297 function out(r
, g
, b
) {
298 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
303 return c
.length
< 2 ? '0' + c
: c
;
309 Terminal
._colors
= Terminal
.colors
.slice();
311 Terminal
.vcolors
= (function() {
313 , colors
= Terminal
.colors
317 for (; i
< 256; i
++) {
318 color
= parseInt(colors
[i
].substring(1), 16);
320 (color
>> 16) & 0xff,
333 Terminal
.defaults
= {
334 colors
: Terminal
.colors
,
340 cursorStyle
: 'block',
348 useFlowControl
: false,
350 // programFeatures: false,
354 Terminal
.options
= {};
356 Terminal
.focus
= null;
358 each(keys(Terminal
.defaults
), function(key
) {
359 Terminal
[key
] = Terminal
.defaults
[key
];
360 Terminal
.options
[key
] = Terminal
.defaults
[key
];
364 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
366 Terminal
.prototype.focus = function() {
367 return this.textarea
.focus();
371 * Retrieves an option's value from the terminal.
372 * @param {string} key The option key.
374 Terminal
.prototype.getOption = function(key
) {
375 if (!(key
in Terminal
.defaults
)) {
376 throw new Error('No option with key "' + key
+ '"');
379 if (typeof this.options
[key
] !== 'undefined') {
380 return this.options
[key
];
387 * Sets an option on the terminal.
388 * @param {string} key The option key.
389 * @param {string} value The option value.
391 Terminal
.prototype.setOption = function(key
, value
) {
392 if (!(key
in Terminal
.defaults
)) {
393 throw new Error('No option with key "' + key
+ '"');
397 if (value
< this.rows
) {
398 let msg
= 'Setting the scrollback value less than the number of rows ';
400 msg
+= `(${this.rows}) is not allowed.`;
406 if (this.options
[key
] !== value
) {
407 if (this.buffer
.lines
.length
> value
) {
408 const amountToTrim
= this.buffer
.lines
.length
- value
;
409 const needsRefresh
= (this.buffer
.ydisp
- amountToTrim
< 0);
410 this.buffer
.lines
.trimStart(amountToTrim
);
411 this.buffer
.ybase
= Math
.max(this.buffer
.ybase
- amountToTrim
, 0);
412 this.buffer
.ydisp
= Math
.max(this.buffer
.ydisp
- amountToTrim
, 0);
414 this.refresh(0, this.rows
- 1);
417 this.buffer
.lines
.maxLength
= value
;
418 this.viewport
.syncScrollArea();
423 this.options
[key
] = value
;
425 case 'cursorBlink': this.setCursorBlinking(value
); break;
427 this.element
.classList
.toggle(`xterm-cursor-style-block`, value
=== 'block');
428 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
429 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
431 case 'tabStopWidth': this.setupStops(); break;
435 Terminal
.prototype.restartCursorBlinking = function () {
436 this.setCursorBlinking(this.options
.cursorBlink
);
439 Terminal
.prototype.setCursorBlinking = function (enabled
) {
440 this.element
.classList
.toggle('xterm-cursor-blink', enabled
);
441 this.clearCursorBlinkingInterval();
444 this.cursorBlinkInterval
= setInterval(function () {
445 self
.element
.classList
.toggle('xterm-cursor-blink-on');
446 }, CURSOR_BLINK_INTERVAL
);
450 Terminal
.prototype.clearCursorBlinkingInterval = function () {
451 this.element
.classList
.remove('xterm-cursor-blink-on');
452 if (this.cursorBlinkInterval
) {
453 clearInterval(this.cursorBlinkInterval
);
454 this.cursorBlinkInterval
= null;
459 * Binds the desired focus behavior on a given terminal object.
463 Terminal
.bindFocus = function (term
) {
464 on(term
.textarea
, 'focus', function (ev
) {
465 if (term
.sendFocus
) {
466 term
.send(C0
.ESC
+ '[I');
468 term
.element
.classList
.add('focus');
470 term
.restartCursorBlinking
.apply(term
);
471 Terminal
.focus
= term
;
472 term
.emit('focus', {terminal
: term
});
477 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
479 Terminal
.prototype.blur = function() {
480 return this.textarea
.blur();
484 * Binds the desired blur behavior on a given terminal object.
488 Terminal
.bindBlur = function (term
) {
489 on(term
.textarea
, 'blur', function (ev
) {
490 term
.refresh(term
.buffer
.y
, term
.buffer
.y
);
491 if (term
.sendFocus
) {
492 term
.send(C0
.ESC
+ '[O');
494 term
.element
.classList
.remove('focus');
495 term
.clearCursorBlinkingInterval
.apply(term
);
496 Terminal
.focus
= null;
497 term
.emit('blur', {terminal
: term
});
502 * Initialize default behavior
504 Terminal
.prototype.initGlobal = function() {
507 Terminal
.bindKeys(this);
508 Terminal
.bindFocus(this);
509 Terminal
.bindBlur(this);
511 // Bind clipboard functionality
512 on(this.element
, 'copy', event
=> {
513 // If mouse events are active it means the selection manager is disabled and
514 // copy should be handled by the host program.
515 if (!term
.hasSelection()) {
518 copyHandler(event
, term
, this.selectionManager
);
520 const pasteHandlerWrapper
= event
=> pasteHandler(event
, term
);
521 on(this.textarea
, 'paste', pasteHandlerWrapper
);
522 on(this.element
, 'paste', pasteHandlerWrapper
);
524 // Handle right click context menus
525 if (term
.browser
.isFirefox
) {
526 // Firefox doesn't appear to fire the contextmenu event on right click
527 on(this.element
, 'mousedown', event
=> {
528 if (event
.button
== 2) {
529 rightClickHandler(event
, this.textarea
, this.selectionManager
);
533 on(this.element
, 'contextmenu', event
=> {
534 rightClickHandler(event
, this.textarea
, this.selectionManager
);
538 // Move the textarea under the cursor when middle clicking on Linux to ensure
539 // middle click to paste selection works. This only appears to work in Chrome
540 // at the time is writing.
541 if (term
.browser
.isLinux
) {
542 // Use auxclick event over mousedown the latter doesn't seem to work. Note
543 // that the regular click event doesn't fire for the middle mouse button.
544 on(this.element
, 'auxclick', event
=> {
545 if (event
.button
=== 1) {
546 moveTextAreaUnderMouseCursor(event
, this.textarea
, this.selectionManager
);
553 * Apply key handling to the terminal
555 Terminal
.bindKeys = function(term
) {
556 on(term
.element
, 'keydown', function(ev
) {
557 if (document
.activeElement
!= this) {
563 on(term
.element
, 'keypress', function(ev
) {
564 if (document
.activeElement
!= this) {
570 on(term
.element
, 'keyup', function(ev
) {
571 if (!wasMondifierKeyOnlyEvent(ev
)) {
576 on(term
.textarea
, 'keydown', function(ev
) {
580 on(term
.textarea
, 'keypress', function(ev
) {
582 // Truncate the textarea's value, since it is not needed
586 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
587 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
588 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
589 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
590 term
.on('refresh', function (data
) {
591 term
.queueLinkification(data
.start
, data
.end
)
597 * Insert the given row to the terminal or produce a new one
598 * if no row argument is passed. Return the inserted row.
599 * @param {HTMLElement} row (optional) The row to append to the terminal.
601 Terminal
.prototype.insertRow = function (row
) {
602 if (typeof row
!= 'object') {
603 row
= document
.createElement('div');
606 this.rowContainer
.appendChild(row
);
607 this.children
.push(row
);
613 * Opens the terminal within an element.
615 * @param {HTMLElement} parent The element to create the terminal within.
616 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
618 Terminal
.prototype.open = function(parent
, focus
) {
619 var self
=this, i
=0, div
;
621 this.parent
= parent
|| this.parent
;
624 throw new Error('Terminal requires a parent element.');
627 // Grab global elements
628 this.context
= this.parent
.ownerDocument
.defaultView
;
629 this.document
= this.parent
.ownerDocument
;
630 this.body
= this.document
.getElementsByTagName('body')[0];
632 //Create main element container
633 this.element
= this.document
.createElement('div');
634 this.element
.classList
.add('terminal');
635 this.element
.classList
.add('xterm');
636 this.element
.classList
.add('xterm-theme-' + this.theme
);
637 this.element
.classList
.add(`xterm-cursor-style-${this.options.cursorStyle}`);
638 this.setCursorBlinking(this.options
.cursorBlink
);
640 this.element
.setAttribute('tabindex', 0);
642 this.viewportElement
= document
.createElement('div');
643 this.viewportElement
.classList
.add('xterm-viewport');
644 this.element
.appendChild(this.viewportElement
);
645 this.viewportScrollArea
= document
.createElement('div');
646 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
647 this.viewportElement
.appendChild(this.viewportScrollArea
);
649 // Create the selection container.
650 this.selectionContainer
= document
.createElement('div');
651 this.selectionContainer
.classList
.add('xterm-selection');
652 this.element
.appendChild(this.selectionContainer
);
654 // Create the container that will hold the lines of the terminal and then
655 // produce the lines the lines.
656 this.rowContainer
= document
.createElement('div');
657 this.rowContainer
.classList
.add('xterm-rows');
658 this.element
.appendChild(this.rowContainer
);
660 this.linkifier
.attachToDom(document
, this.children
);
662 // Create the container that will hold helpers like the textarea for
663 // capturing DOM Events. Then produce the helpers.
664 this.helperContainer
= document
.createElement('div');
665 this.helperContainer
.classList
.add('xterm-helpers');
666 // TODO: This should probably be inserted once it's filled to prevent an additional layout
667 this.element
.appendChild(this.helperContainer
);
668 this.textarea
= document
.createElement('textarea');
669 this.textarea
.classList
.add('xterm-helper-textarea');
670 this.textarea
.setAttribute('autocorrect', 'off');
671 this.textarea
.setAttribute('autocapitalize', 'off');
672 this.textarea
.setAttribute('spellcheck', 'false');
673 this.textarea
.tabIndex
= 0;
674 this.textarea
.addEventListener('focus', function() {
675 self
.emit('focus', {terminal
: self
});
677 this.textarea
.addEventListener('blur', function() {
678 self
.emit('blur', {terminal
: self
});
680 this.helperContainer
.appendChild(this.textarea
);
682 this.compositionView
= document
.createElement('div');
683 this.compositionView
.classList
.add('composition-view');
684 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
685 this.helperContainer
.appendChild(this.compositionView
);
687 this.charSizeStyleElement
= document
.createElement('style');
688 this.helperContainer
.appendChild(this.charSizeStyleElement
);
690 for (; i
< this.rows
; i
++) {
693 this.parent
.appendChild(this.element
);
695 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
696 this.charMeasure
.on('charsizechanged', function () {
697 self
.updateCharSizeStyles();
699 this.charMeasure
.measure();
701 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
702 this.renderer
= new Renderer(this);
703 this.selectionManager
= new SelectionManager(
704 this, this.buffer
.lines
, this.rowContainer
, this.charMeasure
706 this.selectionManager
.on('refresh', data
=> {
707 this.renderer
.refreshSelection(data
.start
, data
.end
);
709 this.selectionManager
.on('newselection', text
=> {
710 // If there's a new selection, put it into the textarea, focus and select it
711 // in order to register it as a selection on the OS. This event is fired
712 // only on Linux to enable middle click to paste selection.
713 this.textarea
.value
= text
;
714 this.textarea
.focus();
715 this.textarea
.select();
717 this.on('scroll', () => this.selectionManager
.refresh());
718 this.viewportElement
.addEventListener('scroll', () => this.selectionManager
.refresh());
720 // Setup loop that draws to screen
721 this.refresh(0, this.rows
- 1);
723 // Initialize global actions that
724 // need to be taken on the document.
728 * Automatic focus functionality.
729 * TODO: Default to `false` starting with xterm.js 3.0.
731 if (typeof focus
== 'undefined') {
732 let message
= 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
734 message
+= 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
735 message
+= 'it will default to `false`.';
737 console
.warn(message
);
745 // Listen for mouse events and translate
746 // them into terminal mouse protocols.
750 * This event is emitted when terminal has completed opening.
759 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
760 * @param {string} addon The name of the addon to load
763 Terminal
.loadAddon = function(addon
, callback
) {
764 if (typeof exports
=== 'object' && typeof module
=== 'object') {
766 return require('./addons/' + addon
+ '/' + addon
);
767 } else if (typeof define
== 'function') {
769 return require(['./addons/' + addon
+ '/' + addon
], callback
);
771 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
777 * Updates the helper CSS class with any changes necessary after the terminal's
778 * character width has been changed.
780 Terminal
.prototype.updateCharSizeStyles = function() {
781 this.charSizeStyleElement
.textContent
=
782 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
783 `.xterm-normal-char{width:${this.charMeasure.width}px;}` +
784 `.xterm-rows > div{height:${this.charMeasure.height}px;}`;
789 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
790 * To better understand these
791 * the xterm code is very helpful:
793 * button.c, charproc.c, misc.c
794 * Relevant functions in xterm/button.c:
795 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
797 Terminal
.prototype.bindMouse = function() {
798 var el
= this.element
, self
= this, pressed
= 32;
800 // mouseup, mousedown, wheel
801 // left click: ^[[M 3<^[[M#3<
803 function sendButton(ev
) {
807 // get the xterm-style button
808 button
= getButton(ev
);
810 // get mouse coordinates
811 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
814 sendEvent(button
, pos
);
816 switch (ev
.overrideType
|| ev
.type
) {
821 // keep it at the left
822 // button, just in case.
833 // motion example of a left click:
834 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
835 function sendMove(ev
) {
839 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
842 // buttons marked as motions
843 // are incremented by 32
846 sendEvent(button
, pos
);
850 // position to characters
851 function encode(data
, ch
) {
852 if (!self
.utfMouse
) {
853 if (ch
=== 255) return data
.push(0);
854 if (ch
> 127) ch
= 127;
857 if (ch
=== 2047) return data
.push(0);
861 if (ch
> 2047) ch
= 2047;
862 data
.push(0xC0 | (ch
>> 6));
863 data
.push(0x80 | (ch
& 0x3F));
868 // send a mouse event:
869 // regular/utf8: ^[[M Cb Cx Cy
870 // urxvt: ^[[ Cb ; Cx ; Cy M
871 // sgr: ^[[ Cb ; Cx ; Cy M/m
872 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
873 // locator: CSI P e ; P b ; P r ; P c ; P p & w
874 function sendEvent(button
, pos
) {
875 // self.emit('mouse', {
881 if (self
.vt300Mouse
) {
883 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
887 var data
= C0
.ESC
+ '[24';
888 if (button
=== 0) data
+= '1';
889 else if (button
=== 1) data
+= '3';
890 else if (button
=== 2) data
+= '5';
891 else if (button
=== 3) return;
893 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
898 if (self
.decLocator
) {
903 if (button
=== 0) button
= 2;
904 else if (button
=== 1) button
= 4;
905 else if (button
=== 2) button
= 6;
906 else if (button
=== 3) button
= 3;
907 self
.send(C0
.ESC
+ '['
910 + (button
=== 3 ? 4 : 0)
921 if (self
.urxvtMouse
) {
926 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
933 self
.send(C0
.ESC
+ '[<'
934 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
939 + ((button
& 3) === 3 ? 'm' : 'M'));
945 encode(data
, button
);
949 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
952 function getButton(ev
) {
965 // 1, and 2 - with 64 added
966 switch (ev
.overrideType
|| ev
.type
) {
968 button
= ev
.button
!= null
974 if (self
.browser
.isMSIE
) {
975 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
981 case 'DOMMouseScroll':
982 button
= ev
.detail
< 0
987 button
= ev
.wheelDeltaY
> 0
993 // next three bits are the modifiers:
994 // 4 = shift, 8 = meta, 16 = control
995 shift
= ev
.shiftKey
? 4 : 0;
996 meta
= ev
.metaKey
? 8 : 0;
997 ctrl
= ev
.ctrlKey
? 16 : 0;
998 mod
= shift
| meta
| ctrl
;
1001 if (self
.vt200Mouse
) {
1004 } else if (!self
.normalMouse
) {
1009 button
= (32 + (mod
<< 2)) + button
;
1014 on(el
, 'mousedown', function(ev
) {
1016 // Prevent the focus on the textarea from getting lost
1017 // and make sure we get focused on mousedown
1018 ev
.preventDefault();
1021 if (!self
.mouseEvents
) return;
1027 //if (self.vt200Mouse && !self.normalMouse) {
1028 if (self
.vt200Mouse
) {
1029 ev
.overrideType
= 'mouseup';
1031 return self
.cancel(ev
);
1035 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1037 // x10 compatibility mode can't send button releases
1038 if (!self
.x10Mouse
) {
1039 on(self
.document
, 'mouseup', function up(ev
) {
1041 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1042 off(self
.document
, 'mouseup', up
);
1043 return self
.cancel(ev
);
1047 return self
.cancel(ev
);
1050 //if (self.normalMouse) {
1051 // on(self.document, 'mousemove', sendMove);
1054 on(el
, 'wheel', function(ev
) {
1055 if (!self
.mouseEvents
) return;
1058 || self
.decLocator
) return;
1060 return self
.cancel(ev
);
1063 // allow wheel scrolling in
1064 // the shell for example
1065 on(el
, 'wheel', function(ev
) {
1066 if (self
.mouseEvents
) return;
1067 self
.viewport
.onWheel(ev
);
1068 return self
.cancel(ev
);
1071 on(el
, 'touchstart', function(ev
) {
1072 if (self
.mouseEvents
) return;
1073 self
.viewport
.onTouchStart(ev
);
1074 return self
.cancel(ev
);
1077 on(el
, 'touchmove', function(ev
) {
1078 if (self
.mouseEvents
) return;
1079 self
.viewport
.onTouchMove(ev
);
1080 return self
.cancel(ev
);
1085 * Destroys the terminal.
1087 Terminal
.prototype.destroy = function() {
1088 this.readable
= false;
1089 this.writable
= false;
1091 this.handler = function() {};
1092 this.write = function() {};
1093 if (this.element
&& this.element
.parentNode
) {
1094 this.element
.parentNode
.removeChild(this.element
);
1096 //this.emit('close');
1100 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1102 * @param {number} start The row to start from (between 0 and this.rows - 1).
1103 * @param {number} end The row to end at (between start and this.rows - 1).
1105 Terminal
.prototype.refresh = function(start
, end
) {
1106 if (this.renderer
) {
1107 this.renderer
.queueRefresh(start
, end
);
1112 * Queues linkification for the specified rows.
1113 * @param {number} start The row to start from (between 0 and this.rows - 1).
1114 * @param {number} end The row to end at (between start and this.rows - 1).
1116 Terminal
.prototype.queueLinkification = function(start
, end
) {
1117 if (this.linkifier
) {
1118 for (let i
= start
; i
<= end
; i
++) {
1119 this.linkifier
.linkifyRow(i
);
1125 * Display the cursor element
1127 Terminal
.prototype.showCursor = function() {
1128 if (!this.cursorState
) {
1129 this.cursorState
= 1;
1130 this.refresh(this.buffer
.y
, this.buffer
.y
);
1135 * Scroll the terminal down 1 row, creating a blank line.
1136 * @param {boolean} isWrapped Whether the new line is wrapped from the previous
1139 Terminal
.prototype.scroll = function(isWrapped
) {
1142 // Make room for the new row in lines
1143 if (this.buffer
.lines
.length
=== this.buffer
.lines
.maxLength
) {
1144 this.buffer
.lines
.trimStart(1);
1145 this.buffer
.ybase
--;
1146 if (this.buffer
.ydisp
!== 0) {
1147 this.buffer
.ydisp
--;
1151 this.buffer
.ybase
++;
1153 // TODO: Why is this done twice?
1154 if (!this.userScrolling
) {
1155 this.buffer
.ydisp
= this.buffer
.ybase
;
1159 row
= this.buffer
.ybase
+ this.rows
- 1;
1161 // subtract the bottom scroll region
1162 row
-= this.rows
- 1 - this.buffer
.scrollBottom
;
1164 if (row
=== this.buffer
.lines
.length
) {
1165 // Optimization: pushing is faster than splicing when they amount to the same behavior
1166 this.buffer
.lines
.push(this.blankLine(undefined, isWrapped
));
1169 this.buffer
.lines
.splice(row
, 0, this.blankLine(undefined, isWrapped
));
1172 if (this.buffer
.scrollTop
!== 0) {
1173 if (this.buffer
.ybase
!== 0) {
1174 this.buffer
.ybase
--;
1175 if (!this.userScrolling
) {
1176 this.buffer
.ydisp
= this.buffer
.ybase
;
1179 this.buffer
.lines
.splice(this.buffer
.ybase
+ this.buffer
.scrollTop
, 1);
1183 this.updateRange(this.buffer
.scrollTop
);
1184 this.updateRange(this.buffer
.scrollBottom
);
1187 * This event is emitted whenever the terminal is scrolled.
1188 * The one parameter passed is the new y display position.
1192 this.emit('scroll', this.buffer
.ydisp
);
1196 * Scroll the display of the terminal
1197 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1198 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1199 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1200 * viewport originally.
1202 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1204 if (this.buffer
.ydisp
=== 0) {
1207 this.userScrolling
= true;
1208 } else if (disp
+ this.buffer
.ydisp
>= this.buffer
.ybase
) {
1209 this.userScrolling
= false;
1212 const oldYdisp
= this.buffer
.ydisp
;
1213 this.buffer
.ydisp
= Math
.max(Math
.min(this.buffer
.ydisp
+ disp
, this.buffer
.ybase
), 0);
1215 // No change occurred, don't trigger scroll/refresh
1216 if (oldYdisp
=== this.buffer
.ydisp
) {
1220 if (!suppressScrollEvent
) {
1221 this.emit('scroll', this.buffer
.ydisp
);
1224 this.refresh(0, this.rows
- 1);
1228 * Scroll the display of the terminal by a number of pages.
1229 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1231 Terminal
.prototype.scrollPages = function(pageCount
) {
1232 this.scrollDisp(pageCount
* (this.rows
- 1));
1236 * Scrolls the display of the terminal to the top.
1238 Terminal
.prototype.scrollToTop = function() {
1239 this.scrollDisp(-this.buffer
.ydisp
);
1243 * Scrolls the display of the terminal to the bottom.
1245 Terminal
.prototype.scrollToBottom = function() {
1246 this.scrollDisp(this.buffer
.ybase
- this.buffer
.ydisp
);
1250 * Writes text to the terminal.
1251 * @param {string} data The text to write to the terminal.
1253 Terminal
.prototype.write = function(data
) {
1254 this.writeBuffer
.push(data
);
1256 // Send XOFF to pause the pty process if the write buffer becomes too large so
1257 // xterm.js can catch up before more data is sent. This is necessary in order
1258 // to keep signals such as ^C responsive.
1259 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1260 // XOFF - stop pty pipe
1261 // XON will be triggered by emulator before processing data chunk
1263 this.xoffSentToCatchUp
= true;
1266 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1267 // Kick off a write which will write all data in sequence recursively
1268 this.writeInProgress
= true;
1269 // Kick off an async innerWrite so more writes can come in while processing data
1271 setTimeout(function () {
1277 Terminal
.prototype.innerWrite = function() {
1278 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1279 while (writeBatch
.length
> 0) {
1280 var data
= writeBatch
.shift();
1281 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1283 // If XOFF was sent in order to catch up with the pty process, resume it if
1284 // the writeBuffer is empty to allow more data to come in.
1285 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1287 this.xoffSentToCatchUp
= false;
1290 this.refreshStart
= this.buffer
.y
;
1291 this.refreshEnd
= this.buffer
.y
;
1293 // HACK: Set the parser state based on it's state at the time of return.
1294 // This works around the bug #662 which saw the parser state reset in the
1295 // middle of parsing escape sequence in two chunks. For some reason the
1296 // state of the parser resets to 0 after exiting parser.parse. This change
1297 // just sets the state back based on the correct return statement.
1298 var state
= this.parser
.parse(data
);
1299 this.parser
.setState(state
);
1301 this.updateRange(this.buffer
.y
);
1302 this.refresh(this.refreshStart
, this.refreshEnd
);
1304 if (this.writeBuffer
.length
> 0) {
1305 // Allow renderer to catch up before processing the next batch
1307 setTimeout(function () {
1311 this.writeInProgress
= false;
1316 * Writes text to the terminal, followed by a break line character (\n).
1317 * @param {string} data The text to write to the terminal.
1319 Terminal
.prototype.writeln = function(data
) {
1320 this.write(data
+ '\r\n');
1324 * DEPRECATED: only for backward compatibility. Please use attachCustomKeyEventHandler() instead.
1325 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1326 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1327 * the default action. The function returns whether the event should be processed by xterm.js.
1329 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1330 let message
= 'attachCustomKeydownHandler() is DEPRECATED and will be removed soon. Please use attachCustomKeyEventHandler() instead.';
1331 console
.warn(message
);
1332 this.attachCustomKeyEventHandler(customKeydownHandler
);
1336 * Attaches a custom key event handler which is run before keys are processed, giving consumers of
1337 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1339 * @param {function} customKeyEventHandler The custom KeyboardEvent handler to attach. This is a
1340 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1341 * the default action. The function returns whether the event should be processed by xterm.js.
1343 Terminal
.prototype.attachCustomKeyEventHandler = function(customKeyEventHandler
) {
1344 this.customKeyEventHandler
= customKeyEventHandler
;
1348 * Attaches a http(s) link handler, forcing web links to behave differently to
1349 * regular <a> tags. This will trigger a refresh as links potentially need to be
1350 * reconstructed. Calling this with null will remove the handler.
1351 * @param {LinkMatcherHandler} handler The handler callback function.
1353 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1354 if (!this.linkifier
) {
1355 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1357 this.linkifier
.setHypertextLinkHandler(handler
);
1358 // Refresh to force links to refresh
1359 this.refresh(0, this.rows
- 1);
1363 * Attaches a validation callback for hypertext links. This is useful to use
1364 * validation logic or to do something with the link's element and url.
1365 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1366 * be cleared with null.
1368 Terminal
.prototype.setHypertextValidationCallback = function(callback
) {
1369 if (!this.linkifier
) {
1370 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1372 this.linkifier
.setHypertextValidationCallback(callback
);
1373 // Refresh to force links to refresh
1374 this.refresh(0, this.rows
- 1);
1378 * Registers a link matcher, allowing custom link patterns to be matched and
1380 * @param {RegExp} regex The regular expression to search for, specifically
1381 * this searches the textContent of the rows. You will want to use \s to match
1382 * a space ' ' character for example.
1383 * @param {LinkMatcherHandler} handler The callback when the link is called.
1384 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1385 * @return {number} The ID of the new matcher, this can be used to deregister.
1387 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1388 if (this.linkifier
) {
1389 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1390 this.refresh(0, this.rows
- 1);
1396 * Deregisters a link matcher if it has been registered.
1397 * @param {number} matcherId The link matcher's ID (returned after register)
1399 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1400 if (this.linkifier
) {
1401 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1402 this.refresh(0, this.rows
- 1);
1408 * Gets whether the terminal has an active selection.
1410 Terminal
.prototype.hasSelection = function() {
1411 return this.selectionManager
? this.selectionManager
.hasSelection
: false;
1415 * Gets the terminal's current selection, this is useful for implementing copy
1416 * behavior outside of xterm.js.
1418 Terminal
.prototype.getSelection = function() {
1419 return this.selectionManager
? this.selectionManager
.selectionText
: '';
1423 * Clears the current terminal selection.
1425 Terminal
.prototype.clearSelection = function() {
1426 if (this.selectionManager
) {
1427 this.selectionManager
.clearSelection();
1432 * Selects all text within the terminal.
1434 Terminal
.prototype.selectAll = function() {
1435 if (this.selectionManager
) {
1436 this.selectionManager
.selectAll();
1441 * Handle a keydown event
1443 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1444 * @param {KeyboardEvent} ev The keydown event to be handled.
1446 Terminal
.prototype.keyDown = function(ev
) {
1447 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1451 this.restartCursorBlinking();
1453 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1454 if (this.buffer
.ybase
!== this.buffer
.ydisp
) {
1455 this.scrollToBottom();
1461 var result
= this.evaluateKeyEscapeSequence(ev
);
1463 if (result
.key
=== C0
.DC3
) { // XOFF
1464 this.writeStopped
= true;
1465 } else if (result
.key
=== C0
.DC1
) { // XON
1466 this.writeStopped
= false;
1469 if (result
.scrollDisp
) {
1470 this.scrollDisp(result
.scrollDisp
);
1471 return this.cancel(ev
, true);
1474 if (isThirdLevelShift(this, ev
)) {
1478 if (result
.cancel
) {
1479 // The event is canceled at the end already, is this necessary?
1480 this.cancel(ev
, true);
1487 this.emit('keydown', ev
);
1488 this.emit('key', result
.key
, ev
);
1490 this.handler(result
.key
);
1492 return this.cancel(ev
, true);
1496 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1497 * returned value is the new key code to pass to the PTY.
1499 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1500 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1502 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1504 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1505 // canceled at the end of keyDown
1507 // The new key even to emit
1509 // The number of characters to scroll, if this is defined it will cancel the event
1510 scrollDisp
: undefined
1512 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1513 switch (ev
.keyCode
) {
1517 result
.key
= C0
.BS
; // ^H
1520 result
.key
= C0
.DEL
; // ^?
1525 result
.key
= C0
.ESC
+ '[Z';
1529 result
.cancel
= true;
1534 result
.cancel
= true;
1538 result
.key
= C0
.ESC
;
1539 result
.cancel
= true;
1544 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1545 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1546 // http://unix.stackexchange.com/a/108106
1547 // macOS uses different escape sequences than linux
1548 if (result
.key
== C0
.ESC
+ '[1;3D') {
1549 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1551 } else if (this.applicationCursor
) {
1552 result
.key
= C0
.ESC
+ 'OD';
1554 result
.key
= C0
.ESC
+ '[D';
1560 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1561 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1562 // http://unix.stackexchange.com/a/108106
1563 // macOS uses different escape sequences than linux
1564 if (result
.key
== C0
.ESC
+ '[1;3C') {
1565 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1567 } else if (this.applicationCursor
) {
1568 result
.key
= C0
.ESC
+ 'OC';
1570 result
.key
= C0
.ESC
+ '[C';
1576 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1577 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1578 // http://unix.stackexchange.com/a/108106
1579 if (result
.key
== C0
.ESC
+ '[1;3A') {
1580 result
.key
= C0
.ESC
+ '[1;5A';
1582 } else if (this.applicationCursor
) {
1583 result
.key
= C0
.ESC
+ 'OA';
1585 result
.key
= C0
.ESC
+ '[A';
1591 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1592 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1593 // http://unix.stackexchange.com/a/108106
1594 if (result
.key
== C0
.ESC
+ '[1;3B') {
1595 result
.key
= C0
.ESC
+ '[1;5B';
1597 } else if (this.applicationCursor
) {
1598 result
.key
= C0
.ESC
+ 'OB';
1600 result
.key
= C0
.ESC
+ '[B';
1605 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1606 // <Ctrl> or <Shift> + <Insert> are used to
1607 // copy-paste on some systems.
1608 result
.key
= C0
.ESC
+ '[2~';
1614 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1616 result
.key
= C0
.ESC
+ '[3~';
1622 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1623 else if (this.applicationCursor
)
1624 result
.key
= C0
.ESC
+ 'OH';
1626 result
.key
= C0
.ESC
+ '[H';
1631 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1632 else if (this.applicationCursor
)
1633 result
.key
= C0
.ESC
+ 'OF';
1635 result
.key
= C0
.ESC
+ '[F';
1640 result
.scrollDisp
= -(this.rows
- 1);
1642 result
.key
= C0
.ESC
+ '[5~';
1648 result
.scrollDisp
= this.rows
- 1;
1650 result
.key
= C0
.ESC
+ '[6~';
1656 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1658 result
.key
= C0
.ESC
+ 'OP';
1663 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1665 result
.key
= C0
.ESC
+ 'OQ';
1670 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1672 result
.key
= C0
.ESC
+ 'OR';
1677 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1679 result
.key
= C0
.ESC
+ 'OS';
1684 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1686 result
.key
= C0
.ESC
+ '[15~';
1691 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1693 result
.key
= C0
.ESC
+ '[17~';
1698 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1700 result
.key
= C0
.ESC
+ '[18~';
1705 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1707 result
.key
= C0
.ESC
+ '[19~';
1712 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1714 result
.key
= C0
.ESC
+ '[20~';
1719 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1721 result
.key
= C0
.ESC
+ '[21~';
1726 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1728 result
.key
= C0
.ESC
+ '[23~';
1733 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1735 result
.key
= C0
.ESC
+ '[24~';
1740 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1741 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1742 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1743 } else if (ev
.keyCode
=== 32) {
1745 result
.key
= String
.fromCharCode(0);
1746 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1747 // escape, file sep, group sep, record sep, unit sep
1748 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1749 } else if (ev
.keyCode
=== 56) {
1751 result
.key
= String
.fromCharCode(127);
1752 } else if (ev
.keyCode
=== 219) {
1753 // ^[ - Control Sequence Introducer (CSI)
1754 result
.key
= String
.fromCharCode(27);
1755 } else if (ev
.keyCode
=== 220) {
1756 // ^\ - String Terminator (ST)
1757 result
.key
= String
.fromCharCode(28);
1758 } else if (ev
.keyCode
=== 221) {
1759 // ^] - Operating System Command (OSC)
1760 result
.key
= String
.fromCharCode(29);
1762 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1763 // On Mac this is a third level shift. Use <Esc> instead.
1764 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1765 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1766 } else if (ev
.keyCode
=== 192) {
1767 result
.key
= C0
.ESC
+ '`';
1768 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1769 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1771 } else if (this.browser
.isMac
&& !ev
.altKey
&& !ev
.ctrlKey
&& ev
.metaKey
) {
1772 if (ev
.keyCode
=== 65) { // cmd + a
1783 * Set the G level of the terminal
1786 Terminal
.prototype.setgLevel = function(g
) {
1788 this.charset
= this.charsets
[g
];
1792 * Set the charset for the given G level of the terminal
1796 Terminal
.prototype.setgCharset = function(g
, charset
) {
1797 this.charsets
[g
] = charset
;
1798 if (this.glevel
=== g
) {
1799 this.charset
= charset
;
1804 * Handle a keypress event.
1806 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1807 * @param {KeyboardEvent} ev The keypress event to be handled.
1809 Terminal
.prototype.keyPress = function(ev
) {
1812 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1820 } else if (ev
.which
== null) {
1822 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1829 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1834 key
= String
.fromCharCode(key
);
1836 this.emit('keypress', key
, ev
);
1837 this.emit('key', key
, ev
);
1845 * Send data for handling to the terminal
1846 * @param {string} data
1848 Terminal
.prototype.send = function(data
) {
1852 setTimeout(function() {
1853 self
.handler(self
.queue
);
1863 * Note: We could do sweet things with webaudio here
1865 Terminal
.prototype.bell = function() {
1866 if (!this.visualBell
) return;
1868 this.element
.style
.borderColor
= 'white';
1869 setTimeout(function() {
1870 self
.element
.style
.borderColor
= '';
1872 if (this.popOnBell
) this.focus();
1876 * Log the current state to the console.
1878 Terminal
.prototype.log = function() {
1879 if (!this.debug
) return;
1880 if (!this.context
.console
|| !this.context
.console
.log
) return;
1881 var args
= Array
.prototype.slice
.call(arguments
);
1882 this.context
.console
.log
.apply(this.context
.console
, args
);
1886 * Log the current state as error to the console.
1888 Terminal
.prototype.error = function() {
1889 if (!this.debug
) return;
1890 if (!this.context
.console
|| !this.context
.console
.error
) return;
1891 var args
= Array
.prototype.slice
.call(arguments
);
1892 this.context
.console
.error
.apply(this.context
.console
, args
);
1896 * Resizes the terminal.
1898 * @param {number} x The number of columns to resize to.
1899 * @param {number} y The number of rows to resize to.
1901 Terminal
.prototype.resize = function(x
, y
) {
1902 if (isNaN(x
) || isNaN(y
)) {
1906 if (y
> this.getOption('scrollback')) {
1907 this.setOption('scrollback', y
)
1917 if (x
=== this.cols
&& y
=== this.rows
) {
1918 // Check if we still need to measure the char size (fixes #785).
1919 if (!this.charMeasure
.width
|| !this.charMeasure
.height
) {
1920 this.charMeasure
.measure();
1928 this.buffers
.resize(x
, y
);
1930 // Adjust rows in the DOM to accurately reflect the new dimensions
1931 while (this.children
.length
< y
) {
1934 while (this.children
.length
> y
) {
1935 el
= this.children
.shift();
1937 el
.parentNode
.removeChild(el
);
1942 this.setupStops(this.cols
);
1944 this.charMeasure
.measure();
1946 this.refresh(0, this.rows
- 1);
1948 this.geometry
= [this.cols
, this.rows
];
1949 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
1953 * Updates the range of rows to refresh
1954 * @param {number} y The number of rows to refresh next.
1956 Terminal
.prototype.updateRange = function(y
) {
1957 if (y
< this.refreshStart
) this.refreshStart
= y
;
1958 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
1959 // if (y > this.refreshEnd) {
1960 // this.refreshEnd = y;
1961 // if (y > this.rows - 1) {
1962 // this.refreshEnd = this.rows - 1;
1968 * Set the range of refreshing to the maximum value
1970 Terminal
.prototype.maxRange = function() {
1971 this.refreshStart
= 0;
1972 this.refreshEnd
= this.rows
- 1;
1978 * Setup the tab stops.
1981 Terminal
.prototype.setupStops = function(i
) {
1983 if (!this.buffer
.tabs
[i
]) {
1984 i
= this.prevStop(i
);
1987 this.buffer
.tabs
= {};
1991 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
1992 this.buffer
.tabs
[i
] = true;
1998 * Move the cursor to the previous tab stop from the given position (default is current).
1999 * @param {number} x The position to move the cursor to the previous tab stop.
2001 Terminal
.prototype.prevStop = function(x
) {
2002 if (x
== null) x
= this.buffer
.x
;
2003 while (!this.buffer
.tabs
[--x
] && x
> 0);
2004 return x
>= this.cols
2011 * Move the cursor one tab stop forward from the given position (default is current).
2012 * @param {number} x The position to move the cursor one tab stop forward.
2014 Terminal
.prototype.nextStop = function(x
) {
2015 if (x
== null) x
= this.buffer
.x
;
2016 while (!this.buffer
.tabs
[++x
] && x
< this.cols
);
2017 return x
>= this.cols
2024 * Erase in the identified line everything from "x" to the end of the line (right).
2025 * @param {number} x The column from which to start erasing to the end of the line.
2026 * @param {number} y The line in which to operate.
2028 Terminal
.prototype.eraseRight = function(x
, y
) {
2029 var line
= this.buffer
.lines
.get(this.buffer
.ybase
+ y
);
2033 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2034 for (; x
< this.cols
; x
++) {
2037 this.updateRange(y
);
2043 * Erase in the identified line everything from "x" to the start of the line (left).
2044 * @param {number} x The column from which to start erasing to the start of the line.
2045 * @param {number} y The line in which to operate.
2047 Terminal
.prototype.eraseLeft = function(x
, y
) {
2048 var line
= this.buffer
.lines
.get(this.buffer
.ybase
+ y
);
2052 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2057 this.updateRange(y
);
2061 * Clears the entire buffer, making the prompt line the new first line.
2063 Terminal
.prototype.clear = function() {
2064 if (this.buffer
.ybase
=== 0 && this.buffer
.y
=== 0) {
2065 // Don't clear if it's already clear
2068 this.buffer
.lines
.set(0, this.buffer
.lines
.get(this.buffer
.ybase
+ this.buffer
.y
));
2069 this.buffer
.lines
.length
= 1;
2070 this.buffer
.ydisp
= 0;
2071 this.buffer
.ybase
= 0;
2073 for (var i
= 1; i
< this.rows
; i
++) {
2074 this.buffer
.lines
.push(this.blankLine());
2076 this.refresh(0, this.rows
- 1);
2077 this.emit('scroll', this.buffer
.ydisp
);
2081 * Erase all content in the given line
2082 * @param {number} y The line to erase all of its contents.
2084 Terminal
.prototype.eraseLine = function(y
) {
2085 this.eraseRight(0, y
);
2090 * Return the data array of a blank line
2091 * @param {number} cur First bunch of data for each "blank" character.
2092 * @param {boolean} isWrapped Whether the new line is wrapped from the previous line.
2094 Terminal
.prototype.blankLine = function(cur
, isWrapped
, cols
) {
2099 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2103 // TODO: It is not ideal that this is a property on an array, a buffer line
2104 // class should be added that will hold this data and other useful functions.
2106 line
.isWrapped
= isWrapped
;
2109 cols
= cols
|| this.cols
;
2110 for (; i
< cols
; i
++) {
2119 * If cur return the back color xterm feature attribute. Else return defAttr.
2120 * @param {object} cur
2122 Terminal
.prototype.ch = function(cur
) {
2124 ? [this.eraseAttr(), ' ', 1]
2125 : [this.defAttr
, ' ', 1];
2130 * Evaluate if the current terminal is the given argument.
2131 * @param {object} term The terminal to evaluate
2133 Terminal
.prototype.is = function(term
) {
2134 var name
= this.termName
;
2135 return (name
+ '').indexOf(term
) === 0;
2140 * Emit the 'data' event and populate the given data.
2141 * @param {string} data The data to populate in the event.
2143 Terminal
.prototype.handler = function(data
) {
2144 // Prevents all events to pty process if stdin is disabled
2145 if (this.options
.disableStdin
) {
2149 // Clear the selection if the selection manager is available and has an active selection
2150 if (this.selectionManager
&& this.selectionManager
.hasSelection
) {
2151 this.selectionManager
.clearSelection();
2154 // Input is being sent to the terminal, the terminal should focus the prompt.
2155 if (this.buffer
.ybase
!== this.buffer
.ydisp
) {
2156 this.scrollToBottom();
2158 this.emit('data', data
);
2163 * Emit the 'title' event and populate the given title.
2164 * @param {string} title The title to populate in the event.
2166 Terminal
.prototype.handleTitle = function(title
) {
2168 * This event is emitted when the title of the terminal is changed
2169 * from inside the terminal. The parameter is the new title.
2173 this.emit('title', title
);
2182 * ESC D Index (IND is 0x84).
2184 Terminal
.prototype.index = function() {
2186 if (this.buffer
.y
> this.buffer
.scrollBottom
) {
2190 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2191 if (this.buffer
.x
>= this.cols
) {
2198 * ESC M Reverse Index (RI is 0x8d).
2200 * Move the cursor up one row, inserting a new blank line if necessary.
2202 Terminal
.prototype.reverseIndex = function() {
2204 if (this.buffer
.y
=== this.buffer
.scrollTop
) {
2205 // possibly move the code below to term.reverseScroll();
2206 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2207 // blankLine(true) is xterm/linux behavior
2208 this.buffer
.lines
.shiftElements(this.buffer
.y
+ this.buffer
.ybase
, this.rows
- 1, 1);
2209 this.buffer
.lines
.set(this.buffer
.y
+ this.buffer
.ybase
, this.blankLine(true));
2210 this.updateRange(this.buffer
.scrollTop
);
2211 this.updateRange(this.buffer
.scrollBottom
);
2219 * ESC c Full Reset (RIS).
2221 Terminal
.prototype.reset = function() {
2222 this.options
.rows
= this.rows
;
2223 this.options
.cols
= this.cols
;
2224 var customKeyEventHandler
= this.customKeyEventHandler
;
2225 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2226 var inputHandler
= this.inputHandler
;
2227 Terminal
.call(this, this.options
);
2228 this.customKeyEventHandler
= customKeyEventHandler
;
2229 this.cursorBlinkInterval
= cursorBlinkInterval
;
2230 this.inputHandler
= inputHandler
;
2231 this.refresh(0, this.rows
- 1);
2232 this.viewport
.syncScrollArea();
2237 * ESC H Tab Set (HTS is 0x88).
2239 Terminal
.prototype.tabSet = function() {
2240 this.buffer
.tabs
[this.buffer
.x
] = true;
2247 function on(el
, type
, handler
, capture
) {
2248 if (!Array
.isArray(el
)) {
2251 el
.forEach(function (element
) {
2252 element
.addEventListener(type
, handler
, capture
|| false);
2256 function off(el
, type
, handler
, capture
) {
2257 el
.removeEventListener(type
, handler
, capture
|| false);
2260 function cancel(ev
, force
) {
2261 if (!this.cancelEvents
&& !force
) {
2264 ev
.preventDefault();
2265 ev
.stopPropagation();
2269 function inherits(child
, parent
) {
2271 this.constructor = child
;
2273 f
.prototype = parent
.prototype;
2274 child
.prototype = new f
;
2277 function indexOf(obj
, el
) {
2280 if (obj
[i
] === el
) return i
;
2285 function isThirdLevelShift(term
, ev
) {
2287 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2288 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2290 if (ev
.type
== 'keypress') {
2291 return thirdLevelKey
;
2294 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2295 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2298 // Expose to InputHandler (temporary)
2299 Terminal
.prototype.matchColor
= matchColor
;
2301 function matchColor(r1
, g1
, b1
) {
2302 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2304 if (matchColor
._cache
[hash
] != null) {
2305 return matchColor
._cache
[hash
];
2308 var ldiff
= Infinity
2317 for (; i
< Terminal
.vcolors
.length
; i
++) {
2318 c
= Terminal
.vcolors
[i
];
2323 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2336 return matchColor
._cache
[hash
] = li
;
2339 matchColor
._cache
= {};
2341 // http://stackoverflow.com/questions/1633828
2342 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2343 return Math
.pow(30 * (r1
- r2
), 2)
2344 + Math
.pow(59 * (g1
- g2
), 2)
2345 + Math
.pow(11 * (b1
- b2
), 2);
2348 function each(obj
, iter
, con
) {
2349 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2350 for (var i
= 0; i
< obj
.length
; i
++) {
2351 iter
.call(con
, obj
[i
], i
, obj
);
2355 function wasMondifierKeyOnlyEvent(ev
) {
2356 return ev
.keyCode
=== 16 || // Shift
2357 ev
.keyCode
=== 17 || // Ctrl
2358 ev
.keyCode
=== 18; // Alt
2361 function keys(obj
) {
2362 if (Object
.keys
) return Object
.keys(obj
);
2365 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2376 Terminal
.translateBufferLineToString
= translateBufferLineToString
;
2377 Terminal
.EventEmitter
= EventEmitter
;
2378 Terminal
.inherits
= inherits
;
2381 * Adds an event listener to the terminal.
2383 * @param {string} event The name of the event. TODO: Document all event types
2384 * @param {function} callback The function to call when the event is triggered.
2388 Terminal
.cancel
= cancel
;
2390 module
.exports
= Terminal
;