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
);
146 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
152 * The scroll position of the viewport
157 * The cursor's x position after ybase
162 * The cursor's y position after ybase
166 this.cursorState
= 0;
167 this.cursorHidden
= false;
171 this.scrollBottom
= this.rows
- 1;
172 this.customKeyEventHandler
= null;
173 this.cursorBlinkInterval
= null;
176 this.applicationKeypad
= false;
177 this.applicationCursor
= false;
178 this.originMode
= false;
179 this.insertMode
= false;
180 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
185 this.gcharset
= null;
187 this.charsets
= [null];
211 this.readable
= true;
212 this.writable
= true;
214 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
215 this.curAttr
= this.defAttr
;
218 this.currentParam
= 0;
222 this.inputHandler
= new InputHandler(this);
223 this.parser
= new Parser(this.inputHandler
, this);
224 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
225 this.renderer
= this.renderer
|| null;
226 this.selectionManager
= this.selectionManager
|| null;
227 this.linkifier
= this.linkifier
|| new Linkifier();
230 this.writeBuffer
= [];
231 this.writeInProgress
= false;
234 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
235 * This is a distinct state from writeStopped so that if the user requested
236 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
239 this.xoffSentToCatchUp
= false;
241 /** Whether writing has been stopped as a result of XOFF */
242 this.writeStopped
= false;
244 // leftover surrogate high from previous write invocation
245 this.surrogate_high
= '';
247 this.buffers
= new BufferSet(this);
249 * An array of all lines in the entire buffer, including the prompt. The lines are array of
250 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
252 this.lines
= new CircularList(this.scrollback
);
255 this.lines
.push(this.blankLine());
257 // Ensure the selection manager has the correct buffer
258 if (this.selectionManager
) {
259 this.selectionManager
.setBuffer(this.lines
);
265 // Store if user went browsing history in scrollback
266 this.userScrolling
= false;
269 inherits(Terminal
, EventEmitter
);
272 * back_color_erase feature for xterm.
274 Terminal
.prototype.eraseAttr = function() {
275 // if (this.is('screen')) return this.defAttr;
276 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
284 Terminal
.tangoColors
= [
305 // Colors 0-15 + 16-255
306 // Much thanks to TooTallNate for writing this.
307 Terminal
.colors
= (function() {
308 var colors
= Terminal
.tangoColors
.slice()
309 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
314 for (; i
< 216; i
++) {
315 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
320 for (; i
< 24; i
++) {
325 function out(r
, g
, b
) {
326 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
331 return c
.length
< 2 ? '0' + c
: c
;
337 Terminal
._colors
= Terminal
.colors
.slice();
339 Terminal
.vcolors
= (function() {
341 , colors
= Terminal
.colors
345 for (; i
< 256; i
++) {
346 color
= parseInt(colors
[i
].substring(1), 16);
348 (color
>> 16) & 0xff,
361 Terminal
.defaults
= {
362 colors
: Terminal
.colors
,
368 cursorStyle
: 'block',
376 useFlowControl
: false,
378 // programFeatures: false,
382 Terminal
.options
= {};
384 Terminal
.focus
= null;
386 each(keys(Terminal
.defaults
), function(key
) {
387 Terminal
[key
] = Terminal
.defaults
[key
];
388 Terminal
.options
[key
] = Terminal
.defaults
[key
];
392 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
394 Terminal
.prototype.focus = function() {
395 return this.textarea
.focus();
399 * Retrieves an option's value from the terminal.
400 * @param {string} key The option key.
402 Terminal
.prototype.getOption = function(key
) {
403 if (!(key
in Terminal
.defaults
)) {
404 throw new Error('No option with key "' + key
+ '"');
407 if (typeof this.options
[key
] !== 'undefined') {
408 return this.options
[key
];
415 * Sets an option on the terminal.
416 * @param {string} key The option key.
417 * @param {string} value The option value.
419 Terminal
.prototype.setOption = function(key
, value
) {
420 if (!(key
in Terminal
.defaults
)) {
421 throw new Error('No option with key "' + key
+ '"');
425 if (value
< this.rows
) {
426 let msg
= 'Setting the scrollback value less than the number of rows ';
428 msg
+= `(${this.rows}) is not allowed.`;
434 if (this.options
[key
] !== value
) {
435 if (this.lines
.length
> value
) {
436 const amountToTrim
= this.lines
.length
- value
;
437 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
438 this.lines
.trimStart(amountToTrim
);
439 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
440 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
442 this.refresh(0, this.rows
- 1);
445 this.lines
.maxLength
= value
;
446 this.viewport
.syncScrollArea();
451 this.options
[key
] = value
;
453 case 'cursorBlink': this.setCursorBlinking(value
); break;
455 // Style 'block' applies with no class
456 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
457 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
459 case 'tabStopWidth': this.setupStops(); break;
463 Terminal
.prototype.restartCursorBlinking = function () {
464 this.setCursorBlinking(this.options
.cursorBlink
);
467 Terminal
.prototype.setCursorBlinking = function (enabled
) {
468 this.element
.classList
.toggle('xterm-cursor-blink', enabled
);
469 this.clearCursorBlinkingInterval();
472 this.cursorBlinkInterval
= setInterval(function () {
473 self
.element
.classList
.toggle('xterm-cursor-blink-on');
474 }, CURSOR_BLINK_INTERVAL
);
478 Terminal
.prototype.clearCursorBlinkingInterval = function () {
479 this.element
.classList
.remove('xterm-cursor-blink-on');
480 if (this.cursorBlinkInterval
) {
481 clearInterval(this.cursorBlinkInterval
);
482 this.cursorBlinkInterval
= null;
487 * Binds the desired focus behavior on a given terminal object.
491 Terminal
.bindFocus = function (term
) {
492 on(term
.textarea
, 'focus', function (ev
) {
493 if (term
.sendFocus
) {
494 term
.send(C0
.ESC
+ '[I');
496 term
.element
.classList
.add('focus');
498 term
.restartCursorBlinking
.apply(term
);
499 Terminal
.focus
= term
;
500 term
.emit('focus', {terminal
: term
});
505 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
507 Terminal
.prototype.blur = function() {
508 return this.textarea
.blur();
512 * Binds the desired blur behavior on a given terminal object.
516 Terminal
.bindBlur = function (term
) {
517 on(term
.textarea
, 'blur', function (ev
) {
518 term
.refresh(term
.y
, term
.y
);
519 if (term
.sendFocus
) {
520 term
.send(C0
.ESC
+ '[O');
522 term
.element
.classList
.remove('focus');
523 term
.clearCursorBlinkingInterval
.apply(term
);
524 Terminal
.focus
= null;
525 term
.emit('blur', {terminal
: term
});
530 * Initialize default behavior
532 Terminal
.prototype.initGlobal = function() {
535 Terminal
.bindKeys(this);
536 Terminal
.bindFocus(this);
537 Terminal
.bindBlur(this);
539 // Bind clipboard functionality
540 on(this.element
, 'copy', event
=> {
541 // If mouse events are active it means the selection manager is disabled and
542 // copy should be handled by the host program.
543 if (this.mouseEvents
) {
546 copyHandler(event
, term
, this.selectionManager
);
548 const pasteHandlerWrapper
= event
=> pasteHandler(event
, term
);
549 on(this.textarea
, 'paste', pasteHandlerWrapper
);
550 on(this.element
, 'paste', pasteHandlerWrapper
);
552 // Handle right click context menus
553 if (term
.browser
.isFirefox
) {
554 // Firefox doesn't appear to fire the contextmenu event on right click
555 on(this.element
, 'mousedown', event
=> {
556 if (event
.button
== 2) {
557 rightClickHandler(event
, this.textarea
, this.selectionManager
);
561 on(this.element
, 'contextmenu', event
=> {
562 rightClickHandler(event
, this.textarea
, this.selectionManager
);
566 // Move the textarea under the cursor when middle clicking on Linux to ensure
567 // middle click to paste selection works. This only appears to work in Chrome
568 // at the time is writing.
569 if (term
.browser
.isLinux
) {
570 // Use auxclick event over mousedown the latter doesn't seem to work. Note
571 // that the regular click event doesn't fire for the middle mouse button.
572 on(this.element
, 'auxclick', event
=> {
573 if (event
.button
=== 1) {
574 moveTextAreaUnderMouseCursor(event
, this.textarea
, this.selectionManager
);
581 * Apply key handling to the terminal
583 Terminal
.bindKeys = function(term
) {
584 on(term
.element
, 'keydown', function(ev
) {
585 if (document
.activeElement
!= this) {
591 on(term
.element
, 'keypress', function(ev
) {
592 if (document
.activeElement
!= this) {
598 on(term
.element
, 'keyup', function(ev
) {
599 if (!wasMondifierKeyOnlyEvent(ev
)) {
604 on(term
.textarea
, 'keydown', function(ev
) {
608 on(term
.textarea
, 'keypress', function(ev
) {
610 // Truncate the textarea's value, since it is not needed
614 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
615 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
616 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
617 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
618 term
.on('refresh', function (data
) {
619 term
.queueLinkification(data
.start
, data
.end
)
625 * Insert the given row to the terminal or produce a new one
626 * if no row argument is passed. Return the inserted row.
627 * @param {HTMLElement} row (optional) The row to append to the terminal.
629 Terminal
.prototype.insertRow = function (row
) {
630 if (typeof row
!= 'object') {
631 row
= document
.createElement('div');
634 this.rowContainer
.appendChild(row
);
635 this.children
.push(row
);
641 * Opens the terminal within an element.
643 * @param {HTMLElement} parent The element to create the terminal within.
644 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
646 Terminal
.prototype.open = function(parent
, focus
) {
647 var self
=this, i
=0, div
;
649 this.parent
= parent
|| this.parent
;
652 throw new Error('Terminal requires a parent element.');
655 // Grab global elements
656 this.context
= this.parent
.ownerDocument
.defaultView
;
657 this.document
= this.parent
.ownerDocument
;
658 this.body
= this.document
.getElementsByTagName('body')[0];
660 //Create main element container
661 this.element
= this.document
.createElement('div');
662 this.element
.classList
.add('terminal');
663 this.element
.classList
.add('xterm');
664 this.element
.classList
.add('xterm-theme-' + this.theme
);
665 this.setCursorBlinking(this.options
.cursorBlink
);
667 this.element
.setAttribute('tabindex', 0);
669 this.viewportElement
= document
.createElement('div');
670 this.viewportElement
.classList
.add('xterm-viewport');
671 this.element
.appendChild(this.viewportElement
);
672 this.viewportScrollArea
= document
.createElement('div');
673 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
674 this.viewportElement
.appendChild(this.viewportScrollArea
);
676 // Create the selection container.
677 this.selectionContainer
= document
.createElement('div');
678 this.selectionContainer
.classList
.add('xterm-selection');
679 this.element
.appendChild(this.selectionContainer
);
681 // Create the container that will hold the lines of the terminal and then
682 // produce the lines the lines.
683 this.rowContainer
= document
.createElement('div');
684 this.rowContainer
.classList
.add('xterm-rows');
685 this.element
.appendChild(this.rowContainer
);
687 this.linkifier
.attachToDom(document
, this.children
);
689 // Create the container that will hold helpers like the textarea for
690 // capturing DOM Events. Then produce the helpers.
691 this.helperContainer
= document
.createElement('div');
692 this.helperContainer
.classList
.add('xterm-helpers');
693 // TODO: This should probably be inserted once it's filled to prevent an additional layout
694 this.element
.appendChild(this.helperContainer
);
695 this.textarea
= document
.createElement('textarea');
696 this.textarea
.classList
.add('xterm-helper-textarea');
697 this.textarea
.setAttribute('autocorrect', 'off');
698 this.textarea
.setAttribute('autocapitalize', 'off');
699 this.textarea
.setAttribute('spellcheck', 'false');
700 this.textarea
.tabIndex
= 0;
701 this.textarea
.addEventListener('focus', function() {
702 self
.emit('focus', {terminal
: self
});
704 this.textarea
.addEventListener('blur', function() {
705 self
.emit('blur', {terminal
: self
});
707 this.helperContainer
.appendChild(this.textarea
);
709 this.compositionView
= document
.createElement('div');
710 this.compositionView
.classList
.add('composition-view');
711 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
712 this.helperContainer
.appendChild(this.compositionView
);
714 this.charSizeStyleElement
= document
.createElement('style');
715 this.helperContainer
.appendChild(this.charSizeStyleElement
);
717 for (; i
< this.rows
; i
++) {
720 this.parent
.appendChild(this.element
);
722 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
723 this.charMeasure
.on('charsizechanged', function () {
724 self
.updateCharSizeStyles();
726 this.charMeasure
.measure();
728 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
729 this.renderer
= new Renderer(this);
730 this.selectionManager
= new SelectionManager(this, this.lines
, this.rowContainer
, this.charMeasure
);
731 this.selectionManager
.on('refresh', data
=> {
732 this.renderer
.refreshSelection(data
.start
, data
.end
);
734 this.selectionManager
.on('newselection', text
=> {
735 // If there's a new selection, put it into the textarea, focus and select it
736 // in order to register it as a selection on the OS. This event is fired
737 // only on Linux to enable middle click to paste selection.
738 this.textarea
.value
= text
;
739 this.textarea
.focus();
740 this.textarea
.select();
742 this.on('scroll', () => this.selectionManager
.refresh());
743 this.viewportElement
.addEventListener('scroll', () => this.selectionManager
.refresh());
745 // Setup loop that draws to screen
746 this.refresh(0, this.rows
- 1);
748 // Initialize global actions that
749 // need to be taken on the document.
753 * Automatic focus functionality.
754 * TODO: Default to `false` starting with xterm.js 3.0.
756 if (typeof focus
== 'undefined') {
757 let message
= 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
759 message
+= 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
760 message
+= 'it will default to `false`.';
762 console
.warn(message
);
770 on(this.element
, 'click', function() {
771 var selection
= document
.getSelection(),
772 collapsed
= selection
.isCollapsed
,
773 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
779 // Listen for mouse events and translate
780 // them into terminal mouse protocols.
784 * This event is emitted when terminal has completed opening.
793 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
794 * @param {string} addon The name of the addon to load
797 Terminal
.loadAddon = function(addon
, callback
) {
798 if (typeof exports
=== 'object' && typeof module
=== 'object') {
800 return require('./addons/' + addon
+ '/' + addon
);
801 } else if (typeof define
== 'function') {
803 return require(['./addons/' + addon
+ '/' + addon
], callback
);
805 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
811 * Updates the helper CSS class with any changes necessary after the terminal's
812 * character width has been changed.
814 Terminal
.prototype.updateCharSizeStyles = function() {
815 this.charSizeStyleElement
.textContent
=
816 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
817 `.xterm-normal-char{width:${this.charMeasure.width}px;}` +
818 `.xterm-rows > div{height:${this.charMeasure.height}px;}`;
823 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
824 * To better understand these
825 * the xterm code is very helpful:
827 * button.c, charproc.c, misc.c
828 * Relevant functions in xterm/button.c:
829 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
831 Terminal
.prototype.bindMouse = function() {
832 var el
= this.element
, self
= this, pressed
= 32;
834 // mouseup, mousedown, wheel
835 // left click: ^[[M 3<^[[M#3<
837 function sendButton(ev
) {
841 // get the xterm-style button
842 button
= getButton(ev
);
844 // get mouse coordinates
845 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
848 sendEvent(button
, pos
);
850 switch (ev
.overrideType
|| ev
.type
) {
855 // keep it at the left
856 // button, just in case.
867 // motion example of a left click:
868 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
869 function sendMove(ev
) {
873 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
876 // buttons marked as motions
877 // are incremented by 32
880 sendEvent(button
, pos
);
884 // position to characters
885 function encode(data
, ch
) {
886 if (!self
.utfMouse
) {
887 if (ch
=== 255) return data
.push(0);
888 if (ch
> 127) ch
= 127;
891 if (ch
=== 2047) return data
.push(0);
895 if (ch
> 2047) ch
= 2047;
896 data
.push(0xC0 | (ch
>> 6));
897 data
.push(0x80 | (ch
& 0x3F));
902 // send a mouse event:
903 // regular/utf8: ^[[M Cb Cx Cy
904 // urxvt: ^[[ Cb ; Cx ; Cy M
905 // sgr: ^[[ Cb ; Cx ; Cy M/m
906 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
907 // locator: CSI P e ; P b ; P r ; P c ; P p & w
908 function sendEvent(button
, pos
) {
909 // self.emit('mouse', {
915 if (self
.vt300Mouse
) {
917 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
921 var data
= C0
.ESC
+ '[24';
922 if (button
=== 0) data
+= '1';
923 else if (button
=== 1) data
+= '3';
924 else if (button
=== 2) data
+= '5';
925 else if (button
=== 3) return;
927 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
932 if (self
.decLocator
) {
937 if (button
=== 0) button
= 2;
938 else if (button
=== 1) button
= 4;
939 else if (button
=== 2) button
= 6;
940 else if (button
=== 3) button
= 3;
941 self
.send(C0
.ESC
+ '['
944 + (button
=== 3 ? 4 : 0)
955 if (self
.urxvtMouse
) {
960 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
967 self
.send(C0
.ESC
+ '[<'
968 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
973 + ((button
& 3) === 3 ? 'm' : 'M'));
979 encode(data
, button
);
983 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
986 function getButton(ev
) {
999 // 1, and 2 - with 64 added
1000 switch (ev
.overrideType
|| ev
.type
) {
1002 button
= ev
.button
!= null
1008 if (self
.browser
.isMSIE
) {
1009 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
1015 case 'DOMMouseScroll':
1016 button
= ev
.detail
< 0
1021 button
= ev
.wheelDeltaY
> 0
1027 // next three bits are the modifiers:
1028 // 4 = shift, 8 = meta, 16 = control
1029 shift
= ev
.shiftKey
? 4 : 0;
1030 meta
= ev
.metaKey
? 8 : 0;
1031 ctrl
= ev
.ctrlKey
? 16 : 0;
1032 mod
= shift
| meta
| ctrl
;
1035 if (self
.vt200Mouse
) {
1038 } else if (!self
.normalMouse
) {
1043 button
= (32 + (mod
<< 2)) + button
;
1048 on(el
, 'mousedown', function(ev
) {
1049 if (!self
.mouseEvents
) return;
1058 //if (self.vt200Mouse && !self.normalMouse) {
1059 if (self
.vt200Mouse
) {
1060 ev
.overrideType
= 'mouseup';
1062 return self
.cancel(ev
);
1066 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1068 // x10 compatibility mode can't send button releases
1069 if (!self
.x10Mouse
) {
1070 on(self
.document
, 'mouseup', function up(ev
) {
1072 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1073 off(self
.document
, 'mouseup', up
);
1074 return self
.cancel(ev
);
1078 return self
.cancel(ev
);
1081 //if (self.normalMouse) {
1082 // on(self.document, 'mousemove', sendMove);
1085 on(el
, 'wheel', function(ev
) {
1086 if (!self
.mouseEvents
) return;
1089 || self
.decLocator
) return;
1091 return self
.cancel(ev
);
1094 // allow wheel scrolling in
1095 // the shell for example
1096 on(el
, 'wheel', function(ev
) {
1097 if (self
.mouseEvents
) return;
1098 self
.viewport
.onWheel(ev
);
1099 return self
.cancel(ev
);
1102 on(el
, 'touchstart', function(ev
) {
1103 if (self
.mouseEvents
) return;
1104 self
.viewport
.onTouchStart(ev
);
1105 return self
.cancel(ev
);
1108 on(el
, 'touchmove', function(ev
) {
1109 if (self
.mouseEvents
) return;
1110 self
.viewport
.onTouchMove(ev
);
1111 return self
.cancel(ev
);
1116 * Destroys the terminal.
1118 Terminal
.prototype.destroy = function() {
1119 this.readable
= false;
1120 this.writable
= false;
1122 this.handler = function() {};
1123 this.write = function() {};
1124 if (this.element
&& this.element
.parentNode
) {
1125 this.element
.parentNode
.removeChild(this.element
);
1127 //this.emit('close');
1131 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1133 * @param {number} start The row to start from (between 0 and this.rows - 1).
1134 * @param {number} end The row to end at (between start and this.rows - 1).
1136 Terminal
.prototype.refresh = function(start
, end
) {
1137 if (this.renderer
) {
1138 this.renderer
.queueRefresh(start
, end
);
1143 * Queues linkification for the specified rows.
1144 * @param {number} start The row to start from (between 0 and this.rows - 1).
1145 * @param {number} end The row to end at (between start and this.rows - 1).
1147 Terminal
.prototype.queueLinkification = function(start
, end
) {
1148 if (this.linkifier
) {
1149 for (let i
= start
; i
<= end
; i
++) {
1150 this.linkifier
.linkifyRow(i
);
1156 * Display the cursor element
1158 Terminal
.prototype.showCursor = function() {
1159 if (!this.cursorState
) {
1160 this.cursorState
= 1;
1161 this.refresh(this.y
, this.y
);
1166 * Scroll the terminal down 1 row, creating a blank line.
1167 * @param {boolean} isWrapped Whether the new line is wrapped from the previous
1170 Terminal
.prototype.scroll = function(isWrapped
) {
1173 // Make room for the new row in lines
1174 if (this.lines
.length
=== this.lines
.maxLength
) {
1175 this.lines
.trimStart(1);
1177 if (this.ydisp
!== 0) {
1184 // TODO: Why is this done twice?
1185 if (!this.userScrolling
) {
1186 this.ydisp
= this.ybase
;
1190 row
= this.ybase
+ this.rows
- 1;
1192 // subtract the bottom scroll region
1193 row
-= this.rows
- 1 - this.scrollBottom
;
1195 if (row
=== this.lines
.length
) {
1196 // Optimization: pushing is faster than splicing when they amount to the same behavior
1197 this.lines
.push(this.blankLine(undefined, isWrapped
));
1200 this.lines
.splice(row
, 0, this.blankLine(undefined, isWrapped
));
1203 if (this.scrollTop
!== 0) {
1204 if (this.ybase
!== 0) {
1206 if (!this.userScrolling
) {
1207 this.ydisp
= this.ybase
;
1210 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1214 this.updateRange(this.scrollTop
);
1215 this.updateRange(this.scrollBottom
);
1218 * This event is emitted whenever the terminal is scrolled.
1219 * The one parameter passed is the new y display position.
1223 this.emit('scroll', this.ydisp
);
1227 * Scroll the display of the terminal
1228 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1229 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1230 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1231 * viewport originally.
1233 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1235 if (this.ydisp
=== 0) {
1238 this.userScrolling
= true;
1239 } else if (disp
+ this.ydisp
>= this.ybase
) {
1240 this.userScrolling
= false;
1243 const oldYdisp
= this.ydisp
;
1244 this.ydisp
= Math
.max(Math
.min(this.ydisp
+ disp
, this.ybase
), 0);
1246 // No change occurred, don't trigger scroll/refresh
1247 if (oldYdisp
=== this.ydisp
) {
1251 if (!suppressScrollEvent
) {
1252 this.emit('scroll', this.ydisp
);
1255 this.refresh(0, this.rows
- 1);
1259 * Scroll the display of the terminal by a number of pages.
1260 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1262 Terminal
.prototype.scrollPages = function(pageCount
) {
1263 this.scrollDisp(pageCount
* (this.rows
- 1));
1267 * Scrolls the display of the terminal to the top.
1269 Terminal
.prototype.scrollToTop = function() {
1270 this.scrollDisp(-this.ydisp
);
1274 * Scrolls the display of the terminal to the bottom.
1276 Terminal
.prototype.scrollToBottom = function() {
1277 this.scrollDisp(this.ybase
- this.ydisp
);
1281 * Writes text to the terminal.
1282 * @param {string} data The text to write to the terminal.
1284 Terminal
.prototype.write = function(data
) {
1285 this.writeBuffer
.push(data
);
1287 // Send XOFF to pause the pty process if the write buffer becomes too large so
1288 // xterm.js can catch up before more data is sent. This is necessary in order
1289 // to keep signals such as ^C responsive.
1290 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1291 // XOFF - stop pty pipe
1292 // XON will be triggered by emulator before processing data chunk
1294 this.xoffSentToCatchUp
= true;
1297 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1298 // Kick off a write which will write all data in sequence recursively
1299 this.writeInProgress
= true;
1300 // Kick off an async innerWrite so more writes can come in while processing data
1302 setTimeout(function () {
1308 Terminal
.prototype.innerWrite = function() {
1309 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1310 while (writeBatch
.length
> 0) {
1311 var data
= writeBatch
.shift();
1312 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1314 // If XOFF was sent in order to catch up with the pty process, resume it if
1315 // the writeBuffer is empty to allow more data to come in.
1316 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1318 this.xoffSentToCatchUp
= false;
1321 this.refreshStart
= this.y
;
1322 this.refreshEnd
= this.y
;
1324 // HACK: Set the parser state based on it's state at the time of return.
1325 // This works around the bug #662 which saw the parser state reset in the
1326 // middle of parsing escape sequence in two chunks. For some reason the
1327 // state of the parser resets to 0 after exiting parser.parse. This change
1328 // just sets the state back based on the correct return statement.
1329 var state
= this.parser
.parse(data
);
1330 this.parser
.setState(state
);
1332 this.updateRange(this.y
);
1333 this.refresh(this.refreshStart
, this.refreshEnd
);
1335 if (this.writeBuffer
.length
> 0) {
1336 // Allow renderer to catch up before processing the next batch
1338 setTimeout(function () {
1342 this.writeInProgress
= false;
1347 * Writes text to the terminal, followed by a break line character (\n).
1348 * @param {string} data The text to write to the terminal.
1350 Terminal
.prototype.writeln = function(data
) {
1351 this.write(data
+ '\r\n');
1355 * DEPRECATED: only for backward compatibility. Please use attachCustomKeyEventHandler() instead.
1356 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1357 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1358 * the default action. The function returns whether the event should be processed by xterm.js.
1360 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1361 let message
= 'attachCustomKeydownHandler() is DEPRECATED and will be removed soon. Please use attachCustomKeyEventHandler() instead.';
1362 console
.warn(message
);
1363 this.attachCustomKeyEventHandler(customKeydownHandler
);
1367 * Attaches a custom key event handler which is run before keys are processed, giving consumers of
1368 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1370 * @param {function} customKeyEventHandler The custom KeyboardEvent handler to attach. This is a
1371 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1372 * the default action. The function returns whether the event should be processed by xterm.js.
1374 Terminal
.prototype.attachCustomKeyEventHandler = function(customKeyEventHandler
) {
1375 this.customKeyEventHandler
= customKeyEventHandler
;
1379 * Attaches a http(s) link handler, forcing web links to behave differently to
1380 * regular <a> tags. This will trigger a refresh as links potentially need to be
1381 * reconstructed. Calling this with null will remove the handler.
1382 * @param {LinkMatcherHandler} handler The handler callback function.
1384 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1385 if (!this.linkifier
) {
1386 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1388 this.linkifier
.setHypertextLinkHandler(handler
);
1389 // Refresh to force links to refresh
1390 this.refresh(0, this.rows
- 1);
1394 * Attaches a validation callback for hypertext links. This is useful to use
1395 * validation logic or to do something with the link's element and url.
1396 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1397 * be cleared with null.
1399 Terminal
.prototype.setHypertextValidationCallback = function(callback
) {
1400 if (!this.linkifier
) {
1401 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1403 this.linkifier
.setHypertextValidationCallback(callback
);
1404 // Refresh to force links to refresh
1405 this.refresh(0, this.rows
- 1);
1409 * Registers a link matcher, allowing custom link patterns to be matched and
1411 * @param {RegExp} regex The regular expression to search for, specifically
1412 * this searches the textContent of the rows. You will want to use \s to match
1413 * a space ' ' character for example.
1414 * @param {LinkMatcherHandler} handler The callback when the link is called.
1415 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1416 * @return {number} The ID of the new matcher, this can be used to deregister.
1418 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1419 if (this.linkifier
) {
1420 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1421 this.refresh(0, this.rows
- 1);
1427 * Deregisters a link matcher if it has been registered.
1428 * @param {number} matcherId The link matcher's ID (returned after register)
1430 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1431 if (this.linkifier
) {
1432 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1433 this.refresh(0, this.rows
- 1);
1439 * Gets whether the terminal has an active selection.
1441 Terminal
.prototype.hasSelection = function() {
1442 return this.selectionManager
? this.selectionManager
.hasSelection
: false;
1446 * Gets the terminal's current selection, this is useful for implementing copy
1447 * behavior outside of xterm.js.
1449 Terminal
.prototype.getSelection = function() {
1450 return this.selectionManager
? this.selectionManager
.selectionText
: '';
1454 * Clears the current terminal selection.
1456 Terminal
.prototype.clearSelection = function() {
1457 if (this.selectionManager
) {
1458 this.selectionManager
.clearSelection();
1463 * Selects all text within the terminal.
1465 Terminal
.prototype.selectAll = function() {
1466 if (this.selectionManager
) {
1467 this.selectionManager
.selectAll();
1472 * Handle a keydown event
1474 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1475 * @param {KeyboardEvent} ev The keydown event to be handled.
1477 Terminal
.prototype.keyDown = function(ev
) {
1478 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1482 this.restartCursorBlinking();
1484 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1485 if (this.ybase
!== this.ydisp
) {
1486 this.scrollToBottom();
1492 var result
= this.evaluateKeyEscapeSequence(ev
);
1494 if (result
.key
=== C0
.DC3
) { // XOFF
1495 this.writeStopped
= true;
1496 } else if (result
.key
=== C0
.DC1
) { // XON
1497 this.writeStopped
= false;
1500 if (result
.scrollDisp
) {
1501 this.scrollDisp(result
.scrollDisp
);
1502 return this.cancel(ev
, true);
1505 if (isThirdLevelShift(this, ev
)) {
1509 if (result
.cancel
) {
1510 // The event is canceled at the end already, is this necessary?
1511 this.cancel(ev
, true);
1518 this.emit('keydown', ev
);
1519 this.emit('key', result
.key
, ev
);
1521 this.handler(result
.key
);
1523 return this.cancel(ev
, true);
1527 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1528 * returned value is the new key code to pass to the PTY.
1530 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1531 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1533 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1535 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1536 // canceled at the end of keyDown
1538 // The new key even to emit
1540 // The number of characters to scroll, if this is defined it will cancel the event
1541 scrollDisp
: undefined
1543 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1544 switch (ev
.keyCode
) {
1548 result
.key
= C0
.BS
; // ^H
1551 result
.key
= C0
.DEL
; // ^?
1556 result
.key
= C0
.ESC
+ '[Z';
1560 result
.cancel
= true;
1565 result
.cancel
= true;
1569 result
.key
= C0
.ESC
;
1570 result
.cancel
= true;
1575 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1576 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1577 // http://unix.stackexchange.com/a/108106
1578 // macOS uses different escape sequences than linux
1579 if (result
.key
== C0
.ESC
+ '[1;3D') {
1580 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1582 } else if (this.applicationCursor
) {
1583 result
.key
= C0
.ESC
+ 'OD';
1585 result
.key
= C0
.ESC
+ '[D';
1591 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1592 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1593 // http://unix.stackexchange.com/a/108106
1594 // macOS uses different escape sequences than linux
1595 if (result
.key
== C0
.ESC
+ '[1;3C') {
1596 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1598 } else if (this.applicationCursor
) {
1599 result
.key
= C0
.ESC
+ 'OC';
1601 result
.key
= C0
.ESC
+ '[C';
1607 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1608 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1609 // http://unix.stackexchange.com/a/108106
1610 if (result
.key
== C0
.ESC
+ '[1;3A') {
1611 result
.key
= C0
.ESC
+ '[1;5A';
1613 } else if (this.applicationCursor
) {
1614 result
.key
= C0
.ESC
+ 'OA';
1616 result
.key
= C0
.ESC
+ '[A';
1622 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1623 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1624 // http://unix.stackexchange.com/a/108106
1625 if (result
.key
== C0
.ESC
+ '[1;3B') {
1626 result
.key
= C0
.ESC
+ '[1;5B';
1628 } else if (this.applicationCursor
) {
1629 result
.key
= C0
.ESC
+ 'OB';
1631 result
.key
= C0
.ESC
+ '[B';
1636 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1637 // <Ctrl> or <Shift> + <Insert> are used to
1638 // copy-paste on some systems.
1639 result
.key
= C0
.ESC
+ '[2~';
1645 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1647 result
.key
= C0
.ESC
+ '[3~';
1653 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1654 else if (this.applicationCursor
)
1655 result
.key
= C0
.ESC
+ 'OH';
1657 result
.key
= C0
.ESC
+ '[H';
1662 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1663 else if (this.applicationCursor
)
1664 result
.key
= C0
.ESC
+ 'OF';
1666 result
.key
= C0
.ESC
+ '[F';
1671 result
.scrollDisp
= -(this.rows
- 1);
1673 result
.key
= C0
.ESC
+ '[5~';
1679 result
.scrollDisp
= this.rows
- 1;
1681 result
.key
= C0
.ESC
+ '[6~';
1687 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1689 result
.key
= C0
.ESC
+ 'OP';
1694 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1696 result
.key
= C0
.ESC
+ 'OQ';
1701 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1703 result
.key
= C0
.ESC
+ 'OR';
1708 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1710 result
.key
= C0
.ESC
+ 'OS';
1715 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1717 result
.key
= C0
.ESC
+ '[15~';
1722 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1724 result
.key
= C0
.ESC
+ '[17~';
1729 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1731 result
.key
= C0
.ESC
+ '[18~';
1736 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1738 result
.key
= C0
.ESC
+ '[19~';
1743 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1745 result
.key
= C0
.ESC
+ '[20~';
1750 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1752 result
.key
= C0
.ESC
+ '[21~';
1757 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1759 result
.key
= C0
.ESC
+ '[23~';
1764 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1766 result
.key
= C0
.ESC
+ '[24~';
1771 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1772 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1773 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1774 } else if (ev
.keyCode
=== 32) {
1776 result
.key
= String
.fromCharCode(0);
1777 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1778 // escape, file sep, group sep, record sep, unit sep
1779 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1780 } else if (ev
.keyCode
=== 56) {
1782 result
.key
= String
.fromCharCode(127);
1783 } else if (ev
.keyCode
=== 219) {
1784 // ^[ - Control Sequence Introducer (CSI)
1785 result
.key
= String
.fromCharCode(27);
1786 } else if (ev
.keyCode
=== 220) {
1787 // ^\ - String Terminator (ST)
1788 result
.key
= String
.fromCharCode(28);
1789 } else if (ev
.keyCode
=== 221) {
1790 // ^] - Operating System Command (OSC)
1791 result
.key
= String
.fromCharCode(29);
1793 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1794 // On Mac this is a third level shift. Use <Esc> instead.
1795 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1796 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1797 } else if (ev
.keyCode
=== 192) {
1798 result
.key
= C0
.ESC
+ '`';
1799 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1800 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1802 } else if (this.browser
.isMac
&& !ev
.altKey
&& !ev
.ctrlKey
&& ev
.metaKey
) {
1803 if (ev
.keyCode
=== 65) { // cmd + a
1814 * Set the G level of the terminal
1817 Terminal
.prototype.setgLevel = function(g
) {
1819 this.charset
= this.charsets
[g
];
1823 * Set the charset for the given G level of the terminal
1827 Terminal
.prototype.setgCharset = function(g
, charset
) {
1828 this.charsets
[g
] = charset
;
1829 if (this.glevel
=== g
) {
1830 this.charset
= charset
;
1835 * Handle a keypress event.
1837 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1838 * @param {KeyboardEvent} ev The keypress event to be handled.
1840 Terminal
.prototype.keyPress = function(ev
) {
1843 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1851 } else if (ev
.which
== null) {
1853 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1860 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1865 key
= String
.fromCharCode(key
);
1867 this.emit('keypress', key
, ev
);
1868 this.emit('key', key
, ev
);
1876 * Send data for handling to the terminal
1877 * @param {string} data
1879 Terminal
.prototype.send = function(data
) {
1883 setTimeout(function() {
1884 self
.handler(self
.queue
);
1894 * Note: We could do sweet things with webaudio here
1896 Terminal
.prototype.bell = function() {
1897 if (!this.visualBell
) return;
1899 this.element
.style
.borderColor
= 'white';
1900 setTimeout(function() {
1901 self
.element
.style
.borderColor
= '';
1903 if (this.popOnBell
) this.focus();
1907 * Log the current state to the console.
1909 Terminal
.prototype.log = function() {
1910 if (!this.debug
) return;
1911 if (!this.context
.console
|| !this.context
.console
.log
) return;
1912 var args
= Array
.prototype.slice
.call(arguments
);
1913 this.context
.console
.log
.apply(this.context
.console
, args
);
1917 * Log the current state as error to the console.
1919 Terminal
.prototype.error = function() {
1920 if (!this.debug
) return;
1921 if (!this.context
.console
|| !this.context
.console
.error
) return;
1922 var args
= Array
.prototype.slice
.call(arguments
);
1923 this.context
.console
.error
.apply(this.context
.console
, args
);
1927 * Resizes the terminal.
1929 * @param {number} x The number of columns to resize to.
1930 * @param {number} y The number of rows to resize to.
1932 Terminal
.prototype.resize = function(x
, y
) {
1933 if (isNaN(x
) || isNaN(y
)) {
1937 if (y
> this.getOption('scrollback')) {
1938 this.setOption('scrollback', y
)
1948 if (x
=== this.cols
&& y
=== this.rows
) {
1949 // Check if we still need to measure the char size (fixes #785).
1950 if (!this.charMeasure
.width
|| !this.charMeasure
.height
) {
1951 this.charMeasure
.measure();
1962 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1963 i
= this.lines
.length
;
1965 while (this.lines
.get(i
).length
< x
) {
1966 this.lines
.get(i
).push(ch
);
1972 this.setupStops(this.cols
);
1980 // y is rows, not this.y
1981 if (this.lines
.length
< y
+ this.ybase
) {
1982 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
1983 // There is room above the buffer and there are no empty elements below the line,
1987 if (this.ydisp
> 0) {
1988 // Viewport is at the top of the buffer, must increase downwards
1992 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1993 // are blank lines after the cursor
1994 this.lines
.push(this.blankLine());
1997 if (this.children
.length
< y
) {
2003 if (this.lines
.length
> y
+ this.ybase
) {
2004 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
2005 // The line is a blank line below the cursor, remove it
2008 // The line is the cursor, scroll down
2013 if (this.children
.length
> y
) {
2014 el
= this.children
.shift();
2016 el
.parentNode
.removeChild(el
);
2022 // Make sure that the cursor stays on screen
2035 this.scrollBottom
= y
- 1;
2037 this.charMeasure
.measure();
2039 this.refresh(0, this.rows
- 1);
2043 this.geometry
= [this.cols
, this.rows
];
2044 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
2048 * Updates the range of rows to refresh
2049 * @param {number} y The number of rows to refresh next.
2051 Terminal
.prototype.updateRange = function(y
) {
2052 if (y
< this.refreshStart
) this.refreshStart
= y
;
2053 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
2054 // if (y > this.refreshEnd) {
2055 // this.refreshEnd = y;
2056 // if (y > this.rows - 1) {
2057 // this.refreshEnd = this.rows - 1;
2063 * Set the range of refreshing to the maximum value
2065 Terminal
.prototype.maxRange = function() {
2066 this.refreshStart
= 0;
2067 this.refreshEnd
= this.rows
- 1;
2073 * Setup the tab stops.
2076 Terminal
.prototype.setupStops = function(i
) {
2078 if (!this.tabs
[i
]) {
2079 i
= this.prevStop(i
);
2086 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
2087 this.tabs
[i
] = true;
2093 * Move the cursor to the previous tab stop from the given position (default is current).
2094 * @param {number} x The position to move the cursor to the previous tab stop.
2096 Terminal
.prototype.prevStop = function(x
) {
2097 if (x
== null) x
= this.x
;
2098 while (!this.tabs
[--x
] && x
> 0);
2099 return x
>= this.cols
2106 * Move the cursor one tab stop forward from the given position (default is current).
2107 * @param {number} x The position to move the cursor one tab stop forward.
2109 Terminal
.prototype.nextStop = function(x
) {
2110 if (x
== null) x
= this.x
;
2111 while (!this.tabs
[++x
] && x
< this.cols
);
2112 return x
>= this.cols
2119 * Erase in the identified line everything from "x" to the end of the line (right).
2120 * @param {number} x The column from which to start erasing to the end of the line.
2121 * @param {number} y The line in which to operate.
2123 Terminal
.prototype.eraseRight = function(x
, y
) {
2124 var line
= this.lines
.get(this.ybase
+ y
);
2128 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2129 for (; x
< this.cols
; x
++) {
2132 this.updateRange(y
);
2138 * Erase in the identified line everything from "x" to the start of the line (left).
2139 * @param {number} x The column from which to start erasing to the start of the line.
2140 * @param {number} y The line in which to operate.
2142 Terminal
.prototype.eraseLeft = function(x
, y
) {
2143 var line
= this.lines
.get(this.ybase
+ y
);
2147 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2152 this.updateRange(y
);
2156 * Clears the entire buffer, making the prompt line the new first line.
2158 Terminal
.prototype.clear = function() {
2159 if (this.ybase
=== 0 && this.y
=== 0) {
2160 // Don't clear if it's already clear
2163 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2164 this.lines
.length
= 1;
2168 for (var i
= 1; i
< this.rows
; i
++) {
2169 this.lines
.push(this.blankLine());
2171 this.refresh(0, this.rows
- 1);
2172 this.emit('scroll', this.ydisp
);
2176 * Erase all content in the given line
2177 * @param {number} y The line to erase all of its contents.
2179 Terminal
.prototype.eraseLine = function(y
) {
2180 this.eraseRight(0, y
);
2185 * Return the data array of a blank line
2186 * @param {number} cur First bunch of data for each "blank" character.
2187 * @param {boolean} isWrapped Whether the new line is wrapped from the previous line.
2189 Terminal
.prototype.blankLine = function(cur
, isWrapped
) {
2194 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2198 // TODO: It is not ideal that this is a property on an array, a buffer line
2199 // class should be added that will hold this data and other useful functions.
2201 line
.isWrapped
= isWrapped
;
2204 for (; i
< this.cols
; i
++) {
2213 * If cur return the back color xterm feature attribute. Else return defAttr.
2214 * @param {object} cur
2216 Terminal
.prototype.ch = function(cur
) {
2218 ? [this.eraseAttr(), ' ', 1]
2219 : [this.defAttr
, ' ', 1];
2224 * Evaluate if the current erminal is the given argument.
2225 * @param {object} term The terminal to evaluate
2227 Terminal
.prototype.is = function(term
) {
2228 var name
= this.termName
;
2229 return (name
+ '').indexOf(term
) === 0;
2234 * Emit the 'data' event and populate the given data.
2235 * @param {string} data The data to populate in the event.
2237 Terminal
.prototype.handler = function(data
) {
2238 // Prevents all events to pty process if stdin is disabled
2239 if (this.options
.disableStdin
) {
2243 // Clear the selection if the selection manager is available and has an active selection
2244 if (this.selectionManager
&& this.selectionManager
.hasSelection
) {
2245 this.selectionManager
.clearSelection();
2248 // Input is being sent to the terminal, the terminal should focus the prompt.
2249 if (this.ybase
!== this.ydisp
) {
2250 this.scrollToBottom();
2252 this.emit('data', data
);
2257 * Emit the 'title' event and populate the given title.
2258 * @param {string} title The title to populate in the event.
2260 Terminal
.prototype.handleTitle = function(title
) {
2262 * This event is emitted when the title of the terminal is changed
2263 * from inside the terminal. The parameter is the new title.
2267 this.emit('title', title
);
2276 * ESC D Index (IND is 0x84).
2278 Terminal
.prototype.index = function() {
2280 if (this.y
> this.scrollBottom
) {
2284 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2285 if (this.x
>= this.cols
) {
2292 * ESC M Reverse Index (RI is 0x8d).
2294 * Move the cursor up one row, inserting a new blank line if necessary.
2296 Terminal
.prototype.reverseIndex = function() {
2298 if (this.y
=== this.scrollTop
) {
2299 // possibly move the code below to term.reverseScroll();
2300 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2301 // blankLine(true) is xterm/linux behavior
2302 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2303 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2304 this.updateRange(this.scrollTop
);
2305 this.updateRange(this.scrollBottom
);
2313 * ESC c Full Reset (RIS).
2315 Terminal
.prototype.reset = function() {
2316 this.options
.rows
= this.rows
;
2317 this.options
.cols
= this.cols
;
2318 var customKeyEventHandler
= this.customKeyEventHandler
;
2319 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2320 Terminal
.call(this, this.options
);
2321 this.customKeyEventHandler
= customKeyEventHandler
;
2322 this.cursorBlinkInterval
= cursorBlinkInterval
;
2323 this.refresh(0, this.rows
- 1);
2324 this.viewport
.syncScrollArea();
2329 * ESC H Tab Set (HTS is 0x88).
2331 Terminal
.prototype.tabSet = function() {
2332 this.tabs
[this.x
] = true;
2339 function on(el
, type
, handler
, capture
) {
2340 if (!Array
.isArray(el
)) {
2343 el
.forEach(function (element
) {
2344 element
.addEventListener(type
, handler
, capture
|| false);
2348 function off(el
, type
, handler
, capture
) {
2349 el
.removeEventListener(type
, handler
, capture
|| false);
2352 function cancel(ev
, force
) {
2353 if (!this.cancelEvents
&& !force
) {
2356 ev
.preventDefault();
2357 ev
.stopPropagation();
2361 function inherits(child
, parent
) {
2363 this.constructor = child
;
2365 f
.prototype = parent
.prototype;
2366 child
.prototype = new f
;
2369 function indexOf(obj
, el
) {
2372 if (obj
[i
] === el
) return i
;
2377 function isThirdLevelShift(term
, ev
) {
2379 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2380 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2382 if (ev
.type
== 'keypress') {
2383 return thirdLevelKey
;
2386 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2387 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2390 // Expose to InputHandler (temporary)
2391 Terminal
.prototype.matchColor
= matchColor
;
2393 function matchColor(r1
, g1
, b1
) {
2394 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2396 if (matchColor
._cache
[hash
] != null) {
2397 return matchColor
._cache
[hash
];
2400 var ldiff
= Infinity
2409 for (; i
< Terminal
.vcolors
.length
; i
++) {
2410 c
= Terminal
.vcolors
[i
];
2415 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2428 return matchColor
._cache
[hash
] = li
;
2431 matchColor
._cache
= {};
2433 // http://stackoverflow.com/questions/1633828
2434 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2435 return Math
.pow(30 * (r1
- r2
), 2)
2436 + Math
.pow(59 * (g1
- g2
), 2)
2437 + Math
.pow(11 * (b1
- b2
), 2);
2440 function each(obj
, iter
, con
) {
2441 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2442 for (var i
= 0; i
< obj
.length
; i
++) {
2443 iter
.call(con
, obj
[i
], i
, obj
);
2447 function wasMondifierKeyOnlyEvent(ev
) {
2448 return ev
.keyCode
=== 16 || // Shift
2449 ev
.keyCode
=== 17 || // Ctrl
2450 ev
.keyCode
=== 18; // Alt
2453 function keys(obj
) {
2454 if (Object
.keys
) return Object
.keys(obj
);
2457 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2468 Terminal
.translateBufferLineToString
= translateBufferLineToString
;
2469 Terminal
.EventEmitter
= EventEmitter
;
2470 Terminal
.inherits
= inherits
;
2473 * Adds an event listener to the terminal.
2475 * @param {string} event The name of the event. TODO: Document all event types
2476 * @param {function} callback The function to call when the event is triggered.
2480 Terminal
.cancel
= cancel
;
2482 module
.exports
= Terminal
;