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 // Create the terminal's buffers and set the current buffer
248 this.buffers
= new BufferSet(this);
249 this.buffer
= this.buffers
.active
; // Convenience shortcut;
250 this.buffers
.on('activate', function (buffer
) {
251 this.buffer
= buffer
;
255 * An array of all lines in the entire buffer, including the prompt. The lines are array of
256 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
261 this.buffer
.lines
.push(this.blankLine());
263 // Ensure the selection manager has the correct buffer
264 if (this.selectionManager
) {
265 this.selectionManager
.setBuffer(this.buffer
.lines
);
271 // Store if user went browsing history in scrollback
272 this.userScrolling
= false;
275 inherits(Terminal
, EventEmitter
);
278 * back_color_erase feature for xterm.
280 Terminal
.prototype.eraseAttr = function() {
281 // if (this.is('screen')) return this.defAttr;
282 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
290 Terminal
.tangoColors
= [
311 // Colors 0-15 + 16-255
312 // Much thanks to TooTallNate for writing this.
313 Terminal
.colors
= (function() {
314 var colors
= Terminal
.tangoColors
.slice()
315 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
320 for (; i
< 216; i
++) {
321 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
326 for (; i
< 24; i
++) {
331 function out(r
, g
, b
) {
332 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
337 return c
.length
< 2 ? '0' + c
: c
;
343 Terminal
._colors
= Terminal
.colors
.slice();
345 Terminal
.vcolors
= (function() {
347 , colors
= Terminal
.colors
351 for (; i
< 256; i
++) {
352 color
= parseInt(colors
[i
].substring(1), 16);
354 (color
>> 16) & 0xff,
367 Terminal
.defaults
= {
368 colors
: Terminal
.colors
,
374 cursorStyle
: 'block',
382 useFlowControl
: false,
384 // programFeatures: false,
388 Terminal
.options
= {};
390 Terminal
.focus
= null;
392 each(keys(Terminal
.defaults
), function(key
) {
393 Terminal
[key
] = Terminal
.defaults
[key
];
394 Terminal
.options
[key
] = Terminal
.defaults
[key
];
398 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
400 Terminal
.prototype.focus = function() {
401 return this.textarea
.focus();
405 * Retrieves an option's value from the terminal.
406 * @param {string} key The option key.
408 Terminal
.prototype.getOption = function(key
) {
409 if (!(key
in Terminal
.defaults
)) {
410 throw new Error('No option with key "' + key
+ '"');
413 if (typeof this.options
[key
] !== 'undefined') {
414 return this.options
[key
];
421 * Sets an option on the terminal.
422 * @param {string} key The option key.
423 * @param {string} value The option value.
425 Terminal
.prototype.setOption = function(key
, value
) {
426 if (!(key
in Terminal
.defaults
)) {
427 throw new Error('No option with key "' + key
+ '"');
431 if (value
< this.rows
) {
432 let msg
= 'Setting the scrollback value less than the number of rows ';
434 msg
+= `(${this.rows}) is not allowed.`;
440 if (this.options
[key
] !== value
) {
441 if (this.buffer
.length
> value
) {
442 const amountToTrim
= this.buffer
.lines
.length
- value
;
443 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
444 this.buffer
.lines
.trimStart(amountToTrim
);
445 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
446 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
448 this.refresh(0, this.rows
- 1);
451 this.buffer
.lines
.maxLength
= value
;
452 this.viewport
.syncScrollArea();
457 this.options
[key
] = value
;
459 case 'cursorBlink': this.setCursorBlinking(value
); break;
461 // Style 'block' applies with no class
462 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
463 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
465 case 'tabStopWidth': this.setupStops(); break;
469 Terminal
.prototype.restartCursorBlinking = function () {
470 this.setCursorBlinking(this.options
.cursorBlink
);
473 Terminal
.prototype.setCursorBlinking = function (enabled
) {
474 this.element
.classList
.toggle('xterm-cursor-blink', enabled
);
475 this.clearCursorBlinkingInterval();
478 this.cursorBlinkInterval
= setInterval(function () {
479 self
.element
.classList
.toggle('xterm-cursor-blink-on');
480 }, CURSOR_BLINK_INTERVAL
);
484 Terminal
.prototype.clearCursorBlinkingInterval = function () {
485 this.element
.classList
.remove('xterm-cursor-blink-on');
486 if (this.cursorBlinkInterval
) {
487 clearInterval(this.cursorBlinkInterval
);
488 this.cursorBlinkInterval
= null;
493 * Binds the desired focus behavior on a given terminal object.
497 Terminal
.bindFocus = function (term
) {
498 on(term
.textarea
, 'focus', function (ev
) {
499 if (term
.sendFocus
) {
500 term
.send(C0
.ESC
+ '[I');
502 term
.element
.classList
.add('focus');
504 term
.restartCursorBlinking
.apply(term
);
505 Terminal
.focus
= term
;
506 term
.emit('focus', {terminal
: term
});
511 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
513 Terminal
.prototype.blur = function() {
514 return this.textarea
.blur();
518 * Binds the desired blur behavior on a given terminal object.
522 Terminal
.bindBlur = function (term
) {
523 on(term
.textarea
, 'blur', function (ev
) {
524 term
.refresh(term
.y
, term
.y
);
525 if (term
.sendFocus
) {
526 term
.send(C0
.ESC
+ '[O');
528 term
.element
.classList
.remove('focus');
529 term
.clearCursorBlinkingInterval
.apply(term
);
530 Terminal
.focus
= null;
531 term
.emit('blur', {terminal
: term
});
536 * Initialize default behavior
538 Terminal
.prototype.initGlobal = function() {
541 Terminal
.bindKeys(this);
542 Terminal
.bindFocus(this);
543 Terminal
.bindBlur(this);
545 // Bind clipboard functionality
546 on(this.element
, 'copy', event
=> {
547 // If mouse events are active it means the selection manager is disabled and
548 // copy should be handled by the host program.
549 if (this.mouseEvents
) {
552 copyHandler(event
, term
, this.selectionManager
);
554 const pasteHandlerWrapper
= event
=> pasteHandler(event
, term
);
555 on(this.textarea
, 'paste', pasteHandlerWrapper
);
556 on(this.element
, 'paste', pasteHandlerWrapper
);
558 // Handle right click context menus
559 if (term
.browser
.isFirefox
) {
560 // Firefox doesn't appear to fire the contextmenu event on right click
561 on(this.element
, 'mousedown', event
=> {
562 if (event
.button
== 2) {
563 rightClickHandler(event
, this.textarea
, this.selectionManager
);
567 on(this.element
, 'contextmenu', event
=> {
568 rightClickHandler(event
, this.textarea
, this.selectionManager
);
572 // Move the textarea under the cursor when middle clicking on Linux to ensure
573 // middle click to paste selection works. This only appears to work in Chrome
574 // at the time is writing.
575 if (term
.browser
.isLinux
) {
576 // Use auxclick event over mousedown the latter doesn't seem to work. Note
577 // that the regular click event doesn't fire for the middle mouse button.
578 on(this.element
, 'auxclick', event
=> {
579 if (event
.button
=== 1) {
580 moveTextAreaUnderMouseCursor(event
, this.textarea
, this.selectionManager
);
587 * Apply key handling to the terminal
589 Terminal
.bindKeys = function(term
) {
590 on(term
.element
, 'keydown', function(ev
) {
591 if (document
.activeElement
!= this) {
597 on(term
.element
, 'keypress', function(ev
) {
598 if (document
.activeElement
!= this) {
604 on(term
.element
, 'keyup', function(ev
) {
605 if (!wasMondifierKeyOnlyEvent(ev
)) {
610 on(term
.textarea
, 'keydown', function(ev
) {
614 on(term
.textarea
, 'keypress', function(ev
) {
616 // Truncate the textarea's value, since it is not needed
620 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
621 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
622 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
623 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
624 term
.on('refresh', function (data
) {
625 term
.queueLinkification(data
.start
, data
.end
)
631 * Insert the given row to the terminal or produce a new one
632 * if no row argument is passed. Return the inserted row.
633 * @param {HTMLElement} row (optional) The row to append to the terminal.
635 Terminal
.prototype.insertRow = function (row
) {
636 if (typeof row
!= 'object') {
637 row
= document
.createElement('div');
640 this.rowContainer
.appendChild(row
);
641 this.children
.push(row
);
647 * Opens the terminal within an element.
649 * @param {HTMLElement} parent The element to create the terminal within.
650 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
652 Terminal
.prototype.open = function(parent
, focus
) {
653 var self
=this, i
=0, div
;
655 this.parent
= parent
|| this.parent
;
658 throw new Error('Terminal requires a parent element.');
661 // Grab global elements
662 this.context
= this.parent
.ownerDocument
.defaultView
;
663 this.document
= this.parent
.ownerDocument
;
664 this.body
= this.document
.getElementsByTagName('body')[0];
666 //Create main element container
667 this.element
= this.document
.createElement('div');
668 this.element
.classList
.add('terminal');
669 this.element
.classList
.add('xterm');
670 this.element
.classList
.add('xterm-theme-' + this.theme
);
671 this.setCursorBlinking(this.options
.cursorBlink
);
673 this.element
.setAttribute('tabindex', 0);
675 this.viewportElement
= document
.createElement('div');
676 this.viewportElement
.classList
.add('xterm-viewport');
677 this.element
.appendChild(this.viewportElement
);
678 this.viewportScrollArea
= document
.createElement('div');
679 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
680 this.viewportElement
.appendChild(this.viewportScrollArea
);
682 // Create the selection container.
683 this.selectionContainer
= document
.createElement('div');
684 this.selectionContainer
.classList
.add('xterm-selection');
685 this.element
.appendChild(this.selectionContainer
);
687 // Create the container that will hold the lines of the terminal and then
688 // produce the lines the lines.
689 this.rowContainer
= document
.createElement('div');
690 this.rowContainer
.classList
.add('xterm-rows');
691 this.element
.appendChild(this.rowContainer
);
693 this.linkifier
.attachToDom(document
, this.children
);
695 // Create the container that will hold helpers like the textarea for
696 // capturing DOM Events. Then produce the helpers.
697 this.helperContainer
= document
.createElement('div');
698 this.helperContainer
.classList
.add('xterm-helpers');
699 // TODO: This should probably be inserted once it's filled to prevent an additional layout
700 this.element
.appendChild(this.helperContainer
);
701 this.textarea
= document
.createElement('textarea');
702 this.textarea
.classList
.add('xterm-helper-textarea');
703 this.textarea
.setAttribute('autocorrect', 'off');
704 this.textarea
.setAttribute('autocapitalize', 'off');
705 this.textarea
.setAttribute('spellcheck', 'false');
706 this.textarea
.tabIndex
= 0;
707 this.textarea
.addEventListener('focus', function() {
708 self
.emit('focus', {terminal
: self
});
710 this.textarea
.addEventListener('blur', function() {
711 self
.emit('blur', {terminal
: self
});
713 this.helperContainer
.appendChild(this.textarea
);
715 this.compositionView
= document
.createElement('div');
716 this.compositionView
.classList
.add('composition-view');
717 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
718 this.helperContainer
.appendChild(this.compositionView
);
720 this.charSizeStyleElement
= document
.createElement('style');
721 this.helperContainer
.appendChild(this.charSizeStyleElement
);
723 for (; i
< this.rows
; i
++) {
726 this.parent
.appendChild(this.element
);
728 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
729 this.charMeasure
.on('charsizechanged', function () {
730 self
.updateCharSizeStyles();
732 this.charMeasure
.measure();
734 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
735 this.renderer
= new Renderer(this);
737 this.selectionManager
= new SelectionManager(this, this.lines
, this.rowContainer
, this.charMeasure
);
738 this.selectionManager
.on('refresh', data
=> {
739 this.renderer
.refreshSelection(data
.start
, data
.end
);
741 this.selectionManager
.on('newselection', text
=> {
742 // If there's a new selection, put it into the textarea, focus and select it
743 // in order to register it as a selection on the OS. This event is fired
744 // only on Linux to enable middle click to paste selection.
745 this.textarea
.value
= text
;
746 this.textarea
.focus();
747 this.textarea
.select();
750 this.selectionManager
= new SelectionManager(this, this.buffer
.lines
, this.rowContainer
, this.charMeasure
);
751 this.selectionManager
.on('refresh', data
=> this.renderer
.refreshSelection(data
.start
, data
.end
));
752 >>>>>>> Create
`terminal.buffer` convenience attribute
753 this.on('scroll', () => this.selectionManager
.refresh());
754 this.viewportElement
.addEventListener('scroll', () => this.selectionManager
.refresh());
756 // Setup loop that draws to screen
757 this.refresh(0, this.rows
- 1);
759 // Initialize global actions that
760 // need to be taken on the document.
764 * Automatic focus functionality.
765 * TODO: Default to `false` starting with xterm.js 3.0.
767 if (typeof focus
== 'undefined') {
768 let message
= 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
770 message
+= 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
771 message
+= 'it will default to `false`.';
773 console
.warn(message
);
781 on(this.element
, 'click', function() {
782 var selection
= document
.getSelection(),
783 collapsed
= selection
.isCollapsed
,
784 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
790 // Listen for mouse events and translate
791 // them into terminal mouse protocols.
795 * This event is emitted when terminal has completed opening.
804 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
805 * @param {string} addon The name of the addon to load
808 Terminal
.loadAddon = function(addon
, callback
) {
809 if (typeof exports
=== 'object' && typeof module
=== 'object') {
811 return require('./addons/' + addon
+ '/' + addon
);
812 } else if (typeof define
== 'function') {
814 return require(['./addons/' + addon
+ '/' + addon
], callback
);
816 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
822 * Updates the helper CSS class with any changes necessary after the terminal's
823 * character width has been changed.
825 Terminal
.prototype.updateCharSizeStyles = function() {
826 this.charSizeStyleElement
.textContent
=
827 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
828 `.xterm-normal-char{width:${this.charMeasure.width}px;}` +
829 `.xterm-rows > div{height:${this.charMeasure.height}px;}`;
834 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
835 * To better understand these
836 * the xterm code is very helpful:
838 * button.c, charproc.c, misc.c
839 * Relevant functions in xterm/button.c:
840 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
842 Terminal
.prototype.bindMouse = function() {
843 var el
= this.element
, self
= this, pressed
= 32;
845 // mouseup, mousedown, wheel
846 // left click: ^[[M 3<^[[M#3<
848 function sendButton(ev
) {
852 // get the xterm-style button
853 button
= getButton(ev
);
855 // get mouse coordinates
856 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
859 sendEvent(button
, pos
);
861 switch (ev
.overrideType
|| ev
.type
) {
866 // keep it at the left
867 // button, just in case.
878 // motion example of a left click:
879 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
880 function sendMove(ev
) {
884 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
887 // buttons marked as motions
888 // are incremented by 32
891 sendEvent(button
, pos
);
895 // position to characters
896 function encode(data
, ch
) {
897 if (!self
.utfMouse
) {
898 if (ch
=== 255) return data
.push(0);
899 if (ch
> 127) ch
= 127;
902 if (ch
=== 2047) return data
.push(0);
906 if (ch
> 2047) ch
= 2047;
907 data
.push(0xC0 | (ch
>> 6));
908 data
.push(0x80 | (ch
& 0x3F));
913 // send a mouse event:
914 // regular/utf8: ^[[M Cb Cx Cy
915 // urxvt: ^[[ Cb ; Cx ; Cy M
916 // sgr: ^[[ Cb ; Cx ; Cy M/m
917 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
918 // locator: CSI P e ; P b ; P r ; P c ; P p & w
919 function sendEvent(button
, pos
) {
920 // self.emit('mouse', {
926 if (self
.vt300Mouse
) {
928 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
932 var data
= C0
.ESC
+ '[24';
933 if (button
=== 0) data
+= '1';
934 else if (button
=== 1) data
+= '3';
935 else if (button
=== 2) data
+= '5';
936 else if (button
=== 3) return;
938 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
943 if (self
.decLocator
) {
948 if (button
=== 0) button
= 2;
949 else if (button
=== 1) button
= 4;
950 else if (button
=== 2) button
= 6;
951 else if (button
=== 3) button
= 3;
952 self
.send(C0
.ESC
+ '['
955 + (button
=== 3 ? 4 : 0)
966 if (self
.urxvtMouse
) {
971 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
978 self
.send(C0
.ESC
+ '[<'
979 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
984 + ((button
& 3) === 3 ? 'm' : 'M'));
990 encode(data
, button
);
994 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
997 function getButton(ev
) {
1010 // 1, and 2 - with 64 added
1011 switch (ev
.overrideType
|| ev
.type
) {
1013 button
= ev
.button
!= null
1019 if (self
.browser
.isMSIE
) {
1020 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
1026 case 'DOMMouseScroll':
1027 button
= ev
.detail
< 0
1032 button
= ev
.wheelDeltaY
> 0
1038 // next three bits are the modifiers:
1039 // 4 = shift, 8 = meta, 16 = control
1040 shift
= ev
.shiftKey
? 4 : 0;
1041 meta
= ev
.metaKey
? 8 : 0;
1042 ctrl
= ev
.ctrlKey
? 16 : 0;
1043 mod
= shift
| meta
| ctrl
;
1046 if (self
.vt200Mouse
) {
1049 } else if (!self
.normalMouse
) {
1054 button
= (32 + (mod
<< 2)) + button
;
1059 on(el
, 'mousedown', function(ev
) {
1060 if (!self
.mouseEvents
) return;
1069 //if (self.vt200Mouse && !self.normalMouse) {
1070 if (self
.vt200Mouse
) {
1071 ev
.overrideType
= 'mouseup';
1073 return self
.cancel(ev
);
1077 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1079 // x10 compatibility mode can't send button releases
1080 if (!self
.x10Mouse
) {
1081 on(self
.document
, 'mouseup', function up(ev
) {
1083 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1084 off(self
.document
, 'mouseup', up
);
1085 return self
.cancel(ev
);
1089 return self
.cancel(ev
);
1092 //if (self.normalMouse) {
1093 // on(self.document, 'mousemove', sendMove);
1096 on(el
, 'wheel', function(ev
) {
1097 if (!self
.mouseEvents
) return;
1100 || self
.decLocator
) return;
1102 return self
.cancel(ev
);
1105 // allow wheel scrolling in
1106 // the shell for example
1107 on(el
, 'wheel', function(ev
) {
1108 if (self
.mouseEvents
) return;
1109 self
.viewport
.onWheel(ev
);
1110 return self
.cancel(ev
);
1113 on(el
, 'touchstart', function(ev
) {
1114 if (self
.mouseEvents
) return;
1115 self
.viewport
.onTouchStart(ev
);
1116 return self
.cancel(ev
);
1119 on(el
, 'touchmove', function(ev
) {
1120 if (self
.mouseEvents
) return;
1121 self
.viewport
.onTouchMove(ev
);
1122 return self
.cancel(ev
);
1127 * Destroys the terminal.
1129 Terminal
.prototype.destroy = function() {
1130 this.readable
= false;
1131 this.writable
= false;
1133 this.handler = function() {};
1134 this.write = function() {};
1135 if (this.element
&& this.element
.parentNode
) {
1136 this.element
.parentNode
.removeChild(this.element
);
1138 //this.emit('close');
1142 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
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.refresh = function(start
, end
) {
1148 if (this.renderer
) {
1149 this.renderer
.queueRefresh(start
, end
);
1154 * Queues linkification for the specified rows.
1155 * @param {number} start The row to start from (between 0 and this.rows - 1).
1156 * @param {number} end The row to end at (between start and this.rows - 1).
1158 Terminal
.prototype.queueLinkification = function(start
, end
) {
1159 if (this.linkifier
) {
1160 for (let i
= start
; i
<= end
; i
++) {
1161 this.linkifier
.linkifyRow(i
);
1167 * Display the cursor element
1169 Terminal
.prototype.showCursor = function() {
1170 if (!this.cursorState
) {
1171 this.cursorState
= 1;
1172 this.refresh(this.y
, this.y
);
1177 * Scroll the terminal down 1 row, creating a blank line.
1178 * @param {boolean} isWrapped Whether the new line is wrapped from the previous
1181 Terminal
.prototype.scroll = function(isWrapped
) {
1184 // Make room for the new row in lines
1185 if (this.buffer
.lines
.length
=== this.buffer
.lines
.maxLength
) {
1186 this.buffer
.lines
.trimStart(1);
1188 if (this.ydisp
!== 0) {
1195 // TODO: Why is this done twice?
1196 if (!this.userScrolling
) {
1197 this.ydisp
= this.ybase
;
1201 row
= this.ybase
+ this.rows
- 1;
1203 // subtract the bottom scroll region
1204 row
-= this.rows
- 1 - this.scrollBottom
;
1206 if (row
=== this.buffer
.lines
.length
) {
1207 // Optimization: pushing is faster than splicing when they amount to the same behavior
1208 this.buffer
.lines
.push(this.blankLine(undefined, isWrapped
));
1211 this.buffer
.lines
.splice(row
, 0, this.blankLine(undefined, isWrapped
));
1214 if (this.scrollTop
!== 0) {
1215 if (this.ybase
!== 0) {
1217 if (!this.userScrolling
) {
1218 this.ydisp
= this.ybase
;
1221 this.buffer
.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1225 this.updateRange(this.scrollTop
);
1226 this.updateRange(this.scrollBottom
);
1229 * This event is emitted whenever the terminal is scrolled.
1230 * The one parameter passed is the new y display position.
1234 this.emit('scroll', this.ydisp
);
1238 * Scroll the display of the terminal
1239 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1240 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1241 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1242 * viewport originally.
1244 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1246 if (this.ydisp
=== 0) {
1249 this.userScrolling
= true;
1250 } else if (disp
+ this.ydisp
>= this.ybase
) {
1251 this.userScrolling
= false;
1254 const oldYdisp
= this.ydisp
;
1255 this.ydisp
= Math
.max(Math
.min(this.ydisp
+ disp
, this.ybase
), 0);
1257 // No change occurred, don't trigger scroll/refresh
1258 if (oldYdisp
=== this.ydisp
) {
1262 if (!suppressScrollEvent
) {
1263 this.emit('scroll', this.ydisp
);
1266 this.refresh(0, this.rows
- 1);
1270 * Scroll the display of the terminal by a number of pages.
1271 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1273 Terminal
.prototype.scrollPages = function(pageCount
) {
1274 this.scrollDisp(pageCount
* (this.rows
- 1));
1278 * Scrolls the display of the terminal to the top.
1280 Terminal
.prototype.scrollToTop = function() {
1281 this.scrollDisp(-this.ydisp
);
1285 * Scrolls the display of the terminal to the bottom.
1287 Terminal
.prototype.scrollToBottom = function() {
1288 this.scrollDisp(this.ybase
- this.ydisp
);
1292 * Writes text to the terminal.
1293 * @param {string} data The text to write to the terminal.
1295 Terminal
.prototype.write = function(data
) {
1296 this.writeBuffer
.push(data
);
1298 // Send XOFF to pause the pty process if the write buffer becomes too large so
1299 // xterm.js can catch up before more data is sent. This is necessary in order
1300 // to keep signals such as ^C responsive.
1301 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1302 // XOFF - stop pty pipe
1303 // XON will be triggered by emulator before processing data chunk
1305 this.xoffSentToCatchUp
= true;
1308 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1309 // Kick off a write which will write all data in sequence recursively
1310 this.writeInProgress
= true;
1311 // Kick off an async innerWrite so more writes can come in while processing data
1313 setTimeout(function () {
1319 Terminal
.prototype.innerWrite = function() {
1320 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1321 while (writeBatch
.length
> 0) {
1322 var data
= writeBatch
.shift();
1323 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1325 // If XOFF was sent in order to catch up with the pty process, resume it if
1326 // the writeBuffer is empty to allow more data to come in.
1327 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1329 this.xoffSentToCatchUp
= false;
1332 this.refreshStart
= this.y
;
1333 this.refreshEnd
= this.y
;
1335 // HACK: Set the parser state based on it's state at the time of return.
1336 // This works around the bug #662 which saw the parser state reset in the
1337 // middle of parsing escape sequence in two chunks. For some reason the
1338 // state of the parser resets to 0 after exiting parser.parse. This change
1339 // just sets the state back based on the correct return statement.
1340 var state
= this.parser
.parse(data
);
1341 this.parser
.setState(state
);
1343 this.updateRange(this.y
);
1344 this.refresh(this.refreshStart
, this.refreshEnd
);
1346 if (this.writeBuffer
.length
> 0) {
1347 // Allow renderer to catch up before processing the next batch
1349 setTimeout(function () {
1353 this.writeInProgress
= false;
1358 * Writes text to the terminal, followed by a break line character (\n).
1359 * @param {string} data The text to write to the terminal.
1361 Terminal
.prototype.writeln = function(data
) {
1362 this.write(data
+ '\r\n');
1366 * DEPRECATED: only for backward compatibility. Please use attachCustomKeyEventHandler() instead.
1367 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1368 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1369 * the default action. The function returns whether the event should be processed by xterm.js.
1371 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1372 let message
= 'attachCustomKeydownHandler() is DEPRECATED and will be removed soon. Please use attachCustomKeyEventHandler() instead.';
1373 console
.warn(message
);
1374 this.attachCustomKeyEventHandler(customKeydownHandler
);
1378 * Attaches a custom key event handler which is run before keys are processed, giving consumers of
1379 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1381 * @param {function} customKeyEventHandler The custom KeyboardEvent handler to attach. This is a
1382 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1383 * the default action. The function returns whether the event should be processed by xterm.js.
1385 Terminal
.prototype.attachCustomKeyEventHandler = function(customKeyEventHandler
) {
1386 this.customKeyEventHandler
= customKeyEventHandler
;
1390 * Attaches a http(s) link handler, forcing web links to behave differently to
1391 * regular <a> tags. This will trigger a refresh as links potentially need to be
1392 * reconstructed. Calling this with null will remove the handler.
1393 * @param {LinkMatcherHandler} handler The handler callback function.
1395 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1396 if (!this.linkifier
) {
1397 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1399 this.linkifier
.setHypertextLinkHandler(handler
);
1400 // Refresh to force links to refresh
1401 this.refresh(0, this.rows
- 1);
1405 * Attaches a validation callback for hypertext links. This is useful to use
1406 * validation logic or to do something with the link's element and url.
1407 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1408 * be cleared with null.
1410 Terminal
.prototype.setHypertextValidationCallback = function(callback
) {
1411 if (!this.linkifier
) {
1412 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1414 this.linkifier
.setHypertextValidationCallback(callback
);
1415 // Refresh to force links to refresh
1416 this.refresh(0, this.rows
- 1);
1420 * Registers a link matcher, allowing custom link patterns to be matched and
1422 * @param {RegExp} regex The regular expression to search for, specifically
1423 * this searches the textContent of the rows. You will want to use \s to match
1424 * a space ' ' character for example.
1425 * @param {LinkMatcherHandler} handler The callback when the link is called.
1426 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1427 * @return {number} The ID of the new matcher, this can be used to deregister.
1429 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1430 if (this.linkifier
) {
1431 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1432 this.refresh(0, this.rows
- 1);
1438 * Deregisters a link matcher if it has been registered.
1439 * @param {number} matcherId The link matcher's ID (returned after register)
1441 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1442 if (this.linkifier
) {
1443 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1444 this.refresh(0, this.rows
- 1);
1450 * Gets whether the terminal has an active selection.
1452 Terminal
.prototype.hasSelection = function() {
1453 return this.selectionManager
? this.selectionManager
.hasSelection
: false;
1457 * Gets the terminal's current selection, this is useful for implementing copy
1458 * behavior outside of xterm.js.
1460 Terminal
.prototype.getSelection = function() {
1461 return this.selectionManager
? this.selectionManager
.selectionText
: '';
1465 * Clears the current terminal selection.
1467 Terminal
.prototype.clearSelection = function() {
1468 if (this.selectionManager
) {
1469 this.selectionManager
.clearSelection();
1474 * Selects all text within the terminal.
1476 Terminal
.prototype.selectAll = function() {
1477 if (this.selectionManager
) {
1478 this.selectionManager
.selectAll();
1483 * Handle a keydown event
1485 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1486 * @param {KeyboardEvent} ev The keydown event to be handled.
1488 Terminal
.prototype.keyDown = function(ev
) {
1489 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1493 this.restartCursorBlinking();
1495 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1496 if (this.ybase
!== this.ydisp
) {
1497 this.scrollToBottom();
1503 var result
= this.evaluateKeyEscapeSequence(ev
);
1505 if (result
.key
=== C0
.DC3
) { // XOFF
1506 this.writeStopped
= true;
1507 } else if (result
.key
=== C0
.DC1
) { // XON
1508 this.writeStopped
= false;
1511 if (result
.scrollDisp
) {
1512 this.scrollDisp(result
.scrollDisp
);
1513 return this.cancel(ev
, true);
1516 if (isThirdLevelShift(this, ev
)) {
1520 if (result
.cancel
) {
1521 // The event is canceled at the end already, is this necessary?
1522 this.cancel(ev
, true);
1529 this.emit('keydown', ev
);
1530 this.emit('key', result
.key
, ev
);
1532 this.handler(result
.key
);
1534 return this.cancel(ev
, true);
1538 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1539 * returned value is the new key code to pass to the PTY.
1541 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1542 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1544 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1546 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1547 // canceled at the end of keyDown
1549 // The new key even to emit
1551 // The number of characters to scroll, if this is defined it will cancel the event
1552 scrollDisp
: undefined
1554 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1555 switch (ev
.keyCode
) {
1559 result
.key
= C0
.BS
; // ^H
1562 result
.key
= C0
.DEL
; // ^?
1567 result
.key
= C0
.ESC
+ '[Z';
1571 result
.cancel
= true;
1576 result
.cancel
= true;
1580 result
.key
= C0
.ESC
;
1581 result
.cancel
= true;
1586 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1587 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1588 // http://unix.stackexchange.com/a/108106
1589 // macOS uses different escape sequences than linux
1590 if (result
.key
== C0
.ESC
+ '[1;3D') {
1591 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1593 } else if (this.applicationCursor
) {
1594 result
.key
= C0
.ESC
+ 'OD';
1596 result
.key
= C0
.ESC
+ '[D';
1602 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1603 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1604 // http://unix.stackexchange.com/a/108106
1605 // macOS uses different escape sequences than linux
1606 if (result
.key
== C0
.ESC
+ '[1;3C') {
1607 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1609 } else if (this.applicationCursor
) {
1610 result
.key
= C0
.ESC
+ 'OC';
1612 result
.key
= C0
.ESC
+ '[C';
1618 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1619 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1620 // http://unix.stackexchange.com/a/108106
1621 if (result
.key
== C0
.ESC
+ '[1;3A') {
1622 result
.key
= C0
.ESC
+ '[1;5A';
1624 } else if (this.applicationCursor
) {
1625 result
.key
= C0
.ESC
+ 'OA';
1627 result
.key
= C0
.ESC
+ '[A';
1633 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1634 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1635 // http://unix.stackexchange.com/a/108106
1636 if (result
.key
== C0
.ESC
+ '[1;3B') {
1637 result
.key
= C0
.ESC
+ '[1;5B';
1639 } else if (this.applicationCursor
) {
1640 result
.key
= C0
.ESC
+ 'OB';
1642 result
.key
= C0
.ESC
+ '[B';
1647 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1648 // <Ctrl> or <Shift> + <Insert> are used to
1649 // copy-paste on some systems.
1650 result
.key
= C0
.ESC
+ '[2~';
1656 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1658 result
.key
= C0
.ESC
+ '[3~';
1664 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1665 else if (this.applicationCursor
)
1666 result
.key
= C0
.ESC
+ 'OH';
1668 result
.key
= C0
.ESC
+ '[H';
1673 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1674 else if (this.applicationCursor
)
1675 result
.key
= C0
.ESC
+ 'OF';
1677 result
.key
= C0
.ESC
+ '[F';
1682 result
.scrollDisp
= -(this.rows
- 1);
1684 result
.key
= C0
.ESC
+ '[5~';
1690 result
.scrollDisp
= this.rows
- 1;
1692 result
.key
= C0
.ESC
+ '[6~';
1698 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1700 result
.key
= C0
.ESC
+ 'OP';
1705 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1707 result
.key
= C0
.ESC
+ 'OQ';
1712 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1714 result
.key
= C0
.ESC
+ 'OR';
1719 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1721 result
.key
= C0
.ESC
+ 'OS';
1726 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1728 result
.key
= C0
.ESC
+ '[15~';
1733 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1735 result
.key
= C0
.ESC
+ '[17~';
1740 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1742 result
.key
= C0
.ESC
+ '[18~';
1747 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1749 result
.key
= C0
.ESC
+ '[19~';
1754 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1756 result
.key
= C0
.ESC
+ '[20~';
1761 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1763 result
.key
= C0
.ESC
+ '[21~';
1768 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1770 result
.key
= C0
.ESC
+ '[23~';
1775 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1777 result
.key
= C0
.ESC
+ '[24~';
1782 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1783 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1784 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1785 } else if (ev
.keyCode
=== 32) {
1787 result
.key
= String
.fromCharCode(0);
1788 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1789 // escape, file sep, group sep, record sep, unit sep
1790 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1791 } else if (ev
.keyCode
=== 56) {
1793 result
.key
= String
.fromCharCode(127);
1794 } else if (ev
.keyCode
=== 219) {
1795 // ^[ - Control Sequence Introducer (CSI)
1796 result
.key
= String
.fromCharCode(27);
1797 } else if (ev
.keyCode
=== 220) {
1798 // ^\ - String Terminator (ST)
1799 result
.key
= String
.fromCharCode(28);
1800 } else if (ev
.keyCode
=== 221) {
1801 // ^] - Operating System Command (OSC)
1802 result
.key
= String
.fromCharCode(29);
1804 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1805 // On Mac this is a third level shift. Use <Esc> instead.
1806 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1807 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1808 } else if (ev
.keyCode
=== 192) {
1809 result
.key
= C0
.ESC
+ '`';
1810 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1811 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1813 } else if (this.browser
.isMac
&& !ev
.altKey
&& !ev
.ctrlKey
&& ev
.metaKey
) {
1814 if (ev
.keyCode
=== 65) { // cmd + a
1825 * Set the G level of the terminal
1828 Terminal
.prototype.setgLevel = function(g
) {
1830 this.charset
= this.charsets
[g
];
1834 * Set the charset for the given G level of the terminal
1838 Terminal
.prototype.setgCharset = function(g
, charset
) {
1839 this.charsets
[g
] = charset
;
1840 if (this.glevel
=== g
) {
1841 this.charset
= charset
;
1846 * Handle a keypress event.
1848 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1849 * @param {KeyboardEvent} ev The keypress event to be handled.
1851 Terminal
.prototype.keyPress = function(ev
) {
1854 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1862 } else if (ev
.which
== null) {
1864 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1871 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1876 key
= String
.fromCharCode(key
);
1878 this.emit('keypress', key
, ev
);
1879 this.emit('key', key
, ev
);
1887 * Send data for handling to the terminal
1888 * @param {string} data
1890 Terminal
.prototype.send = function(data
) {
1894 setTimeout(function() {
1895 self
.handler(self
.queue
);
1905 * Note: We could do sweet things with webaudio here
1907 Terminal
.prototype.bell = function() {
1908 if (!this.visualBell
) return;
1910 this.element
.style
.borderColor
= 'white';
1911 setTimeout(function() {
1912 self
.element
.style
.borderColor
= '';
1914 if (this.popOnBell
) this.focus();
1918 * Log the current state to the console.
1920 Terminal
.prototype.log = function() {
1921 if (!this.debug
) return;
1922 if (!this.context
.console
|| !this.context
.console
.log
) return;
1923 var args
= Array
.prototype.slice
.call(arguments
);
1924 this.context
.console
.log
.apply(this.context
.console
, args
);
1928 * Log the current state as error to the console.
1930 Terminal
.prototype.error = function() {
1931 if (!this.debug
) return;
1932 if (!this.context
.console
|| !this.context
.console
.error
) return;
1933 var args
= Array
.prototype.slice
.call(arguments
);
1934 this.context
.console
.error
.apply(this.context
.console
, args
);
1938 * Resizes the terminal.
1940 * @param {number} x The number of columns to resize to.
1941 * @param {number} y The number of rows to resize to.
1943 Terminal
.prototype.resize = function(x
, y
) {
1944 if (isNaN(x
) || isNaN(y
)) {
1948 if (y
> this.getOption('scrollback')) {
1949 this.setOption('scrollback', y
)
1959 if (x
=== this.cols
&& y
=== this.rows
) {
1960 // Check if we still need to measure the char size (fixes #785).
1961 if (!this.charMeasure
.width
|| !this.charMeasure
.height
) {
1962 this.charMeasure
.measure();
1973 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1974 i
= this.buffer
.lines
.length
;
1976 while (this.buffer
.lines
.get(i
).length
< x
) {
1977 this.buffer
.lines
.get(i
).push(ch
);
1983 this.setupStops(this.cols
);
1991 // y is rows, not this.y
1992 if (this.buffer
.lines
.length
< y
+ this.ybase
) {
1993 if (this.ybase
> 0 && this.buffer
.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
1994 // There is room above the buffer and there are no empty elements below the line,
1998 if (this.ydisp
> 0) {
1999 // Viewport is at the top of the buffer, must increase downwards
2003 // Add a blank line if there is no buffer left at the top to scroll to, or if there
2004 // are blank lines after the cursor
2005 this.buffer
.lines
.push(this.blankLine());
2008 if (this.children
.length
< y
) {
2014 if (this.buffer
.lines
.length
> y
+ this.ybase
) {
2015 if (this.buffer
.lines
.length
> this.ybase
+ this.y
+ 1) {
2016 // The line is a blank line below the cursor, remove it
2017 this.buffer
.lines
.pop();
2019 // The line is the cursor, scroll down
2024 if (this.children
.length
> y
) {
2025 el
= this.children
.shift();
2027 el
.parentNode
.removeChild(el
);
2033 // Make sure that the cursor stays on screen
2046 this.scrollBottom
= y
- 1;
2048 this.charMeasure
.measure();
2050 this.refresh(0, this.rows
- 1);
2054 this.geometry
= [this.cols
, this.rows
];
2055 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
2059 * Updates the range of rows to refresh
2060 * @param {number} y The number of rows to refresh next.
2062 Terminal
.prototype.updateRange = function(y
) {
2063 if (y
< this.refreshStart
) this.refreshStart
= y
;
2064 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
2065 // if (y > this.refreshEnd) {
2066 // this.refreshEnd = y;
2067 // if (y > this.rows - 1) {
2068 // this.refreshEnd = this.rows - 1;
2074 * Set the range of refreshing to the maximum value
2076 Terminal
.prototype.maxRange = function() {
2077 this.refreshStart
= 0;
2078 this.refreshEnd
= this.rows
- 1;
2084 * Setup the tab stops.
2087 Terminal
.prototype.setupStops = function(i
) {
2089 if (!this.tabs
[i
]) {
2090 i
= this.prevStop(i
);
2097 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
2098 this.tabs
[i
] = true;
2104 * Move the cursor to the previous tab stop from the given position (default is current).
2105 * @param {number} x The position to move the cursor to the previous tab stop.
2107 Terminal
.prototype.prevStop = function(x
) {
2108 if (x
== null) x
= this.x
;
2109 while (!this.tabs
[--x
] && x
> 0);
2110 return x
>= this.cols
2117 * Move the cursor one tab stop forward from the given position (default is current).
2118 * @param {number} x The position to move the cursor one tab stop forward.
2120 Terminal
.prototype.nextStop = function(x
) {
2121 if (x
== null) x
= this.x
;
2122 while (!this.tabs
[++x
] && x
< this.cols
);
2123 return x
>= this.cols
2130 * Erase in the identified line everything from "x" to the end of the line (right).
2131 * @param {number} x The column from which to start erasing to the end of the line.
2132 * @param {number} y The line in which to operate.
2134 Terminal
.prototype.eraseRight = function(x
, y
) {
2135 var line
= this.buffer
.lines
.get(this.ybase
+ y
);
2139 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2140 for (; x
< this.cols
; x
++) {
2143 this.updateRange(y
);
2149 * Erase in the identified line everything from "x" to the start of the line (left).
2150 * @param {number} x The column from which to start erasing to the start of the line.
2151 * @param {number} y The line in which to operate.
2153 Terminal
.prototype.eraseLeft = function(x
, y
) {
2154 var line
= this.buffer
.lines
.get(this.ybase
+ y
);
2158 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2163 this.updateRange(y
);
2167 * Clears the entire buffer, making the prompt line the new first line.
2169 Terminal
.prototype.clear = function() {
2170 if (this.ybase
=== 0 && this.y
=== 0) {
2171 // Don't clear if it's already clear
2174 this.buffer
.lines
.set(0, this.buffer
.lines
.get(this.ybase
+ this.y
));
2175 this.buffer
.lines
.length
= 1;
2179 for (var i
= 1; i
< this.rows
; i
++) {
2180 this.buffer
.lines
.push(this.blankLine());
2182 this.refresh(0, this.rows
- 1);
2183 this.emit('scroll', this.ydisp
);
2187 * Erase all content in the given line
2188 * @param {number} y The line to erase all of its contents.
2190 Terminal
.prototype.eraseLine = function(y
) {
2191 this.eraseRight(0, y
);
2196 * Return the data array of a blank line
2197 * @param {number} cur First bunch of data for each "blank" character.
2198 * @param {boolean} isWrapped Whether the new line is wrapped from the previous line.
2200 Terminal
.prototype.blankLine = function(cur
, isWrapped
) {
2205 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2209 // TODO: It is not ideal that this is a property on an array, a buffer line
2210 // class should be added that will hold this data and other useful functions.
2212 line
.isWrapped
= isWrapped
;
2215 for (; i
< this.cols
; i
++) {
2224 * If cur return the back color xterm feature attribute. Else return defAttr.
2225 * @param {object} cur
2227 Terminal
.prototype.ch = function(cur
) {
2229 ? [this.eraseAttr(), ' ', 1]
2230 : [this.defAttr
, ' ', 1];
2235 * Evaluate if the current erminal is the given argument.
2236 * @param {object} term The terminal to evaluate
2238 Terminal
.prototype.is = function(term
) {
2239 var name
= this.termName
;
2240 return (name
+ '').indexOf(term
) === 0;
2245 * Emit the 'data' event and populate the given data.
2246 * @param {string} data The data to populate in the event.
2248 Terminal
.prototype.handler = function(data
) {
2249 // Prevents all events to pty process if stdin is disabled
2250 if (this.options
.disableStdin
) {
2254 // Clear the selection if the selection manager is available and has an active selection
2255 if (this.selectionManager
&& this.selectionManager
.hasSelection
) {
2256 this.selectionManager
.clearSelection();
2259 // Input is being sent to the terminal, the terminal should focus the prompt.
2260 if (this.ybase
!== this.ydisp
) {
2261 this.scrollToBottom();
2263 this.emit('data', data
);
2268 * Emit the 'title' event and populate the given title.
2269 * @param {string} title The title to populate in the event.
2271 Terminal
.prototype.handleTitle = function(title
) {
2273 * This event is emitted when the title of the terminal is changed
2274 * from inside the terminal. The parameter is the new title.
2278 this.emit('title', title
);
2287 * ESC D Index (IND is 0x84).
2289 Terminal
.prototype.index = function() {
2291 if (this.y
> this.scrollBottom
) {
2295 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2296 if (this.x
>= this.cols
) {
2303 * ESC M Reverse Index (RI is 0x8d).
2305 * Move the cursor up one row, inserting a new blank line if necessary.
2307 Terminal
.prototype.reverseIndex = function() {
2309 if (this.y
=== this.scrollTop
) {
2310 // possibly move the code below to term.reverseScroll();
2311 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2312 // blankLine(true) is xterm/linux behavior
2313 this.buffer
.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2314 this.buffer
.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2315 this.updateRange(this.scrollTop
);
2316 this.updateRange(this.scrollBottom
);
2324 * ESC c Full Reset (RIS).
2326 Terminal
.prototype.reset = function() {
2327 this.options
.rows
= this.rows
;
2328 this.options
.cols
= this.cols
;
2329 var customKeyEventHandler
= this.customKeyEventHandler
;
2330 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2331 Terminal
.call(this, this.options
);
2332 this.customKeyEventHandler
= customKeyEventHandler
;
2333 this.cursorBlinkInterval
= cursorBlinkInterval
;
2334 this.refresh(0, this.rows
- 1);
2335 this.viewport
.syncScrollArea();
2340 * ESC H Tab Set (HTS is 0x88).
2342 Terminal
.prototype.tabSet = function() {
2343 this.tabs
[this.x
] = true;
2350 function on(el
, type
, handler
, capture
) {
2351 if (!Array
.isArray(el
)) {
2354 el
.forEach(function (element
) {
2355 element
.addEventListener(type
, handler
, capture
|| false);
2359 function off(el
, type
, handler
, capture
) {
2360 el
.removeEventListener(type
, handler
, capture
|| false);
2363 function cancel(ev
, force
) {
2364 if (!this.cancelEvents
&& !force
) {
2367 ev
.preventDefault();
2368 ev
.stopPropagation();
2372 function inherits(child
, parent
) {
2374 this.constructor = child
;
2376 f
.prototype = parent
.prototype;
2377 child
.prototype = new f
;
2380 function indexOf(obj
, el
) {
2383 if (obj
[i
] === el
) return i
;
2388 function isThirdLevelShift(term
, ev
) {
2390 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2391 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2393 if (ev
.type
== 'keypress') {
2394 return thirdLevelKey
;
2397 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2398 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2401 // Expose to InputHandler (temporary)
2402 Terminal
.prototype.matchColor
= matchColor
;
2404 function matchColor(r1
, g1
, b1
) {
2405 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2407 if (matchColor
._cache
[hash
] != null) {
2408 return matchColor
._cache
[hash
];
2411 var ldiff
= Infinity
2420 for (; i
< Terminal
.vcolors
.length
; i
++) {
2421 c
= Terminal
.vcolors
[i
];
2426 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2439 return matchColor
._cache
[hash
] = li
;
2442 matchColor
._cache
= {};
2444 // http://stackoverflow.com/questions/1633828
2445 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2446 return Math
.pow(30 * (r1
- r2
), 2)
2447 + Math
.pow(59 * (g1
- g2
), 2)
2448 + Math
.pow(11 * (b1
- b2
), 2);
2451 function each(obj
, iter
, con
) {
2452 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2453 for (var i
= 0; i
< obj
.length
; i
++) {
2454 iter
.call(con
, obj
[i
], i
, obj
);
2458 function wasMondifierKeyOnlyEvent(ev
) {
2459 return ev
.keyCode
=== 16 || // Shift
2460 ev
.keyCode
=== 17 || // Ctrl
2461 ev
.keyCode
=== 18; // Alt
2464 function keys(obj
) {
2465 if (Object
.keys
) return Object
.keys(obj
);
2468 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2479 Terminal
.translateBufferLineToString
= translateBufferLineToString
;
2480 Terminal
.EventEmitter
= EventEmitter
;
2481 Terminal
.inherits
= inherits
;
2484 * Adds an event listener to the terminal.
2486 * @param {string} event The name of the event. TODO: Document all event types
2487 * @param {function} callback The function to call when the event is triggered.
2491 Terminal
.cancel
= cancel
;
2493 module
.exports
= Terminal
;