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
225 this.buffers
= new BufferSet(this);
226 this.buffer
= this.buffers
.active
; // Convenience shortcut;
228 this.buffers
.on('activate', function (buffer
) {
229 this._terminal
.buffer
= buffer
;
233 * An array of all lines in the entire buffer, including the prompt. The lines are array of
234 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
239 this.buffer
.lines
.push(this.blankLine());
241 // Ensure the selection manager has the correct buffer
242 if (this.selectionManager
) {
243 this.selectionManager
.setBuffer(this.buffer
.lines
);
248 // Store if user went browsing history in scrollback
249 this.userScrolling
= false;
252 inherits(Terminal
, EventEmitter
);
255 * back_color_erase feature for xterm.
257 Terminal
.prototype.eraseAttr = function() {
258 // if (this.is('screen')) return this.defAttr;
259 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
267 Terminal
.tangoColors
= [
288 // Colors 0-15 + 16-255
289 // Much thanks to TooTallNate for writing this.
290 Terminal
.colors
= (function() {
291 var colors
= Terminal
.tangoColors
.slice()
292 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
297 for (; i
< 216; i
++) {
298 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
303 for (; i
< 24; i
++) {
308 function out(r
, g
, b
) {
309 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
314 return c
.length
< 2 ? '0' + c
: c
;
320 Terminal
._colors
= Terminal
.colors
.slice();
322 Terminal
.vcolors
= (function() {
324 , colors
= Terminal
.colors
328 for (; i
< 256; i
++) {
329 color
= parseInt(colors
[i
].substring(1), 16);
331 (color
>> 16) & 0xff,
344 Terminal
.defaults
= {
345 colors
: Terminal
.colors
,
351 cursorStyle
: 'block',
359 useFlowControl
: false,
361 // programFeatures: false,
365 Terminal
.options
= {};
367 Terminal
.focus
= null;
369 each(keys(Terminal
.defaults
), function(key
) {
370 Terminal
[key
] = Terminal
.defaults
[key
];
371 Terminal
.options
[key
] = Terminal
.defaults
[key
];
375 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
377 Terminal
.prototype.focus = function() {
378 return this.textarea
.focus();
382 * Retrieves an option's value from the terminal.
383 * @param {string} key The option key.
385 Terminal
.prototype.getOption = function(key
) {
386 if (!(key
in Terminal
.defaults
)) {
387 throw new Error('No option with key "' + key
+ '"');
390 if (typeof this.options
[key
] !== 'undefined') {
391 return this.options
[key
];
398 * Sets an option on the terminal.
399 * @param {string} key The option key.
400 * @param {string} value The option value.
402 Terminal
.prototype.setOption = function(key
, value
) {
403 if (!(key
in Terminal
.defaults
)) {
404 throw new Error('No option with key "' + key
+ '"');
408 if (value
< this.rows
) {
409 let msg
= 'Setting the scrollback value less than the number of rows ';
411 msg
+= `(${this.rows}) is not allowed.`;
417 if (this.options
[key
] !== value
) {
418 if (this.buffer
.length
> value
) {
419 const amountToTrim
= this.buffer
.lines
.length
- value
;
420 const needsRefresh
= (this.buffer
.ydisp
- amountToTrim
< 0);
421 this.buffer
.lines
.trimStart(amountToTrim
);
422 this.buffer
.ybase
= Math
.max(this.buffer
.ybase
- amountToTrim
, 0);
423 this.buffer
.ydisp
= Math
.max(this.buffer
.ydisp
- amountToTrim
, 0);
425 this.refresh(0, this.rows
- 1);
428 this.buffer
.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', event
=> {
524 // If mouse events are active it means the selection manager is disabled and
525 // copy should be handled by the host program.
526 if (this.mouseEvents
) {
529 copyHandler(event
, term
, this.selectionManager
);
531 const pasteHandlerWrapper
= event
=> pasteHandler(event
, term
);
532 on(this.textarea
, 'paste', pasteHandlerWrapper
);
533 on(this.element
, 'paste', pasteHandlerWrapper
);
535 // Handle right click context menus
536 if (term
.browser
.isFirefox
) {
537 // Firefox doesn't appear to fire the contextmenu event on right click
538 on(this.element
, 'mousedown', event
=> {
539 if (event
.button
== 2) {
540 rightClickHandler(event
, this.textarea
, this.selectionManager
);
544 on(this.element
, 'contextmenu', event
=> {
545 rightClickHandler(event
, this.textarea
, this.selectionManager
);
549 // Move the textarea under the cursor when middle clicking on Linux to ensure
550 // middle click to paste selection works. This only appears to work in Chrome
551 // at the time is writing.
552 if (term
.browser
.isLinux
) {
553 // Use auxclick event over mousedown the latter doesn't seem to work. Note
554 // that the regular click event doesn't fire for the middle mouse button.
555 on(this.element
, 'auxclick', event
=> {
556 if (event
.button
=== 1) {
557 moveTextAreaUnderMouseCursor(event
, this.textarea
, this.selectionManager
);
564 * Apply key handling to the terminal
566 Terminal
.bindKeys = function(term
) {
567 on(term
.element
, 'keydown', function(ev
) {
568 if (document
.activeElement
!= this) {
574 on(term
.element
, 'keypress', function(ev
) {
575 if (document
.activeElement
!= this) {
581 on(term
.element
, 'keyup', function(ev
) {
582 if (!wasMondifierKeyOnlyEvent(ev
)) {
587 on(term
.textarea
, 'keydown', function(ev
) {
591 on(term
.textarea
, 'keypress', function(ev
) {
593 // Truncate the textarea's value, since it is not needed
597 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
598 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
599 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
600 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
601 term
.on('refresh', function (data
) {
602 term
.queueLinkification(data
.start
, data
.end
)
608 * Insert the given row to the terminal or produce a new one
609 * if no row argument is passed. Return the inserted row.
610 * @param {HTMLElement} row (optional) The row to append to the terminal.
612 Terminal
.prototype.insertRow = function (row
) {
613 if (typeof row
!= 'object') {
614 row
= document
.createElement('div');
617 this.rowContainer
.appendChild(row
);
618 this.children
.push(row
);
624 * Opens the terminal within an element.
626 * @param {HTMLElement} parent The element to create the terminal within.
627 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
629 Terminal
.prototype.open = function(parent
, focus
) {
630 var self
=this, i
=0, div
;
632 this.parent
= parent
|| this.parent
;
635 throw new Error('Terminal requires a parent element.');
638 // Grab global elements
639 this.context
= this.parent
.ownerDocument
.defaultView
;
640 this.document
= this.parent
.ownerDocument
;
641 this.body
= this.document
.getElementsByTagName('body')[0];
643 //Create main element container
644 this.element
= this.document
.createElement('div');
645 this.element
.classList
.add('terminal');
646 this.element
.classList
.add('xterm');
647 this.element
.classList
.add('xterm-theme-' + this.theme
);
648 this.setCursorBlinking(this.options
.cursorBlink
);
650 this.element
.setAttribute('tabindex', 0);
652 this.viewportElement
= document
.createElement('div');
653 this.viewportElement
.classList
.add('xterm-viewport');
654 this.element
.appendChild(this.viewportElement
);
655 this.viewportScrollArea
= document
.createElement('div');
656 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
657 this.viewportElement
.appendChild(this.viewportScrollArea
);
659 // Create the selection container.
660 this.selectionContainer
= document
.createElement('div');
661 this.selectionContainer
.classList
.add('xterm-selection');
662 this.element
.appendChild(this.selectionContainer
);
664 // Create the container that will hold the lines of the terminal and then
665 // produce the lines the lines.
666 this.rowContainer
= document
.createElement('div');
667 this.rowContainer
.classList
.add('xterm-rows');
668 this.element
.appendChild(this.rowContainer
);
670 this.linkifier
.attachToDom(document
, this.children
);
672 // Create the container that will hold helpers like the textarea for
673 // capturing DOM Events. Then produce the helpers.
674 this.helperContainer
= document
.createElement('div');
675 this.helperContainer
.classList
.add('xterm-helpers');
676 // TODO: This should probably be inserted once it's filled to prevent an additional layout
677 this.element
.appendChild(this.helperContainer
);
678 this.textarea
= document
.createElement('textarea');
679 this.textarea
.classList
.add('xterm-helper-textarea');
680 this.textarea
.setAttribute('autocorrect', 'off');
681 this.textarea
.setAttribute('autocapitalize', 'off');
682 this.textarea
.setAttribute('spellcheck', 'false');
683 this.textarea
.tabIndex
= 0;
684 this.textarea
.addEventListener('focus', function() {
685 self
.emit('focus', {terminal
: self
});
687 this.textarea
.addEventListener('blur', function() {
688 self
.emit('blur', {terminal
: self
});
690 this.helperContainer
.appendChild(this.textarea
);
692 this.compositionView
= document
.createElement('div');
693 this.compositionView
.classList
.add('composition-view');
694 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
695 this.helperContainer
.appendChild(this.compositionView
);
697 this.charSizeStyleElement
= document
.createElement('style');
698 this.helperContainer
.appendChild(this.charSizeStyleElement
);
700 for (; i
< this.rows
; i
++) {
703 this.parent
.appendChild(this.element
);
705 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
706 this.charMeasure
.on('charsizechanged', function () {
707 self
.updateCharSizeStyles();
709 this.charMeasure
.measure();
711 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
712 this.renderer
= new Renderer(this);
713 this.selectionManager
= new SelectionManager(this, this.buffer
.lines
, this.rowContainer
, this.charMeasure
);
714 this.selectionManager
.on('refresh', data
=> {
715 this.renderer
.refreshSelection(data
.start
, data
.end
);
717 this.selectionManager
.on('newselection', text
=> {
718 // If there's a new selection, put it into the textarea, focus and select it
719 // in order to register it as a selection on the OS. This event is fired
720 // only on Linux to enable middle click to paste selection.
721 this.textarea
.value
= text
;
722 this.textarea
.focus();
723 this.textarea
.select();
725 this.on('scroll', () => this.selectionManager
.refresh());
726 this.viewportElement
.addEventListener('scroll', () => this.selectionManager
.refresh());
728 // Setup loop that draws to screen
729 this.refresh(0, this.rows
- 1);
731 // Initialize global actions that
732 // need to be taken on the document.
736 * Automatic focus functionality.
737 * TODO: Default to `false` starting with xterm.js 3.0.
739 if (typeof focus
== 'undefined') {
740 let message
= 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
742 message
+= 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
743 message
+= 'it will default to `false`.';
745 console
.warn(message
);
753 on(this.element
, 'click', function() {
754 var selection
= document
.getSelection(),
755 collapsed
= selection
.isCollapsed
,
756 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
762 // Listen for mouse events and translate
763 // them into terminal mouse protocols.
767 * This event is emitted when terminal has completed opening.
776 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
777 * @param {string} addon The name of the addon to load
780 Terminal
.loadAddon = function(addon
, callback
) {
781 if (typeof exports
=== 'object' && typeof module
=== 'object') {
783 return require('./addons/' + addon
+ '/' + addon
);
784 } else if (typeof define
== 'function') {
786 return require(['./addons/' + addon
+ '/' + addon
], callback
);
788 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
794 * Updates the helper CSS class with any changes necessary after the terminal's
795 * character width has been changed.
797 Terminal
.prototype.updateCharSizeStyles = function() {
798 this.charSizeStyleElement
.textContent
=
799 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
800 `.xterm-normal-char{width:${this.charMeasure.width}px;}` +
801 `.xterm-rows > div{height:${this.charMeasure.height}px;}`;
806 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
807 * To better understand these
808 * the xterm code is very helpful:
810 * button.c, charproc.c, misc.c
811 * Relevant functions in xterm/button.c:
812 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
814 Terminal
.prototype.bindMouse = function() {
815 var el
= this.element
, self
= this, pressed
= 32;
817 // mouseup, mousedown, wheel
818 // left click: ^[[M 3<^[[M#3<
820 function sendButton(ev
) {
824 // get the xterm-style button
825 button
= getButton(ev
);
827 // get mouse coordinates
828 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
831 sendEvent(button
, pos
);
833 switch (ev
.overrideType
|| ev
.type
) {
838 // keep it at the left
839 // button, just in case.
850 // motion example of a left click:
851 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
852 function sendMove(ev
) {
856 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
859 // buttons marked as motions
860 // are incremented by 32
863 sendEvent(button
, pos
);
867 // position to characters
868 function encode(data
, ch
) {
869 if (!self
.utfMouse
) {
870 if (ch
=== 255) return data
.push(0);
871 if (ch
> 127) ch
= 127;
874 if (ch
=== 2047) return data
.push(0);
878 if (ch
> 2047) ch
= 2047;
879 data
.push(0xC0 | (ch
>> 6));
880 data
.push(0x80 | (ch
& 0x3F));
885 // send a mouse event:
886 // regular/utf8: ^[[M Cb Cx Cy
887 // urxvt: ^[[ Cb ; Cx ; Cy M
888 // sgr: ^[[ Cb ; Cx ; Cy M/m
889 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
890 // locator: CSI P e ; P b ; P r ; P c ; P p & w
891 function sendEvent(button
, pos
) {
892 // self.emit('mouse', {
898 if (self
.vt300Mouse
) {
900 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
904 var data
= C0
.ESC
+ '[24';
905 if (button
=== 0) data
+= '1';
906 else if (button
=== 1) data
+= '3';
907 else if (button
=== 2) data
+= '5';
908 else if (button
=== 3) return;
910 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
915 if (self
.decLocator
) {
920 if (button
=== 0) button
= 2;
921 else if (button
=== 1) button
= 4;
922 else if (button
=== 2) button
= 6;
923 else if (button
=== 3) button
= 3;
924 self
.send(C0
.ESC
+ '['
927 + (button
=== 3 ? 4 : 0)
938 if (self
.urxvtMouse
) {
943 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
950 self
.send(C0
.ESC
+ '[<'
951 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
956 + ((button
& 3) === 3 ? 'm' : 'M'));
962 encode(data
, button
);
966 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
969 function getButton(ev
) {
982 // 1, and 2 - with 64 added
983 switch (ev
.overrideType
|| ev
.type
) {
985 button
= ev
.button
!= null
991 if (self
.browser
.isMSIE
) {
992 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
998 case 'DOMMouseScroll':
999 button
= ev
.detail
< 0
1004 button
= ev
.wheelDeltaY
> 0
1010 // next three bits are the modifiers:
1011 // 4 = shift, 8 = meta, 16 = control
1012 shift
= ev
.shiftKey
? 4 : 0;
1013 meta
= ev
.metaKey
? 8 : 0;
1014 ctrl
= ev
.ctrlKey
? 16 : 0;
1015 mod
= shift
| meta
| ctrl
;
1018 if (self
.vt200Mouse
) {
1021 } else if (!self
.normalMouse
) {
1026 button
= (32 + (mod
<< 2)) + button
;
1031 on(el
, 'mousedown', function(ev
) {
1032 if (!self
.mouseEvents
) return;
1041 //if (self.vt200Mouse && !self.normalMouse) {
1042 if (self
.vt200Mouse
) {
1043 ev
.overrideType
= 'mouseup';
1045 return self
.cancel(ev
);
1049 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1051 // x10 compatibility mode can't send button releases
1052 if (!self
.x10Mouse
) {
1053 on(self
.document
, 'mouseup', function up(ev
) {
1055 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1056 off(self
.document
, 'mouseup', up
);
1057 return self
.cancel(ev
);
1061 return self
.cancel(ev
);
1064 //if (self.normalMouse) {
1065 // on(self.document, 'mousemove', sendMove);
1068 on(el
, 'wheel', function(ev
) {
1069 if (!self
.mouseEvents
) return;
1072 || self
.decLocator
) return;
1074 return self
.cancel(ev
);
1077 // allow wheel scrolling in
1078 // the shell for example
1079 on(el
, 'wheel', function(ev
) {
1080 if (self
.mouseEvents
) return;
1081 self
.viewport
.onWheel(ev
);
1082 return self
.cancel(ev
);
1085 on(el
, 'touchstart', function(ev
) {
1086 if (self
.mouseEvents
) return;
1087 self
.viewport
.onTouchStart(ev
);
1088 return self
.cancel(ev
);
1091 on(el
, 'touchmove', function(ev
) {
1092 if (self
.mouseEvents
) return;
1093 self
.viewport
.onTouchMove(ev
);
1094 return self
.cancel(ev
);
1099 * Destroys the terminal.
1101 Terminal
.prototype.destroy = function() {
1102 this.readable
= false;
1103 this.writable
= false;
1105 this.handler = function() {};
1106 this.write = function() {};
1107 if (this.element
&& this.element
.parentNode
) {
1108 this.element
.parentNode
.removeChild(this.element
);
1110 //this.emit('close');
1114 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1116 * @param {number} start The row to start from (between 0 and this.rows - 1).
1117 * @param {number} end The row to end at (between start and this.rows - 1).
1119 Terminal
.prototype.refresh = function(start
, end
) {
1120 if (this.renderer
) {
1121 this.renderer
.queueRefresh(start
, end
);
1126 * Queues linkification for the specified rows.
1127 * @param {number} start The row to start from (between 0 and this.rows - 1).
1128 * @param {number} end The row to end at (between start and this.rows - 1).
1130 Terminal
.prototype.queueLinkification = function(start
, end
) {
1131 if (this.linkifier
) {
1132 for (let i
= start
; i
<= end
; i
++) {
1133 this.linkifier
.linkifyRow(i
);
1139 * Display the cursor element
1141 Terminal
.prototype.showCursor = function() {
1142 if (!this.cursorState
) {
1143 this.cursorState
= 1;
1144 this.refresh(this.buffer
.y
, this.buffer
.y
);
1149 * Scroll the terminal down 1 row, creating a blank line.
1150 * @param {boolean} isWrapped Whether the new line is wrapped from the previous
1153 Terminal
.prototype.scroll = function(isWrapped
) {
1156 // Make room for the new row in lines
1157 if (this.buffer
.lines
.length
=== this.buffer
.lines
.maxLength
) {
1158 this.buffer
.lines
.trimStart(1);
1159 this.buffer
.ybase
--;
1160 if (this.buffer
.ydisp
!== 0) {
1161 this.buffer
.ydisp
--;
1165 this.buffer
.ybase
++;
1167 // TODO: Why is this done twice?
1168 if (!this.userScrolling
) {
1169 this.buffer
.ydisp
= this.buffer
.ybase
;
1173 row
= this.buffer
.ybase
+ this.rows
- 1;
1175 // subtract the bottom scroll region
1176 row
-= this.rows
- 1 - this.buffer
.scrollBottom
;
1178 if (row
=== this.buffer
.lines
.length
) {
1179 // Optimization: pushing is faster than splicing when they amount to the same behavior
1180 this.buffer
.lines
.push(this.blankLine(undefined, isWrapped
));
1183 this.buffer
.lines
.splice(row
, 0, this.blankLine(undefined, isWrapped
));
1186 if (this.buffer
.scrollTop
!== 0) {
1187 if (this.buffer
.ybase
!== 0) {
1188 this.buffer
.ybase
--;
1189 if (!this.userScrolling
) {
1190 this.buffer
.ydisp
= this.buffer
.ybase
;
1193 this.buffer
.lines
.splice(this.buffer
.ybase
+ this.buffer
.scrollTop
, 1);
1197 this.updateRange(this.buffer
.scrollTop
);
1198 this.updateRange(this.buffer
.scrollBottom
);
1201 * This event is emitted whenever the terminal is scrolled.
1202 * The one parameter passed is the new y display position.
1206 this.emit('scroll', this.buffer
.ydisp
);
1210 * Scroll the display of the terminal
1211 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1212 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1213 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1214 * viewport originally.
1216 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1218 if (this.buffer
.ydisp
=== 0) {
1221 this.userScrolling
= true;
1222 } else if (disp
+ this.buffer
.ydisp
>= this.buffer
.ybase
) {
1223 this.userScrolling
= false;
1226 const oldYdisp
= this.buffer
.ydisp
;
1227 this.buffer
.ydisp
= Math
.max(Math
.min(this.buffer
.ydisp
+ disp
, this.buffer
.ybase
), 0);
1229 // No change occurred, don't trigger scroll/refresh
1230 if (oldYdisp
=== this.buffer
.ydisp
) {
1234 if (!suppressScrollEvent
) {
1235 this.emit('scroll', this.buffer
.ydisp
);
1238 this.refresh(0, this.rows
- 1);
1242 * Scroll the display of the terminal by a number of pages.
1243 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1245 Terminal
.prototype.scrollPages = function(pageCount
) {
1246 this.scrollDisp(pageCount
* (this.rows
- 1));
1250 * Scrolls the display of the terminal to the top.
1252 Terminal
.prototype.scrollToTop = function() {
1253 this.scrollDisp(-this.buffer
.ydisp
);
1257 * Scrolls the display of the terminal to the bottom.
1259 Terminal
.prototype.scrollToBottom = function() {
1260 this.scrollDisp(this.buffer
.ybase
- this.buffer
.ydisp
);
1264 * Writes text to the terminal.
1265 * @param {string} data The text to write to the terminal.
1267 Terminal
.prototype.write = function(data
) {
1268 this.writeBuffer
.push(data
);
1270 // Send XOFF to pause the pty process if the write buffer becomes too large so
1271 // xterm.js can catch up before more data is sent. This is necessary in order
1272 // to keep signals such as ^C responsive.
1273 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1274 // XOFF - stop pty pipe
1275 // XON will be triggered by emulator before processing data chunk
1277 this.xoffSentToCatchUp
= true;
1280 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1281 // Kick off a write which will write all data in sequence recursively
1282 this.writeInProgress
= true;
1283 // Kick off an async innerWrite so more writes can come in while processing data
1285 setTimeout(function () {
1291 Terminal
.prototype.innerWrite = function() {
1292 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1293 while (writeBatch
.length
> 0) {
1294 var data
= writeBatch
.shift();
1295 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1297 // If XOFF was sent in order to catch up with the pty process, resume it if
1298 // the writeBuffer is empty to allow more data to come in.
1299 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1301 this.xoffSentToCatchUp
= false;
1304 this.refreshStart
= this.buffer
.y
;
1305 this.refreshEnd
= this.buffer
.y
;
1307 // HACK: Set the parser state based on it's state at the time of return.
1308 // This works around the bug #662 which saw the parser state reset in the
1309 // middle of parsing escape sequence in two chunks. For some reason the
1310 // state of the parser resets to 0 after exiting parser.parse. This change
1311 // just sets the state back based on the correct return statement.
1312 var state
= this.parser
.parse(data
);
1313 this.parser
.setState(state
);
1315 this.updateRange(this.buffer
.y
);
1316 this.refresh(this.refreshStart
, this.refreshEnd
);
1318 if (this.writeBuffer
.length
> 0) {
1319 // Allow renderer to catch up before processing the next batch
1321 setTimeout(function () {
1325 this.writeInProgress
= false;
1330 * Writes text to the terminal, followed by a break line character (\n).
1331 * @param {string} data The text to write to the terminal.
1333 Terminal
.prototype.writeln = function(data
) {
1334 this.write(data
+ '\r\n');
1338 * DEPRECATED: only for backward compatibility. Please use attachCustomKeyEventHandler() instead.
1339 * @param {function} customKeydownHandler 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.attachCustomKeydownHandler = function(customKeydownHandler
) {
1344 let message
= 'attachCustomKeydownHandler() is DEPRECATED and will be removed soon. Please use attachCustomKeyEventHandler() instead.';
1345 console
.warn(message
);
1346 this.attachCustomKeyEventHandler(customKeydownHandler
);
1350 * Attaches a custom key event handler which is run before keys are processed, giving consumers of
1351 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1353 * @param {function} customKeyEventHandler The custom KeyboardEvent handler to attach. This is a
1354 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1355 * the default action. The function returns whether the event should be processed by xterm.js.
1357 Terminal
.prototype.attachCustomKeyEventHandler = function(customKeyEventHandler
) {
1358 this.customKeyEventHandler
= customKeyEventHandler
;
1362 * Attaches a http(s) link handler, forcing web links to behave differently to
1363 * regular <a> tags. This will trigger a refresh as links potentially need to be
1364 * reconstructed. Calling this with null will remove the handler.
1365 * @param {LinkMatcherHandler} handler The handler callback function.
1367 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1368 if (!this.linkifier
) {
1369 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1371 this.linkifier
.setHypertextLinkHandler(handler
);
1372 // Refresh to force links to refresh
1373 this.refresh(0, this.rows
- 1);
1377 * Attaches a validation callback for hypertext links. This is useful to use
1378 * validation logic or to do something with the link's element and url.
1379 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1380 * be cleared with null.
1382 Terminal
.prototype.setHypertextValidationCallback = function(callback
) {
1383 if (!this.linkifier
) {
1384 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1386 this.linkifier
.setHypertextValidationCallback(callback
);
1387 // Refresh to force links to refresh
1388 this.refresh(0, this.rows
- 1);
1392 * Registers a link matcher, allowing custom link patterns to be matched and
1394 * @param {RegExp} regex The regular expression to search for, specifically
1395 * this searches the textContent of the rows. You will want to use \s to match
1396 * a space ' ' character for example.
1397 * @param {LinkMatcherHandler} handler The callback when the link is called.
1398 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1399 * @return {number} The ID of the new matcher, this can be used to deregister.
1401 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1402 if (this.linkifier
) {
1403 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1404 this.refresh(0, this.rows
- 1);
1410 * Deregisters a link matcher if it has been registered.
1411 * @param {number} matcherId The link matcher's ID (returned after register)
1413 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1414 if (this.linkifier
) {
1415 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1416 this.refresh(0, this.rows
- 1);
1422 * Gets whether the terminal has an active selection.
1424 Terminal
.prototype.hasSelection = function() {
1425 return this.selectionManager
? this.selectionManager
.hasSelection
: false;
1429 * Gets the terminal's current selection, this is useful for implementing copy
1430 * behavior outside of xterm.js.
1432 Terminal
.prototype.getSelection = function() {
1433 return this.selectionManager
? this.selectionManager
.selectionText
: '';
1437 * Clears the current terminal selection.
1439 Terminal
.prototype.clearSelection = function() {
1440 if (this.selectionManager
) {
1441 this.selectionManager
.clearSelection();
1446 * Selects all text within the terminal.
1448 Terminal
.prototype.selectAll = function() {
1449 if (this.selectionManager
) {
1450 this.selectionManager
.selectAll();
1455 * Handle a keydown event
1457 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1458 * @param {KeyboardEvent} ev The keydown event to be handled.
1460 Terminal
.prototype.keyDown = function(ev
) {
1461 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1465 this.restartCursorBlinking();
1467 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1468 if (this.buffer
.ybase
!== this.buffer
.ydisp
) {
1469 this.scrollToBottom();
1475 var result
= this.evaluateKeyEscapeSequence(ev
);
1477 if (result
.key
=== C0
.DC3
) { // XOFF
1478 this.writeStopped
= true;
1479 } else if (result
.key
=== C0
.DC1
) { // XON
1480 this.writeStopped
= false;
1483 if (result
.scrollDisp
) {
1484 this.scrollDisp(result
.scrollDisp
);
1485 return this.cancel(ev
, true);
1488 if (isThirdLevelShift(this, ev
)) {
1492 if (result
.cancel
) {
1493 // The event is canceled at the end already, is this necessary?
1494 this.cancel(ev
, true);
1501 this.emit('keydown', ev
);
1502 this.emit('key', result
.key
, ev
);
1504 this.handler(result
.key
);
1506 return this.cancel(ev
, true);
1510 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1511 * returned value is the new key code to pass to the PTY.
1513 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1514 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1516 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1518 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1519 // canceled at the end of keyDown
1521 // The new key even to emit
1523 // The number of characters to scroll, if this is defined it will cancel the event
1524 scrollDisp
: undefined
1526 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1527 switch (ev
.keyCode
) {
1531 result
.key
= C0
.BS
; // ^H
1534 result
.key
= C0
.DEL
; // ^?
1539 result
.key
= C0
.ESC
+ '[Z';
1543 result
.cancel
= true;
1548 result
.cancel
= true;
1552 result
.key
= C0
.ESC
;
1553 result
.cancel
= true;
1558 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1559 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1560 // http://unix.stackexchange.com/a/108106
1561 // macOS uses different escape sequences than linux
1562 if (result
.key
== C0
.ESC
+ '[1;3D') {
1563 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1565 } else if (this.applicationCursor
) {
1566 result
.key
= C0
.ESC
+ 'OD';
1568 result
.key
= C0
.ESC
+ '[D';
1574 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1575 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1576 // http://unix.stackexchange.com/a/108106
1577 // macOS uses different escape sequences than linux
1578 if (result
.key
== C0
.ESC
+ '[1;3C') {
1579 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1581 } else if (this.applicationCursor
) {
1582 result
.key
= C0
.ESC
+ 'OC';
1584 result
.key
= C0
.ESC
+ '[C';
1590 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1591 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1592 // http://unix.stackexchange.com/a/108106
1593 if (result
.key
== C0
.ESC
+ '[1;3A') {
1594 result
.key
= C0
.ESC
+ '[1;5A';
1596 } else if (this.applicationCursor
) {
1597 result
.key
= C0
.ESC
+ 'OA';
1599 result
.key
= C0
.ESC
+ '[A';
1605 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1606 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1607 // http://unix.stackexchange.com/a/108106
1608 if (result
.key
== C0
.ESC
+ '[1;3B') {
1609 result
.key
= C0
.ESC
+ '[1;5B';
1611 } else if (this.applicationCursor
) {
1612 result
.key
= C0
.ESC
+ 'OB';
1614 result
.key
= C0
.ESC
+ '[B';
1619 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1620 // <Ctrl> or <Shift> + <Insert> are used to
1621 // copy-paste on some systems.
1622 result
.key
= C0
.ESC
+ '[2~';
1628 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1630 result
.key
= C0
.ESC
+ '[3~';
1636 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1637 else if (this.applicationCursor
)
1638 result
.key
= C0
.ESC
+ 'OH';
1640 result
.key
= C0
.ESC
+ '[H';
1645 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1646 else if (this.applicationCursor
)
1647 result
.key
= C0
.ESC
+ 'OF';
1649 result
.key
= C0
.ESC
+ '[F';
1654 result
.scrollDisp
= -(this.rows
- 1);
1656 result
.key
= C0
.ESC
+ '[5~';
1662 result
.scrollDisp
= this.rows
- 1;
1664 result
.key
= C0
.ESC
+ '[6~';
1670 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1672 result
.key
= C0
.ESC
+ 'OP';
1677 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1679 result
.key
= C0
.ESC
+ 'OQ';
1684 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1686 result
.key
= C0
.ESC
+ 'OR';
1691 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1693 result
.key
= C0
.ESC
+ 'OS';
1698 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1700 result
.key
= C0
.ESC
+ '[15~';
1705 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1707 result
.key
= C0
.ESC
+ '[17~';
1712 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1714 result
.key
= C0
.ESC
+ '[18~';
1719 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1721 result
.key
= C0
.ESC
+ '[19~';
1726 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1728 result
.key
= C0
.ESC
+ '[20~';
1733 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1735 result
.key
= C0
.ESC
+ '[21~';
1740 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1742 result
.key
= C0
.ESC
+ '[23~';
1747 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1749 result
.key
= C0
.ESC
+ '[24~';
1754 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1755 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1756 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1757 } else if (ev
.keyCode
=== 32) {
1759 result
.key
= String
.fromCharCode(0);
1760 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1761 // escape, file sep, group sep, record sep, unit sep
1762 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1763 } else if (ev
.keyCode
=== 56) {
1765 result
.key
= String
.fromCharCode(127);
1766 } else if (ev
.keyCode
=== 219) {
1767 // ^[ - Control Sequence Introducer (CSI)
1768 result
.key
= String
.fromCharCode(27);
1769 } else if (ev
.keyCode
=== 220) {
1770 // ^\ - String Terminator (ST)
1771 result
.key
= String
.fromCharCode(28);
1772 } else if (ev
.keyCode
=== 221) {
1773 // ^] - Operating System Command (OSC)
1774 result
.key
= String
.fromCharCode(29);
1776 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1777 // On Mac this is a third level shift. Use <Esc> instead.
1778 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1779 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1780 } else if (ev
.keyCode
=== 192) {
1781 result
.key
= C0
.ESC
+ '`';
1782 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1783 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1785 } else if (this.browser
.isMac
&& !ev
.altKey
&& !ev
.ctrlKey
&& ev
.metaKey
) {
1786 if (ev
.keyCode
=== 65) { // cmd + a
1797 * Set the G level of the terminal
1800 Terminal
.prototype.setgLevel = function(g
) {
1802 this.charset
= this.charsets
[g
];
1806 * Set the charset for the given G level of the terminal
1810 Terminal
.prototype.setgCharset = function(g
, charset
) {
1811 this.charsets
[g
] = charset
;
1812 if (this.glevel
=== g
) {
1813 this.charset
= charset
;
1818 * Handle a keypress event.
1820 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1821 * @param {KeyboardEvent} ev The keypress event to be handled.
1823 Terminal
.prototype.keyPress = function(ev
) {
1826 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1834 } else if (ev
.which
== null) {
1836 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1843 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1848 key
= String
.fromCharCode(key
);
1850 this.emit('keypress', key
, ev
);
1851 this.emit('key', key
, ev
);
1859 * Send data for handling to the terminal
1860 * @param {string} data
1862 Terminal
.prototype.send = function(data
) {
1866 setTimeout(function() {
1867 self
.handler(self
.queue
);
1877 * Note: We could do sweet things with webaudio here
1879 Terminal
.prototype.bell = function() {
1880 if (!this.visualBell
) return;
1882 this.element
.style
.borderColor
= 'white';
1883 setTimeout(function() {
1884 self
.element
.style
.borderColor
= '';
1886 if (this.popOnBell
) this.focus();
1890 * Log the current state to the console.
1892 Terminal
.prototype.log = function() {
1893 if (!this.debug
) return;
1894 if (!this.context
.console
|| !this.context
.console
.log
) return;
1895 var args
= Array
.prototype.slice
.call(arguments
);
1896 this.context
.console
.log
.apply(this.context
.console
, args
);
1900 * Log the current state as error to the console.
1902 Terminal
.prototype.error = function() {
1903 if (!this.debug
) return;
1904 if (!this.context
.console
|| !this.context
.console
.error
) return;
1905 var args
= Array
.prototype.slice
.call(arguments
);
1906 this.context
.console
.error
.apply(this.context
.console
, args
);
1910 * Resizes the terminal.
1912 * @param {number} x The number of columns to resize to.
1913 * @param {number} y The number of rows to resize to.
1915 Terminal
.prototype.resize = function(x
, y
) {
1916 if (isNaN(x
) || isNaN(y
)) {
1920 if (y
> this.getOption('scrollback')) {
1921 this.setOption('scrollback', y
)
1931 if (x
=== this.cols
&& y
=== this.rows
) {
1932 // Check if we still need to measure the char size (fixes #785).
1933 if (!this.charMeasure
.width
|| !this.charMeasure
.height
) {
1934 this.charMeasure
.measure();
1945 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1946 i
= this.buffer
.lines
.length
;
1948 while (this.buffer
.lines
.get(i
).length
< x
) {
1949 this.buffer
.lines
.get(i
).push(ch
);
1955 this.setupStops(this.cols
);
1963 // y is rows, not this.buffer.y
1964 if (this.buffer
.lines
.length
< y
+ this.buffer
.ybase
) {
1965 if (this.buffer
.ybase
> 0 && this.buffer
.lines
.length
<= this.buffer
.ybase
+ this.buffer
.y
+ addToY
+ 1) {
1966 // There is room above the buffer and there are no empty elements below the line,
1968 this.buffer
.ybase
--;
1970 if (this.buffer
.ydisp
> 0) {
1971 // Viewport is at the top of the buffer, must increase downwards
1972 this.buffer
.ydisp
--;
1975 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1976 // are blank lines after the cursor
1977 this.buffer
.lines
.push(this.blankLine());
1980 if (this.children
.length
< y
) {
1986 if (this.buffer
.lines
.length
> y
+ this.buffer
.ybase
) {
1987 if (this.buffer
.lines
.length
> this.buffer
.ybase
+ this.buffer
.y
+ 1) {
1988 // The line is a blank line below the cursor, remove it
1989 this.buffer
.lines
.pop();
1991 // The line is the cursor, scroll down
1992 this.buffer
.ybase
++;
1993 this.buffer
.ydisp
++;
1996 if (this.children
.length
> y
) {
1997 el
= this.children
.shift();
1999 el
.parentNode
.removeChild(el
);
2005 // Make sure that the cursor stays on screen
2006 if (this.buffer
.y
>= y
) {
2007 this.buffer
.y
= y
- 1;
2010 this.buffer
.y
+= addToY
;
2013 if (this.buffer
.x
>= x
) {
2014 this.buffer
.x
= x
- 1;
2017 this.buffer
.scrollTop
= 0;
2018 this.buffer
.scrollBottom
= y
- 1;
2020 this.charMeasure
.measure();
2022 this.refresh(0, this.rows
- 1);
2024 this.geometry
= [this.cols
, this.rows
];
2025 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
2029 * Updates the range of rows to refresh
2030 * @param {number} y The number of rows to refresh next.
2032 Terminal
.prototype.updateRange = function(y
) {
2033 if (y
< this.refreshStart
) this.refreshStart
= y
;
2034 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
2035 // if (y > this.refreshEnd) {
2036 // this.refreshEnd = y;
2037 // if (y > this.rows - 1) {
2038 // this.refreshEnd = this.rows - 1;
2044 * Set the range of refreshing to the maximum value
2046 Terminal
.prototype.maxRange = function() {
2047 this.refreshStart
= 0;
2048 this.refreshEnd
= this.rows
- 1;
2054 * Setup the tab stops.
2057 Terminal
.prototype.setupStops = function(i
) {
2059 if (!this.buffer
.tabs
[i
]) {
2060 i
= this.prevStop(i
);
2063 this.buffer
.tabs
= {};
2067 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
2068 this.buffer
.tabs
[i
] = true;
2074 * Move the cursor to the previous tab stop from the given position (default is current).
2075 * @param {number} x The position to move the cursor to the previous tab stop.
2077 Terminal
.prototype.prevStop = function(x
) {
2078 if (x
== null) x
= this.buffer
.x
;
2079 while (!this.buffer
.tabs
[--x
] && x
> 0);
2080 return x
>= this.cols
2087 * Move the cursor one tab stop forward from the given position (default is current).
2088 * @param {number} x The position to move the cursor one tab stop forward.
2090 Terminal
.prototype.nextStop = function(x
) {
2091 if (x
== null) x
= this.buffer
.x
;
2092 while (!this.buffer
.tabs
[++x
] && x
< this.cols
);
2093 return x
>= this.cols
2100 * Erase in the identified line everything from "x" to the end of the line (right).
2101 * @param {number} x The column from which to start erasing to the end of the line.
2102 * @param {number} y The line in which to operate.
2104 Terminal
.prototype.eraseRight = function(x
, y
) {
2105 var line
= this.buffer
.lines
.get(this.buffer
.ybase
+ y
);
2109 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2110 for (; x
< this.cols
; x
++) {
2113 this.updateRange(y
);
2119 * Erase in the identified line everything from "x" to the start of the line (left).
2120 * @param {number} x The column from which to start erasing to the start of the line.
2121 * @param {number} y The line in which to operate.
2123 Terminal
.prototype.eraseLeft = function(x
, y
) {
2124 var line
= this.buffer
.lines
.get(this.buffer
.ybase
+ y
);
2128 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2133 this.updateRange(y
);
2137 * Clears the entire buffer, making the prompt line the new first line.
2139 Terminal
.prototype.clear = function() {
2140 if (this.buffer
.ybase
=== 0 && this.buffer
.y
=== 0) {
2141 // Don't clear if it's already clear
2144 this.buffer
.lines
.set(0, this.buffer
.lines
.get(this.buffer
.ybase
+ this.buffer
.y
));
2145 this.buffer
.lines
.length
= 1;
2146 this.buffer
.ydisp
= 0;
2147 this.buffer
.ybase
= 0;
2149 for (var i
= 1; i
< this.rows
; i
++) {
2150 this.buffer
.lines
.push(this.blankLine());
2152 this.refresh(0, this.rows
- 1);
2153 this.emit('scroll', this.buffer
.ydisp
);
2157 * Erase all content in the given line
2158 * @param {number} y The line to erase all of its contents.
2160 Terminal
.prototype.eraseLine = function(y
) {
2161 this.eraseRight(0, y
);
2166 * Return the data array of a blank line
2167 * @param {number} cur First bunch of data for each "blank" character.
2168 * @param {boolean} isWrapped Whether the new line is wrapped from the previous line.
2170 Terminal
.prototype.blankLine = function(cur
, isWrapped
) {
2175 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2179 // TODO: It is not ideal that this is a property on an array, a buffer line
2180 // class should be added that will hold this data and other useful functions.
2182 line
.isWrapped
= isWrapped
;
2185 for (; i
< this.cols
; i
++) {
2194 * If cur return the back color xterm feature attribute. Else return defAttr.
2195 * @param {object} cur
2197 Terminal
.prototype.ch = function(cur
) {
2199 ? [this.eraseAttr(), ' ', 1]
2200 : [this.defAttr
, ' ', 1];
2205 * Evaluate if the current erminal is the given argument.
2206 * @param {object} term The terminal to evaluate
2208 Terminal
.prototype.is = function(term
) {
2209 var name
= this.termName
;
2210 return (name
+ '').indexOf(term
) === 0;
2215 * Emit the 'data' event and populate the given data.
2216 * @param {string} data The data to populate in the event.
2218 Terminal
.prototype.handler = function(data
) {
2219 // Prevents all events to pty process if stdin is disabled
2220 if (this.options
.disableStdin
) {
2224 // Clear the selection if the selection manager is available and has an active selection
2225 if (this.selectionManager
&& this.selectionManager
.hasSelection
) {
2226 this.selectionManager
.clearSelection();
2229 // Input is being sent to the terminal, the terminal should focus the prompt.
2230 if (this.buffer
.ybase
!== this.buffer
.ydisp
) {
2231 this.scrollToBottom();
2233 this.emit('data', data
);
2238 * Emit the 'title' event and populate the given title.
2239 * @param {string} title The title to populate in the event.
2241 Terminal
.prototype.handleTitle = function(title
) {
2243 * This event is emitted when the title of the terminal is changed
2244 * from inside the terminal. The parameter is the new title.
2248 this.emit('title', title
);
2257 * ESC D Index (IND is 0x84).
2259 Terminal
.prototype.index = function() {
2261 if (this.buffer
.y
> this.buffer
.scrollBottom
) {
2265 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2266 if (this.buffer
.x
>= this.cols
) {
2273 * ESC M Reverse Index (RI is 0x8d).
2275 * Move the cursor up one row, inserting a new blank line if necessary.
2277 Terminal
.prototype.reverseIndex = function() {
2279 if (this.buffer
.y
=== this.buffer
.scrollTop
) {
2280 // possibly move the code below to term.reverseScroll();
2281 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2282 // blankLine(true) is xterm/linux behavior
2283 this.buffer
.lines
.shiftElements(this.buffer
.y
+ this.buffer
.ybase
, this.rows
- 1, 1);
2284 this.buffer
.lines
.set(this.buffer
.y
+ this.buffer
.ybase
, this.blankLine(true));
2285 this.updateRange(this.buffer
.scrollTop
);
2286 this.updateRange(this.buffer
.scrollBottom
);
2294 * ESC c Full Reset (RIS).
2296 Terminal
.prototype.reset = function() {
2297 this.options
.rows
= this.rows
;
2298 this.options
.cols
= this.cols
;
2299 var customKeyEventHandler
= this.customKeyEventHandler
;
2300 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2301 var inputHandler
= this.inputHandler
;
2302 var buf
= this.buffers
;
2303 Terminal
.call(this, this.options
);
2304 this.customKeyEventHandler
= customKeyEventHandler
;
2305 this.cursorBlinkInterval
= cursorBlinkInterval
;
2306 this.inputHandler
= inputHandler
;
2308 this.refresh(0, this.rows
- 1);
2309 this.viewport
.syncScrollArea();
2314 * ESC H Tab Set (HTS is 0x88).
2316 Terminal
.prototype.tabSet = function() {
2317 this.buffer
.tabs
[this.buffer
.x
] = true;
2324 function on(el
, type
, handler
, capture
) {
2325 if (!Array
.isArray(el
)) {
2328 el
.forEach(function (element
) {
2329 element
.addEventListener(type
, handler
, capture
|| false);
2333 function off(el
, type
, handler
, capture
) {
2334 el
.removeEventListener(type
, handler
, capture
|| false);
2337 function cancel(ev
, force
) {
2338 if (!this.cancelEvents
&& !force
) {
2341 ev
.preventDefault();
2342 ev
.stopPropagation();
2346 function inherits(child
, parent
) {
2348 this.constructor = child
;
2350 f
.prototype = parent
.prototype;
2351 child
.prototype = new f
;
2354 function indexOf(obj
, el
) {
2357 if (obj
[i
] === el
) return i
;
2362 function isThirdLevelShift(term
, ev
) {
2364 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2365 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2367 if (ev
.type
== 'keypress') {
2368 return thirdLevelKey
;
2371 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2372 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2375 // Expose to InputHandler (temporary)
2376 Terminal
.prototype.matchColor
= matchColor
;
2378 function matchColor(r1
, g1
, b1
) {
2379 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2381 if (matchColor
._cache
[hash
] != null) {
2382 return matchColor
._cache
[hash
];
2385 var ldiff
= Infinity
2394 for (; i
< Terminal
.vcolors
.length
; i
++) {
2395 c
= Terminal
.vcolors
[i
];
2400 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2413 return matchColor
._cache
[hash
] = li
;
2416 matchColor
._cache
= {};
2418 // http://stackoverflow.com/questions/1633828
2419 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2420 return Math
.pow(30 * (r1
- r2
), 2)
2421 + Math
.pow(59 * (g1
- g2
), 2)
2422 + Math
.pow(11 * (b1
- b2
), 2);
2425 function each(obj
, iter
, con
) {
2426 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2427 for (var i
= 0; i
< obj
.length
; i
++) {
2428 iter
.call(con
, obj
[i
], i
, obj
);
2432 function wasMondifierKeyOnlyEvent(ev
) {
2433 return ev
.keyCode
=== 16 || // Shift
2434 ev
.keyCode
=== 17 || // Ctrl
2435 ev
.keyCode
=== 18; // Alt
2438 function keys(obj
) {
2439 if (Object
.keys
) return Object
.keys(obj
);
2442 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2453 Terminal
.translateBufferLineToString
= translateBufferLineToString
;
2454 Terminal
.EventEmitter
= EventEmitter
;
2455 Terminal
.inherits
= inherits
;
2458 * Adds an event listener to the terminal.
2460 * @param {string} event The name of the event. TODO: Document all event types
2461 * @param {function} callback The function to call when the event is triggered.
2465 Terminal
.cancel
= cancel
;
2467 module
.exports
= Terminal
;