2 * xterm.js: xterm, in the browser
3 * Originally forked from (with the author's permission):
4 * Fabrice Bellard's javascript vt100 for jslinux:
5 * http://bellard.org/jslinux/
6 * Copyright (c) 2011 Fabrice Bellard
7 * The original design remains. The terminal itself
8 * has been extended to include xterm CSI codes, among
13 import { CompositionHelper
} from './CompositionHelper';
14 import { EventEmitter
} from './EventEmitter';
15 import { Viewport
} from './Viewport';
16 import { rightClickHandler
, moveTextAreaUnderMouseCursor
, pasteHandler
, copyHandler
} from './handlers/Clipboard';
17 import { CircularList
} from './utils/CircularList';
18 import { C0
} from './EscapeSequences';
19 import { InputHandler
} from './InputHandler';
20 import { Parser
} from './Parser';
21 import { Renderer
} from './Renderer';
22 import { Linkifier
} from './Linkifier';
23 import { SelectionManager
} from './SelectionManager';
24 import { CharMeasure
} from './utils/CharMeasure';
25 import * as Browser
from './utils/Browser';
26 import * as Mouse
from './utils/Mouse';
27 import { CHARSETS
} from './Charsets';
28 import { getRawByteCoords
} from './utils/Mouse';
29 import { translateBufferLineToString
} from './utils/BufferLine';
32 * Terminal Emulation References:
34 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
35 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
36 * http://invisible-island.net/vttest/
37 * http://www.inwap.com/pdp10/ansicode.txt
38 * http://linux.die.net/man/4/console_codes
39 * http://linux.die.net/man/7/urxvt
42 // Let it work inside Node.js for automated testing purposes.
43 var document
= (typeof window
!= 'undefined') ? window
.document
: null;
46 * The amount of write requests to queue before sending an XOFF signal to the
47 * pty process. This number must be small in order for ^C and similar sequences
50 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
53 * The number of writes to perform in a single batch before allowing the
54 * renderer to catch up with a 0ms setTimeout.
56 var WRITE_BATCH_SIZE
= 300;
59 * The time between cursor blinks. This is driven by JS rather than a CSS
60 * animation due to a bug in Chromium that causes it to use excessive CPU time.
61 * See https://github.com/Microsoft/vscode/issues/22900
63 var CURSOR_BLINK_INTERVAL
= 600;
70 * Creates a new `Terminal` object.
72 * @param {object} options An object containing a set of options, the available options are:
73 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
74 * - `cols` (number): The number of columns of the terminal (horizontal size)
75 * - `rows` (number): The number of rows of the terminal (vertical size)
79 * @alias module:xterm/src/xterm
81 function Terminal(options
) {
84 if (!(this instanceof Terminal
)) {
85 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
88 self
.browser
= Browser
;
89 self
.cancel
= Terminal
.cancel
;
91 EventEmitter
.call(this);
93 if (typeof options
=== 'number') {
101 options
= options
|| {};
104 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
105 if (options
[key
] == null) {
106 options
[key
] = Terminal
.options
[key
];
108 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
109 options
[key
] = Terminal
[key
];
112 self
[key
] = options
[key
];
115 if (options
.colors
.length
=== 8) {
116 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
117 } else if (options
.colors
.length
=== 16) {
118 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
119 } else if (options
.colors
.length
=== 10) {
120 options
.colors
= options
.colors
.slice(0, -2).concat(
121 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
122 } else if (options
.colors
.length
=== 18) {
123 options
.colors
= options
.colors
.concat(
124 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
126 this.colors
= options
.colors
;
128 this.options
= options
;
130 // this.context = options.context || window;
131 // this.document = options.document || document;
132 this.parent
= options
.body
|| options
.parent
|| (
133 document
? document
.getElementsByTagName('body')[0] : null
136 this.cols
= options
.cols
|| options
.geometry
[0];
137 this.rows
= options
.rows
|| options
.geometry
[1];
138 this.geometry
= [this.cols
, this.rows
];
140 if (options
.handler
) {
141 this.on('data', options
.handler
);
145 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
151 * The scroll position of the viewport
156 * The cursor's x position after ybase
161 * The cursor's y position after ybase
165 this.cursorState
= 0;
166 this.cursorHidden
= false;
170 this.scrollBottom
= this.rows
- 1;
171 this.customKeyEventHandler
= null;
172 this.cursorBlinkInterval
= null;
175 this.applicationKeypad
= false;
176 this.applicationCursor
= false;
177 this.originMode
= false;
178 this.insertMode
= false;
179 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
184 this.gcharset
= null;
186 this.charsets
= [null];
210 this.readable
= true;
211 this.writable
= true;
213 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
214 this.curAttr
= this.defAttr
;
217 this.currentParam
= 0;
221 this.inputHandler
= new InputHandler(this);
222 this.parser
= new Parser(this.inputHandler
, this);
223 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
224 this.renderer
= this.renderer
|| null;
225 this.selectionManager
= this.selectionManager
|| null;
226 this.linkifier
= this.linkifier
|| new Linkifier();
229 this.writeBuffer
= [];
230 this.writeInProgress
= false;
233 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
234 * This is a distinct state from writeStopped so that if the user requested
235 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
238 this.xoffSentToCatchUp
= false;
240 /** Whether writing has been stopped as a result of XOFF */
241 this.writeStopped
= false;
243 // leftover surrogate high from previous write invocation
244 this.surrogate_high
= '';
247 * An array of all lines in the entire buffer, including the prompt. The lines are array of
248 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
250 this.lines
= new CircularList(this.scrollback
);
253 this.lines
.push(this.blankLine());
255 // Ensure the selection manager has the correct buffer
256 if (this.selectionManager
) {
257 this.selectionManager
.setBuffer(this.lines
);
263 // Store if user went browsing history in scrollback
264 this.userScrolling
= false;
267 inherits(Terminal
, EventEmitter
);
270 * back_color_erase feature for xterm.
272 Terminal
.prototype.eraseAttr = function() {
273 // if (this.is('screen')) return this.defAttr;
274 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
282 Terminal
.tangoColors
= [
303 // Colors 0-15 + 16-255
304 // Much thanks to TooTallNate for writing this.
305 Terminal
.colors
= (function() {
306 var colors
= Terminal
.tangoColors
.slice()
307 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
312 for (; i
< 216; i
++) {
313 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
318 for (; i
< 24; i
++) {
323 function out(r
, g
, b
) {
324 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
329 return c
.length
< 2 ? '0' + c
: c
;
335 Terminal
._colors
= Terminal
.colors
.slice();
337 Terminal
.vcolors
= (function() {
339 , colors
= Terminal
.colors
343 for (; i
< 256; i
++) {
344 color
= parseInt(colors
[i
].substring(1), 16);
346 (color
>> 16) & 0xff,
359 Terminal
.defaults
= {
360 colors
: Terminal
.colors
,
366 cursorStyle
: 'block',
374 useFlowControl
: false,
376 // programFeatures: false,
380 Terminal
.options
= {};
382 Terminal
.focus
= null;
384 each(keys(Terminal
.defaults
), function(key
) {
385 Terminal
[key
] = Terminal
.defaults
[key
];
386 Terminal
.options
[key
] = Terminal
.defaults
[key
];
390 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
392 Terminal
.prototype.focus = function() {
393 return this.textarea
.focus();
397 * Retrieves an option's value from the terminal.
398 * @param {string} key The option key.
400 Terminal
.prototype.getOption = function(key
, value
) {
401 if (!(key
in Terminal
.defaults
)) {
402 throw new Error('No option with key "' + key
+ '"');
405 if (typeof this.options
[key
] !== 'undefined') {
406 return this.options
[key
];
413 * Sets an option on the terminal.
414 * @param {string} key The option key.
415 * @param {string} value The option value.
417 Terminal
.prototype.setOption = function(key
, value
) {
418 if (!(key
in Terminal
.defaults
)) {
419 throw new Error('No option with key "' + key
+ '"');
423 if (value
< this.rows
) {
424 let msg
= 'Setting the scrollback value less than the number of rows ';
426 msg
+= `(${this.rows}) is not allowed.`;
432 if (this.options
[key
] !== value
) {
433 if (this.lines
.length
> value
) {
434 const amountToTrim
= this.lines
.length
- value
;
435 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
436 this.lines
.trimStart(amountToTrim
);
437 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
438 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
440 this.refresh(0, this.rows
- 1);
443 this.lines
.maxLength
= value
;
444 this.viewport
.syncScrollArea();
449 this.options
[key
] = value
;
451 case 'cursorBlink': this.setCursorBlinking(value
); break;
453 // Style 'block' applies with no class
454 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
455 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
457 case 'tabStopWidth': this.setupStops(); break;
461 Terminal
.prototype.restartCursorBlinking = function () {
462 this.setCursorBlinking(this.options
.cursorBlink
);
465 Terminal
.prototype.setCursorBlinking = function (enabled
) {
466 this.element
.classList
.toggle('xterm-cursor-blink', enabled
);
467 this.clearCursorBlinkingInterval();
470 this.cursorBlinkInterval
= setInterval(function () {
471 self
.element
.classList
.toggle('xterm-cursor-blink-on');
472 }, CURSOR_BLINK_INTERVAL
);
476 Terminal
.prototype.clearCursorBlinkingInterval = function () {
477 this.element
.classList
.remove('xterm-cursor-blink-on');
478 if (this.cursorBlinkInterval
) {
479 clearInterval(this.cursorBlinkInterval
);
480 this.cursorBlinkInterval
= null;
485 * Binds the desired focus behavior on a given terminal object.
489 Terminal
.bindFocus = function (term
) {
490 on(term
.textarea
, 'focus', function (ev
) {
491 if (term
.sendFocus
) {
492 term
.send(C0
.ESC
+ '[I');
494 term
.element
.classList
.add('focus');
496 term
.restartCursorBlinking
.apply(term
);
497 Terminal
.focus
= term
;
498 term
.emit('focus', {terminal
: term
});
503 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
505 Terminal
.prototype.blur = function() {
506 return this.textarea
.blur();
510 * Binds the desired blur behavior on a given terminal object.
514 Terminal
.bindBlur = function (term
) {
515 on(term
.textarea
, 'blur', function (ev
) {
516 term
.refresh(term
.y
, term
.y
);
517 if (term
.sendFocus
) {
518 term
.send(C0
.ESC
+ '[O');
520 term
.element
.classList
.remove('focus');
521 term
.clearCursorBlinkingInterval
.apply(term
);
522 Terminal
.focus
= null;
523 term
.emit('blur', {terminal
: term
});
528 * Initialize default behavior
530 Terminal
.prototype.initGlobal = function() {
533 Terminal
.bindKeys(this);
534 Terminal
.bindFocus(this);
535 Terminal
.bindBlur(this);
537 // Bind clipboard functionality
538 on(this.element
, 'copy', event
=> {
539 // If mouse events are active it means the selection manager is disabled and
540 // copy should be handled by the host program.
541 if (this.mouseEvents
) {
544 copyHandler(event
, term
, this.selectionManager
);
546 const pasteHandlerWrapper
= event
=> pasteHandler(event
, term
);
547 on(this.textarea
, 'paste', pasteHandlerWrapper
);
548 on(this.element
, 'paste', pasteHandlerWrapper
);
550 // Handle right click context menus
551 if (term
.browser
.isFirefox
) {
552 // Firefox doesn't appear to fire the contextmenu event on right click
553 on(this.element
, 'mousedown', event
=> {
554 if (event
.button
== 2) {
555 rightClickHandler(event
, this.textarea
, this.selectionManager
);
559 on(this.element
, 'contextmenu', event
=> {
560 rightClickHandler(event
, this.textarea
, this.selectionManager
);
564 // Move the textarea under the cursor when middle clicking on Linux to ensure
565 // middle click to paste selection works. This only appears to work in Chrome
566 // at the time is writing.
567 if (term
.browser
.isLinux
) {
568 // Use auxclick event over mousedown the latter doesn't seem to work. Note
569 // that the regular click event doesn't fire for the middle mouse button.
570 on(this.element
, 'auxclick', event
=> {
571 if (event
.button
=== 1) {
572 moveTextAreaUnderMouseCursor(event
, this.textarea
, this.selectionManager
);
579 * Apply key handling to the terminal
581 Terminal
.bindKeys = function(term
) {
582 on(term
.element
, 'keydown', function(ev
) {
583 if (document
.activeElement
!= this) {
589 on(term
.element
, 'keypress', function(ev
) {
590 if (document
.activeElement
!= this) {
596 on(term
.element
, 'keyup', function(ev
) {
597 if (!wasMondifierKeyOnlyEvent(ev
)) {
602 on(term
.textarea
, 'keydown', function(ev
) {
606 on(term
.textarea
, 'keypress', function(ev
) {
608 // Truncate the textarea's value, since it is not needed
612 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
613 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
614 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
615 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
616 term
.on('refresh', function (data
) {
617 term
.queueLinkification(data
.start
, data
.end
)
623 * Insert the given row to the terminal or produce a new one
624 * if no row argument is passed. Return the inserted row.
625 * @param {HTMLElement} row (optional) The row to append to the terminal.
627 Terminal
.prototype.insertRow = function (row
) {
628 if (typeof row
!= 'object') {
629 row
= document
.createElement('div');
632 this.rowContainer
.appendChild(row
);
633 this.children
.push(row
);
639 * Opens the terminal within an element.
641 * @param {HTMLElement} parent The element to create the terminal within.
642 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
644 Terminal
.prototype.open = function(parent
, focus
) {
645 var self
=this, i
=0, div
;
647 this.parent
= parent
|| this.parent
;
650 throw new Error('Terminal requires a parent element.');
653 // Grab global elements
654 this.context
= this.parent
.ownerDocument
.defaultView
;
655 this.document
= this.parent
.ownerDocument
;
656 this.body
= this.document
.getElementsByTagName('body')[0];
658 //Create main element container
659 this.element
= this.document
.createElement('div');
660 this.element
.classList
.add('terminal');
661 this.element
.classList
.add('xterm');
662 this.element
.classList
.add('xterm-theme-' + this.theme
);
663 this.setCursorBlinking(this.options
.cursorBlink
);
665 this.element
.setAttribute('tabindex', 0);
667 this.viewportElement
= document
.createElement('div');
668 this.viewportElement
.classList
.add('xterm-viewport');
669 this.element
.appendChild(this.viewportElement
);
670 this.viewportScrollArea
= document
.createElement('div');
671 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
672 this.viewportElement
.appendChild(this.viewportScrollArea
);
674 // Create the selection container.
675 this.selectionContainer
= document
.createElement('div');
676 this.selectionContainer
.classList
.add('xterm-selection');
677 this.element
.appendChild(this.selectionContainer
);
679 // Create the container that will hold the lines of the terminal and then
680 // produce the lines the lines.
681 this.rowContainer
= document
.createElement('div');
682 this.rowContainer
.classList
.add('xterm-rows');
683 this.element
.appendChild(this.rowContainer
);
685 this.linkifier
.attachToDom(document
, this.children
);
687 // Create the container that will hold helpers like the textarea for
688 // capturing DOM Events. Then produce the helpers.
689 this.helperContainer
= document
.createElement('div');
690 this.helperContainer
.classList
.add('xterm-helpers');
691 // TODO: This should probably be inserted once it's filled to prevent an additional layout
692 this.element
.appendChild(this.helperContainer
);
693 this.textarea
= document
.createElement('textarea');
694 this.textarea
.classList
.add('xterm-helper-textarea');
695 this.textarea
.setAttribute('autocorrect', 'off');
696 this.textarea
.setAttribute('autocapitalize', 'off');
697 this.textarea
.setAttribute('spellcheck', 'false');
698 this.textarea
.tabIndex
= 0;
699 this.textarea
.addEventListener('focus', function() {
700 self
.emit('focus', {terminal
: self
});
702 this.textarea
.addEventListener('blur', function() {
703 self
.emit('blur', {terminal
: self
});
705 this.helperContainer
.appendChild(this.textarea
);
707 this.compositionView
= document
.createElement('div');
708 this.compositionView
.classList
.add('composition-view');
709 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
710 this.helperContainer
.appendChild(this.compositionView
);
712 this.charSizeStyleElement
= document
.createElement('style');
713 this.helperContainer
.appendChild(this.charSizeStyleElement
);
715 for (; i
< this.rows
; i
++) {
718 this.parent
.appendChild(this.element
);
720 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
721 this.charMeasure
.on('charsizechanged', function () {
722 self
.updateCharSizeStyles();
724 this.charMeasure
.measure();
726 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
727 this.renderer
= new Renderer(this);
728 this.selectionManager
= new SelectionManager(this, this.lines
, this.rowContainer
, this.charMeasure
);
729 this.selectionManager
.on('refresh', data
=> {
730 this.renderer
.refreshSelection(data
.start
, data
.end
);
732 this.selectionManager
.on('newselection', text
=> {
733 // If there's a new selection, put it into the textarea, focus and select it
734 // in order to register it as a selection on the OS. This event is fired
735 // only on Linux to enable middle click to paste selection.
736 this.textarea
.value
= text
;
737 this.textarea
.focus();
738 this.textarea
.select();
740 this.on('scroll', () => this.selectionManager
.refresh());
741 this.viewportElement
.addEventListener('scroll', () => this.selectionManager
.refresh());
743 // Setup loop that draws to screen
744 this.refresh(0, this.rows
- 1);
746 // Initialize global actions that
747 // need to be taken on the document.
751 * Automatic focus functionality.
752 * TODO: Default to `false` starting with xterm.js 3.0.
754 if (typeof focus
== 'undefined') {
755 let message
= 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
757 message
+= 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
758 message
+= 'it will default to `false`.';
760 console
.warn(message
);
768 on(this.element
, 'click', function() {
769 var selection
= document
.getSelection(),
770 collapsed
= selection
.isCollapsed
,
771 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
777 // Listen for mouse events and translate
778 // them into terminal mouse protocols.
782 * This event is emitted when terminal has completed opening.
791 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
792 * @param {string} addon The name of the addon to load
795 Terminal
.loadAddon = function(addon
, callback
) {
796 if (typeof exports
=== 'object' && typeof module
=== 'object') {
798 return require('./addons/' + addon
+ '/' + addon
);
799 } else if (typeof define
== 'function') {
801 return require(['./addons/' + addon
+ '/' + addon
], callback
);
803 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
809 * Updates the helper CSS class with any changes necessary after the terminal's
810 * character width has been changed.
812 Terminal
.prototype.updateCharSizeStyles = function() {
813 this.charSizeStyleElement
.textContent
=
814 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
815 `.xterm-normal-char{width:${this.charMeasure.width}px;}` +
816 `.xterm-rows > div{height:${this.charMeasure.height}px;}`;
821 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
822 * To better understand these
823 * the xterm code is very helpful:
825 * button.c, charproc.c, misc.c
826 * Relevant functions in xterm/button.c:
827 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
829 Terminal
.prototype.bindMouse = function() {
830 var el
= this.element
, self
= this, pressed
= 32;
832 // mouseup, mousedown, wheel
833 // left click: ^[[M 3<^[[M#3<
835 function sendButton(ev
) {
839 // get the xterm-style button
840 button
= getButton(ev
);
842 // get mouse coordinates
843 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
846 sendEvent(button
, pos
);
848 switch (ev
.overrideType
|| ev
.type
) {
853 // keep it at the left
854 // button, just in case.
865 // motion example of a left click:
866 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
867 function sendMove(ev
) {
871 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
874 // buttons marked as motions
875 // are incremented by 32
878 sendEvent(button
, pos
);
882 // position to characters
883 function encode(data
, ch
) {
884 if (!self
.utfMouse
) {
885 if (ch
=== 255) return data
.push(0);
886 if (ch
> 127) ch
= 127;
889 if (ch
=== 2047) return data
.push(0);
893 if (ch
> 2047) ch
= 2047;
894 data
.push(0xC0 | (ch
>> 6));
895 data
.push(0x80 | (ch
& 0x3F));
900 // send a mouse event:
901 // regular/utf8: ^[[M Cb Cx Cy
902 // urxvt: ^[[ Cb ; Cx ; Cy M
903 // sgr: ^[[ Cb ; Cx ; Cy M/m
904 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
905 // locator: CSI P e ; P b ; P r ; P c ; P p & w
906 function sendEvent(button
, pos
) {
907 // self.emit('mouse', {
913 if (self
.vt300Mouse
) {
915 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
919 var data
= C0
.ESC
+ '[24';
920 if (button
=== 0) data
+= '1';
921 else if (button
=== 1) data
+= '3';
922 else if (button
=== 2) data
+= '5';
923 else if (button
=== 3) return;
925 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
930 if (self
.decLocator
) {
935 if (button
=== 0) button
= 2;
936 else if (button
=== 1) button
= 4;
937 else if (button
=== 2) button
= 6;
938 else if (button
=== 3) button
= 3;
939 self
.send(C0
.ESC
+ '['
942 + (button
=== 3 ? 4 : 0)
953 if (self
.urxvtMouse
) {
958 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
965 self
.send(C0
.ESC
+ '[<'
966 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
971 + ((button
& 3) === 3 ? 'm' : 'M'));
977 encode(data
, button
);
981 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
984 function getButton(ev
) {
997 // 1, and 2 - with 64 added
998 switch (ev
.overrideType
|| ev
.type
) {
1000 button
= ev
.button
!= null
1006 if (self
.browser
.isMSIE
) {
1007 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
1013 case 'DOMMouseScroll':
1014 button
= ev
.detail
< 0
1019 button
= ev
.wheelDeltaY
> 0
1025 // next three bits are the modifiers:
1026 // 4 = shift, 8 = meta, 16 = control
1027 shift
= ev
.shiftKey
? 4 : 0;
1028 meta
= ev
.metaKey
? 8 : 0;
1029 ctrl
= ev
.ctrlKey
? 16 : 0;
1030 mod
= shift
| meta
| ctrl
;
1033 if (self
.vt200Mouse
) {
1036 } else if (!self
.normalMouse
) {
1041 button
= (32 + (mod
<< 2)) + button
;
1046 on(el
, 'mousedown', function(ev
) {
1047 if (!self
.mouseEvents
) return;
1056 //if (self.vt200Mouse && !self.normalMouse) {
1057 if (self
.vt200Mouse
) {
1058 ev
.overrideType
= 'mouseup';
1060 return self
.cancel(ev
);
1064 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1066 // x10 compatibility mode can't send button releases
1067 if (!self
.x10Mouse
) {
1068 on(self
.document
, 'mouseup', function up(ev
) {
1070 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1071 off(self
.document
, 'mouseup', up
);
1072 return self
.cancel(ev
);
1076 return self
.cancel(ev
);
1079 //if (self.normalMouse) {
1080 // on(self.document, 'mousemove', sendMove);
1083 on(el
, 'wheel', function(ev
) {
1084 if (!self
.mouseEvents
) return;
1087 || self
.decLocator
) return;
1089 return self
.cancel(ev
);
1092 // allow wheel scrolling in
1093 // the shell for example
1094 on(el
, 'wheel', function(ev
) {
1095 if (self
.mouseEvents
) return;
1096 self
.viewport
.onWheel(ev
);
1097 return self
.cancel(ev
);
1100 on(el
, 'touchstart', function(ev
) {
1101 if (self
.mouseEvents
) return;
1102 self
.viewport
.onTouchStart(ev
);
1103 return self
.cancel(ev
);
1106 on(el
, 'touchmove', function(ev
) {
1107 if (self
.mouseEvents
) return;
1108 self
.viewport
.onTouchMove(ev
);
1109 return self
.cancel(ev
);
1114 * Destroys the terminal.
1116 Terminal
.prototype.destroy = function() {
1117 this.readable
= false;
1118 this.writable
= false;
1120 this.handler = function() {};
1121 this.write = function() {};
1122 if (this.element
&& this.element
.parentNode
) {
1123 this.element
.parentNode
.removeChild(this.element
);
1125 //this.emit('close');
1129 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1131 * @param {number} start The row to start from (between 0 and this.rows - 1).
1132 * @param {number} end The row to end at (between start and this.rows - 1).
1134 Terminal
.prototype.refresh = function(start
, end
) {
1135 if (this.renderer
) {
1136 this.renderer
.queueRefresh(start
, end
);
1141 * Queues linkification for the specified rows.
1142 * @param {number} start The row to start from (between 0 and this.rows - 1).
1143 * @param {number} end The row to end at (between start and this.rows - 1).
1145 Terminal
.prototype.queueLinkification = function(start
, end
) {
1146 if (this.linkifier
) {
1147 for (let i
= start
; i
<= end
; i
++) {
1148 this.linkifier
.linkifyRow(i
);
1154 * Display the cursor element
1156 Terminal
.prototype.showCursor = function() {
1157 if (!this.cursorState
) {
1158 this.cursorState
= 1;
1159 this.refresh(this.y
, this.y
);
1164 * Scroll the terminal down 1 row, creating a blank line.
1165 * @param {boolean} isWrapped Whether the new line is wrapped from the previous
1168 Terminal
.prototype.scroll = function(isWrapped
) {
1171 // Make room for the new row in lines
1172 if (this.lines
.length
=== this.lines
.maxLength
) {
1173 this.lines
.trimStart(1);
1175 if (this.ydisp
!== 0) {
1182 // TODO: Why is this done twice?
1183 if (!this.userScrolling
) {
1184 this.ydisp
= this.ybase
;
1188 row
= this.ybase
+ this.rows
- 1;
1190 // subtract the bottom scroll region
1191 row
-= this.rows
- 1 - this.scrollBottom
;
1193 if (row
=== this.lines
.length
) {
1194 // Optimization: pushing is faster than splicing when they amount to the same behavior
1195 this.lines
.push(this.blankLine(undefined, isWrapped
));
1198 this.lines
.splice(row
, 0, this.blankLine(undefined, isWrapped
));
1201 if (this.scrollTop
!== 0) {
1202 if (this.ybase
!== 0) {
1204 if (!this.userScrolling
) {
1205 this.ydisp
= this.ybase
;
1208 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1212 this.updateRange(this.scrollTop
);
1213 this.updateRange(this.scrollBottom
);
1216 * This event is emitted whenever the terminal is scrolled.
1217 * The one parameter passed is the new y display position.
1221 this.emit('scroll', this.ydisp
);
1225 * Scroll the display of the terminal
1226 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1227 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1228 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1229 * viewport originally.
1231 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1233 if (this.ydisp
=== 0) {
1236 this.userScrolling
= true;
1237 } else if (disp
+ this.ydisp
>= this.ybase
) {
1238 this.userScrolling
= false;
1241 const oldYdisp
= this.ydisp
;
1242 this.ydisp
= Math
.max(Math
.min(this.ydisp
+ disp
, this.ybase
), 0);
1244 // No change occurred, don't trigger scroll/refresh
1245 if (oldYdisp
=== this.ydisp
) {
1249 if (!suppressScrollEvent
) {
1250 this.emit('scroll', this.ydisp
);
1253 this.refresh(0, this.rows
- 1);
1257 * Scroll the display of the terminal by a number of pages.
1258 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1260 Terminal
.prototype.scrollPages = function(pageCount
) {
1261 this.scrollDisp(pageCount
* (this.rows
- 1));
1265 * Scrolls the display of the terminal to the top.
1267 Terminal
.prototype.scrollToTop = function() {
1268 this.scrollDisp(-this.ydisp
);
1272 * Scrolls the display of the terminal to the bottom.
1274 Terminal
.prototype.scrollToBottom = function() {
1275 this.scrollDisp(this.ybase
- this.ydisp
);
1279 * Writes text to the terminal.
1280 * @param {string} data The text to write to the terminal.
1282 Terminal
.prototype.write = function(data
) {
1283 this.writeBuffer
.push(data
);
1285 // Send XOFF to pause the pty process if the write buffer becomes too large so
1286 // xterm.js can catch up before more data is sent. This is necessary in order
1287 // to keep signals such as ^C responsive.
1288 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1289 // XOFF - stop pty pipe
1290 // XON will be triggered by emulator before processing data chunk
1292 this.xoffSentToCatchUp
= true;
1295 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1296 // Kick off a write which will write all data in sequence recursively
1297 this.writeInProgress
= true;
1298 // Kick off an async innerWrite so more writes can come in while processing data
1300 setTimeout(function () {
1306 Terminal
.prototype.innerWrite = function() {
1307 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1308 while (writeBatch
.length
> 0) {
1309 var data
= writeBatch
.shift();
1310 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1312 // If XOFF was sent in order to catch up with the pty process, resume it if
1313 // the writeBuffer is empty to allow more data to come in.
1314 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1316 this.xoffSentToCatchUp
= false;
1319 this.refreshStart
= this.y
;
1320 this.refreshEnd
= this.y
;
1322 // HACK: Set the parser state based on it's state at the time of return.
1323 // This works around the bug #662 which saw the parser state reset in the
1324 // middle of parsing escape sequence in two chunks. For some reason the
1325 // state of the parser resets to 0 after exiting parser.parse. This change
1326 // just sets the state back based on the correct return statement.
1327 var state
= this.parser
.parse(data
);
1328 this.parser
.setState(state
);
1330 this.updateRange(this.y
);
1331 this.refresh(this.refreshStart
, this.refreshEnd
);
1333 if (this.writeBuffer
.length
> 0) {
1334 // Allow renderer to catch up before processing the next batch
1336 setTimeout(function () {
1340 this.writeInProgress
= false;
1345 * Writes text to the terminal, followed by a break line character (\n).
1346 * @param {string} data The text to write to the terminal.
1348 Terminal
.prototype.writeln = function(data
) {
1349 this.write(data
+ '\r\n');
1353 * DEPRECATED: only for backward compatibility. Please use attachCustomKeyEventHandler() instead.
1354 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1355 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1356 * the default action. The function returns whether the event should be processed by xterm.js.
1358 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1359 let message
= 'attachCustomKeydownHandler() is DEPRECATED and will be removed soon. Please use attachCustomKeyEventHandler() instead.';
1360 console
.warn(message
);
1361 this.attachCustomKeyEventHandler(customKeydownHandler
);
1365 * Attaches a custom key event handler which is run before keys are processed, giving consumers of
1366 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1368 * @param {function} customKeyEventHandler The custom KeyboardEvent handler to attach. This is a
1369 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1370 * the default action. The function returns whether the event should be processed by xterm.js.
1372 Terminal
.prototype.attachCustomKeyEventHandler = function(customKeyEventHandler
) {
1373 this.customKeyEventHandler
= customKeyEventHandler
;
1377 * Attaches a http(s) link handler, forcing web links to behave differently to
1378 * regular <a> tags. This will trigger a refresh as links potentially need to be
1379 * reconstructed. Calling this with null will remove the handler.
1380 * @param {LinkMatcherHandler} handler The handler callback function.
1382 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1383 if (!this.linkifier
) {
1384 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1386 this.linkifier
.setHypertextLinkHandler(handler
);
1387 // Refresh to force links to refresh
1388 this.refresh(0, this.rows
- 1);
1392 * Attaches a validation callback for hypertext links. This is useful to use
1393 * validation logic or to do something with the link's element and url.
1394 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1395 * be cleared with null.
1397 Terminal
.prototype.setHypertextValidationCallback = function(callback
) {
1398 if (!this.linkifier
) {
1399 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1401 this.linkifier
.setHypertextValidationCallback(callback
);
1402 // Refresh to force links to refresh
1403 this.refresh(0, this.rows
- 1);
1407 * Registers a link matcher, allowing custom link patterns to be matched and
1409 * @param {RegExp} regex The regular expression to search for, specifically
1410 * this searches the textContent of the rows. You will want to use \s to match
1411 * a space ' ' character for example.
1412 * @param {LinkMatcherHandler} handler The callback when the link is called.
1413 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1414 * @return {number} The ID of the new matcher, this can be used to deregister.
1416 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1417 if (this.linkifier
) {
1418 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1419 this.refresh(0, this.rows
- 1);
1425 * Deregisters a link matcher if it has been registered.
1426 * @param {number} matcherId The link matcher's ID (returned after register)
1428 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1429 if (this.linkifier
) {
1430 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1431 this.refresh(0, this.rows
- 1);
1437 * Gets whether the terminal has an active selection.
1439 Terminal
.prototype.hasSelection = function() {
1440 return this.selectionManager
.hasSelection
;
1444 * Gets the terminal's current selection, this is useful for implementing copy
1445 * behavior outside of xterm.js.
1447 Terminal
.prototype.getSelection = function() {
1448 return this.selectionManager
.selectionText
;
1452 * Clears the current terminal selection.
1454 Terminal
.prototype.clearSelection = function() {
1455 this.selectionManager
.clearSelection();
1459 * Selects all text within the terminal.
1461 Terminal
.prototype.selectAll = function() {
1462 this.selectionManager
.selectAll();
1466 * Handle a keydown event
1468 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1469 * @param {KeyboardEvent} ev The keydown event to be handled.
1471 Terminal
.prototype.keyDown = function(ev
) {
1472 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1476 this.restartCursorBlinking();
1478 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1479 if (this.ybase
!== this.ydisp
) {
1480 this.scrollToBottom();
1486 var result
= this.evaluateKeyEscapeSequence(ev
);
1488 if (result
.key
=== C0
.DC3
) { // XOFF
1489 this.writeStopped
= true;
1490 } else if (result
.key
=== C0
.DC1
) { // XON
1491 this.writeStopped
= false;
1494 if (result
.scrollDisp
) {
1495 this.scrollDisp(result
.scrollDisp
);
1496 return this.cancel(ev
, true);
1499 if (isThirdLevelShift(this, ev
)) {
1503 if (result
.cancel
) {
1504 // The event is canceled at the end already, is this necessary?
1505 this.cancel(ev
, true);
1512 this.emit('keydown', ev
);
1513 this.emit('key', result
.key
, ev
);
1515 this.handler(result
.key
);
1517 return this.cancel(ev
, true);
1521 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1522 * returned value is the new key code to pass to the PTY.
1524 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1525 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1527 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1529 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1530 // canceled at the end of keyDown
1532 // The new key even to emit
1534 // The number of characters to scroll, if this is defined it will cancel the event
1535 scrollDisp
: undefined
1537 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1538 switch (ev
.keyCode
) {
1542 result
.key
= C0
.BS
; // ^H
1545 result
.key
= C0
.DEL
; // ^?
1550 result
.key
= C0
.ESC
+ '[Z';
1554 result
.cancel
= true;
1559 result
.cancel
= true;
1563 result
.key
= C0
.ESC
;
1564 result
.cancel
= true;
1569 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1570 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1571 // http://unix.stackexchange.com/a/108106
1572 // macOS uses different escape sequences than linux
1573 if (result
.key
== C0
.ESC
+ '[1;3D') {
1574 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1576 } else if (this.applicationCursor
) {
1577 result
.key
= C0
.ESC
+ 'OD';
1579 result
.key
= C0
.ESC
+ '[D';
1585 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1586 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1587 // http://unix.stackexchange.com/a/108106
1588 // macOS uses different escape sequences than linux
1589 if (result
.key
== C0
.ESC
+ '[1;3C') {
1590 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1592 } else if (this.applicationCursor
) {
1593 result
.key
= C0
.ESC
+ 'OC';
1595 result
.key
= C0
.ESC
+ '[C';
1601 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1602 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1603 // http://unix.stackexchange.com/a/108106
1604 if (result
.key
== C0
.ESC
+ '[1;3A') {
1605 result
.key
= C0
.ESC
+ '[1;5A';
1607 } else if (this.applicationCursor
) {
1608 result
.key
= C0
.ESC
+ 'OA';
1610 result
.key
= C0
.ESC
+ '[A';
1616 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1617 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1618 // http://unix.stackexchange.com/a/108106
1619 if (result
.key
== C0
.ESC
+ '[1;3B') {
1620 result
.key
= C0
.ESC
+ '[1;5B';
1622 } else if (this.applicationCursor
) {
1623 result
.key
= C0
.ESC
+ 'OB';
1625 result
.key
= C0
.ESC
+ '[B';
1630 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1631 // <Ctrl> or <Shift> + <Insert> are used to
1632 // copy-paste on some systems.
1633 result
.key
= C0
.ESC
+ '[2~';
1639 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1641 result
.key
= C0
.ESC
+ '[3~';
1647 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1648 else if (this.applicationCursor
)
1649 result
.key
= C0
.ESC
+ 'OH';
1651 result
.key
= C0
.ESC
+ '[H';
1656 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1657 else if (this.applicationCursor
)
1658 result
.key
= C0
.ESC
+ 'OF';
1660 result
.key
= C0
.ESC
+ '[F';
1665 result
.scrollDisp
= -(this.rows
- 1);
1667 result
.key
= C0
.ESC
+ '[5~';
1673 result
.scrollDisp
= this.rows
- 1;
1675 result
.key
= C0
.ESC
+ '[6~';
1681 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1683 result
.key
= C0
.ESC
+ 'OP';
1688 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1690 result
.key
= C0
.ESC
+ 'OQ';
1695 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1697 result
.key
= C0
.ESC
+ 'OR';
1702 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1704 result
.key
= C0
.ESC
+ 'OS';
1709 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1711 result
.key
= C0
.ESC
+ '[15~';
1716 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1718 result
.key
= C0
.ESC
+ '[17~';
1723 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1725 result
.key
= C0
.ESC
+ '[18~';
1730 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1732 result
.key
= C0
.ESC
+ '[19~';
1737 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1739 result
.key
= C0
.ESC
+ '[20~';
1744 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1746 result
.key
= C0
.ESC
+ '[21~';
1751 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1753 result
.key
= C0
.ESC
+ '[23~';
1758 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1760 result
.key
= C0
.ESC
+ '[24~';
1765 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1766 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1767 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1768 } else if (ev
.keyCode
=== 32) {
1770 result
.key
= String
.fromCharCode(0);
1771 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1772 // escape, file sep, group sep, record sep, unit sep
1773 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1774 } else if (ev
.keyCode
=== 56) {
1776 result
.key
= String
.fromCharCode(127);
1777 } else if (ev
.keyCode
=== 219) {
1778 // ^[ - Control Sequence Introducer (CSI)
1779 result
.key
= String
.fromCharCode(27);
1780 } else if (ev
.keyCode
=== 220) {
1781 // ^\ - String Terminator (ST)
1782 result
.key
= String
.fromCharCode(28);
1783 } else if (ev
.keyCode
=== 221) {
1784 // ^] - Operating System Command (OSC)
1785 result
.key
= String
.fromCharCode(29);
1787 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1788 // On Mac this is a third level shift. Use <Esc> instead.
1789 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1790 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1791 } else if (ev
.keyCode
=== 192) {
1792 result
.key
= C0
.ESC
+ '`';
1793 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1794 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1796 } else if (this.browser
.isMac
&& !ev
.altKey
&& !ev
.ctrlKey
&& ev
.metaKey
) {
1797 if (ev
.keyCode
=== 65) { // cmd + a
1808 * Set the G level of the terminal
1811 Terminal
.prototype.setgLevel = function(g
) {
1813 this.charset
= this.charsets
[g
];
1817 * Set the charset for the given G level of the terminal
1821 Terminal
.prototype.setgCharset = function(g
, charset
) {
1822 this.charsets
[g
] = charset
;
1823 if (this.glevel
=== g
) {
1824 this.charset
= charset
;
1829 * Handle a keypress event.
1831 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1832 * @param {KeyboardEvent} ev The keypress event to be handled.
1834 Terminal
.prototype.keyPress = function(ev
) {
1837 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1845 } else if (ev
.which
== null) {
1847 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1854 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1859 key
= String
.fromCharCode(key
);
1861 this.emit('keypress', key
, ev
);
1862 this.emit('key', key
, ev
);
1870 * Send data for handling to the terminal
1871 * @param {string} data
1873 Terminal
.prototype.send = function(data
) {
1877 setTimeout(function() {
1878 self
.handler(self
.queue
);
1888 * Note: We could do sweet things with webaudio here
1890 Terminal
.prototype.bell = function() {
1891 if (!this.visualBell
) return;
1893 this.element
.style
.borderColor
= 'white';
1894 setTimeout(function() {
1895 self
.element
.style
.borderColor
= '';
1897 if (this.popOnBell
) this.focus();
1901 * Log the current state to the console.
1903 Terminal
.prototype.log = function() {
1904 if (!this.debug
) return;
1905 if (!this.context
.console
|| !this.context
.console
.log
) return;
1906 var args
= Array
.prototype.slice
.call(arguments
);
1907 this.context
.console
.log
.apply(this.context
.console
, args
);
1911 * Log the current state as error to the console.
1913 Terminal
.prototype.error = function() {
1914 if (!this.debug
) return;
1915 if (!this.context
.console
|| !this.context
.console
.error
) return;
1916 var args
= Array
.prototype.slice
.call(arguments
);
1917 this.context
.console
.error
.apply(this.context
.console
, args
);
1921 * Resizes the terminal.
1923 * @param {number} x The number of columns to resize to.
1924 * @param {number} y The number of rows to resize to.
1926 Terminal
.prototype.resize = function(x
, y
) {
1927 if (isNaN(x
) || isNaN(y
)) {
1931 if (y
> this.getOption('scrollback')) {
1932 this.setOption('scrollback', y
)
1942 if (x
=== this.cols
&& y
=== this.rows
) {
1943 // Check if we still need to measure the char size (fixes #785).
1944 if (!this.charMeasure
.width
|| !this.charMeasure
.height
) {
1945 this.charMeasure
.measure();
1956 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1957 i
= this.lines
.length
;
1959 while (this.lines
.get(i
).length
< x
) {
1960 this.lines
.get(i
).push(ch
);
1966 this.setupStops(this.cols
);
1974 // y is rows, not this.y
1975 if (this.lines
.length
< y
+ this.ybase
) {
1976 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
1977 // There is room above the buffer and there are no empty elements below the line,
1981 if (this.ydisp
> 0) {
1982 // Viewport is at the top of the buffer, must increase downwards
1986 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1987 // are blank lines after the cursor
1988 this.lines
.push(this.blankLine());
1991 if (this.children
.length
< y
) {
1997 if (this.lines
.length
> y
+ this.ybase
) {
1998 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
1999 // The line is a blank line below the cursor, remove it
2002 // The line is the cursor, scroll down
2007 if (this.children
.length
> y
) {
2008 el
= this.children
.shift();
2010 el
.parentNode
.removeChild(el
);
2016 // Make sure that the cursor stays on screen
2029 this.scrollBottom
= y
- 1;
2031 this.charMeasure
.measure();
2033 this.refresh(0, this.rows
- 1);
2037 this.geometry
= [this.cols
, this.rows
];
2038 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
2042 * Updates the range of rows to refresh
2043 * @param {number} y The number of rows to refresh next.
2045 Terminal
.prototype.updateRange = function(y
) {
2046 if (y
< this.refreshStart
) this.refreshStart
= y
;
2047 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
2048 // if (y > this.refreshEnd) {
2049 // this.refreshEnd = y;
2050 // if (y > this.rows - 1) {
2051 // this.refreshEnd = this.rows - 1;
2057 * Set the range of refreshing to the maximum value
2059 Terminal
.prototype.maxRange = function() {
2060 this.refreshStart
= 0;
2061 this.refreshEnd
= this.rows
- 1;
2067 * Setup the tab stops.
2070 Terminal
.prototype.setupStops = function(i
) {
2072 if (!this.tabs
[i
]) {
2073 i
= this.prevStop(i
);
2080 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
2081 this.tabs
[i
] = true;
2087 * Move the cursor to the previous tab stop from the given position (default is current).
2088 * @param {number} x The position to move the cursor to the previous tab stop.
2090 Terminal
.prototype.prevStop = function(x
) {
2091 if (x
== null) x
= this.x
;
2092 while (!this.tabs
[--x
] && x
> 0);
2093 return x
>= this.cols
2100 * Move the cursor one tab stop forward from the given position (default is current).
2101 * @param {number} x The position to move the cursor one tab stop forward.
2103 Terminal
.prototype.nextStop = function(x
) {
2104 if (x
== null) x
= this.x
;
2105 while (!this.tabs
[++x
] && x
< this.cols
);
2106 return x
>= this.cols
2113 * Erase in the identified line everything from "x" to the end of the line (right).
2114 * @param {number} x The column from which to start erasing to the end of the line.
2115 * @param {number} y The line in which to operate.
2117 Terminal
.prototype.eraseRight = function(x
, y
) {
2118 var line
= this.lines
.get(this.ybase
+ y
);
2122 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2123 for (; x
< this.cols
; x
++) {
2126 this.updateRange(y
);
2132 * Erase in the identified line everything from "x" to the start of the line (left).
2133 * @param {number} x The column from which to start erasing to the start of the line.
2134 * @param {number} y The line in which to operate.
2136 Terminal
.prototype.eraseLeft = function(x
, y
) {
2137 var line
= this.lines
.get(this.ybase
+ y
);
2141 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2146 this.updateRange(y
);
2150 * Clears the entire buffer, making the prompt line the new first line.
2152 Terminal
.prototype.clear = function() {
2153 if (this.ybase
=== 0 && this.y
=== 0) {
2154 // Don't clear if it's already clear
2157 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2158 this.lines
.length
= 1;
2162 for (var i
= 1; i
< this.rows
; i
++) {
2163 this.lines
.push(this.blankLine());
2165 this.refresh(0, this.rows
- 1);
2166 this.emit('scroll', this.ydisp
);
2170 * Erase all content in the given line
2171 * @param {number} y The line to erase all of its contents.
2173 Terminal
.prototype.eraseLine = function(y
) {
2174 this.eraseRight(0, y
);
2179 * Return the data array of a blank line
2180 * @param {number} cur First bunch of data for each "blank" character.
2181 * @param {boolean} isWrapped Whether the new line is wrapped from the previous line.
2183 Terminal
.prototype.blankLine = function(cur
, isWrapped
) {
2188 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2192 // TODO: It is not ideal that this is a property on an array, a buffer line
2193 // class should be added that will hold this data and other useful functions.
2195 line
.isWrapped
= isWrapped
;
2198 for (; i
< this.cols
; i
++) {
2207 * If cur return the back color xterm feature attribute. Else return defAttr.
2208 * @param {object} cur
2210 Terminal
.prototype.ch = function(cur
) {
2212 ? [this.eraseAttr(), ' ', 1]
2213 : [this.defAttr
, ' ', 1];
2218 * Evaluate if the current erminal is the given argument.
2219 * @param {object} term The terminal to evaluate
2221 Terminal
.prototype.is = function(term
) {
2222 var name
= this.termName
;
2223 return (name
+ '').indexOf(term
) === 0;
2228 * Emit the 'data' event and populate the given data.
2229 * @param {string} data The data to populate in the event.
2231 Terminal
.prototype.handler = function(data
) {
2232 // Prevents all events to pty process if stdin is disabled
2233 if (this.options
.disableStdin
) {
2237 // Input is being sent to the terminal, the terminal should focus the prompt.
2238 if (this.ybase
!== this.ydisp
) {
2239 this.scrollToBottom();
2241 this.emit('data', data
);
2246 * Emit the 'title' event and populate the given title.
2247 * @param {string} title The title to populate in the event.
2249 Terminal
.prototype.handleTitle = function(title
) {
2251 * This event is emitted when the title of the terminal is changed
2252 * from inside the terminal. The parameter is the new title.
2256 this.emit('title', title
);
2265 * ESC D Index (IND is 0x84).
2267 Terminal
.prototype.index = function() {
2269 if (this.y
> this.scrollBottom
) {
2273 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2274 if (this.x
>= this.cols
) {
2281 * ESC M Reverse Index (RI is 0x8d).
2283 * Move the cursor up one row, inserting a new blank line if necessary.
2285 Terminal
.prototype.reverseIndex = function() {
2287 if (this.y
=== this.scrollTop
) {
2288 // possibly move the code below to term.reverseScroll();
2289 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2290 // blankLine(true) is xterm/linux behavior
2291 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2292 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2293 this.updateRange(this.scrollTop
);
2294 this.updateRange(this.scrollBottom
);
2302 * ESC c Full Reset (RIS).
2304 Terminal
.prototype.reset = function() {
2305 this.options
.rows
= this.rows
;
2306 this.options
.cols
= this.cols
;
2307 var customKeyEventHandler
= this.customKeyEventHandler
;
2308 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2309 Terminal
.call(this, this.options
);
2310 this.customKeyEventHandler
= customKeyEventHandler
;
2311 this.cursorBlinkInterval
= cursorBlinkInterval
;
2312 this.refresh(0, this.rows
- 1);
2313 this.viewport
.syncScrollArea();
2318 * ESC H Tab Set (HTS is 0x88).
2320 Terminal
.prototype.tabSet = function() {
2321 this.tabs
[this.x
] = true;
2328 function on(el
, type
, handler
, capture
) {
2329 if (!Array
.isArray(el
)) {
2332 el
.forEach(function (element
) {
2333 element
.addEventListener(type
, handler
, capture
|| false);
2337 function off(el
, type
, handler
, capture
) {
2338 el
.removeEventListener(type
, handler
, capture
|| false);
2341 function cancel(ev
, force
) {
2342 if (!this.cancelEvents
&& !force
) {
2345 ev
.preventDefault();
2346 ev
.stopPropagation();
2350 function inherits(child
, parent
) {
2352 this.constructor = child
;
2354 f
.prototype = parent
.prototype;
2355 child
.prototype = new f
;
2358 function indexOf(obj
, el
) {
2361 if (obj
[i
] === el
) return i
;
2366 function isThirdLevelShift(term
, ev
) {
2368 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2369 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2371 if (ev
.type
== 'keypress') {
2372 return thirdLevelKey
;
2375 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2376 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2379 // Expose to InputHandler (temporary)
2380 Terminal
.prototype.matchColor
= matchColor
;
2382 function matchColor(r1
, g1
, b1
) {
2383 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2385 if (matchColor
._cache
[hash
] != null) {
2386 return matchColor
._cache
[hash
];
2389 var ldiff
= Infinity
2398 for (; i
< Terminal
.vcolors
.length
; i
++) {
2399 c
= Terminal
.vcolors
[i
];
2404 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2417 return matchColor
._cache
[hash
] = li
;
2420 matchColor
._cache
= {};
2422 // http://stackoverflow.com/questions/1633828
2423 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2424 return Math
.pow(30 * (r1
- r2
), 2)
2425 + Math
.pow(59 * (g1
- g2
), 2)
2426 + Math
.pow(11 * (b1
- b2
), 2);
2429 function each(obj
, iter
, con
) {
2430 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2431 for (var i
= 0; i
< obj
.length
; i
++) {
2432 iter
.call(con
, obj
[i
], i
, obj
);
2436 function wasMondifierKeyOnlyEvent(ev
) {
2437 return ev
.keyCode
=== 16 || // Shift
2438 ev
.keyCode
=== 17 || // Ctrl
2439 ev
.keyCode
=== 18; // Alt
2442 function keys(obj
) {
2443 if (Object
.keys
) return Object
.keys(obj
);
2446 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2457 Terminal
.translateBufferLineToString
= translateBufferLineToString
;
2458 Terminal
.EventEmitter
= EventEmitter
;
2459 Terminal
.inherits
= inherits
;
2462 * Adds an event listener to the terminal.
2464 * @param {string} event The name of the event. TODO: Document all event types
2465 * @param {function} callback The function to call when the event is triggered.
2469 Terminal
.cancel
= cancel
;
2471 module
.exports
= Terminal
;