2 * xterm.js: xterm, in the browser
3 * Originally forked from (with the author's permission):
4 * Fabrice Bellard's javascript vt100 for jslinux:
5 * http://bellard.org/jslinux/
6 * Copyright (c) 2011 Fabrice Bellard
7 * The original design remains. The terminal itself
8 * has been extended to include xterm CSI codes, among
13 import { CompositionHelper
} from './CompositionHelper';
14 import { EventEmitter
} from './EventEmitter';
15 import { Viewport
} from './Viewport';
16 import { rightClickHandler
, pasteHandler
, copyHandler
} from './handlers/Clipboard';
17 import { CircularList
} from './utils/CircularList';
18 import { C0
} from './EscapeSequences';
19 import { InputHandler
} from './InputHandler';
20 import { Parser
} from './Parser';
21 import { Renderer
} from './Renderer';
22 import { Linkifier
} from './Linkifier';
23 import { SelectionManager
} from './SelectionManager';
24 import { CharMeasure
} from './utils/CharMeasure';
25 import * as Browser
from './utils/Browser';
26 import * as Mouse
from './utils/Mouse';
27 import { CHARSETS
} from './Charsets';
28 import { getRawByteCoords
} from './utils/Mouse';
29 import { translateBufferLineToString
} from './utils/BufferLine';
32 * Terminal Emulation References:
34 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
35 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
36 * http://invisible-island.net/vttest/
37 * http://www.inwap.com/pdp10/ansicode.txt
38 * http://linux.die.net/man/4/console_codes
39 * http://linux.die.net/man/7/urxvt
42 // Let it work inside Node.js for automated testing purposes.
43 var document
= (typeof window
!= 'undefined') ? window
.document
: null;
46 * The amount of write requests to queue before sending an XOFF signal to the
47 * pty process. This number must be small in order for ^C and similar sequences
50 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
53 * The number of writes to perform in a single batch before allowing the
54 * renderer to catch up with a 0ms setTimeout.
56 var WRITE_BATCH_SIZE
= 300;
59 * The time between cursor blinks. This is driven by JS rather than a CSS
60 * animation due to a bug in Chromium that causes it to use excessive CPU time.
61 * See https://github.com/Microsoft/vscode/issues/22900
63 var CURSOR_BLINK_INTERVAL
= 600;
70 * Creates a new `Terminal` object.
72 * @param {object} options An object containing a set of options, the available options are:
73 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
74 * - `cols` (number): The number of columns of the terminal (horizontal size)
75 * - `rows` (number): The number of rows of the terminal (vertical size)
79 * @alias module:xterm/src/xterm
81 function Terminal(options
) {
84 if (!(this instanceof Terminal
)) {
85 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
88 self
.browser
= Browser
;
89 self
.cancel
= Terminal
.cancel
;
91 EventEmitter
.call(this);
93 if (typeof options
=== 'number') {
101 options
= options
|| {};
104 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
105 if (options
[key
] == null) {
106 options
[key
] = Terminal
.options
[key
];
108 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
109 options
[key
] = Terminal
[key
];
112 self
[key
] = options
[key
];
115 if (options
.colors
.length
=== 8) {
116 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
117 } else if (options
.colors
.length
=== 16) {
118 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
119 } else if (options
.colors
.length
=== 10) {
120 options
.colors
= options
.colors
.slice(0, -2).concat(
121 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
122 } else if (options
.colors
.length
=== 18) {
123 options
.colors
= options
.colors
.concat(
124 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
126 this.colors
= options
.colors
;
128 this.options
= options
;
130 // this.context = options.context || window;
131 // this.document = options.document || document;
132 this.parent
= options
.body
|| options
.parent
|| (
133 document
? document
.getElementsByTagName('body')[0] : null
136 this.cols
= options
.cols
|| options
.geometry
[0];
137 this.rows
= options
.rows
|| options
.geometry
[1];
138 this.geometry
= [this.cols
, this.rows
];
140 if (options
.handler
) {
141 this.on('data', options
.handler
);
145 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
151 * The scroll position of the viewport
156 * The cursor's x position after ybase
161 * The cursor's y position after ybase
165 this.cursorState
= 0;
166 this.cursorHidden
= false;
170 this.scrollBottom
= this.rows
- 1;
171 this.customKeydownHandler
= null;
172 this.cursorBlinkInterval
= null;
175 this.applicationKeypad
= false;
176 this.applicationCursor
= false;
177 this.originMode
= false;
178 this.insertMode
= false;
179 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
184 this.gcharset
= null;
186 this.charsets
= [null];
210 this.readable
= true;
211 this.writable
= true;
213 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
214 this.curAttr
= this.defAttr
;
217 this.currentParam
= 0;
221 this.inputHandler
= new InputHandler(this);
222 this.parser
= new Parser(this.inputHandler
, this);
223 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
224 this.renderer
= this.renderer
|| null;
225 this.selectionManager
= this.selectionManager
|| null;
226 this.linkifier
= this.linkifier
|| new Linkifier();
229 this.writeBuffer
= [];
230 this.writeInProgress
= false;
233 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
234 * This is a distinct state from writeStopped so that if the user requested
235 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
238 this.xoffSentToCatchUp
= false;
240 /** Whether writing has been stopped as a result of XOFF */
241 this.writeStopped
= false;
243 // leftover surrogate high from previous write invocation
244 this.surrogate_high
= '';
247 * An array of all lines in the entire buffer, including the prompt. The lines are array of
248 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
250 this.lines
= new CircularList(this.scrollback
);
253 this.lines
.push(this.blankLine());
255 // Ensure the selection manager has the correct buffer
256 if (this.selectionManager
) {
257 this.selectionManager
.setBuffer(this.lines
);
263 // Store if user went browsing history in scrollback
264 this.userScrolling
= false;
267 inherits(Terminal
, EventEmitter
);
270 * back_color_erase feature for xterm.
272 Terminal
.prototype.eraseAttr = function() {
273 // if (this.is('screen')) return this.defAttr;
274 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
282 Terminal
.tangoColors
= [
303 // Colors 0-15 + 16-255
304 // Much thanks to TooTallNate for writing this.
305 Terminal
.colors
= (function() {
306 var colors
= Terminal
.tangoColors
.slice()
307 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
312 for (; i
< 216; i
++) {
313 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
318 for (; i
< 24; i
++) {
323 function out(r
, g
, b
) {
324 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
329 return c
.length
< 2 ? '0' + c
: c
;
335 Terminal
._colors
= Terminal
.colors
.slice();
337 Terminal
.vcolors
= (function() {
339 , colors
= Terminal
.colors
343 for (; i
< 256; i
++) {
344 color
= parseInt(colors
[i
].substring(1), 16);
346 (color
>> 16) & 0xff,
359 Terminal
.defaults
= {
360 colors
: Terminal
.colors
,
366 cursorStyle
: 'block',
374 useFlowControl
: false,
376 // programFeatures: false,
380 Terminal
.options
= {};
382 Terminal
.focus
= null;
384 each(keys(Terminal
.defaults
), function(key
) {
385 Terminal
[key
] = Terminal
.defaults
[key
];
386 Terminal
.options
[key
] = Terminal
.defaults
[key
];
390 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
392 Terminal
.prototype.focus = function() {
393 return this.textarea
.focus();
397 * Retrieves an option's value from the terminal.
398 * @param {string} key The option key.
400 Terminal
.prototype.getOption = function(key
, value
) {
401 if (!(key
in Terminal
.defaults
)) {
402 throw new Error('No option with key "' + key
+ '"');
405 if (typeof this.options
[key
] !== 'undefined') {
406 return this.options
[key
];
413 * Sets an option on the terminal.
414 * @param {string} key The option key.
415 * @param {string} value The option value.
417 Terminal
.prototype.setOption = function(key
, value
) {
418 if (!(key
in Terminal
.defaults
)) {
419 throw new Error('No option with key "' + key
+ '"');
423 if (this.options
[key
] !== value
) {
424 if (this.lines
.length
> value
) {
425 const amountToTrim
= this.lines
.length
- value
;
426 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
427 this.lines
.trimStart(amountToTrim
);
428 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
429 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
431 this.refresh(0, this.rows
- 1);
434 this.lines
.maxLength
= value
;
435 this.viewport
.syncScrollArea();
440 this.options
[key
] = value
;
442 case 'cursorBlink': this.setCursorBlinking(value
); break;
444 // Style 'block' applies with no class
445 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
446 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
448 case 'tabStopWidth': this.setupStops(); break;
452 Terminal
.prototype.restartCursorBlinking = function () {
453 this.setCursorBlinking(this.options
.cursorBlink
);
456 Terminal
.prototype.setCursorBlinking = function (enabled
) {
457 this.element
.classList
.toggle('xterm-cursor-blink', enabled
);
458 this.clearCursorBlinkingInterval();
461 this.cursorBlinkInterval
= setInterval(function () {
462 self
.element
.classList
.toggle('xterm-cursor-blink-on');
463 }, CURSOR_BLINK_INTERVAL
);
467 Terminal
.prototype.clearCursorBlinkingInterval = function () {
468 this.element
.classList
.remove('xterm-cursor-blink-on');
469 if (this.cursorBlinkInterval
) {
470 clearInterval(this.cursorBlinkInterval
);
471 this.cursorBlinkInterval
= null;
476 * Binds the desired focus behavior on a given terminal object.
480 Terminal
.bindFocus = function (term
) {
481 on(term
.textarea
, 'focus', function (ev
) {
482 if (term
.sendFocus
) {
483 term
.send(C0
.ESC
+ '[I');
485 term
.element
.classList
.add('focus');
487 term
.restartCursorBlinking
.apply(term
);
488 Terminal
.focus
= term
;
489 term
.emit('focus', {terminal
: term
});
494 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
496 Terminal
.prototype.blur = function() {
497 return this.textarea
.blur();
501 * Binds the desired blur behavior on a given terminal object.
505 Terminal
.bindBlur = function (term
) {
506 on(term
.textarea
, 'blur', function (ev
) {
507 term
.refresh(term
.y
, term
.y
);
508 if (term
.sendFocus
) {
509 term
.send(C0
.ESC
+ '[O');
511 term
.element
.classList
.remove('focus');
512 term
.clearCursorBlinkingInterval
.apply(term
);
513 Terminal
.focus
= null;
514 term
.emit('blur', {terminal
: term
});
519 * Initialize default behavior
521 Terminal
.prototype.initGlobal = function() {
524 Terminal
.bindKeys(this);
525 Terminal
.bindFocus(this);
526 Terminal
.bindBlur(this);
528 // Bind clipboard functionality
529 on(this.element
, 'copy', event
=> {
530 // If mouse events are active it means the selection manager is disabled and
531 // copy should be handled by the host program.
532 if (this.mouseEvents
) {
535 copyHandler(event
, term
, this.selectionManager
);
537 const pasteHandlerWrapper
= event
=> pasteHandler(event
, term
);
538 on(this.textarea
, 'paste', pasteHandlerWrapper
);
539 on(this.element
, 'paste', pasteHandlerWrapper
);
541 if (term
.browser
.isFirefox
) {
542 on(this.element
, 'mousedown', event
=> {
543 if (ev
.button
== 2) {
544 rightClickHandler(event
, this.textarea
, this.selectionManager
);
548 on(this.element
, 'contextmenu', event
=> {
549 rightClickHandler(event
, this.textarea
, this.selectionManager
);
555 * Apply key handling to the terminal
557 Terminal
.bindKeys = function(term
) {
558 on(term
.element
, 'keydown', function(ev
) {
559 if (document
.activeElement
!= this) {
565 on(term
.element
, 'keypress', function(ev
) {
566 if (document
.activeElement
!= this) {
572 on(term
.element
, 'keyup', function(ev
) {
573 if (!wasMondifierKeyOnlyEvent(ev
)) {
578 on(term
.textarea
, 'keydown', function(ev
) {
582 on(term
.textarea
, 'keypress', function(ev
) {
584 // Truncate the textarea's value, since it is not needed
588 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
589 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
590 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
591 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
592 term
.on('refresh', function (data
) {
593 term
.queueLinkification(data
.start
, data
.end
)
599 * Insert the given row to the terminal or produce a new one
600 * if no row argument is passed. Return the inserted row.
601 * @param {HTMLElement} row (optional) The row to append to the terminal.
603 Terminal
.prototype.insertRow = function (row
) {
604 if (typeof row
!= 'object') {
605 row
= document
.createElement('div');
608 this.rowContainer
.appendChild(row
);
609 this.children
.push(row
);
615 * Opens the terminal within an element.
617 * @param {HTMLElement} parent The element to create the terminal within.
618 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
620 Terminal
.prototype.open = function(parent
, focus
) {
621 var self
=this, i
=0, div
;
623 this.parent
= parent
|| this.parent
;
626 throw new Error('Terminal requires a parent element.');
629 // Grab global elements
630 this.context
= this.parent
.ownerDocument
.defaultView
;
631 this.document
= this.parent
.ownerDocument
;
632 this.body
= this.document
.getElementsByTagName('body')[0];
634 //Create main element container
635 this.element
= this.document
.createElement('div');
636 this.element
.classList
.add('terminal');
637 this.element
.classList
.add('xterm');
638 this.element
.classList
.add('xterm-theme-' + this.theme
);
639 this.setCursorBlinking(this.options
.cursorBlink
);
641 this.element
.style
.height
;
642 this.element
.setAttribute('tabindex', 0);
644 this.viewportElement
= document
.createElement('div');
645 this.viewportElement
.classList
.add('xterm-viewport');
646 this.element
.appendChild(this.viewportElement
);
647 this.viewportScrollArea
= document
.createElement('div');
648 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
649 this.viewportElement
.appendChild(this.viewportScrollArea
);
651 // Create the selection container. This needs to be added before the
652 // rowContainer as the selection must be below the text.
653 this.selectionContainer
= document
.createElement('div');
654 this.selectionContainer
.classList
.add('xterm-selection');
655 this.element
.appendChild(this.selectionContainer
);
657 // Create the container that will hold the lines of the terminal and then
658 // produce the lines the lines.
659 this.rowContainer
= document
.createElement('div');
660 this.rowContainer
.classList
.add('xterm-rows');
661 this.element
.appendChild(this.rowContainer
);
663 this.linkifier
.attachToDom(document
, this.children
);
665 // Create the container that will hold helpers like the textarea for
666 // capturing DOM Events. Then produce the helpers.
667 this.helperContainer
= document
.createElement('div');
668 this.helperContainer
.classList
.add('xterm-helpers');
669 // TODO: This should probably be inserted once it's filled to prevent an additional layout
670 this.element
.appendChild(this.helperContainer
);
671 this.textarea
= document
.createElement('textarea');
672 this.textarea
.classList
.add('xterm-helper-textarea');
673 this.textarea
.setAttribute('autocorrect', 'off');
674 this.textarea
.setAttribute('autocapitalize', 'off');
675 this.textarea
.setAttribute('spellcheck', 'false');
676 this.textarea
.tabIndex
= 0;
677 this.textarea
.addEventListener('focus', function() {
678 self
.emit('focus', {terminal
: self
});
680 this.textarea
.addEventListener('blur', function() {
681 self
.emit('blur', {terminal
: self
});
683 this.helperContainer
.appendChild(this.textarea
);
685 this.compositionView
= document
.createElement('div');
686 this.compositionView
.classList
.add('composition-view');
687 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
688 this.helperContainer
.appendChild(this.compositionView
);
690 this.charSizeStyleElement
= document
.createElement('style');
691 this.helperContainer
.appendChild(this.charSizeStyleElement
);
693 for (; i
< this.rows
; i
++) {
696 this.parent
.appendChild(this.element
);
698 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
699 this.charMeasure
.on('charsizechanged', function () {
700 self
.updateCharSizeStyles();
702 this.charMeasure
.measure();
704 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
705 this.renderer
= new Renderer(this);
706 this.selectionManager
= new SelectionManager(this, this.lines
, this.rowContainer
, this.charMeasure
);
707 this.selectionManager
.on('refresh', data
=> this.renderer
.refreshSelection(data
.start
, data
.end
));
708 this.on('scroll', () => this.selectionManager
.refresh());
709 this.viewportElement
.addEventListener('scroll', () => this.selectionManager
.refresh());
711 // Setup loop that draws to screen
712 this.refresh(0, this.rows
- 1);
714 // Initialize global actions that
715 // need to be taken on the document.
719 * Automatic focus functionality.
720 * TODO: Default to `false` starting with xterm.js 3.0.
722 if (typeof focus
== 'undefined') {
723 let message
= 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
725 message
+= 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
726 message
+= 'it will default to `false`.';
728 console
.warn(message
);
736 on(this.element
, 'click', function() {
737 var selection
= document
.getSelection(),
738 collapsed
= selection
.isCollapsed
,
739 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
745 // Listen for mouse events and translate
746 // them into terminal mouse protocols.
750 * This event is emitted when terminal has completed opening.
759 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
760 * @param {string} addon The name of the addon to load
763 Terminal
.loadAddon = function(addon
, callback
) {
764 if (typeof exports
=== 'object' && typeof module
=== 'object') {
766 return require('./addons/' + addon
+ '/' + addon
);
767 } else if (typeof define
== 'function') {
769 return require(['./addons/' + addon
+ '/' + addon
], callback
);
771 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
777 * Updates the helper CSS class with any changes necessary after the terminal's
778 * character width has been changed.
780 Terminal
.prototype.updateCharSizeStyles = function() {
781 this.charSizeStyleElement
.textContent
=
782 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
783 `.xterm-normal-char{width:${this.charMeasure.width}px;}` +
784 `.xterm-rows > div{height:${this.charMeasure.height}px;}`;
789 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
790 * To better understand these
791 * the xterm code is very helpful:
793 * button.c, charproc.c, misc.c
794 * Relevant functions in xterm/button.c:
795 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
797 Terminal
.prototype.bindMouse = function() {
798 var el
= this.element
, self
= this, pressed
= 32;
800 // mouseup, mousedown, wheel
801 // left click: ^[[M 3<^[[M#3<
803 function sendButton(ev
) {
807 // get the xterm-style button
808 button
= getButton(ev
);
810 // get mouse coordinates
811 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
814 sendEvent(button
, pos
);
816 switch (ev
.overrideType
|| ev
.type
) {
821 // keep it at the left
822 // button, just in case.
833 // motion example of a left click:
834 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
835 function sendMove(ev
) {
839 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
842 // buttons marked as motions
843 // are incremented by 32
846 sendEvent(button
, pos
);
850 // position to characters
851 function encode(data
, ch
) {
852 if (!self
.utfMouse
) {
853 if (ch
=== 255) return data
.push(0);
854 if (ch
> 127) ch
= 127;
857 if (ch
=== 2047) return data
.push(0);
861 if (ch
> 2047) ch
= 2047;
862 data
.push(0xC0 | (ch
>> 6));
863 data
.push(0x80 | (ch
& 0x3F));
868 // send a mouse event:
869 // regular/utf8: ^[[M Cb Cx Cy
870 // urxvt: ^[[ Cb ; Cx ; Cy M
871 // sgr: ^[[ Cb ; Cx ; Cy M/m
872 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
873 // locator: CSI P e ; P b ; P r ; P c ; P p & w
874 function sendEvent(button
, pos
) {
875 // self.emit('mouse', {
881 if (self
.vt300Mouse
) {
883 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
887 var data
= C0
.ESC
+ '[24';
888 if (button
=== 0) data
+= '1';
889 else if (button
=== 1) data
+= '3';
890 else if (button
=== 2) data
+= '5';
891 else if (button
=== 3) return;
893 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
898 if (self
.decLocator
) {
903 if (button
=== 0) button
= 2;
904 else if (button
=== 1) button
= 4;
905 else if (button
=== 2) button
= 6;
906 else if (button
=== 3) button
= 3;
907 self
.send(C0
.ESC
+ '['
910 + (button
=== 3 ? 4 : 0)
921 if (self
.urxvtMouse
) {
926 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
933 self
.send(C0
.ESC
+ '[<'
934 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
939 + ((button
& 3) === 3 ? 'm' : 'M'));
945 encode(data
, button
);
949 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
952 function getButton(ev
) {
965 // 1, and 2 - with 64 added
966 switch (ev
.overrideType
|| ev
.type
) {
968 button
= ev
.button
!= null
974 if (self
.browser
.isMSIE
) {
975 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
981 case 'DOMMouseScroll':
982 button
= ev
.detail
< 0
987 button
= ev
.wheelDeltaY
> 0
993 // next three bits are the modifiers:
994 // 4 = shift, 8 = meta, 16 = control
995 shift
= ev
.shiftKey
? 4 : 0;
996 meta
= ev
.metaKey
? 8 : 0;
997 ctrl
= ev
.ctrlKey
? 16 : 0;
998 mod
= shift
| meta
| ctrl
;
1001 if (self
.vt200Mouse
) {
1004 } else if (!self
.normalMouse
) {
1009 button
= (32 + (mod
<< 2)) + button
;
1014 on(el
, 'mousedown', function(ev
) {
1015 if (!self
.mouseEvents
) return;
1024 //if (self.vt200Mouse && !self.normalMouse) {
1025 if (self
.vt200Mouse
) {
1026 ev
.overrideType
= 'mouseup';
1028 return self
.cancel(ev
);
1032 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1034 // x10 compatibility mode can't send button releases
1035 if (!self
.x10Mouse
) {
1036 on(self
.document
, 'mouseup', function up(ev
) {
1038 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1039 off(self
.document
, 'mouseup', up
);
1040 return self
.cancel(ev
);
1044 return self
.cancel(ev
);
1047 //if (self.normalMouse) {
1048 // on(self.document, 'mousemove', sendMove);
1051 on(el
, 'wheel', function(ev
) {
1052 if (!self
.mouseEvents
) return;
1055 || self
.decLocator
) return;
1057 return self
.cancel(ev
);
1060 // allow wheel scrolling in
1061 // the shell for example
1062 on(el
, 'wheel', function(ev
) {
1063 if (self
.mouseEvents
) return;
1064 self
.viewport
.onWheel(ev
);
1065 return self
.cancel(ev
);
1070 * Destroys the terminal.
1072 Terminal
.prototype.destroy = function() {
1073 this.readable
= false;
1074 this.writable
= false;
1076 this.handler = function() {};
1077 this.write = function() {};
1078 if (this.element
&& this.element
.parentNode
) {
1079 this.element
.parentNode
.removeChild(this.element
);
1081 //this.emit('close');
1085 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1087 * @param {number} start The row to start from (between 0 and this.rows - 1).
1088 * @param {number} end The row to end at (between start and this.rows - 1).
1090 Terminal
.prototype.refresh = function(start
, end
) {
1091 if (this.renderer
) {
1092 this.renderer
.queueRefresh(start
, end
);
1097 * Queues linkification for the specified rows.
1098 * @param {number} start The row to start from (between 0 and this.rows - 1).
1099 * @param {number} end The row to end at (between start and this.rows - 1).
1101 Terminal
.prototype.queueLinkification = function(start
, end
) {
1102 if (this.linkifier
) {
1103 for (let i
= start
; i
<= end
; i
++) {
1104 this.linkifier
.linkifyRow(i
);
1110 * Display the cursor element
1112 Terminal
.prototype.showCursor = function() {
1113 if (!this.cursorState
) {
1114 this.cursorState
= 1;
1115 this.refresh(this.y
, this.y
);
1120 * Scroll the terminal down 1 row, creating a blank line.
1121 * @param {boolean} isWrapped Whether the new line is wrapped from the previous
1124 Terminal
.prototype.scroll = function(isWrapped
) {
1127 // Make room for the new row in lines
1128 if (this.lines
.length
=== this.lines
.maxLength
) {
1129 this.lines
.trimStart(1);
1131 if (this.ydisp
!== 0) {
1138 // TODO: Why is this done twice?
1139 if (!this.userScrolling
) {
1140 this.ydisp
= this.ybase
;
1144 row
= this.ybase
+ this.rows
- 1;
1146 // subtract the bottom scroll region
1147 row
-= this.rows
- 1 - this.scrollBottom
;
1149 if (row
=== this.lines
.length
) {
1150 // Optimization: pushing is faster than splicing when they amount to the same behavior
1151 this.lines
.push(this.blankLine(undefined, isWrapped
));
1154 this.lines
.splice(row
, 0, this.blankLine(undefined, isWrapped
));
1157 if (this.scrollTop
!== 0) {
1158 if (this.ybase
!== 0) {
1160 if (!this.userScrolling
) {
1161 this.ydisp
= this.ybase
;
1164 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1168 this.updateRange(this.scrollTop
);
1169 this.updateRange(this.scrollBottom
);
1172 * This event is emitted whenever the terminal is scrolled.
1173 * The one parameter passed is the new y display position.
1177 this.emit('scroll', this.ydisp
);
1181 * Scroll the display of the terminal
1182 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1183 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1184 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1185 * viewport originally.
1187 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1189 if (this.ydisp
=== 0) {
1192 this.userScrolling
= true;
1193 } else if (disp
+ this.ydisp
>= this.ybase
) {
1194 this.userScrolling
= false;
1199 if (this.ydisp
> this.ybase
) {
1200 this.ydisp
= this.ybase
;
1201 } else if (this.ydisp
< 0) {
1205 if (!suppressScrollEvent
) {
1206 this.emit('scroll', this.ydisp
);
1209 this.refresh(0, this.rows
- 1);
1213 * Scroll the display of the terminal by a number of pages.
1214 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1216 Terminal
.prototype.scrollPages = function(pageCount
) {
1217 this.scrollDisp(pageCount
* (this.rows
- 1));
1221 * Scrolls the display of the terminal to the top.
1223 Terminal
.prototype.scrollToTop = function() {
1224 this.scrollDisp(-this.ydisp
);
1228 * Scrolls the display of the terminal to the bottom.
1230 Terminal
.prototype.scrollToBottom = function() {
1231 this.scrollDisp(this.ybase
- this.ydisp
);
1235 * Writes text to the terminal.
1236 * @param {string} text The text to write to the terminal.
1238 Terminal
.prototype.write = function(data
) {
1239 this.writeBuffer
.push(data
);
1241 // Send XOFF to pause the pty process if the write buffer becomes too large so
1242 // xterm.js can catch up before more data is sent. This is necessary in order
1243 // to keep signals such as ^C responsive.
1244 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1245 // XOFF - stop pty pipe
1246 // XON will be triggered by emulator before processing data chunk
1248 this.xoffSentToCatchUp
= true;
1251 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1252 // Kick off a write which will write all data in sequence recursively
1253 this.writeInProgress
= true;
1254 // Kick off an async innerWrite so more writes can come in while processing data
1256 setTimeout(function () {
1262 Terminal
.prototype.innerWrite = function() {
1263 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1264 while (writeBatch
.length
> 0) {
1265 var data
= writeBatch
.shift();
1266 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1268 // If XOFF was sent in order to catch up with the pty process, resume it if
1269 // the writeBuffer is empty to allow more data to come in.
1270 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1272 this.xoffSentToCatchUp
= false;
1275 this.refreshStart
= this.y
;
1276 this.refreshEnd
= this.y
;
1278 // HACK: Set the parser state based on it's state at the time of return.
1279 // This works around the bug #662 which saw the parser state reset in the
1280 // middle of parsing escape sequence in two chunks. For some reason the
1281 // state of the parser resets to 0 after exiting parser.parse. This change
1282 // just sets the state back based on the correct return statement.
1283 var state
= this.parser
.parse(data
);
1284 this.parser
.setState(state
);
1286 this.updateRange(this.y
);
1287 this.refresh(this.refreshStart
, this.refreshEnd
);
1289 if (this.writeBuffer
.length
> 0) {
1290 // Allow renderer to catch up before processing the next batch
1292 setTimeout(function () {
1296 this.writeInProgress
= false;
1301 * Writes text to the terminal, followed by a break line character (\n).
1302 * @param {string} text The text to write to the terminal.
1304 Terminal
.prototype.writeln = function(data
) {
1305 this.write(data
+ '\r\n');
1309 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1310 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1312 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1313 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1314 * the default action. The function returns whether the event should be processed by xterm.js.
1316 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1317 this.customKeydownHandler
= customKeydownHandler
;
1321 * Attaches a http(s) link handler, forcing web links to behave differently to
1322 * regular <a> tags. This will trigger a refresh as links potentially need to be
1323 * reconstructed. Calling this with null will remove the handler.
1324 * @param {LinkHandler} handler The handler callback function.
1326 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1327 if (!this.linkifier
) {
1328 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1330 this.linkifier
.setHypertextLinkHandler(handler
);
1331 // Refresh to force links to refresh
1332 this.refresh(0, this.rows
- 1);
1336 * Attaches a validation callback for hypertext links. This is useful to use
1337 * validation logic or to do something with the link's element and url.
1338 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1339 * be cleared with null.
1341 Terminal
.prototype.setHypertextValidationCallback = function(handler
) {
1342 if (!this.linkifier
) {
1343 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1345 this.linkifier
.setHypertextValidationCallback(handler
);
1346 // Refresh to force links to refresh
1347 this.refresh(0, this.rows
- 1);
1351 * Registers a link matcher, allowing custom link patterns to be matched and
1353 * @param {RegExp} regex The regular expression to search for, specifically
1354 * this searches the textContent of the rows. You will want to use \s to match
1355 * a space ' ' character for example.
1356 * @param {LinkHandler} handler The callback when the link is called.
1357 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1358 * @return {number} The ID of the new matcher, this can be used to deregister.
1360 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1361 if (this.linkifier
) {
1362 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1363 this.refresh(0, this.rows
- 1);
1369 * Deregisters a link matcher if it has been registered.
1370 * @param {number} matcherId The link matcher's ID (returned after register)
1372 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1373 if (this.linkifier
) {
1374 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1375 this.refresh(0, this.rows
- 1);
1381 * Gets whether the terminal has an active selection.
1383 Terminal
.prototype.hasSelection = function() {
1384 return this.selectionManager
.hasSelection
;
1388 * Gets the terminal's current selection, this is useful for implementing copy
1389 * behavior outside of xterm.js.
1391 Terminal
.prototype.getSelection = function() {
1392 return this.selectionManager
.selectionText
;
1396 * Clears the current terminal selection.
1398 Terminal
.prototype.clearSelection = function() {
1399 this.selectionManager
.clearSelection();
1403 * Selects all text within the terminal.
1405 Terminal
.prototype.selectAll = function() {
1406 this.selectionManager
.selectAll();
1410 * Handle a keydown event
1412 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1413 * @param {KeyboardEvent} ev The keydown event to be handled.
1415 Terminal
.prototype.keyDown = function(ev
) {
1416 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1420 this.restartCursorBlinking();
1422 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1423 if (this.ybase
!== this.ydisp
) {
1424 this.scrollToBottom();
1430 var result
= this.evaluateKeyEscapeSequence(ev
);
1432 if (result
.key
=== C0
.DC3
) { // XOFF
1433 this.writeStopped
= true;
1434 } else if (result
.key
=== C0
.DC1
) { // XON
1435 this.writeStopped
= false;
1438 if (result
.scrollDisp
) {
1439 this.scrollDisp(result
.scrollDisp
);
1440 return this.cancel(ev
, true);
1443 if (isThirdLevelShift(this, ev
)) {
1447 if (result
.cancel
) {
1448 // The event is canceled at the end already, is this necessary?
1449 this.cancel(ev
, true);
1456 this.emit('keydown', ev
);
1457 this.emit('key', result
.key
, ev
);
1459 this.handler(result
.key
);
1461 return this.cancel(ev
, true);
1465 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1466 * returned value is the new key code to pass to the PTY.
1468 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1469 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1471 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1473 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1474 // canceled at the end of keyDown
1476 // The new key even to emit
1478 // The number of characters to scroll, if this is defined it will cancel the event
1479 scrollDisp
: undefined
1481 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1482 switch (ev
.keyCode
) {
1486 result
.key
= C0
.BS
; // ^H
1489 result
.key
= C0
.DEL
; // ^?
1494 result
.key
= C0
.ESC
+ '[Z';
1498 result
.cancel
= true;
1503 result
.cancel
= true;
1507 result
.key
= C0
.ESC
;
1508 result
.cancel
= true;
1513 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1514 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1515 // http://unix.stackexchange.com/a/108106
1516 // macOS uses different escape sequences than linux
1517 if (result
.key
== C0
.ESC
+ '[1;3D') {
1518 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1520 } else if (this.applicationCursor
) {
1521 result
.key
= C0
.ESC
+ 'OD';
1523 result
.key
= C0
.ESC
+ '[D';
1529 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1530 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1531 // http://unix.stackexchange.com/a/108106
1532 // macOS uses different escape sequences than linux
1533 if (result
.key
== C0
.ESC
+ '[1;3C') {
1534 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1536 } else if (this.applicationCursor
) {
1537 result
.key
= C0
.ESC
+ 'OC';
1539 result
.key
= C0
.ESC
+ '[C';
1545 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1546 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1547 // http://unix.stackexchange.com/a/108106
1548 if (result
.key
== C0
.ESC
+ '[1;3A') {
1549 result
.key
= C0
.ESC
+ '[1;5A';
1551 } else if (this.applicationCursor
) {
1552 result
.key
= C0
.ESC
+ 'OA';
1554 result
.key
= C0
.ESC
+ '[A';
1560 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1561 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1562 // http://unix.stackexchange.com/a/108106
1563 if (result
.key
== C0
.ESC
+ '[1;3B') {
1564 result
.key
= C0
.ESC
+ '[1;5B';
1566 } else if (this.applicationCursor
) {
1567 result
.key
= C0
.ESC
+ 'OB';
1569 result
.key
= C0
.ESC
+ '[B';
1574 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1575 // <Ctrl> or <Shift> + <Insert> are used to
1576 // copy-paste on some systems.
1577 result
.key
= C0
.ESC
+ '[2~';
1583 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1585 result
.key
= C0
.ESC
+ '[3~';
1591 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1592 else if (this.applicationCursor
)
1593 result
.key
= C0
.ESC
+ 'OH';
1595 result
.key
= C0
.ESC
+ '[H';
1600 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1601 else if (this.applicationCursor
)
1602 result
.key
= C0
.ESC
+ 'OF';
1604 result
.key
= C0
.ESC
+ '[F';
1609 result
.scrollDisp
= -(this.rows
- 1);
1611 result
.key
= C0
.ESC
+ '[5~';
1617 result
.scrollDisp
= this.rows
- 1;
1619 result
.key
= C0
.ESC
+ '[6~';
1625 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1627 result
.key
= C0
.ESC
+ 'OP';
1632 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1634 result
.key
= C0
.ESC
+ 'OQ';
1639 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1641 result
.key
= C0
.ESC
+ 'OR';
1646 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1648 result
.key
= C0
.ESC
+ 'OS';
1653 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1655 result
.key
= C0
.ESC
+ '[15~';
1660 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1662 result
.key
= C0
.ESC
+ '[17~';
1667 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1669 result
.key
= C0
.ESC
+ '[18~';
1674 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1676 result
.key
= C0
.ESC
+ '[19~';
1681 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1683 result
.key
= C0
.ESC
+ '[20~';
1688 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1690 result
.key
= C0
.ESC
+ '[21~';
1695 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1697 result
.key
= C0
.ESC
+ '[23~';
1702 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1704 result
.key
= C0
.ESC
+ '[24~';
1709 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1710 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1711 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1712 } else if (ev
.keyCode
=== 32) {
1714 result
.key
= String
.fromCharCode(0);
1715 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1716 // escape, file sep, group sep, record sep, unit sep
1717 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1718 } else if (ev
.keyCode
=== 56) {
1720 result
.key
= String
.fromCharCode(127);
1721 } else if (ev
.keyCode
=== 219) {
1722 // ^[ - Control Sequence Introducer (CSI)
1723 result
.key
= String
.fromCharCode(27);
1724 } else if (ev
.keyCode
=== 220) {
1725 // ^\ - String Terminator (ST)
1726 result
.key
= String
.fromCharCode(28);
1727 } else if (ev
.keyCode
=== 221) {
1728 // ^] - Operating System Command (OSC)
1729 result
.key
= String
.fromCharCode(29);
1731 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1732 // On Mac this is a third level shift. Use <Esc> instead.
1733 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1734 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1735 } else if (ev
.keyCode
=== 192) {
1736 result
.key
= C0
.ESC
+ '`';
1737 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1738 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1740 } else if (this.browser
.isMac
&& !ev
.altKey
&& !ev
.ctrlKey
&& ev
.metaKey
) {
1741 if (ev
.keyCode
=== 65) { // cmd + a
1752 * Set the G level of the terminal
1755 Terminal
.prototype.setgLevel = function(g
) {
1757 this.charset
= this.charsets
[g
];
1761 * Set the charset for the given G level of the terminal
1765 Terminal
.prototype.setgCharset = function(g
, charset
) {
1766 this.charsets
[g
] = charset
;
1767 if (this.glevel
=== g
) {
1768 this.charset
= charset
;
1773 * Handle a keypress event.
1775 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1776 * @param {KeyboardEvent} ev The keypress event to be handled.
1778 Terminal
.prototype.keyPress = function(ev
) {
1785 } else if (ev
.which
== null) {
1787 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1794 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1799 key
= String
.fromCharCode(key
);
1801 this.emit('keypress', key
, ev
);
1802 this.emit('key', key
, ev
);
1810 * Send data for handling to the terminal
1811 * @param {string} data
1813 Terminal
.prototype.send = function(data
) {
1817 setTimeout(function() {
1818 self
.handler(self
.queue
);
1828 * Note: We could do sweet things with webaudio here
1830 Terminal
.prototype.bell = function() {
1831 if (!this.visualBell
) return;
1833 this.element
.style
.borderColor
= 'white';
1834 setTimeout(function() {
1835 self
.element
.style
.borderColor
= '';
1837 if (this.popOnBell
) this.focus();
1841 * Log the current state to the console.
1843 Terminal
.prototype.log = function() {
1844 if (!this.debug
) return;
1845 if (!this.context
.console
|| !this.context
.console
.log
) return;
1846 var args
= Array
.prototype.slice
.call(arguments
);
1847 this.context
.console
.log
.apply(this.context
.console
, args
);
1851 * Log the current state as error to the console.
1853 Terminal
.prototype.error = function() {
1854 if (!this.debug
) return;
1855 if (!this.context
.console
|| !this.context
.console
.error
) return;
1856 var args
= Array
.prototype.slice
.call(arguments
);
1857 this.context
.console
.error
.apply(this.context
.console
, args
);
1861 * Resizes the terminal.
1863 * @param {number} x The number of columns to resize to.
1864 * @param {number} y The number of rows to resize to.
1866 Terminal
.prototype.resize = function(x
, y
) {
1867 if (isNaN(x
) || isNaN(y
)) {
1878 if (x
=== this.cols
&& y
=== this.rows
) {
1888 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1889 i
= this.lines
.length
;
1891 while (this.lines
.get(i
).length
< x
) {
1892 this.lines
.get(i
).push(ch
);
1898 this.setupStops(this.cols
);
1906 // y is rows, not this.y
1907 if (this.lines
.length
< y
+ this.ybase
) {
1908 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
1909 // There is room above the buffer and there are no empty elements below the line,
1913 if (this.ydisp
> 0) {
1914 // Viewport is at the top of the buffer, must increase downwards
1918 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1919 // are blank lines after the cursor
1920 this.lines
.push(this.blankLine());
1923 if (this.children
.length
< y
) {
1929 if (this.lines
.length
> y
+ this.ybase
) {
1930 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
1931 // The line is a blank line below the cursor, remove it
1934 // The line is the cursor, scroll down
1939 if (this.children
.length
> y
) {
1940 el
= this.children
.shift();
1942 el
.parentNode
.removeChild(el
);
1948 // Make sure that the cursor stays on screen
1961 this.scrollBottom
= y
- 1;
1963 this.charMeasure
.measure();
1965 this.refresh(0, this.rows
- 1);
1969 this.geometry
= [this.cols
, this.rows
];
1970 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
1974 * Updates the range of rows to refresh
1975 * @param {number} y The number of rows to refresh next.
1977 Terminal
.prototype.updateRange = function(y
) {
1978 if (y
< this.refreshStart
) this.refreshStart
= y
;
1979 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
1980 // if (y > this.refreshEnd) {
1981 // this.refreshEnd = y;
1982 // if (y > this.rows - 1) {
1983 // this.refreshEnd = this.rows - 1;
1989 * Set the range of refreshing to the maximum value
1991 Terminal
.prototype.maxRange = function() {
1992 this.refreshStart
= 0;
1993 this.refreshEnd
= this.rows
- 1;
1999 * Setup the tab stops.
2002 Terminal
.prototype.setupStops = function(i
) {
2004 if (!this.tabs
[i
]) {
2005 i
= this.prevStop(i
);
2012 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
2013 this.tabs
[i
] = true;
2019 * Move the cursor to the previous tab stop from the given position (default is current).
2020 * @param {number} x The position to move the cursor to the previous tab stop.
2022 Terminal
.prototype.prevStop = function(x
) {
2023 if (x
== null) x
= this.x
;
2024 while (!this.tabs
[--x
] && x
> 0);
2025 return x
>= this.cols
2032 * Move the cursor one tab stop forward from the given position (default is current).
2033 * @param {number} x The position to move the cursor one tab stop forward.
2035 Terminal
.prototype.nextStop = function(x
) {
2036 if (x
== null) x
= this.x
;
2037 while (!this.tabs
[++x
] && x
< this.cols
);
2038 return x
>= this.cols
2045 * Erase in the identified line everything from "x" to the end of the line (right).
2046 * @param {number} x The column from which to start erasing to the end of the line.
2047 * @param {number} y The line in which to operate.
2049 Terminal
.prototype.eraseRight = function(x
, y
) {
2050 var line
= this.lines
.get(this.ybase
+ y
);
2054 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2055 for (; x
< this.cols
; x
++) {
2058 this.updateRange(y
);
2064 * Erase in the identified line everything from "x" to the start of the line (left).
2065 * @param {number} x The column from which to start erasing to the start of the line.
2066 * @param {number} y The line in which to operate.
2068 Terminal
.prototype.eraseLeft = function(x
, y
) {
2069 var line
= this.lines
.get(this.ybase
+ y
);
2073 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2078 this.updateRange(y
);
2082 * Clears the entire buffer, making the prompt line the new first line.
2084 Terminal
.prototype.clear = function() {
2085 if (this.ybase
=== 0 && this.y
=== 0) {
2086 // Don't clear if it's already clear
2089 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2090 this.lines
.length
= 1;
2094 for (var i
= 1; i
< this.rows
; i
++) {
2095 this.lines
.push(this.blankLine());
2097 this.refresh(0, this.rows
- 1);
2098 this.emit('scroll', this.ydisp
);
2102 * Erase all content in the given line
2103 * @param {number} y The line to erase all of its contents.
2105 Terminal
.prototype.eraseLine = function(y
) {
2106 this.eraseRight(0, y
);
2111 * Return the data array of a blank line
2112 * @param {number} cur First bunch of data for each "blank" character.
2113 * @param {boolean} isWrapped Whether the new line is wrapped from the previous line.
2115 Terminal
.prototype.blankLine = function(cur
, isWrapped
) {
2120 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2124 // TODO: It is not ideal that this is a property on an array, a buffer line
2125 // class should be added that will hold this data and other useful functions.
2127 line
.isWrapped
= isWrapped
;
2130 for (; i
< this.cols
; i
++) {
2139 * If cur return the back color xterm feature attribute. Else return defAttr.
2140 * @param {object} cur
2142 Terminal
.prototype.ch = function(cur
) {
2144 ? [this.eraseAttr(), ' ', 1]
2145 : [this.defAttr
, ' ', 1];
2150 * Evaluate if the current erminal is the given argument.
2151 * @param {object} term The terminal to evaluate
2153 Terminal
.prototype.is = function(term
) {
2154 var name
= this.termName
;
2155 return (name
+ '').indexOf(term
) === 0;
2160 * Emit the 'data' event and populate the given data.
2161 * @param {string} data The data to populate in the event.
2163 Terminal
.prototype.handler = function(data
) {
2164 // Prevents all events to pty process if stdin is disabled
2165 if (this.options
.disableStdin
) {
2169 // Input is being sent to the terminal, the terminal should focus the prompt.
2170 if (this.ybase
!== this.ydisp
) {
2171 this.scrollToBottom();
2173 this.emit('data', data
);
2178 * Emit the 'title' event and populate the given title.
2179 * @param {string} title The title to populate in the event.
2181 Terminal
.prototype.handleTitle = function(title
) {
2183 * This event is emitted when the title of the terminal is changed
2184 * from inside the terminal. The parameter is the new title.
2188 this.emit('title', title
);
2197 * ESC D Index (IND is 0x84).
2199 Terminal
.prototype.index = function() {
2201 if (this.y
> this.scrollBottom
) {
2205 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2206 if (this.x
>= this.cols
) {
2213 * ESC M Reverse Index (RI is 0x8d).
2215 * Move the cursor up one row, inserting a new blank line if necessary.
2217 Terminal
.prototype.reverseIndex = function() {
2219 if (this.y
=== this.scrollTop
) {
2220 // possibly move the code below to term.reverseScroll();
2221 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2222 // blankLine(true) is xterm/linux behavior
2223 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2224 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2225 this.updateRange(this.scrollTop
);
2226 this.updateRange(this.scrollBottom
);
2234 * ESC c Full Reset (RIS).
2236 Terminal
.prototype.reset = function() {
2237 this.options
.rows
= this.rows
;
2238 this.options
.cols
= this.cols
;
2239 var customKeydownHandler
= this.customKeydownHandler
;
2240 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2241 Terminal
.call(this, this.options
);
2242 this.customKeydownHandler
= customKeydownHandler
;
2243 this.cursorBlinkInterval
= cursorBlinkInterval
;
2244 this.refresh(0, this.rows
- 1);
2245 this.viewport
.syncScrollArea();
2250 * ESC H Tab Set (HTS is 0x88).
2252 Terminal
.prototype.tabSet = function() {
2253 this.tabs
[this.x
] = true;
2260 function on(el
, type
, handler
, capture
) {
2261 if (!Array
.isArray(el
)) {
2264 el
.forEach(function (element
) {
2265 element
.addEventListener(type
, handler
, capture
|| false);
2269 function off(el
, type
, handler
, capture
) {
2270 el
.removeEventListener(type
, handler
, capture
|| false);
2273 function cancel(ev
, force
) {
2274 if (!this.cancelEvents
&& !force
) {
2277 ev
.preventDefault();
2278 ev
.stopPropagation();
2282 function inherits(child
, parent
) {
2284 this.constructor = child
;
2286 f
.prototype = parent
.prototype;
2287 child
.prototype = new f
;
2290 function indexOf(obj
, el
) {
2293 if (obj
[i
] === el
) return i
;
2298 function isThirdLevelShift(term
, ev
) {
2300 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2301 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2303 if (ev
.type
== 'keypress') {
2304 return thirdLevelKey
;
2307 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2308 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2311 // Expose to InputHandler (temporary)
2312 Terminal
.prototype.matchColor
= matchColor
;
2314 function matchColor(r1
, g1
, b1
) {
2315 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2317 if (matchColor
._cache
[hash
] != null) {
2318 return matchColor
._cache
[hash
];
2321 var ldiff
= Infinity
2330 for (; i
< Terminal
.vcolors
.length
; i
++) {
2331 c
= Terminal
.vcolors
[i
];
2336 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2349 return matchColor
._cache
[hash
] = li
;
2352 matchColor
._cache
= {};
2354 // http://stackoverflow.com/questions/1633828
2355 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2356 return Math
.pow(30 * (r1
- r2
), 2)
2357 + Math
.pow(59 * (g1
- g2
), 2)
2358 + Math
.pow(11 * (b1
- b2
), 2);
2361 function each(obj
, iter
, con
) {
2362 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2363 for (var i
= 0; i
< obj
.length
; i
++) {
2364 iter
.call(con
, obj
[i
], i
, obj
);
2368 function wasMondifierKeyOnlyEvent(ev
) {
2369 return ev
.keyCode
=== 16 || // Shift
2370 ev
.keyCode
=== 17 || // Ctrl
2371 ev
.keyCode
=== 18; // Alt
2374 function keys(obj
) {
2375 if (Object
.keys
) return Object
.keys(obj
);
2378 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2389 Terminal
.translateBufferLineToString
= translateBufferLineToString
;
2390 Terminal
.EventEmitter
= EventEmitter
;
2391 Terminal
.inherits
= inherits
;
2394 * Adds an event listener to the terminal.
2396 * @param {string} event The name of the event. TODO: Document all event types
2397 * @param {function} callback The function to call when the event is triggered.
2401 Terminal
.cancel
= cancel
;
2403 module
.exports
= Terminal
;