2 * xterm.js: xterm, in the browser
3 * Originally forked from (with the author's permission):
4 * Fabrice Bellard's javascript vt100 for jslinux:
5 * http://bellard.org/jslinux/
6 * Copyright (c) 2011 Fabrice Bellard
7 * The original design remains. The terminal itself
8 * has been extended to include xterm CSI codes, among
13 import { BufferSet
} from './BufferSet';
14 import { CompositionHelper
} from './CompositionHelper';
15 import { EventEmitter
} from './EventEmitter';
16 import { Viewport
} from './Viewport';
17 import { rightClickHandler
, moveTextAreaUnderMouseCursor
, pasteHandler
, copyHandler
} from './handlers/Clipboard';
18 import { CircularList
} from './utils/CircularList';
19 import { C0
} from './EscapeSequences';
20 import { InputHandler
} from './InputHandler';
21 import { Parser
} from './Parser';
22 import { Renderer
} from './Renderer';
23 import { Linkifier
} from './Linkifier';
24 import { SelectionManager
} from './SelectionManager';
25 import { CharMeasure
} from './utils/CharMeasure';
26 import * as Browser
from './utils/Browser';
27 import * as Mouse
from './utils/Mouse';
28 import { CHARSETS
} from './Charsets';
29 import { getRawByteCoords
} from './utils/Mouse';
30 import { translateBufferLineToString
} from './utils/BufferLine';
33 * Terminal Emulation References:
35 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
36 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
37 * http://invisible-island.net/vttest/
38 * http://www.inwap.com/pdp10/ansicode.txt
39 * http://linux.die.net/man/4/console_codes
40 * http://linux.die.net/man/7/urxvt
43 // Let it work inside Node.js for automated testing purposes.
44 var document
= (typeof window
!= 'undefined') ? window
.document
: null;
47 * The amount of write requests to queue before sending an XOFF signal to the
48 * pty process. This number must be small in order for ^C and similar sequences
51 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
54 * The number of writes to perform in a single batch before allowing the
55 * renderer to catch up with a 0ms setTimeout.
57 var WRITE_BATCH_SIZE
= 300;
60 * The time between cursor blinks. This is driven by JS rather than a CSS
61 * animation due to a bug in Chromium that causes it to use excessive CPU time.
62 * See https://github.com/Microsoft/vscode/issues/22900
64 var CURSOR_BLINK_INTERVAL
= 600;
71 * Creates a new `Terminal` object.
73 * @param {object} options An object containing a set of options, the available options are:
74 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
75 * - `cols` (number): The number of columns of the terminal (horizontal size)
76 * - `rows` (number): The number of rows of the terminal (vertical size)
80 * @alias module:xterm/src/xterm
82 function Terminal(options
) {
85 if (!(this instanceof Terminal
)) {
86 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
89 self
.browser
= Browser
;
90 self
.cancel
= Terminal
.cancel
;
92 EventEmitter
.call(this);
94 if (typeof options
=== 'number') {
102 options
= options
|| {};
105 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
106 if (options
[key
] == null) {
107 options
[key
] = Terminal
.options
[key
];
109 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
110 options
[key
] = Terminal
[key
];
113 self
[key
] = options
[key
];
116 if (options
.colors
.length
=== 8) {
117 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
118 } else if (options
.colors
.length
=== 16) {
119 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
120 } else if (options
.colors
.length
=== 10) {
121 options
.colors
= options
.colors
.slice(0, -2).concat(
122 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
123 } else if (options
.colors
.length
=== 18) {
124 options
.colors
= options
.colors
.concat(
125 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
127 this.colors
= options
.colors
;
129 this.options
= options
;
131 // this.context = options.context || window;
132 // this.document = options.document || document;
133 this.parent
= options
.body
|| options
.parent
|| (
134 document
? document
.getElementsByTagName('body')[0] : null
137 this.cols
= options
.cols
|| options
.geometry
[0];
138 this.rows
= options
.rows
|| options
.geometry
[1];
139 this.geometry
= [this.cols
, this.rows
];
141 if (options
.handler
) {
142 this.on('data', options
.handler
);
145 this.cursorState
= 0;
146 this.cursorHidden
= false;
149 this.customKeyEventHandler
= null;
150 this.cursorBlinkInterval
= null;
153 this.applicationKeypad
= false;
154 this.applicationCursor
= false;
155 this.originMode
= false;
156 this.insertMode
= false;
157 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
161 this.gcharset
= null;
163 this.charsets
= [null];
187 this.readable
= true;
188 this.writable
= true;
190 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
191 this.curAttr
= this.defAttr
;
194 this.currentParam
= 0;
198 this.inputHandler
= new InputHandler(this);
199 this.parser
= new Parser(this.inputHandler
, this);
200 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
201 this.renderer
= this.renderer
|| null;
202 this.selectionManager
= this.selectionManager
|| null;
203 this.linkifier
= this.linkifier
|| new Linkifier();
206 this.writeBuffer
= [];
207 this.writeInProgress
= false;
210 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
211 * This is a distinct state from writeStopped so that if the user requested
212 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
215 this.xoffSentToCatchUp
= false;
217 /** Whether writing has been stopped as a result of XOFF */
218 this.writeStopped
= false;
220 // leftover surrogate high from previous write invocation
221 this.surrogate_high
= '';
223 // Create the terminal's buffers and set the current buffer
224 this.buffers
= new BufferSet(this);
225 this.buffer
= this.buffers
.active
; // Convenience shortcut;
226 this.buffers
.on('activate', function (buffer
) {
227 this._terminal
.buffer
= buffer
;
233 this.buffer
.lines
.push(this.blankLine());
235 // Ensure the selection manager has the correct buffer
236 if (this.selectionManager
) {
237 this.selectionManager
.setBuffer(this.buffer
.lines
);
242 // Store if user went browsing history in scrollback
243 this.userScrolling
= false;
246 inherits(Terminal
, EventEmitter
);
249 * back_color_erase feature for xterm.
251 Terminal
.prototype.eraseAttr = function() {
252 // if (this.is('screen')) return this.defAttr;
253 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
261 Terminal
.tangoColors
= [
282 // Colors 0-15 + 16-255
283 // Much thanks to TooTallNate for writing this.
284 Terminal
.colors
= (function() {
285 var colors
= Terminal
.tangoColors
.slice()
286 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
291 for (; i
< 216; i
++) {
292 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
297 for (; i
< 24; i
++) {
302 function out(r
, g
, b
) {
303 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
308 return c
.length
< 2 ? '0' + c
: c
;
314 Terminal
._colors
= Terminal
.colors
.slice();
316 Terminal
.vcolors
= (function() {
318 , colors
= Terminal
.colors
322 for (; i
< 256; i
++) {
323 color
= parseInt(colors
[i
].substring(1), 16);
325 (color
>> 16) & 0xff,
338 Terminal
.defaults
= {
339 colors
: Terminal
.colors
,
345 cursorStyle
: 'block',
353 useFlowControl
: false,
355 // programFeatures: false,
359 Terminal
.options
= {};
361 Terminal
.focus
= null;
363 each(keys(Terminal
.defaults
), function(key
) {
364 Terminal
[key
] = Terminal
.defaults
[key
];
365 Terminal
.options
[key
] = Terminal
.defaults
[key
];
369 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
371 Terminal
.prototype.focus = function() {
372 return this.textarea
.focus();
376 * Retrieves an option's value from the terminal.
377 * @param {string} key The option key.
379 Terminal
.prototype.getOption = function(key
) {
380 if (!(key
in Terminal
.defaults
)) {
381 throw new Error('No option with key "' + key
+ '"');
384 if (typeof this.options
[key
] !== 'undefined') {
385 return this.options
[key
];
392 * Sets an option on the terminal.
393 * @param {string} key The option key.
394 * @param {string} value The option value.
396 Terminal
.prototype.setOption = function(key
, value
) {
397 if (!(key
in Terminal
.defaults
)) {
398 throw new Error('No option with key "' + key
+ '"');
402 if (value
< this.rows
) {
403 let msg
= 'Setting the scrollback value less than the number of rows ';
405 msg
+= `(${this.rows}) is not allowed.`;
411 if (this.options
[key
] !== value
) {
412 if (this.buffer
.lines
.length
> value
) {
413 const amountToTrim
= this.buffer
.lines
.length
- value
;
414 const needsRefresh
= (this.buffer
.ydisp
- amountToTrim
< 0);
415 this.buffer
.lines
.trimStart(amountToTrim
);
416 this.buffer
.ybase
= Math
.max(this.buffer
.ybase
- amountToTrim
, 0);
417 this.buffer
.ydisp
= Math
.max(this.buffer
.ydisp
- amountToTrim
, 0);
419 this.refresh(0, this.rows
- 1);
422 this.buffer
.lines
.maxLength
= value
;
423 this.viewport
.syncScrollArea();
428 this.options
[key
] = value
;
430 case 'cursorBlink': this.setCursorBlinking(value
); break;
432 // Style 'block' applies with no class
433 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
434 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
436 case 'tabStopWidth': this.setupStops(); break;
440 Terminal
.prototype.restartCursorBlinking = function () {
441 this.setCursorBlinking(this.options
.cursorBlink
);
444 Terminal
.prototype.setCursorBlinking = function (enabled
) {
445 this.element
.classList
.toggle('xterm-cursor-blink', enabled
);
446 this.clearCursorBlinkingInterval();
449 this.cursorBlinkInterval
= setInterval(function () {
450 self
.element
.classList
.toggle('xterm-cursor-blink-on');
451 }, CURSOR_BLINK_INTERVAL
);
455 Terminal
.prototype.clearCursorBlinkingInterval = function () {
456 this.element
.classList
.remove('xterm-cursor-blink-on');
457 if (this.cursorBlinkInterval
) {
458 clearInterval(this.cursorBlinkInterval
);
459 this.cursorBlinkInterval
= null;
464 * Binds the desired focus behavior on a given terminal object.
468 Terminal
.bindFocus = function (term
) {
469 on(term
.textarea
, 'focus', function (ev
) {
470 if (term
.sendFocus
) {
471 term
.send(C0
.ESC
+ '[I');
473 term
.element
.classList
.add('focus');
475 term
.restartCursorBlinking
.apply(term
);
476 Terminal
.focus
= term
;
477 term
.emit('focus', {terminal
: term
});
482 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
484 Terminal
.prototype.blur = function() {
485 return this.textarea
.blur();
489 * Binds the desired blur behavior on a given terminal object.
493 Terminal
.bindBlur = function (term
) {
494 on(term
.textarea
, 'blur', function (ev
) {
495 term
.refresh(term
.buffer
.y
, term
.buffer
.y
);
496 if (term
.sendFocus
) {
497 term
.send(C0
.ESC
+ '[O');
499 term
.element
.classList
.remove('focus');
500 term
.clearCursorBlinkingInterval
.apply(term
);
501 Terminal
.focus
= null;
502 term
.emit('blur', {terminal
: term
});
507 * Initialize default behavior
509 Terminal
.prototype.initGlobal = function() {
512 Terminal
.bindKeys(this);
513 Terminal
.bindFocus(this);
514 Terminal
.bindBlur(this);
516 // Bind clipboard functionality
517 on(this.element
, 'copy', event
=> {
518 // If mouse events are active it means the selection manager is disabled and
519 // copy should be handled by the host program.
520 if (!term
.hasSelection()) {
523 copyHandler(event
, term
, this.selectionManager
);
525 const pasteHandlerWrapper
= event
=> pasteHandler(event
, term
);
526 on(this.textarea
, 'paste', pasteHandlerWrapper
);
527 on(this.element
, 'paste', pasteHandlerWrapper
);
529 // Handle right click context menus
530 if (term
.browser
.isFirefox
) {
531 // Firefox doesn't appear to fire the contextmenu event on right click
532 on(this.element
, 'mousedown', event
=> {
533 if (event
.button
== 2) {
534 rightClickHandler(event
, this.textarea
, this.selectionManager
);
538 on(this.element
, 'contextmenu', event
=> {
539 rightClickHandler(event
, this.textarea
, this.selectionManager
);
543 // Move the textarea under the cursor when middle clicking on Linux to ensure
544 // middle click to paste selection works. This only appears to work in Chrome
545 // at the time is writing.
546 if (term
.browser
.isLinux
) {
547 // Use auxclick event over mousedown the latter doesn't seem to work. Note
548 // that the regular click event doesn't fire for the middle mouse button.
549 on(this.element
, 'auxclick', event
=> {
550 if (event
.button
=== 1) {
551 moveTextAreaUnderMouseCursor(event
, this.textarea
, this.selectionManager
);
558 * Apply key handling to the terminal
560 Terminal
.bindKeys = function(term
) {
561 on(term
.element
, 'keydown', function(ev
) {
562 if (document
.activeElement
!= this) {
568 on(term
.element
, 'keypress', function(ev
) {
569 if (document
.activeElement
!= this) {
575 on(term
.element
, 'keyup', function(ev
) {
576 if (!wasMondifierKeyOnlyEvent(ev
)) {
581 on(term
.textarea
, 'keydown', function(ev
) {
585 on(term
.textarea
, 'keypress', function(ev
) {
587 // Truncate the textarea's value, since it is not needed
591 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
592 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
593 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
594 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
595 term
.on('refresh', function (data
) {
596 term
.queueLinkification(data
.start
, data
.end
)
602 * Insert the given row to the terminal or produce a new one
603 * if no row argument is passed. Return the inserted row.
604 * @param {HTMLElement} row (optional) The row to append to the terminal.
606 Terminal
.prototype.insertRow = function (row
) {
607 if (typeof row
!= 'object') {
608 row
= document
.createElement('div');
611 this.rowContainer
.appendChild(row
);
612 this.children
.push(row
);
618 * Opens the terminal within an element.
620 * @param {HTMLElement} parent The element to create the terminal within.
621 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
623 Terminal
.prototype.open = function(parent
, focus
) {
624 var self
=this, i
=0, div
;
626 this.parent
= parent
|| this.parent
;
629 throw new Error('Terminal requires a parent element.');
632 // Grab global elements
633 this.context
= this.parent
.ownerDocument
.defaultView
;
634 this.document
= this.parent
.ownerDocument
;
635 this.body
= this.document
.getElementsByTagName('body')[0];
637 //Create main element container
638 this.element
= this.document
.createElement('div');
639 this.element
.classList
.add('terminal');
640 this.element
.classList
.add('xterm');
641 this.element
.classList
.add('xterm-theme-' + this.theme
);
642 this.setCursorBlinking(this.options
.cursorBlink
);
644 this.element
.setAttribute('tabindex', 0);
646 this.viewportElement
= document
.createElement('div');
647 this.viewportElement
.classList
.add('xterm-viewport');
648 this.element
.appendChild(this.viewportElement
);
649 this.viewportScrollArea
= document
.createElement('div');
650 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
651 this.viewportElement
.appendChild(this.viewportScrollArea
);
653 // Create the selection container.
654 this.selectionContainer
= document
.createElement('div');
655 this.selectionContainer
.classList
.add('xterm-selection');
656 this.element
.appendChild(this.selectionContainer
);
658 // Create the container that will hold the lines of the terminal and then
659 // produce the lines the lines.
660 this.rowContainer
= document
.createElement('div');
661 this.rowContainer
.classList
.add('xterm-rows');
662 this.element
.appendChild(this.rowContainer
);
664 this.linkifier
.attachToDom(document
, this.children
);
666 // Create the container that will hold helpers like the textarea for
667 // capturing DOM Events. Then produce the helpers.
668 this.helperContainer
= document
.createElement('div');
669 this.helperContainer
.classList
.add('xterm-helpers');
670 // TODO: This should probably be inserted once it's filled to prevent an additional layout
671 this.element
.appendChild(this.helperContainer
);
672 this.textarea
= document
.createElement('textarea');
673 this.textarea
.classList
.add('xterm-helper-textarea');
674 this.textarea
.setAttribute('autocorrect', 'off');
675 this.textarea
.setAttribute('autocapitalize', 'off');
676 this.textarea
.setAttribute('spellcheck', 'false');
677 this.textarea
.tabIndex
= 0;
678 this.textarea
.addEventListener('focus', function() {
679 self
.emit('focus', {terminal
: self
});
681 this.textarea
.addEventListener('blur', function() {
682 self
.emit('blur', {terminal
: self
});
684 this.helperContainer
.appendChild(this.textarea
);
686 this.compositionView
= document
.createElement('div');
687 this.compositionView
.classList
.add('composition-view');
688 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
689 this.helperContainer
.appendChild(this.compositionView
);
691 this.charSizeStyleElement
= document
.createElement('style');
692 this.helperContainer
.appendChild(this.charSizeStyleElement
);
694 for (; i
< this.rows
; i
++) {
697 this.parent
.appendChild(this.element
);
699 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
700 this.charMeasure
.on('charsizechanged', function () {
701 self
.updateCharSizeStyles();
703 this.charMeasure
.measure();
705 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
706 this.renderer
= new Renderer(this);
707 this.selectionManager
= new SelectionManager(
708 this, this.buffer
.lines
, this.rowContainer
, this.charMeasure
710 this.selectionManager
.on('refresh', data
=> {
711 this.renderer
.refreshSelection(data
.start
, data
.end
);
713 this.selectionManager
.on('newselection', text
=> {
714 // If there's a new selection, put it into the textarea, focus and select it
715 // in order to register it as a selection on the OS. This event is fired
716 // only on Linux to enable middle click to paste selection.
717 this.textarea
.value
= text
;
718 this.textarea
.focus();
719 this.textarea
.select();
721 this.on('scroll', () => this.selectionManager
.refresh());
722 this.viewportElement
.addEventListener('scroll', () => this.selectionManager
.refresh());
724 // Setup loop that draws to screen
725 this.refresh(0, this.rows
- 1);
727 // Initialize global actions that
728 // need to be taken on the document.
732 * Automatic focus functionality.
733 * TODO: Default to `false` starting with xterm.js 3.0.
735 if (typeof focus
== 'undefined') {
736 let message
= 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
738 message
+= 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
739 message
+= 'it will default to `false`.';
741 console
.warn(message
);
749 // Focus terminal when it gets clicked
750 on(this.element
, 'click', function() {
754 // Listen for mouse events and translate
755 // them into terminal mouse protocols.
759 * This event is emitted when terminal has completed opening.
768 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
769 * @param {string} addon The name of the addon to load
772 Terminal
.loadAddon = function(addon
, callback
) {
773 if (typeof exports
=== 'object' && typeof module
=== 'object') {
775 return require('./addons/' + addon
+ '/' + addon
);
776 } else if (typeof define
== 'function') {
778 return require(['./addons/' + addon
+ '/' + addon
], callback
);
780 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
786 * Updates the helper CSS class with any changes necessary after the terminal's
787 * character width has been changed.
789 Terminal
.prototype.updateCharSizeStyles = function() {
790 this.charSizeStyleElement
.textContent
=
791 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
792 `.xterm-normal-char{width:${this.charMeasure.width}px;}` +
793 `.xterm-rows > div{height:${this.charMeasure.height}px;}`;
798 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
799 * To better understand these
800 * the xterm code is very helpful:
802 * button.c, charproc.c, misc.c
803 * Relevant functions in xterm/button.c:
804 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
806 Terminal
.prototype.bindMouse = function() {
807 var el
= this.element
, self
= this, pressed
= 32;
809 // mouseup, mousedown, wheel
810 // left click: ^[[M 3<^[[M#3<
812 function sendButton(ev
) {
816 // get the xterm-style button
817 button
= getButton(ev
);
819 // get mouse coordinates
820 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
823 sendEvent(button
, pos
);
825 switch (ev
.overrideType
|| ev
.type
) {
830 // keep it at the left
831 // button, just in case.
842 // motion example of a left click:
843 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
844 function sendMove(ev
) {
848 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
851 // buttons marked as motions
852 // are incremented by 32
855 sendEvent(button
, pos
);
859 // position to characters
860 function encode(data
, ch
) {
861 if (!self
.utfMouse
) {
862 if (ch
=== 255) return data
.push(0);
863 if (ch
> 127) ch
= 127;
866 if (ch
=== 2047) return data
.push(0);
870 if (ch
> 2047) ch
= 2047;
871 data
.push(0xC0 | (ch
>> 6));
872 data
.push(0x80 | (ch
& 0x3F));
877 // send a mouse event:
878 // regular/utf8: ^[[M Cb Cx Cy
879 // urxvt: ^[[ Cb ; Cx ; Cy M
880 // sgr: ^[[ Cb ; Cx ; Cy M/m
881 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
882 // locator: CSI P e ; P b ; P r ; P c ; P p & w
883 function sendEvent(button
, pos
) {
884 // self.emit('mouse', {
890 if (self
.vt300Mouse
) {
892 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
896 var data
= C0
.ESC
+ '[24';
897 if (button
=== 0) data
+= '1';
898 else if (button
=== 1) data
+= '3';
899 else if (button
=== 2) data
+= '5';
900 else if (button
=== 3) return;
902 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
907 if (self
.decLocator
) {
912 if (button
=== 0) button
= 2;
913 else if (button
=== 1) button
= 4;
914 else if (button
=== 2) button
= 6;
915 else if (button
=== 3) button
= 3;
916 self
.send(C0
.ESC
+ '['
919 + (button
=== 3 ? 4 : 0)
930 if (self
.urxvtMouse
) {
935 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
942 self
.send(C0
.ESC
+ '[<'
943 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
948 + ((button
& 3) === 3 ? 'm' : 'M'));
954 encode(data
, button
);
958 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
961 function getButton(ev
) {
974 // 1, and 2 - with 64 added
975 switch (ev
.overrideType
|| ev
.type
) {
977 button
= ev
.button
!= null
983 if (self
.browser
.isMSIE
) {
984 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
990 case 'DOMMouseScroll':
991 button
= ev
.detail
< 0
996 button
= ev
.wheelDeltaY
> 0
1002 // next three bits are the modifiers:
1003 // 4 = shift, 8 = meta, 16 = control
1004 shift
= ev
.shiftKey
? 4 : 0;
1005 meta
= ev
.metaKey
? 8 : 0;
1006 ctrl
= ev
.ctrlKey
? 16 : 0;
1007 mod
= shift
| meta
| ctrl
;
1010 if (self
.vt200Mouse
) {
1013 } else if (!self
.normalMouse
) {
1018 button
= (32 + (mod
<< 2)) + button
;
1023 on(el
, 'mousedown', function(ev
) {
1024 if (!self
.mouseEvents
) return;
1033 //if (self.vt200Mouse && !self.normalMouse) {
1034 if (self
.vt200Mouse
) {
1035 ev
.overrideType
= 'mouseup';
1037 return self
.cancel(ev
);
1041 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1043 // x10 compatibility mode can't send button releases
1044 if (!self
.x10Mouse
) {
1045 on(self
.document
, 'mouseup', function up(ev
) {
1047 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1048 off(self
.document
, 'mouseup', up
);
1049 return self
.cancel(ev
);
1053 return self
.cancel(ev
);
1056 //if (self.normalMouse) {
1057 // on(self.document, 'mousemove', sendMove);
1060 on(el
, 'wheel', function(ev
) {
1061 if (!self
.mouseEvents
) return;
1064 || self
.decLocator
) return;
1066 return self
.cancel(ev
);
1069 // allow wheel scrolling in
1070 // the shell for example
1071 on(el
, 'wheel', function(ev
) {
1072 if (self
.mouseEvents
) return;
1073 self
.viewport
.onWheel(ev
);
1074 return self
.cancel(ev
);
1077 on(el
, 'touchstart', function(ev
) {
1078 if (self
.mouseEvents
) return;
1079 self
.viewport
.onTouchStart(ev
);
1080 return self
.cancel(ev
);
1083 on(el
, 'touchmove', function(ev
) {
1084 if (self
.mouseEvents
) return;
1085 self
.viewport
.onTouchMove(ev
);
1086 return self
.cancel(ev
);
1091 * Destroys the terminal.
1093 Terminal
.prototype.destroy = function() {
1094 this.readable
= false;
1095 this.writable
= false;
1097 this.handler = function() {};
1098 this.write = function() {};
1099 if (this.element
&& this.element
.parentNode
) {
1100 this.element
.parentNode
.removeChild(this.element
);
1102 //this.emit('close');
1106 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1108 * @param {number} start The row to start from (between 0 and this.rows - 1).
1109 * @param {number} end The row to end at (between start and this.rows - 1).
1111 Terminal
.prototype.refresh = function(start
, end
) {
1112 if (this.renderer
) {
1113 this.renderer
.queueRefresh(start
, end
);
1118 * Queues linkification for the specified rows.
1119 * @param {number} start The row to start from (between 0 and this.rows - 1).
1120 * @param {number} end The row to end at (between start and this.rows - 1).
1122 Terminal
.prototype.queueLinkification = function(start
, end
) {
1123 if (this.linkifier
) {
1124 for (let i
= start
; i
<= end
; i
++) {
1125 this.linkifier
.linkifyRow(i
);
1131 * Display the cursor element
1133 Terminal
.prototype.showCursor = function() {
1134 if (!this.cursorState
) {
1135 this.cursorState
= 1;
1136 this.refresh(this.buffer
.y
, this.buffer
.y
);
1141 * Scroll the terminal down 1 row, creating a blank line.
1142 * @param {boolean} isWrapped Whether the new line is wrapped from the previous
1145 Terminal
.prototype.scroll = function(isWrapped
) {
1148 // Make room for the new row in lines
1149 if (this.buffer
.lines
.length
=== this.buffer
.lines
.maxLength
) {
1150 this.buffer
.lines
.trimStart(1);
1151 this.buffer
.ybase
--;
1152 if (this.buffer
.ydisp
!== 0) {
1153 this.buffer
.ydisp
--;
1157 this.buffer
.ybase
++;
1159 // TODO: Why is this done twice?
1160 if (!this.userScrolling
) {
1161 this.buffer
.ydisp
= this.buffer
.ybase
;
1165 row
= this.buffer
.ybase
+ this.rows
- 1;
1167 // subtract the bottom scroll region
1168 row
-= this.rows
- 1 - this.buffer
.scrollBottom
;
1170 if (row
=== this.buffer
.lines
.length
) {
1171 // Optimization: pushing is faster than splicing when they amount to the same behavior
1172 this.buffer
.lines
.push(this.blankLine(undefined, isWrapped
));
1175 this.buffer
.lines
.splice(row
, 0, this.blankLine(undefined, isWrapped
));
1178 if (this.buffer
.scrollTop
!== 0) {
1179 if (this.buffer
.ybase
!== 0) {
1180 this.buffer
.ybase
--;
1181 if (!this.userScrolling
) {
1182 this.buffer
.ydisp
= this.buffer
.ybase
;
1185 this.buffer
.lines
.splice(this.buffer
.ybase
+ this.buffer
.scrollTop
, 1);
1189 this.updateRange(this.buffer
.scrollTop
);
1190 this.updateRange(this.buffer
.scrollBottom
);
1193 * This event is emitted whenever the terminal is scrolled.
1194 * The one parameter passed is the new y display position.
1198 this.emit('scroll', this.buffer
.ydisp
);
1202 * Scroll the display of the terminal
1203 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1204 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1205 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1206 * viewport originally.
1208 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1210 if (this.buffer
.ydisp
=== 0) {
1213 this.userScrolling
= true;
1214 } else if (disp
+ this.buffer
.ydisp
>= this.buffer
.ybase
) {
1215 this.userScrolling
= false;
1218 const oldYdisp
= this.buffer
.ydisp
;
1219 this.buffer
.ydisp
= Math
.max(Math
.min(this.buffer
.ydisp
+ disp
, this.buffer
.ybase
), 0);
1221 // No change occurred, don't trigger scroll/refresh
1222 if (oldYdisp
=== this.buffer
.ydisp
) {
1226 if (!suppressScrollEvent
) {
1227 this.emit('scroll', this.buffer
.ydisp
);
1230 this.refresh(0, this.rows
- 1);
1234 * Scroll the display of the terminal by a number of pages.
1235 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1237 Terminal
.prototype.scrollPages = function(pageCount
) {
1238 this.scrollDisp(pageCount
* (this.rows
- 1));
1242 * Scrolls the display of the terminal to the top.
1244 Terminal
.prototype.scrollToTop = function() {
1245 this.scrollDisp(-this.buffer
.ydisp
);
1249 * Scrolls the display of the terminal to the bottom.
1251 Terminal
.prototype.scrollToBottom = function() {
1252 this.scrollDisp(this.buffer
.ybase
- this.buffer
.ydisp
);
1256 * Writes text to the terminal.
1257 * @param {string} data The text to write to the terminal.
1259 Terminal
.prototype.write = function(data
) {
1260 this.writeBuffer
.push(data
);
1262 // Send XOFF to pause the pty process if the write buffer becomes too large so
1263 // xterm.js can catch up before more data is sent. This is necessary in order
1264 // to keep signals such as ^C responsive.
1265 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1266 // XOFF - stop pty pipe
1267 // XON will be triggered by emulator before processing data chunk
1269 this.xoffSentToCatchUp
= true;
1272 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1273 // Kick off a write which will write all data in sequence recursively
1274 this.writeInProgress
= true;
1275 // Kick off an async innerWrite so more writes can come in while processing data
1277 setTimeout(function () {
1283 Terminal
.prototype.innerWrite = function() {
1284 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1285 while (writeBatch
.length
> 0) {
1286 var data
= writeBatch
.shift();
1287 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1289 // If XOFF was sent in order to catch up with the pty process, resume it if
1290 // the writeBuffer is empty to allow more data to come in.
1291 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1293 this.xoffSentToCatchUp
= false;
1296 this.refreshStart
= this.buffer
.y
;
1297 this.refreshEnd
= this.buffer
.y
;
1299 // HACK: Set the parser state based on it's state at the time of return.
1300 // This works around the bug #662 which saw the parser state reset in the
1301 // middle of parsing escape sequence in two chunks. For some reason the
1302 // state of the parser resets to 0 after exiting parser.parse. This change
1303 // just sets the state back based on the correct return statement.
1304 var state
= this.parser
.parse(data
);
1305 this.parser
.setState(state
);
1307 this.updateRange(this.buffer
.y
);
1308 this.refresh(this.refreshStart
, this.refreshEnd
);
1310 if (this.writeBuffer
.length
> 0) {
1311 // Allow renderer to catch up before processing the next batch
1313 setTimeout(function () {
1317 this.writeInProgress
= false;
1322 * Writes text to the terminal, followed by a break line character (\n).
1323 * @param {string} data The text to write to the terminal.
1325 Terminal
.prototype.writeln = function(data
) {
1326 this.write(data
+ '\r\n');
1330 * DEPRECATED: only for backward compatibility. Please use attachCustomKeyEventHandler() instead.
1331 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1332 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1333 * the default action. The function returns whether the event should be processed by xterm.js.
1335 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1336 let message
= 'attachCustomKeydownHandler() is DEPRECATED and will be removed soon. Please use attachCustomKeyEventHandler() instead.';
1337 console
.warn(message
);
1338 this.attachCustomKeyEventHandler(customKeydownHandler
);
1342 * Attaches a custom key event handler which is run before keys are processed, giving consumers of
1343 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1345 * @param {function} customKeyEventHandler The custom KeyboardEvent handler to attach. This is a
1346 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1347 * the default action. The function returns whether the event should be processed by xterm.js.
1349 Terminal
.prototype.attachCustomKeyEventHandler = function(customKeyEventHandler
) {
1350 this.customKeyEventHandler
= customKeyEventHandler
;
1354 * Attaches a http(s) link handler, forcing web links to behave differently to
1355 * regular <a> tags. This will trigger a refresh as links potentially need to be
1356 * reconstructed. Calling this with null will remove the handler.
1357 * @param {LinkMatcherHandler} handler The handler callback function.
1359 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1360 if (!this.linkifier
) {
1361 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1363 this.linkifier
.setHypertextLinkHandler(handler
);
1364 // Refresh to force links to refresh
1365 this.refresh(0, this.rows
- 1);
1369 * Attaches a validation callback for hypertext links. This is useful to use
1370 * validation logic or to do something with the link's element and url.
1371 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1372 * be cleared with null.
1374 Terminal
.prototype.setHypertextValidationCallback = function(callback
) {
1375 if (!this.linkifier
) {
1376 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1378 this.linkifier
.setHypertextValidationCallback(callback
);
1379 // Refresh to force links to refresh
1380 this.refresh(0, this.rows
- 1);
1384 * Registers a link matcher, allowing custom link patterns to be matched and
1386 * @param {RegExp} regex The regular expression to search for, specifically
1387 * this searches the textContent of the rows. You will want to use \s to match
1388 * a space ' ' character for example.
1389 * @param {LinkMatcherHandler} handler The callback when the link is called.
1390 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1391 * @return {number} The ID of the new matcher, this can be used to deregister.
1393 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1394 if (this.linkifier
) {
1395 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1396 this.refresh(0, this.rows
- 1);
1402 * Deregisters a link matcher if it has been registered.
1403 * @param {number} matcherId The link matcher's ID (returned after register)
1405 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1406 if (this.linkifier
) {
1407 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1408 this.refresh(0, this.rows
- 1);
1414 * Gets whether the terminal has an active selection.
1416 Terminal
.prototype.hasSelection = function() {
1417 return this.selectionManager
? this.selectionManager
.hasSelection
: false;
1421 * Gets the terminal's current selection, this is useful for implementing copy
1422 * behavior outside of xterm.js.
1424 Terminal
.prototype.getSelection = function() {
1425 return this.selectionManager
? this.selectionManager
.selectionText
: '';
1429 * Clears the current terminal selection.
1431 Terminal
.prototype.clearSelection = function() {
1432 if (this.selectionManager
) {
1433 this.selectionManager
.clearSelection();
1438 * Selects all text within the terminal.
1440 Terminal
.prototype.selectAll = function() {
1441 if (this.selectionManager
) {
1442 this.selectionManager
.selectAll();
1447 * Handle a keydown event
1449 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1450 * @param {KeyboardEvent} ev The keydown event to be handled.
1452 Terminal
.prototype.keyDown = function(ev
) {
1453 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1457 this.restartCursorBlinking();
1459 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1460 if (this.buffer
.ybase
!== this.buffer
.ydisp
) {
1461 this.scrollToBottom();
1467 var result
= this.evaluateKeyEscapeSequence(ev
);
1469 if (result
.key
=== C0
.DC3
) { // XOFF
1470 this.writeStopped
= true;
1471 } else if (result
.key
=== C0
.DC1
) { // XON
1472 this.writeStopped
= false;
1475 if (result
.scrollDisp
) {
1476 this.scrollDisp(result
.scrollDisp
);
1477 return this.cancel(ev
, true);
1480 if (isThirdLevelShift(this, ev
)) {
1484 if (result
.cancel
) {
1485 // The event is canceled at the end already, is this necessary?
1486 this.cancel(ev
, true);
1493 this.emit('keydown', ev
);
1494 this.emit('key', result
.key
, ev
);
1496 this.handler(result
.key
);
1498 return this.cancel(ev
, true);
1502 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1503 * returned value is the new key code to pass to the PTY.
1505 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1506 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1508 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1510 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1511 // canceled at the end of keyDown
1513 // The new key even to emit
1515 // The number of characters to scroll, if this is defined it will cancel the event
1516 scrollDisp
: undefined
1518 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1519 switch (ev
.keyCode
) {
1523 result
.key
= C0
.BS
; // ^H
1526 result
.key
= C0
.DEL
; // ^?
1531 result
.key
= C0
.ESC
+ '[Z';
1535 result
.cancel
= true;
1540 result
.cancel
= true;
1544 result
.key
= C0
.ESC
;
1545 result
.cancel
= true;
1550 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1551 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1552 // http://unix.stackexchange.com/a/108106
1553 // macOS uses different escape sequences than linux
1554 if (result
.key
== C0
.ESC
+ '[1;3D') {
1555 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1557 } else if (this.applicationCursor
) {
1558 result
.key
= C0
.ESC
+ 'OD';
1560 result
.key
= C0
.ESC
+ '[D';
1566 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1567 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1568 // http://unix.stackexchange.com/a/108106
1569 // macOS uses different escape sequences than linux
1570 if (result
.key
== C0
.ESC
+ '[1;3C') {
1571 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1573 } else if (this.applicationCursor
) {
1574 result
.key
= C0
.ESC
+ 'OC';
1576 result
.key
= C0
.ESC
+ '[C';
1582 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1583 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1584 // http://unix.stackexchange.com/a/108106
1585 if (result
.key
== C0
.ESC
+ '[1;3A') {
1586 result
.key
= C0
.ESC
+ '[1;5A';
1588 } else if (this.applicationCursor
) {
1589 result
.key
= C0
.ESC
+ 'OA';
1591 result
.key
= C0
.ESC
+ '[A';
1597 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1598 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1599 // http://unix.stackexchange.com/a/108106
1600 if (result
.key
== C0
.ESC
+ '[1;3B') {
1601 result
.key
= C0
.ESC
+ '[1;5B';
1603 } else if (this.applicationCursor
) {
1604 result
.key
= C0
.ESC
+ 'OB';
1606 result
.key
= C0
.ESC
+ '[B';
1611 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1612 // <Ctrl> or <Shift> + <Insert> are used to
1613 // copy-paste on some systems.
1614 result
.key
= C0
.ESC
+ '[2~';
1620 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1622 result
.key
= C0
.ESC
+ '[3~';
1628 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1629 else if (this.applicationCursor
)
1630 result
.key
= C0
.ESC
+ 'OH';
1632 result
.key
= C0
.ESC
+ '[H';
1637 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1638 else if (this.applicationCursor
)
1639 result
.key
= C0
.ESC
+ 'OF';
1641 result
.key
= C0
.ESC
+ '[F';
1646 result
.scrollDisp
= -(this.rows
- 1);
1648 result
.key
= C0
.ESC
+ '[5~';
1654 result
.scrollDisp
= this.rows
- 1;
1656 result
.key
= C0
.ESC
+ '[6~';
1662 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1664 result
.key
= C0
.ESC
+ 'OP';
1669 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1671 result
.key
= C0
.ESC
+ 'OQ';
1676 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1678 result
.key
= C0
.ESC
+ 'OR';
1683 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1685 result
.key
= C0
.ESC
+ 'OS';
1690 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1692 result
.key
= C0
.ESC
+ '[15~';
1697 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1699 result
.key
= C0
.ESC
+ '[17~';
1704 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1706 result
.key
= C0
.ESC
+ '[18~';
1711 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1713 result
.key
= C0
.ESC
+ '[19~';
1718 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1720 result
.key
= C0
.ESC
+ '[20~';
1725 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1727 result
.key
= C0
.ESC
+ '[21~';
1732 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1734 result
.key
= C0
.ESC
+ '[23~';
1739 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1741 result
.key
= C0
.ESC
+ '[24~';
1746 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1747 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1748 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1749 } else if (ev
.keyCode
=== 32) {
1751 result
.key
= String
.fromCharCode(0);
1752 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1753 // escape, file sep, group sep, record sep, unit sep
1754 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1755 } else if (ev
.keyCode
=== 56) {
1757 result
.key
= String
.fromCharCode(127);
1758 } else if (ev
.keyCode
=== 219) {
1759 // ^[ - Control Sequence Introducer (CSI)
1760 result
.key
= String
.fromCharCode(27);
1761 } else if (ev
.keyCode
=== 220) {
1762 // ^\ - String Terminator (ST)
1763 result
.key
= String
.fromCharCode(28);
1764 } else if (ev
.keyCode
=== 221) {
1765 // ^] - Operating System Command (OSC)
1766 result
.key
= String
.fromCharCode(29);
1768 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1769 // On Mac this is a third level shift. Use <Esc> instead.
1770 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1771 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1772 } else if (ev
.keyCode
=== 192) {
1773 result
.key
= C0
.ESC
+ '`';
1774 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1775 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1777 } else if (this.browser
.isMac
&& !ev
.altKey
&& !ev
.ctrlKey
&& ev
.metaKey
) {
1778 if (ev
.keyCode
=== 65) { // cmd + a
1789 * Set the G level of the terminal
1792 Terminal
.prototype.setgLevel = function(g
) {
1794 this.charset
= this.charsets
[g
];
1798 * Set the charset for the given G level of the terminal
1802 Terminal
.prototype.setgCharset = function(g
, charset
) {
1803 this.charsets
[g
] = charset
;
1804 if (this.glevel
=== g
) {
1805 this.charset
= charset
;
1810 * Handle a keypress event.
1812 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1813 * @param {KeyboardEvent} ev The keypress event to be handled.
1815 Terminal
.prototype.keyPress = function(ev
) {
1818 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1826 } else if (ev
.which
== null) {
1828 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1835 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1840 key
= String
.fromCharCode(key
);
1842 this.emit('keypress', key
, ev
);
1843 this.emit('key', key
, ev
);
1851 * Send data for handling to the terminal
1852 * @param {string} data
1854 Terminal
.prototype.send = function(data
) {
1858 setTimeout(function() {
1859 self
.handler(self
.queue
);
1869 * Note: We could do sweet things with webaudio here
1871 Terminal
.prototype.bell = function() {
1872 if (!this.visualBell
) return;
1874 this.element
.style
.borderColor
= 'white';
1875 setTimeout(function() {
1876 self
.element
.style
.borderColor
= '';
1878 if (this.popOnBell
) this.focus();
1882 * Log the current state to the console.
1884 Terminal
.prototype.log = function() {
1885 if (!this.debug
) return;
1886 if (!this.context
.console
|| !this.context
.console
.log
) return;
1887 var args
= Array
.prototype.slice
.call(arguments
);
1888 this.context
.console
.log
.apply(this.context
.console
, args
);
1892 * Log the current state as error to the console.
1894 Terminal
.prototype.error = function() {
1895 if (!this.debug
) return;
1896 if (!this.context
.console
|| !this.context
.console
.error
) return;
1897 var args
= Array
.prototype.slice
.call(arguments
);
1898 this.context
.console
.error
.apply(this.context
.console
, args
);
1902 * Resizes the terminal.
1904 * @param {number} x The number of columns to resize to.
1905 * @param {number} y The number of rows to resize to.
1907 Terminal
.prototype.resize = function(x
, y
) {
1908 if (isNaN(x
) || isNaN(y
)) {
1912 if (y
> this.getOption('scrollback')) {
1913 this.setOption('scrollback', y
)
1923 if (x
=== this.cols
&& y
=== this.rows
) {
1924 // Check if we still need to measure the char size (fixes #785).
1925 if (!this.charMeasure
.width
|| !this.charMeasure
.height
) {
1926 this.charMeasure
.measure();
1937 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1938 i
= this.buffer
.lines
.length
;
1940 if (this.buffer
.lines
.get(i
) === undefined) {
1941 this.buffer
.lines
.set(i
, this.blankLine());
1943 while (this.buffer
.lines
.get(i
).length
< x
) {
1944 this.buffer
.lines
.get(i
).push(ch
);
1950 this.setupStops(this.cols
);
1958 // y is rows, not this.buffer.y
1959 if (this.buffer
.lines
.length
< y
+ this.buffer
.ybase
) {
1960 if (this.buffer
.ybase
> 0 && this.buffer
.lines
.length
<= this.buffer
.ybase
+ this.buffer
.y
+ addToY
+ 1) {
1961 // There is room above the buffer and there are no empty elements below the line,
1963 this.buffer
.ybase
--;
1965 if (this.buffer
.ydisp
> 0) {
1966 // Viewport is at the top of the buffer, must increase downwards
1967 this.buffer
.ydisp
--;
1970 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1971 // are blank lines after the cursor
1972 this.buffer
.lines
.push(this.blankLine());
1975 if (this.children
.length
< y
) {
1981 if (this.buffer
.lines
.length
> y
+ this.buffer
.ybase
) {
1982 if (this.buffer
.lines
.length
> this.buffer
.ybase
+ this.buffer
.y
+ 1) {
1983 // The line is a blank line below the cursor, remove it
1984 this.buffer
.lines
.pop();
1986 // The line is the cursor, scroll down
1987 this.buffer
.ybase
++;
1988 this.buffer
.ydisp
++;
1991 if (this.children
.length
> y
) {
1992 el
= this.children
.shift();
1994 el
.parentNode
.removeChild(el
);
2000 // Make sure that the cursor stays on screen
2001 if (this.buffer
.y
>= y
) {
2002 this.buffer
.y
= y
- 1;
2005 this.buffer
.y
+= addToY
;
2008 if (this.buffer
.x
>= x
) {
2009 this.buffer
.x
= x
- 1;
2012 this.buffer
.scrollTop
= 0;
2013 this.buffer
.scrollBottom
= y
- 1;
2015 this.charMeasure
.measure();
2017 this.refresh(0, this.rows
- 1);
2019 this.geometry
= [this.cols
, this.rows
];
2020 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
2024 * Updates the range of rows to refresh
2025 * @param {number} y The number of rows to refresh next.
2027 Terminal
.prototype.updateRange = function(y
) {
2028 if (y
< this.refreshStart
) this.refreshStart
= y
;
2029 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
2030 // if (y > this.refreshEnd) {
2031 // this.refreshEnd = y;
2032 // if (y > this.rows - 1) {
2033 // this.refreshEnd = this.rows - 1;
2039 * Set the range of refreshing to the maximum value
2041 Terminal
.prototype.maxRange = function() {
2042 this.refreshStart
= 0;
2043 this.refreshEnd
= this.rows
- 1;
2049 * Setup the tab stops.
2052 Terminal
.prototype.setupStops = function(i
) {
2054 if (!this.buffer
.tabs
[i
]) {
2055 i
= this.prevStop(i
);
2058 this.buffer
.tabs
= {};
2062 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
2063 this.buffer
.tabs
[i
] = true;
2069 * Move the cursor to the previous tab stop from the given position (default is current).
2070 * @param {number} x The position to move the cursor to the previous tab stop.
2072 Terminal
.prototype.prevStop = function(x
) {
2073 if (x
== null) x
= this.buffer
.x
;
2074 while (!this.buffer
.tabs
[--x
] && x
> 0);
2075 return x
>= this.cols
2082 * Move the cursor one tab stop forward from the given position (default is current).
2083 * @param {number} x The position to move the cursor one tab stop forward.
2085 Terminal
.prototype.nextStop = function(x
) {
2086 if (x
== null) x
= this.buffer
.x
;
2087 while (!this.buffer
.tabs
[++x
] && x
< this.cols
);
2088 return x
>= this.cols
2095 * Erase in the identified line everything from "x" to the end of the line (right).
2096 * @param {number} x The column from which to start erasing to the end of the line.
2097 * @param {number} y The line in which to operate.
2099 Terminal
.prototype.eraseRight = function(x
, y
) {
2100 var line
= this.buffer
.lines
.get(this.buffer
.ybase
+ y
);
2104 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2105 for (; x
< this.cols
; x
++) {
2108 this.updateRange(y
);
2114 * Erase in the identified line everything from "x" to the start of the line (left).
2115 * @param {number} x The column from which to start erasing to the start of the line.
2116 * @param {number} y The line in which to operate.
2118 Terminal
.prototype.eraseLeft = function(x
, y
) {
2119 var line
= this.buffer
.lines
.get(this.buffer
.ybase
+ y
);
2123 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2128 this.updateRange(y
);
2132 * Clears the entire buffer, making the prompt line the new first line.
2134 Terminal
.prototype.clear = function() {
2135 if (this.buffer
.ybase
=== 0 && this.buffer
.y
=== 0) {
2136 // Don't clear if it's already clear
2139 this.buffer
.lines
.set(0, this.buffer
.lines
.get(this.buffer
.ybase
+ this.buffer
.y
));
2140 this.buffer
.lines
.length
= 1;
2141 this.buffer
.ydisp
= 0;
2142 this.buffer
.ybase
= 0;
2144 for (var i
= 1; i
< this.rows
; i
++) {
2145 this.buffer
.lines
.push(this.blankLine());
2147 this.refresh(0, this.rows
- 1);
2148 this.emit('scroll', this.buffer
.ydisp
);
2152 * Erase all content in the given line
2153 * @param {number} y The line to erase all of its contents.
2155 Terminal
.prototype.eraseLine = function(y
) {
2156 this.eraseRight(0, y
);
2161 * Return the data array of a blank line
2162 * @param {number} cur First bunch of data for each "blank" character.
2163 * @param {boolean} isWrapped Whether the new line is wrapped from the previous line.
2165 Terminal
.prototype.blankLine = function(cur
, isWrapped
) {
2170 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2174 // TODO: It is not ideal that this is a property on an array, a buffer line
2175 // class should be added that will hold this data and other useful functions.
2177 line
.isWrapped
= isWrapped
;
2180 for (; i
< this.cols
; i
++) {
2189 * If cur return the back color xterm feature attribute. Else return defAttr.
2190 * @param {object} cur
2192 Terminal
.prototype.ch = function(cur
) {
2194 ? [this.eraseAttr(), ' ', 1]
2195 : [this.defAttr
, ' ', 1];
2200 * Evaluate if the current terminal is the given argument.
2201 * @param {object} term The terminal to evaluate
2203 Terminal
.prototype.is = function(term
) {
2204 var name
= this.termName
;
2205 return (name
+ '').indexOf(term
) === 0;
2210 * Emit the 'data' event and populate the given data.
2211 * @param {string} data The data to populate in the event.
2213 Terminal
.prototype.handler = function(data
) {
2214 // Prevents all events to pty process if stdin is disabled
2215 if (this.options
.disableStdin
) {
2219 // Clear the selection if the selection manager is available and has an active selection
2220 if (this.selectionManager
&& this.selectionManager
.hasSelection
) {
2221 this.selectionManager
.clearSelection();
2224 // Input is being sent to the terminal, the terminal should focus the prompt.
2225 if (this.buffer
.ybase
!== this.buffer
.ydisp
) {
2226 this.scrollToBottom();
2228 this.emit('data', data
);
2233 * Emit the 'title' event and populate the given title.
2234 * @param {string} title The title to populate in the event.
2236 Terminal
.prototype.handleTitle = function(title
) {
2238 * This event is emitted when the title of the terminal is changed
2239 * from inside the terminal. The parameter is the new title.
2243 this.emit('title', title
);
2252 * ESC D Index (IND is 0x84).
2254 Terminal
.prototype.index = function() {
2256 if (this.buffer
.y
> this.buffer
.scrollBottom
) {
2260 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2261 if (this.buffer
.x
>= this.cols
) {
2268 * ESC M Reverse Index (RI is 0x8d).
2270 * Move the cursor up one row, inserting a new blank line if necessary.
2272 Terminal
.prototype.reverseIndex = function() {
2274 if (this.buffer
.y
=== this.buffer
.scrollTop
) {
2275 // possibly move the code below to term.reverseScroll();
2276 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2277 // blankLine(true) is xterm/linux behavior
2278 this.buffer
.lines
.shiftElements(this.buffer
.y
+ this.buffer
.ybase
, this.rows
- 1, 1);
2279 this.buffer
.lines
.set(this.buffer
.y
+ this.buffer
.ybase
, this.blankLine(true));
2280 this.updateRange(this.buffer
.scrollTop
);
2281 this.updateRange(this.buffer
.scrollBottom
);
2289 * ESC c Full Reset (RIS).
2291 Terminal
.prototype.reset = function() {
2292 this.options
.rows
= this.rows
;
2293 this.options
.cols
= this.cols
;
2294 var customKeyEventHandler
= this.customKeyEventHandler
;
2295 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2296 var inputHandler
= this.inputHandler
;
2297 var buffers
= this.buffers
;
2298 Terminal
.call(this, this.options
);
2299 this.customKeyEventHandler
= customKeyEventHandler
;
2300 this.cursorBlinkInterval
= cursorBlinkInterval
;
2301 this.inputHandler
= inputHandler
;
2302 this.buffers
= buffers
;
2303 this.refresh(0, this.rows
- 1);
2304 this.viewport
.syncScrollArea();
2309 * ESC H Tab Set (HTS is 0x88).
2311 Terminal
.prototype.tabSet = function() {
2312 this.buffer
.tabs
[this.buffer
.x
] = true;
2319 function on(el
, type
, handler
, capture
) {
2320 if (!Array
.isArray(el
)) {
2323 el
.forEach(function (element
) {
2324 element
.addEventListener(type
, handler
, capture
|| false);
2328 function off(el
, type
, handler
, capture
) {
2329 el
.removeEventListener(type
, handler
, capture
|| false);
2332 function cancel(ev
, force
) {
2333 if (!this.cancelEvents
&& !force
) {
2336 ev
.preventDefault();
2337 ev
.stopPropagation();
2341 function inherits(child
, parent
) {
2343 this.constructor = child
;
2345 f
.prototype = parent
.prototype;
2346 child
.prototype = new f
;
2349 function indexOf(obj
, el
) {
2352 if (obj
[i
] === el
) return i
;
2357 function isThirdLevelShift(term
, ev
) {
2359 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2360 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2362 if (ev
.type
== 'keypress') {
2363 return thirdLevelKey
;
2366 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2367 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2370 // Expose to InputHandler (temporary)
2371 Terminal
.prototype.matchColor
= matchColor
;
2373 function matchColor(r1
, g1
, b1
) {
2374 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2376 if (matchColor
._cache
[hash
] != null) {
2377 return matchColor
._cache
[hash
];
2380 var ldiff
= Infinity
2389 for (; i
< Terminal
.vcolors
.length
; i
++) {
2390 c
= Terminal
.vcolors
[i
];
2395 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2408 return matchColor
._cache
[hash
] = li
;
2411 matchColor
._cache
= {};
2413 // http://stackoverflow.com/questions/1633828
2414 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2415 return Math
.pow(30 * (r1
- r2
), 2)
2416 + Math
.pow(59 * (g1
- g2
), 2)
2417 + Math
.pow(11 * (b1
- b2
), 2);
2420 function each(obj
, iter
, con
) {
2421 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2422 for (var i
= 0; i
< obj
.length
; i
++) {
2423 iter
.call(con
, obj
[i
], i
, obj
);
2427 function wasMondifierKeyOnlyEvent(ev
) {
2428 return ev
.keyCode
=== 16 || // Shift
2429 ev
.keyCode
=== 17 || // Ctrl
2430 ev
.keyCode
=== 18; // Alt
2433 function keys(obj
) {
2434 if (Object
.keys
) return Object
.keys(obj
);
2437 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2448 Terminal
.translateBufferLineToString
= translateBufferLineToString
;
2449 Terminal
.EventEmitter
= EventEmitter
;
2450 Terminal
.inherits
= inherits
;
2453 * Adds an event listener to the terminal.
2455 * @param {string} event The name of the event. TODO: Document all event types
2456 * @param {function} callback The function to call when the event is triggered.
2460 Terminal
.cancel
= cancel
;
2462 module
.exports
= Terminal
;