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;
150 this.scrollBottom
= this.rows
- 1;
151 this.customKeyEventHandler
= null;
152 this.cursorBlinkInterval
= null;
155 this.applicationKeypad
= false;
156 this.applicationCursor
= false;
157 this.originMode
= false;
158 this.insertMode
= false;
159 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
164 this.gcharset
= null;
166 this.charsets
= [null];
190 this.readable
= true;
191 this.writable
= true;
193 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
194 this.curAttr
= this.defAttr
;
197 this.currentParam
= 0;
201 this.inputHandler
= new InputHandler(this);
202 this.parser
= new Parser(this.inputHandler
, this);
203 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
204 this.renderer
= this.renderer
|| null;
205 this.selectionManager
= this.selectionManager
|| null;
206 this.linkifier
= this.linkifier
|| new Linkifier();
209 this.writeBuffer
= [];
210 this.writeInProgress
= false;
213 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
214 * This is a distinct state from writeStopped so that if the user requested
215 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
218 this.xoffSentToCatchUp
= false;
220 /** Whether writing has been stopped as a result of XOFF */
221 this.writeStopped
= false;
223 // leftover surrogate high from previous write invocation
224 this.surrogate_high
= '';
226 // Create the terminal's buffers and set the current buffer
227 this.buffers
= new BufferSet(this);
228 this.buffer
= this.buffers
.active
; // Convenience shortcut;
229 this.buffers
.on('activate', function (buffer
) {
230 this.buffer
= buffer
;
234 * An array of all lines in the entire buffer, including the prompt. The lines are array of
235 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
240 this.buffer
.lines
.push(this.blankLine());
242 // Ensure the selection manager has the correct buffer
243 if (this.selectionManager
) {
244 this.selectionManager
.setBuffer(this.buffer
.lines
);
250 // Store if user went browsing history in scrollback
251 this.userScrolling
= false;
254 inherits(Terminal
, EventEmitter
);
257 * back_color_erase feature for xterm.
259 Terminal
.prototype.eraseAttr = function() {
260 // if (this.is('screen')) return this.defAttr;
261 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
269 Terminal
.tangoColors
= [
290 // Colors 0-15 + 16-255
291 // Much thanks to TooTallNate for writing this.
292 Terminal
.colors
= (function() {
293 var colors
= Terminal
.tangoColors
.slice()
294 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
299 for (; i
< 216; i
++) {
300 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
305 for (; i
< 24; i
++) {
310 function out(r
, g
, b
) {
311 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
316 return c
.length
< 2 ? '0' + c
: c
;
322 Terminal
._colors
= Terminal
.colors
.slice();
324 Terminal
.vcolors
= (function() {
326 , colors
= Terminal
.colors
330 for (; i
< 256; i
++) {
331 color
= parseInt(colors
[i
].substring(1), 16);
333 (color
>> 16) & 0xff,
346 Terminal
.defaults
= {
347 colors
: Terminal
.colors
,
353 cursorStyle
: 'block',
361 useFlowControl
: false,
363 // programFeatures: false,
367 Terminal
.options
= {};
369 Terminal
.focus
= null;
371 each(keys(Terminal
.defaults
), function(key
) {
372 Terminal
[key
] = Terminal
.defaults
[key
];
373 Terminal
.options
[key
] = Terminal
.defaults
[key
];
377 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
379 Terminal
.prototype.focus = function() {
380 return this.textarea
.focus();
384 * Retrieves an option's value from the terminal.
385 * @param {string} key The option key.
387 Terminal
.prototype.getOption = function(key
) {
388 if (!(key
in Terminal
.defaults
)) {
389 throw new Error('No option with key "' + key
+ '"');
392 if (typeof this.options
[key
] !== 'undefined') {
393 return this.options
[key
];
400 * Sets an option on the terminal.
401 * @param {string} key The option key.
402 * @param {string} value The option value.
404 Terminal
.prototype.setOption = function(key
, value
) {
405 if (!(key
in Terminal
.defaults
)) {
406 throw new Error('No option with key "' + key
+ '"');
410 if (value
< this.rows
) {
411 let msg
= 'Setting the scrollback value less than the number of rows ';
413 msg
+= `(${this.rows}) is not allowed.`;
419 if (this.options
[key
] !== value
) {
420 if (this.buffer
.length
> value
) {
421 const amountToTrim
= this.buffer
.lines
.length
- value
;
422 const needsRefresh
= (this.buffer
.ydisp
- amountToTrim
< 0);
423 this.buffer
.lines
.trimStart(amountToTrim
);
424 this.buffer
.ybase
= Math
.max(this.buffer
.ybase
- amountToTrim
, 0);
425 this.buffer
.ydisp
= Math
.max(this.buffer
.ydisp
- amountToTrim
, 0);
427 this.refresh(0, this.rows
- 1);
430 this.buffer
.lines
.maxLength
= value
;
431 this.viewport
.syncScrollArea();
436 this.options
[key
] = value
;
438 case 'cursorBlink': this.setCursorBlinking(value
); break;
440 // Style 'block' applies with no class
441 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
442 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
444 case 'tabStopWidth': this.setupStops(); break;
448 Terminal
.prototype.restartCursorBlinking = function () {
449 this.setCursorBlinking(this.options
.cursorBlink
);
452 Terminal
.prototype.setCursorBlinking = function (enabled
) {
453 this.element
.classList
.toggle('xterm-cursor-blink', enabled
);
454 this.clearCursorBlinkingInterval();
457 this.cursorBlinkInterval
= setInterval(function () {
458 self
.element
.classList
.toggle('xterm-cursor-blink-on');
459 }, CURSOR_BLINK_INTERVAL
);
463 Terminal
.prototype.clearCursorBlinkingInterval = function () {
464 this.element
.classList
.remove('xterm-cursor-blink-on');
465 if (this.cursorBlinkInterval
) {
466 clearInterval(this.cursorBlinkInterval
);
467 this.cursorBlinkInterval
= null;
472 * Binds the desired focus behavior on a given terminal object.
476 Terminal
.bindFocus = function (term
) {
477 on(term
.textarea
, 'focus', function (ev
) {
478 if (term
.sendFocus
) {
479 term
.send(C0
.ESC
+ '[I');
481 term
.element
.classList
.add('focus');
483 term
.restartCursorBlinking
.apply(term
);
484 Terminal
.focus
= term
;
485 term
.emit('focus', {terminal
: term
});
490 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
492 Terminal
.prototype.blur = function() {
493 return this.textarea
.blur();
497 * Binds the desired blur behavior on a given terminal object.
501 Terminal
.bindBlur = function (term
) {
502 on(term
.textarea
, 'blur', function (ev
) {
503 term
.refresh(term
.y
, term
.y
);
504 if (term
.sendFocus
) {
505 term
.send(C0
.ESC
+ '[O');
507 term
.element
.classList
.remove('focus');
508 term
.clearCursorBlinkingInterval
.apply(term
);
509 Terminal
.focus
= null;
510 term
.emit('blur', {terminal
: term
});
515 * Initialize default behavior
517 Terminal
.prototype.initGlobal = function() {
520 Terminal
.bindKeys(this);
521 Terminal
.bindFocus(this);
522 Terminal
.bindBlur(this);
524 // Bind clipboard functionality
525 on(this.element
, 'copy', event
=> {
526 // If mouse events are active it means the selection manager is disabled and
527 // copy should be handled by the host program.
528 if (this.mouseEvents
) {
531 copyHandler(event
, term
, this.selectionManager
);
533 const pasteHandlerWrapper
= event
=> pasteHandler(event
, term
);
534 on(this.textarea
, 'paste', pasteHandlerWrapper
);
535 on(this.element
, 'paste', pasteHandlerWrapper
);
537 // Handle right click context menus
538 if (term
.browser
.isFirefox
) {
539 // Firefox doesn't appear to fire the contextmenu event on right click
540 on(this.element
, 'mousedown', event
=> {
541 if (event
.button
== 2) {
542 rightClickHandler(event
, this.textarea
, this.selectionManager
);
546 on(this.element
, 'contextmenu', event
=> {
547 rightClickHandler(event
, this.textarea
, this.selectionManager
);
551 // Move the textarea under the cursor when middle clicking on Linux to ensure
552 // middle click to paste selection works. This only appears to work in Chrome
553 // at the time is writing.
554 if (term
.browser
.isLinux
) {
555 // Use auxclick event over mousedown the latter doesn't seem to work. Note
556 // that the regular click event doesn't fire for the middle mouse button.
557 on(this.element
, 'auxclick', event
=> {
558 if (event
.button
=== 1) {
559 moveTextAreaUnderMouseCursor(event
, this.textarea
, this.selectionManager
);
566 * Apply key handling to the terminal
568 Terminal
.bindKeys = function(term
) {
569 on(term
.element
, 'keydown', function(ev
) {
570 if (document
.activeElement
!= this) {
576 on(term
.element
, 'keypress', function(ev
) {
577 if (document
.activeElement
!= this) {
583 on(term
.element
, 'keyup', function(ev
) {
584 if (!wasMondifierKeyOnlyEvent(ev
)) {
589 on(term
.textarea
, 'keydown', function(ev
) {
593 on(term
.textarea
, 'keypress', function(ev
) {
595 // Truncate the textarea's value, since it is not needed
599 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
600 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
601 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
602 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
603 term
.on('refresh', function (data
) {
604 term
.queueLinkification(data
.start
, data
.end
)
610 * Insert the given row to the terminal or produce a new one
611 * if no row argument is passed. Return the inserted row.
612 * @param {HTMLElement} row (optional) The row to append to the terminal.
614 Terminal
.prototype.insertRow = function (row
) {
615 if (typeof row
!= 'object') {
616 row
= document
.createElement('div');
619 this.rowContainer
.appendChild(row
);
620 this.children
.push(row
);
626 * Opens the terminal within an element.
628 * @param {HTMLElement} parent The element to create the terminal within.
629 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
631 Terminal
.prototype.open = function(parent
, focus
) {
632 var self
=this, i
=0, div
;
634 this.parent
= parent
|| this.parent
;
637 throw new Error('Terminal requires a parent element.');
640 // Grab global elements
641 this.context
= this.parent
.ownerDocument
.defaultView
;
642 this.document
= this.parent
.ownerDocument
;
643 this.body
= this.document
.getElementsByTagName('body')[0];
645 //Create main element container
646 this.element
= this.document
.createElement('div');
647 this.element
.classList
.add('terminal');
648 this.element
.classList
.add('xterm');
649 this.element
.classList
.add('xterm-theme-' + this.theme
);
650 this.setCursorBlinking(this.options
.cursorBlink
);
652 this.element
.setAttribute('tabindex', 0);
654 this.viewportElement
= document
.createElement('div');
655 this.viewportElement
.classList
.add('xterm-viewport');
656 this.element
.appendChild(this.viewportElement
);
657 this.viewportScrollArea
= document
.createElement('div');
658 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
659 this.viewportElement
.appendChild(this.viewportScrollArea
);
661 // Create the selection container.
662 this.selectionContainer
= document
.createElement('div');
663 this.selectionContainer
.classList
.add('xterm-selection');
664 this.element
.appendChild(this.selectionContainer
);
666 // Create the container that will hold the lines of the terminal and then
667 // produce the lines the lines.
668 this.rowContainer
= document
.createElement('div');
669 this.rowContainer
.classList
.add('xterm-rows');
670 this.element
.appendChild(this.rowContainer
);
672 this.linkifier
.attachToDom(document
, this.children
);
674 // Create the container that will hold helpers like the textarea for
675 // capturing DOM Events. Then produce the helpers.
676 this.helperContainer
= document
.createElement('div');
677 this.helperContainer
.classList
.add('xterm-helpers');
678 // TODO: This should probably be inserted once it's filled to prevent an additional layout
679 this.element
.appendChild(this.helperContainer
);
680 this.textarea
= document
.createElement('textarea');
681 this.textarea
.classList
.add('xterm-helper-textarea');
682 this.textarea
.setAttribute('autocorrect', 'off');
683 this.textarea
.setAttribute('autocapitalize', 'off');
684 this.textarea
.setAttribute('spellcheck', 'false');
685 this.textarea
.tabIndex
= 0;
686 this.textarea
.addEventListener('focus', function() {
687 self
.emit('focus', {terminal
: self
});
689 this.textarea
.addEventListener('blur', function() {
690 self
.emit('blur', {terminal
: self
});
692 this.helperContainer
.appendChild(this.textarea
);
694 this.compositionView
= document
.createElement('div');
695 this.compositionView
.classList
.add('composition-view');
696 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
697 this.helperContainer
.appendChild(this.compositionView
);
699 this.charSizeStyleElement
= document
.createElement('style');
700 this.helperContainer
.appendChild(this.charSizeStyleElement
);
702 for (; i
< this.rows
; i
++) {
705 this.parent
.appendChild(this.element
);
707 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
708 this.charMeasure
.on('charsizechanged', function () {
709 self
.updateCharSizeStyles();
711 this.charMeasure
.measure();
713 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
714 this.renderer
= new Renderer(this);
715 this.selectionManager
= new SelectionManager(this, this.buffer
.lines
, this.rowContainer
, this.charMeasure
);
716 this.selectionManager
.on('refresh', data
=> {
717 this.renderer
.refreshSelection(data
.start
, data
.end
);
719 this.selectionManager
.on('newselection', text
=> {
720 // If there's a new selection, put it into the textarea, focus and select it
721 // in order to register it as a selection on the OS. This event is fired
722 // only on Linux to enable middle click to paste selection.
723 this.textarea
.value
= text
;
724 this.textarea
.focus();
725 this.textarea
.select();
727 this.on('scroll', () => this.selectionManager
.refresh());
728 this.viewportElement
.addEventListener('scroll', () => this.selectionManager
.refresh());
730 // Setup loop that draws to screen
731 this.refresh(0, this.rows
- 1);
733 // Initialize global actions that
734 // need to be taken on the document.
738 * Automatic focus functionality.
739 * TODO: Default to `false` starting with xterm.js 3.0.
741 if (typeof focus
== 'undefined') {
742 let message
= 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
744 message
+= 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
745 message
+= 'it will default to `false`.';
747 console
.warn(message
);
755 on(this.element
, 'click', function() {
756 var selection
= document
.getSelection(),
757 collapsed
= selection
.isCollapsed
,
758 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
764 // Listen for mouse events and translate
765 // them into terminal mouse protocols.
769 * This event is emitted when terminal has completed opening.
778 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
779 * @param {string} addon The name of the addon to load
782 Terminal
.loadAddon = function(addon
, callback
) {
783 if (typeof exports
=== 'object' && typeof module
=== 'object') {
785 return require('./addons/' + addon
+ '/' + addon
);
786 } else if (typeof define
== 'function') {
788 return require(['./addons/' + addon
+ '/' + addon
], callback
);
790 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
796 * Updates the helper CSS class with any changes necessary after the terminal's
797 * character width has been changed.
799 Terminal
.prototype.updateCharSizeStyles = function() {
800 this.charSizeStyleElement
.textContent
=
801 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
802 `.xterm-normal-char{width:${this.charMeasure.width}px;}` +
803 `.xterm-rows > div{height:${this.charMeasure.height}px;}`;
808 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
809 * To better understand these
810 * the xterm code is very helpful:
812 * button.c, charproc.c, misc.c
813 * Relevant functions in xterm/button.c:
814 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
816 Terminal
.prototype.bindMouse = function() {
817 var el
= this.element
, self
= this, pressed
= 32;
819 // mouseup, mousedown, wheel
820 // left click: ^[[M 3<^[[M#3<
822 function sendButton(ev
) {
826 // get the xterm-style button
827 button
= getButton(ev
);
829 // get mouse coordinates
830 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
833 sendEvent(button
, pos
);
835 switch (ev
.overrideType
|| ev
.type
) {
840 // keep it at the left
841 // button, just in case.
852 // motion example of a left click:
853 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
854 function sendMove(ev
) {
858 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
861 // buttons marked as motions
862 // are incremented by 32
865 sendEvent(button
, pos
);
869 // position to characters
870 function encode(data
, ch
) {
871 if (!self
.utfMouse
) {
872 if (ch
=== 255) return data
.push(0);
873 if (ch
> 127) ch
= 127;
876 if (ch
=== 2047) return data
.push(0);
880 if (ch
> 2047) ch
= 2047;
881 data
.push(0xC0 | (ch
>> 6));
882 data
.push(0x80 | (ch
& 0x3F));
887 // send a mouse event:
888 // regular/utf8: ^[[M Cb Cx Cy
889 // urxvt: ^[[ Cb ; Cx ; Cy M
890 // sgr: ^[[ Cb ; Cx ; Cy M/m
891 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
892 // locator: CSI P e ; P b ; P r ; P c ; P p & w
893 function sendEvent(button
, pos
) {
894 // self.emit('mouse', {
900 if (self
.vt300Mouse
) {
902 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
906 var data
= C0
.ESC
+ '[24';
907 if (button
=== 0) data
+= '1';
908 else if (button
=== 1) data
+= '3';
909 else if (button
=== 2) data
+= '5';
910 else if (button
=== 3) return;
912 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
917 if (self
.decLocator
) {
922 if (button
=== 0) button
= 2;
923 else if (button
=== 1) button
= 4;
924 else if (button
=== 2) button
= 6;
925 else if (button
=== 3) button
= 3;
926 self
.send(C0
.ESC
+ '['
929 + (button
=== 3 ? 4 : 0)
940 if (self
.urxvtMouse
) {
945 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
952 self
.send(C0
.ESC
+ '[<'
953 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
958 + ((button
& 3) === 3 ? 'm' : 'M'));
964 encode(data
, button
);
968 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
971 function getButton(ev
) {
984 // 1, and 2 - with 64 added
985 switch (ev
.overrideType
|| ev
.type
) {
987 button
= ev
.button
!= null
993 if (self
.browser
.isMSIE
) {
994 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
1000 case 'DOMMouseScroll':
1001 button
= ev
.detail
< 0
1006 button
= ev
.wheelDeltaY
> 0
1012 // next three bits are the modifiers:
1013 // 4 = shift, 8 = meta, 16 = control
1014 shift
= ev
.shiftKey
? 4 : 0;
1015 meta
= ev
.metaKey
? 8 : 0;
1016 ctrl
= ev
.ctrlKey
? 16 : 0;
1017 mod
= shift
| meta
| ctrl
;
1020 if (self
.vt200Mouse
) {
1023 } else if (!self
.normalMouse
) {
1028 button
= (32 + (mod
<< 2)) + button
;
1033 on(el
, 'mousedown', function(ev
) {
1034 if (!self
.mouseEvents
) return;
1043 //if (self.vt200Mouse && !self.normalMouse) {
1044 if (self
.vt200Mouse
) {
1045 ev
.overrideType
= 'mouseup';
1047 return self
.cancel(ev
);
1051 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1053 // x10 compatibility mode can't send button releases
1054 if (!self
.x10Mouse
) {
1055 on(self
.document
, 'mouseup', function up(ev
) {
1057 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1058 off(self
.document
, 'mouseup', up
);
1059 return self
.cancel(ev
);
1063 return self
.cancel(ev
);
1066 //if (self.normalMouse) {
1067 // on(self.document, 'mousemove', sendMove);
1070 on(el
, 'wheel', function(ev
) {
1071 if (!self
.mouseEvents
) return;
1074 || self
.decLocator
) return;
1076 return self
.cancel(ev
);
1079 // allow wheel scrolling in
1080 // the shell for example
1081 on(el
, 'wheel', function(ev
) {
1082 if (self
.mouseEvents
) return;
1083 self
.viewport
.onWheel(ev
);
1084 return self
.cancel(ev
);
1087 on(el
, 'touchstart', function(ev
) {
1088 if (self
.mouseEvents
) return;
1089 self
.viewport
.onTouchStart(ev
);
1090 return self
.cancel(ev
);
1093 on(el
, 'touchmove', function(ev
) {
1094 if (self
.mouseEvents
) return;
1095 self
.viewport
.onTouchMove(ev
);
1096 return self
.cancel(ev
);
1101 * Destroys the terminal.
1103 Terminal
.prototype.destroy = function() {
1104 this.readable
= false;
1105 this.writable
= false;
1107 this.handler = function() {};
1108 this.write = function() {};
1109 if (this.element
&& this.element
.parentNode
) {
1110 this.element
.parentNode
.removeChild(this.element
);
1112 //this.emit('close');
1116 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1118 * @param {number} start The row to start from (between 0 and this.rows - 1).
1119 * @param {number} end The row to end at (between start and this.rows - 1).
1121 Terminal
.prototype.refresh = function(start
, end
) {
1122 if (this.renderer
) {
1123 this.renderer
.queueRefresh(start
, end
);
1128 * Queues linkification for the specified rows.
1129 * @param {number} start The row to start from (between 0 and this.rows - 1).
1130 * @param {number} end The row to end at (between start and this.rows - 1).
1132 Terminal
.prototype.queueLinkification = function(start
, end
) {
1133 if (this.linkifier
) {
1134 for (let i
= start
; i
<= end
; i
++) {
1135 this.linkifier
.linkifyRow(i
);
1141 * Display the cursor element
1143 Terminal
.prototype.showCursor = function() {
1144 if (!this.cursorState
) {
1145 this.cursorState
= 1;
1146 this.refresh(this.buffer
.y
, this.buffer
.y
);
1151 * Scroll the terminal down 1 row, creating a blank line.
1152 * @param {boolean} isWrapped Whether the new line is wrapped from the previous
1155 Terminal
.prototype.scroll = function(isWrapped
) {
1158 // Make room for the new row in lines
1159 if (this.buffer
.lines
.length
=== this.buffer
.lines
.maxLength
) {
1160 this.buffer
.lines
.trimStart(1);
1161 this.buffer
.ybase
--;
1162 if (this.buffer
.ydisp
!== 0) {
1163 this.buffer
.ydisp
--;
1167 this.buffer
.ybase
++;
1169 // TODO: Why is this done twice?
1170 if (!this.userScrolling
) {
1171 this.buffer
.ydisp
= this.buffer
.ybase
;
1175 row
= this.buffer
.ybase
+ this.rows
- 1;
1177 // subtract the bottom scroll region
1178 row
-= this.rows
- 1 - this.scrollBottom
;
1180 if (row
=== this.buffer
.lines
.length
) {
1181 // Optimization: pushing is faster than splicing when they amount to the same behavior
1182 this.buffer
.lines
.push(this.blankLine(undefined, isWrapped
));
1185 this.buffer
.lines
.splice(row
, 0, this.blankLine(undefined, isWrapped
));
1188 if (this.scrollTop
!== 0) {
1189 if (this.buffer
.ybase
!== 0) {
1190 this.buffer
.ybase
--;
1191 if (!this.userScrolling
) {
1192 this.buffer
.ydisp
= this.buffer
.ybase
;
1195 this.buffer
.lines
.splice(this.buffer
.ybase
+ this.scrollTop
, 1);
1199 this.updateRange(this.scrollTop
);
1200 this.updateRange(this.scrollBottom
);
1203 * This event is emitted whenever the terminal is scrolled.
1204 * The one parameter passed is the new y display position.
1208 this.emit('scroll', this.buffer
.ydisp
);
1212 * Scroll the display of the terminal
1213 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1214 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1215 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1216 * viewport originally.
1218 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1220 if (this.buffer
.ydisp
=== 0) {
1223 this.userScrolling
= true;
1224 } else if (disp
+ this.buffer
.ydisp
>= this.buffer
.ybase
) {
1225 this.userScrolling
= false;
1228 const oldYdisp
= this.buffer
.ydisp
;
1229 this.buffer
.ydisp
= Math
.max(Math
.min(this.buffer
.ydisp
+ disp
, this.buffer
.ybase
), 0);
1231 // No change occurred, don't trigger scroll/refresh
1232 if (oldYdisp
=== this.buffer
.ydisp
) {
1236 if (!suppressScrollEvent
) {
1237 this.emit('scroll', this.buffer
.ydisp
);
1240 this.refresh(0, this.rows
- 1);
1244 * Scroll the display of the terminal by a number of pages.
1245 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1247 Terminal
.prototype.scrollPages = function(pageCount
) {
1248 this.scrollDisp(pageCount
* (this.rows
- 1));
1252 * Scrolls the display of the terminal to the top.
1254 Terminal
.prototype.scrollToTop = function() {
1255 this.scrollDisp(-this.buffer
.ydisp
);
1259 * Scrolls the display of the terminal to the bottom.
1261 Terminal
.prototype.scrollToBottom = function() {
1262 this.scrollDisp(this.buffer
.ybase
- this.buffer
.ydisp
);
1266 * Writes text to the terminal.
1267 * @param {string} data The text to write to the terminal.
1269 Terminal
.prototype.write = function(data
) {
1270 this.writeBuffer
.push(data
);
1272 // Send XOFF to pause the pty process if the write buffer becomes too large so
1273 // xterm.js can catch up before more data is sent. This is necessary in order
1274 // to keep signals such as ^C responsive.
1275 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1276 // XOFF - stop pty pipe
1277 // XON will be triggered by emulator before processing data chunk
1279 this.xoffSentToCatchUp
= true;
1282 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1283 // Kick off a write which will write all data in sequence recursively
1284 this.writeInProgress
= true;
1285 // Kick off an async innerWrite so more writes can come in while processing data
1287 setTimeout(function () {
1293 Terminal
.prototype.innerWrite = function() {
1294 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1295 while (writeBatch
.length
> 0) {
1296 var data
= writeBatch
.shift();
1297 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1299 // If XOFF was sent in order to catch up with the pty process, resume it if
1300 // the writeBuffer is empty to allow more data to come in.
1301 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1303 this.xoffSentToCatchUp
= false;
1306 this.refreshStart
= this.buffer
.y
;
1307 this.refreshEnd
= this.buffer
.y
;
1309 // HACK: Set the parser state based on it's state at the time of return.
1310 // This works around the bug #662 which saw the parser state reset in the
1311 // middle of parsing escape sequence in two chunks. For some reason the
1312 // state of the parser resets to 0 after exiting parser.parse. This change
1313 // just sets the state back based on the correct return statement.
1314 var state
= this.parser
.parse(data
);
1315 this.parser
.setState(state
);
1317 this.updateRange(this.buffer
.y
);
1318 this.refresh(this.refreshStart
, this.refreshEnd
);
1320 if (this.writeBuffer
.length
> 0) {
1321 // Allow renderer to catch up before processing the next batch
1323 setTimeout(function () {
1327 this.writeInProgress
= false;
1332 * Writes text to the terminal, followed by a break line character (\n).
1333 * @param {string} data The text to write to the terminal.
1335 Terminal
.prototype.writeln = function(data
) {
1336 this.write(data
+ '\r\n');
1340 * DEPRECATED: only for backward compatibility. Please use attachCustomKeyEventHandler() instead.
1341 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1342 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1343 * the default action. The function returns whether the event should be processed by xterm.js.
1345 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1346 let message
= 'attachCustomKeydownHandler() is DEPRECATED and will be removed soon. Please use attachCustomKeyEventHandler() instead.';
1347 console
.warn(message
);
1348 this.attachCustomKeyEventHandler(customKeydownHandler
);
1352 * Attaches a custom key event handler which is run before keys are processed, giving consumers of
1353 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1355 * @param {function} customKeyEventHandler The custom KeyboardEvent handler to attach. This is a
1356 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1357 * the default action. The function returns whether the event should be processed by xterm.js.
1359 Terminal
.prototype.attachCustomKeyEventHandler = function(customKeyEventHandler
) {
1360 this.customKeyEventHandler
= customKeyEventHandler
;
1364 * Attaches a http(s) link handler, forcing web links to behave differently to
1365 * regular <a> tags. This will trigger a refresh as links potentially need to be
1366 * reconstructed. Calling this with null will remove the handler.
1367 * @param {LinkMatcherHandler} handler The handler callback function.
1369 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1370 if (!this.linkifier
) {
1371 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1373 this.linkifier
.setHypertextLinkHandler(handler
);
1374 // Refresh to force links to refresh
1375 this.refresh(0, this.rows
- 1);
1379 * Attaches a validation callback for hypertext links. This is useful to use
1380 * validation logic or to do something with the link's element and url.
1381 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1382 * be cleared with null.
1384 Terminal
.prototype.setHypertextValidationCallback = function(callback
) {
1385 if (!this.linkifier
) {
1386 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1388 this.linkifier
.setHypertextValidationCallback(callback
);
1389 // Refresh to force links to refresh
1390 this.refresh(0, this.rows
- 1);
1394 * Registers a link matcher, allowing custom link patterns to be matched and
1396 * @param {RegExp} regex The regular expression to search for, specifically
1397 * this searches the textContent of the rows. You will want to use \s to match
1398 * a space ' ' character for example.
1399 * @param {LinkMatcherHandler} handler The callback when the link is called.
1400 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1401 * @return {number} The ID of the new matcher, this can be used to deregister.
1403 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1404 if (this.linkifier
) {
1405 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1406 this.refresh(0, this.rows
- 1);
1412 * Deregisters a link matcher if it has been registered.
1413 * @param {number} matcherId The link matcher's ID (returned after register)
1415 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1416 if (this.linkifier
) {
1417 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1418 this.refresh(0, this.rows
- 1);
1424 * Gets whether the terminal has an active selection.
1426 Terminal
.prototype.hasSelection = function() {
1427 return this.selectionManager
? this.selectionManager
.hasSelection
: false;
1431 * Gets the terminal's current selection, this is useful for implementing copy
1432 * behavior outside of xterm.js.
1434 Terminal
.prototype.getSelection = function() {
1435 return this.selectionManager
? this.selectionManager
.selectionText
: '';
1439 * Clears the current terminal selection.
1441 Terminal
.prototype.clearSelection = function() {
1442 if (this.selectionManager
) {
1443 this.selectionManager
.clearSelection();
1448 * Selects all text within the terminal.
1450 Terminal
.prototype.selectAll = function() {
1451 if (this.selectionManager
) {
1452 this.selectionManager
.selectAll();
1457 * Handle a keydown event
1459 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1460 * @param {KeyboardEvent} ev The keydown event to be handled.
1462 Terminal
.prototype.keyDown = function(ev
) {
1463 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1467 this.restartCursorBlinking();
1469 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1470 if (this.buffer
.ybase
!== this.buffer
.ydisp
) {
1471 this.scrollToBottom();
1477 var result
= this.evaluateKeyEscapeSequence(ev
);
1479 if (result
.key
=== C0
.DC3
) { // XOFF
1480 this.writeStopped
= true;
1481 } else if (result
.key
=== C0
.DC1
) { // XON
1482 this.writeStopped
= false;
1485 if (result
.scrollDisp
) {
1486 this.scrollDisp(result
.scrollDisp
);
1487 return this.cancel(ev
, true);
1490 if (isThirdLevelShift(this, ev
)) {
1494 if (result
.cancel
) {
1495 // The event is canceled at the end already, is this necessary?
1496 this.cancel(ev
, true);
1503 this.emit('keydown', ev
);
1504 this.emit('key', result
.key
, ev
);
1506 this.handler(result
.key
);
1508 return this.cancel(ev
, true);
1512 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1513 * returned value is the new key code to pass to the PTY.
1515 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1516 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1518 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1520 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1521 // canceled at the end of keyDown
1523 // The new key even to emit
1525 // The number of characters to scroll, if this is defined it will cancel the event
1526 scrollDisp
: undefined
1528 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1529 switch (ev
.keyCode
) {
1533 result
.key
= C0
.BS
; // ^H
1536 result
.key
= C0
.DEL
; // ^?
1541 result
.key
= C0
.ESC
+ '[Z';
1545 result
.cancel
= true;
1550 result
.cancel
= true;
1554 result
.key
= C0
.ESC
;
1555 result
.cancel
= true;
1560 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1561 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1562 // http://unix.stackexchange.com/a/108106
1563 // macOS uses different escape sequences than linux
1564 if (result
.key
== C0
.ESC
+ '[1;3D') {
1565 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1567 } else if (this.applicationCursor
) {
1568 result
.key
= C0
.ESC
+ 'OD';
1570 result
.key
= C0
.ESC
+ '[D';
1576 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1577 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1578 // http://unix.stackexchange.com/a/108106
1579 // macOS uses different escape sequences than linux
1580 if (result
.key
== C0
.ESC
+ '[1;3C') {
1581 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1583 } else if (this.applicationCursor
) {
1584 result
.key
= C0
.ESC
+ 'OC';
1586 result
.key
= C0
.ESC
+ '[C';
1592 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1593 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1594 // http://unix.stackexchange.com/a/108106
1595 if (result
.key
== C0
.ESC
+ '[1;3A') {
1596 result
.key
= C0
.ESC
+ '[1;5A';
1598 } else if (this.applicationCursor
) {
1599 result
.key
= C0
.ESC
+ 'OA';
1601 result
.key
= C0
.ESC
+ '[A';
1607 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1608 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1609 // http://unix.stackexchange.com/a/108106
1610 if (result
.key
== C0
.ESC
+ '[1;3B') {
1611 result
.key
= C0
.ESC
+ '[1;5B';
1613 } else if (this.applicationCursor
) {
1614 result
.key
= C0
.ESC
+ 'OB';
1616 result
.key
= C0
.ESC
+ '[B';
1621 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1622 // <Ctrl> or <Shift> + <Insert> are used to
1623 // copy-paste on some systems.
1624 result
.key
= C0
.ESC
+ '[2~';
1630 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1632 result
.key
= C0
.ESC
+ '[3~';
1638 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1639 else if (this.applicationCursor
)
1640 result
.key
= C0
.ESC
+ 'OH';
1642 result
.key
= C0
.ESC
+ '[H';
1647 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1648 else if (this.applicationCursor
)
1649 result
.key
= C0
.ESC
+ 'OF';
1651 result
.key
= C0
.ESC
+ '[F';
1656 result
.scrollDisp
= -(this.rows
- 1);
1658 result
.key
= C0
.ESC
+ '[5~';
1664 result
.scrollDisp
= this.rows
- 1;
1666 result
.key
= C0
.ESC
+ '[6~';
1672 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1674 result
.key
= C0
.ESC
+ 'OP';
1679 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1681 result
.key
= C0
.ESC
+ 'OQ';
1686 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1688 result
.key
= C0
.ESC
+ 'OR';
1693 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1695 result
.key
= C0
.ESC
+ 'OS';
1700 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1702 result
.key
= C0
.ESC
+ '[15~';
1707 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1709 result
.key
= C0
.ESC
+ '[17~';
1714 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1716 result
.key
= C0
.ESC
+ '[18~';
1721 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1723 result
.key
= C0
.ESC
+ '[19~';
1728 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1730 result
.key
= C0
.ESC
+ '[20~';
1735 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1737 result
.key
= C0
.ESC
+ '[21~';
1742 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1744 result
.key
= C0
.ESC
+ '[23~';
1749 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1751 result
.key
= C0
.ESC
+ '[24~';
1756 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1757 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1758 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1759 } else if (ev
.keyCode
=== 32) {
1761 result
.key
= String
.fromCharCode(0);
1762 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1763 // escape, file sep, group sep, record sep, unit sep
1764 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1765 } else if (ev
.keyCode
=== 56) {
1767 result
.key
= String
.fromCharCode(127);
1768 } else if (ev
.keyCode
=== 219) {
1769 // ^[ - Control Sequence Introducer (CSI)
1770 result
.key
= String
.fromCharCode(27);
1771 } else if (ev
.keyCode
=== 220) {
1772 // ^\ - String Terminator (ST)
1773 result
.key
= String
.fromCharCode(28);
1774 } else if (ev
.keyCode
=== 221) {
1775 // ^] - Operating System Command (OSC)
1776 result
.key
= String
.fromCharCode(29);
1778 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1779 // On Mac this is a third level shift. Use <Esc> instead.
1780 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1781 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1782 } else if (ev
.keyCode
=== 192) {
1783 result
.key
= C0
.ESC
+ '`';
1784 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1785 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1787 } else if (this.browser
.isMac
&& !ev
.altKey
&& !ev
.ctrlKey
&& ev
.metaKey
) {
1788 if (ev
.keyCode
=== 65) { // cmd + a
1799 * Set the G level of the terminal
1802 Terminal
.prototype.setgLevel = function(g
) {
1804 this.charset
= this.charsets
[g
];
1808 * Set the charset for the given G level of the terminal
1812 Terminal
.prototype.setgCharset = function(g
, charset
) {
1813 this.charsets
[g
] = charset
;
1814 if (this.glevel
=== g
) {
1815 this.charset
= charset
;
1820 * Handle a keypress event.
1822 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1823 * @param {KeyboardEvent} ev The keypress event to be handled.
1825 Terminal
.prototype.keyPress = function(ev
) {
1828 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1836 } else if (ev
.which
== null) {
1838 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1845 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1850 key
= String
.fromCharCode(key
);
1852 this.emit('keypress', key
, ev
);
1853 this.emit('key', key
, ev
);
1861 * Send data for handling to the terminal
1862 * @param {string} data
1864 Terminal
.prototype.send = function(data
) {
1868 setTimeout(function() {
1869 self
.handler(self
.queue
);
1879 * Note: We could do sweet things with webaudio here
1881 Terminal
.prototype.bell = function() {
1882 if (!this.visualBell
) return;
1884 this.element
.style
.borderColor
= 'white';
1885 setTimeout(function() {
1886 self
.element
.style
.borderColor
= '';
1888 if (this.popOnBell
) this.focus();
1892 * Log the current state to the console.
1894 Terminal
.prototype.log = function() {
1895 if (!this.debug
) return;
1896 if (!this.context
.console
|| !this.context
.console
.log
) return;
1897 var args
= Array
.prototype.slice
.call(arguments
);
1898 this.context
.console
.log
.apply(this.context
.console
, args
);
1902 * Log the current state as error to the console.
1904 Terminal
.prototype.error = function() {
1905 if (!this.debug
) return;
1906 if (!this.context
.console
|| !this.context
.console
.error
) return;
1907 var args
= Array
.prototype.slice
.call(arguments
);
1908 this.context
.console
.error
.apply(this.context
.console
, args
);
1912 * Resizes the terminal.
1914 * @param {number} x The number of columns to resize to.
1915 * @param {number} y The number of rows to resize to.
1917 Terminal
.prototype.resize = function(x
, y
) {
1918 if (isNaN(x
) || isNaN(y
)) {
1922 if (y
> this.getOption('scrollback')) {
1923 this.setOption('scrollback', y
)
1933 if (x
=== this.cols
&& y
=== this.rows
) {
1934 // Check if we still need to measure the char size (fixes #785).
1935 if (!this.charMeasure
.width
|| !this.charMeasure
.height
) {
1936 this.charMeasure
.measure();
1947 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1948 i
= this.buffer
.lines
.length
;
1950 while (this.buffer
.lines
.get(i
).length
< x
) {
1951 this.buffer
.lines
.get(i
).push(ch
);
1957 this.setupStops(this.cols
);
1965 // y is rows, not this.buffer.y
1966 if (this.buffer
.lines
.length
< y
+ this.buffer
.ybase
) {
1967 if (this.buffer
.ybase
> 0 && this.buffer
.lines
.length
<= this.buffer
.ybase
+ this.buffer
.y
+ addToY
+ 1) {
1968 // There is room above the buffer and there are no empty elements below the line,
1970 this.buffer
.ybase
--;
1972 if (this.buffer
.ydisp
> 0) {
1973 // Viewport is at the top of the buffer, must increase downwards
1974 this.buffer
.ydisp
--;
1977 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1978 // are blank lines after the cursor
1979 this.buffer
.lines
.push(this.blankLine());
1982 if (this.children
.length
< y
) {
1988 if (this.buffer
.lines
.length
> y
+ this.buffer
.ybase
) {
1989 if (this.buffer
.lines
.length
> this.buffer
.ybase
+ this.buffer
.y
+ 1) {
1990 // The line is a blank line below the cursor, remove it
1991 this.buffer
.lines
.pop();
1993 // The line is the cursor, scroll down
1994 this.buffer
.ybase
++;
1995 this.buffer
.ydisp
++;
1998 if (this.children
.length
> y
) {
1999 el
= this.children
.shift();
2001 el
.parentNode
.removeChild(el
);
2007 // Make sure that the cursor stays on screen
2008 if (this.buffer
.y
>= y
) {
2009 this.buffer
.y
= y
- 1;
2012 this.buffer
.y
+= addToY
;
2015 if (this.buffer
.x
>= x
) {
2016 this.buffer
.x
= x
- 1;
2020 this.scrollBottom
= y
- 1;
2022 this.charMeasure
.measure();
2024 this.refresh(0, this.rows
- 1);
2028 this.geometry
= [this.cols
, this.rows
];
2029 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
2033 * Updates the range of rows to refresh
2034 * @param {number} y The number of rows to refresh next.
2036 Terminal
.prototype.updateRange = function(y
) {
2037 if (y
< this.refreshStart
) this.refreshStart
= y
;
2038 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
2039 // if (y > this.refreshEnd) {
2040 // this.refreshEnd = y;
2041 // if (y > this.rows - 1) {
2042 // this.refreshEnd = this.rows - 1;
2048 * Set the range of refreshing to the maximum value
2050 Terminal
.prototype.maxRange = function() {
2051 this.refreshStart
= 0;
2052 this.refreshEnd
= this.rows
- 1;
2058 * Setup the tab stops.
2061 Terminal
.prototype.setupStops = function(i
) {
2063 if (!this.tabs
[i
]) {
2064 i
= this.prevStop(i
);
2071 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
2072 this.tabs
[i
] = true;
2078 * Move the cursor to the previous tab stop from the given position (default is current).
2079 * @param {number} x The position to move the cursor to the previous tab stop.
2081 Terminal
.prototype.prevStop = function(x
) {
2082 if (x
== null) x
= this.buffer
.x
;
2083 while (!this.tabs
[--x
] && x
> 0);
2084 return x
>= this.cols
2091 * Move the cursor one tab stop forward from the given position (default is current).
2092 * @param {number} x The position to move the cursor one tab stop forward.
2094 Terminal
.prototype.nextStop = function(x
) {
2095 if (x
== null) x
= this.buffer
.x
;
2096 while (!this.tabs
[++x
] && x
< this.cols
);
2097 return x
>= this.cols
2104 * Erase in the identified line everything from "x" to the end of the line (right).
2105 * @param {number} x The column from which to start erasing to the end of the line.
2106 * @param {number} y The line in which to operate.
2108 Terminal
.prototype.eraseRight = function(x
, y
) {
2109 var line
= this.buffer
.lines
.get(this.buffer
.ybase
+ y
);
2113 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2114 for (; x
< this.cols
; x
++) {
2117 this.updateRange(y
);
2123 * Erase in the identified line everything from "x" to the start of the line (left).
2124 * @param {number} x The column from which to start erasing to the start of the line.
2125 * @param {number} y The line in which to operate.
2127 Terminal
.prototype.eraseLeft = function(x
, y
) {
2128 var line
= this.buffer
.lines
.get(this.buffer
.ybase
+ y
);
2132 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2137 this.updateRange(y
);
2141 * Clears the entire buffer, making the prompt line the new first line.
2143 Terminal
.prototype.clear = function() {
2144 if (this.buffer
.ybase
=== 0 && this.buffer
.y
=== 0) {
2145 // Don't clear if it's already clear
2148 this.buffer
.lines
.set(0, this.buffer
.lines
.get(this.buffer
.ybase
+ this.buffer
.y
));
2149 this.buffer
.lines
.length
= 1;
2150 this.buffer
.ydisp
= 0;
2151 this.buffer
.ybase
= 0;
2153 for (var i
= 1; i
< this.rows
; i
++) {
2154 this.buffer
.lines
.push(this.blankLine());
2156 this.refresh(0, this.rows
- 1);
2157 this.emit('scroll', this.buffer
.ydisp
);
2161 * Erase all content in the given line
2162 * @param {number} y The line to erase all of its contents.
2164 Terminal
.prototype.eraseLine = function(y
) {
2165 this.eraseRight(0, y
);
2170 * Return the data array of a blank line
2171 * @param {number} cur First bunch of data for each "blank" character.
2172 * @param {boolean} isWrapped Whether the new line is wrapped from the previous line.
2174 Terminal
.prototype.blankLine = function(cur
, isWrapped
) {
2179 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2183 // TODO: It is not ideal that this is a property on an array, a buffer line
2184 // class should be added that will hold this data and other useful functions.
2186 line
.isWrapped
= isWrapped
;
2189 for (; i
< this.cols
; i
++) {
2198 * If cur return the back color xterm feature attribute. Else return defAttr.
2199 * @param {object} cur
2201 Terminal
.prototype.ch = function(cur
) {
2203 ? [this.eraseAttr(), ' ', 1]
2204 : [this.defAttr
, ' ', 1];
2209 * Evaluate if the current erminal is the given argument.
2210 * @param {object} term The terminal to evaluate
2212 Terminal
.prototype.is = function(term
) {
2213 var name
= this.termName
;
2214 return (name
+ '').indexOf(term
) === 0;
2219 * Emit the 'data' event and populate the given data.
2220 * @param {string} data The data to populate in the event.
2222 Terminal
.prototype.handler = function(data
) {
2223 // Prevents all events to pty process if stdin is disabled
2224 if (this.options
.disableStdin
) {
2228 // Clear the selection if the selection manager is available and has an active selection
2229 if (this.selectionManager
&& this.selectionManager
.hasSelection
) {
2230 this.selectionManager
.clearSelection();
2233 // Input is being sent to the terminal, the terminal should focus the prompt.
2234 if (this.buffer
.ybase
!== this.buffer
.ydisp
) {
2235 this.scrollToBottom();
2237 this.emit('data', data
);
2242 * Emit the 'title' event and populate the given title.
2243 * @param {string} title The title to populate in the event.
2245 Terminal
.prototype.handleTitle = function(title
) {
2247 * This event is emitted when the title of the terminal is changed
2248 * from inside the terminal. The parameter is the new title.
2252 this.emit('title', title
);
2261 * ESC D Index (IND is 0x84).
2263 Terminal
.prototype.index = function() {
2265 if (this.buffer
.y
> this.scrollBottom
) {
2269 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2270 if (this.buffer
.x
>= this.cols
) {
2277 * ESC M Reverse Index (RI is 0x8d).
2279 * Move the cursor up one row, inserting a new blank line if necessary.
2281 Terminal
.prototype.reverseIndex = function() {
2283 if (this.buffer
.y
=== this.scrollTop
) {
2284 // possibly move the code below to term.reverseScroll();
2285 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2286 // blankLine(true) is xterm/linux behavior
2287 this.buffer
.lines
.shiftElements(this.buffer
.y
+ this.buffer
.ybase
, this.rows
- 1, 1);
2288 this.buffer
.lines
.set(this.buffer
.y
+ this.buffer
.ybase
, this.blankLine(true));
2289 this.updateRange(this.scrollTop
);
2290 this.updateRange(this.scrollBottom
);
2298 * ESC c Full Reset (RIS).
2300 Terminal
.prototype.reset = function() {
2301 this.options
.rows
= this.rows
;
2302 this.options
.cols
= this.cols
;
2303 var customKeyEventHandler
= this.customKeyEventHandler
;
2304 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2305 Terminal
.call(this, this.options
);
2306 this.customKeyEventHandler
= customKeyEventHandler
;
2307 this.cursorBlinkInterval
= cursorBlinkInterval
;
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.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
;