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';
31 * Terminal Emulation References:
33 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
34 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
35 * http://invisible-island.net/vttest/
36 * http://www.inwap.com/pdp10/ansicode.txt
37 * http://linux.die.net/man/4/console_codes
38 * http://linux.die.net/man/7/urxvt
41 // Let it work inside Node.js for automated testing purposes.
42 var document
= (typeof window
!= 'undefined') ? window
.document
: null;
45 * The amount of write requests to queue before sending an XOFF signal to the
46 * pty process. This number must be small in order for ^C and similar sequences
49 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
52 * The number of writes to perform in a single batch before allowing the
53 * renderer to catch up with a 0ms setTimeout.
55 var WRITE_BATCH_SIZE
= 300;
58 * The time between cursor blinks. This is driven by JS rather than a CSS
59 * animation due to a bug in Chromium that causes it to use excessive CPU time.
60 * See https://github.com/Microsoft/vscode/issues/22900
62 var CURSOR_BLINK_INTERVAL
= 600;
69 * Creates a new `Terminal` object.
71 * @param {object} options An object containing a set of options, the available options are:
72 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
73 * - `cols` (number): The number of columns of the terminal (horizontal size)
74 * - `rows` (number): The number of rows of the terminal (vertical size)
78 * @alias module:xterm/src/xterm
80 function Terminal(options
) {
83 if (!(this instanceof Terminal
)) {
84 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
87 self
.browser
= Browser
;
88 self
.cancel
= Terminal
.cancel
;
90 EventEmitter
.call(this);
92 if (typeof options
=== 'number') {
100 options
= options
|| {};
103 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
104 if (options
[key
] == null) {
105 options
[key
] = Terminal
.options
[key
];
107 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
108 options
[key
] = Terminal
[key
];
111 self
[key
] = options
[key
];
114 if (options
.colors
.length
=== 8) {
115 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
116 } else if (options
.colors
.length
=== 16) {
117 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
118 } else if (options
.colors
.length
=== 10) {
119 options
.colors
= options
.colors
.slice(0, -2).concat(
120 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
121 } else if (options
.colors
.length
=== 18) {
122 options
.colors
= options
.colors
.concat(
123 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
125 this.colors
= options
.colors
;
127 this.options
= options
;
129 // this.context = options.context || window;
130 // this.document = options.document || document;
131 this.parent
= options
.body
|| options
.parent
|| (
132 document
? document
.getElementsByTagName('body')[0] : null
135 this.cols
= options
.cols
|| options
.geometry
[0];
136 this.rows
= options
.rows
|| options
.geometry
[1];
137 this.geometry
= [this.cols
, this.rows
];
139 if (options
.handler
) {
140 this.on('data', options
.handler
);
144 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
150 * The scroll position of the viewport
155 * The cursor's x position after ybase
160 * The cursor's y position after ybase
164 this.cursorState
= 0;
165 this.cursorHidden
= false;
169 this.scrollBottom
= this.rows
- 1;
170 this.customKeydownHandler
= null;
171 this.cursorBlinkInterval
= null;
174 this.applicationKeypad
= false;
175 this.applicationCursor
= false;
176 this.originMode
= false;
177 this.insertMode
= false;
178 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
183 this.gcharset
= null;
185 this.charsets
= [null];
209 this.readable
= true;
210 this.writable
= true;
212 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
213 this.curAttr
= this.defAttr
;
216 this.currentParam
= 0;
220 this.inputHandler
= new InputHandler(this);
221 this.parser
= new Parser(this.inputHandler
, this);
222 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
223 this.renderer
= this.renderer
|| null;
224 this.selectionManager
= this.selectionManager
|| null;
225 this.linkifier
= this.linkifier
|| new Linkifier();
228 this.writeBuffer
= [];
229 this.writeInProgress
= false;
232 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
233 * This is a distinct state from writeStopped so that if the user requested
234 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
237 this.xoffSentToCatchUp
= false;
239 /** Whether writing has been stopped as a result of XOFF */
240 this.writeStopped
= false;
242 // leftover surrogate high from previous write invocation
243 this.surrogate_high
= '';
246 * An array of all lines in the entire buffer, including the prompt. The lines are array of
247 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
249 this.lines
= new CircularList(this.scrollback
);
252 this.lines
.push(this.blankLine());
258 // Store if user went browsing history in scrollback
259 this.userScrolling
= false;
262 inherits(Terminal
, EventEmitter
);
265 * back_color_erase feature for xterm.
267 Terminal
.prototype.eraseAttr = function() {
268 // if (this.is('screen')) return this.defAttr;
269 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
277 Terminal
.tangoColors
= [
298 // Colors 0-15 + 16-255
299 // Much thanks to TooTallNate for writing this.
300 Terminal
.colors
= (function() {
301 var colors
= Terminal
.tangoColors
.slice()
302 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
307 for (; i
< 216; i
++) {
308 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
313 for (; i
< 24; i
++) {
318 function out(r
, g
, b
) {
319 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
324 return c
.length
< 2 ? '0' + c
: c
;
330 Terminal
._colors
= Terminal
.colors
.slice();
332 Terminal
.vcolors
= (function() {
334 , colors
= Terminal
.colors
338 for (; i
< 256; i
++) {
339 color
= parseInt(colors
[i
].substring(1), 16);
341 (color
>> 16) & 0xff,
354 Terminal
.defaults
= {
355 colors
: Terminal
.colors
,
361 cursorStyle
: 'block',
369 useFlowControl
: false,
371 // programFeatures: false,
375 Terminal
.options
= {};
377 Terminal
.focus
= null;
379 each(keys(Terminal
.defaults
), function(key
) {
380 Terminal
[key
] = Terminal
.defaults
[key
];
381 Terminal
.options
[key
] = Terminal
.defaults
[key
];
385 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
387 Terminal
.prototype.focus = function() {
388 return this.textarea
.focus();
392 * Retrieves an option's value from the terminal.
393 * @param {string} key The option key.
395 Terminal
.prototype.getOption = function(key
, value
) {
396 if (!(key
in Terminal
.defaults
)) {
397 throw new Error('No option with key "' + key
+ '"');
400 if (typeof this.options
[key
] !== 'undefined') {
401 return this.options
[key
];
408 * Sets an option on the terminal.
409 * @param {string} key The option key.
410 * @param {string} value The option value.
412 Terminal
.prototype.setOption = function(key
, value
) {
413 if (!(key
in Terminal
.defaults
)) {
414 throw new Error('No option with key "' + key
+ '"');
418 if (this.options
[key
] !== value
) {
419 if (this.lines
.length
> value
) {
420 const amountToTrim
= this.lines
.length
- value
;
421 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
422 this.lines
.trimStart(amountToTrim
);
423 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
424 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
426 this.refresh(0, this.rows
- 1);
429 this.lines
.maxLength
= value
;
430 this.viewport
.syncScrollArea();
435 this.options
[key
] = value
;
437 case 'cursorBlink': this.setCursorBlinking(value
); break;
439 // Style 'block' applies with no class
440 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
441 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
443 case 'tabStopWidth': this.setupStops(); break;
447 Terminal
.prototype.restartCursorBlinking = function () {
448 this.setCursorBlinking(this.options
.cursorBlink
);
451 Terminal
.prototype.setCursorBlinking = function (enabled
) {
452 this.element
.classList
.toggle('xterm-cursor-blink', enabled
);
453 this.clearCursorBlinkingInterval();
456 this.cursorBlinkInterval
= setInterval(function () {
457 self
.element
.classList
.toggle('xterm-cursor-blink-on');
458 }, CURSOR_BLINK_INTERVAL
);
462 Terminal
.prototype.clearCursorBlinkingInterval = function () {
463 this.element
.classList
.remove('xterm-cursor-blink-on');
464 if (this.cursorBlinkInterval
) {
465 clearInterval(this.cursorBlinkInterval
);
466 this.cursorBlinkInterval
= null;
471 * Binds the desired focus behavior on a given terminal object.
475 Terminal
.bindFocus = function (term
) {
476 on(term
.textarea
, 'focus', function (ev
) {
477 if (term
.sendFocus
) {
478 term
.send(C0
.ESC
+ '[I');
480 term
.element
.classList
.add('focus');
482 term
.restartCursorBlinking
.apply(term
);
483 Terminal
.focus
= term
;
484 term
.emit('focus', {terminal
: term
});
489 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
491 Terminal
.prototype.blur = function() {
492 return this.textarea
.blur();
496 * Binds the desired blur behavior on a given terminal object.
500 Terminal
.bindBlur = function (term
) {
501 on(term
.textarea
, 'blur', function (ev
) {
502 term
.refresh(term
.y
, term
.y
);
503 if (term
.sendFocus
) {
504 term
.send(C0
.ESC
+ '[O');
506 term
.element
.classList
.remove('focus');
507 term
.clearCursorBlinkingInterval
.apply(term
);
508 Terminal
.focus
= null;
509 term
.emit('blur', {terminal
: term
});
514 * Initialize default behavior
516 Terminal
.prototype.initGlobal = function() {
519 Terminal
.bindKeys(this);
520 Terminal
.bindFocus(this);
521 Terminal
.bindBlur(this);
523 // Bind clipboard functionality
524 on(this.element
, 'copy', event
=> {
525 copyHandler(event
, term
, term
.selectionManager
);
527 const pasteHandlerWrapper
= event
=> pasteHandler(event
, term
);
528 on(this.textarea
, 'paste', pasteHandlerWrapper
);
529 on(this.element
, 'paste', pasteHandlerWrapper
);
531 if (term
.browser
.isFirefox
) {
532 on(this.element
, 'mousedown', event
=> {
533 if (ev
.button
== 2) {
534 rightClickHandler(event
, this.textarea
, this.selectionManager
);
538 on(this.element
, 'contextmenu', event
=> {
539 rightClickHandler(event
, this.textarea
, this.selectionManager
);
545 * Apply key handling to the terminal
547 Terminal
.bindKeys = function(term
) {
548 on(term
.element
, 'keydown', function(ev
) {
549 if (document
.activeElement
!= this) {
555 on(term
.element
, 'keypress', function(ev
) {
556 if (document
.activeElement
!= this) {
562 on(term
.element
, 'keyup', function(ev
) {
563 if (!wasMondifierKeyOnlyEvent(ev
)) {
568 on(term
.textarea
, 'keydown', function(ev
) {
572 on(term
.textarea
, 'keypress', function(ev
) {
574 // Truncate the textarea's value, since it is not needed
578 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
579 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
580 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
581 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
582 term
.on('refresh', function (data
) {
583 term
.queueLinkification(data
.start
, data
.end
)
589 * Insert the given row to the terminal or produce a new one
590 * if no row argument is passed. Return the inserted row.
591 * @param {HTMLElement} row (optional) The row to append to the terminal.
593 Terminal
.prototype.insertRow = function (row
) {
594 if (typeof row
!= 'object') {
595 row
= document
.createElement('div');
598 this.rowContainer
.appendChild(row
);
599 this.children
.push(row
);
605 * Opens the terminal within an element.
607 * @param {HTMLElement} parent The element to create the terminal within.
608 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
610 Terminal
.prototype.open = function(parent
, focus
) {
611 var self
=this, i
=0, div
;
613 this.parent
= parent
|| this.parent
;
616 throw new Error('Terminal requires a parent element.');
619 // Grab global elements
620 this.context
= this.parent
.ownerDocument
.defaultView
;
621 this.document
= this.parent
.ownerDocument
;
622 this.body
= this.document
.getElementsByTagName('body')[0];
624 //Create main element container
625 this.element
= this.document
.createElement('div');
626 this.element
.classList
.add('terminal');
627 this.element
.classList
.add('xterm');
628 this.element
.classList
.add('xterm-theme-' + this.theme
);
629 this.setCursorBlinking(this.options
.cursorBlink
);
631 this.element
.style
.height
;
632 this.element
.setAttribute('tabindex', 0);
634 this.viewportElement
= document
.createElement('div');
635 this.viewportElement
.classList
.add('xterm-viewport');
636 this.element
.appendChild(this.viewportElement
);
637 this.viewportScrollArea
= document
.createElement('div');
638 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
639 this.viewportElement
.appendChild(this.viewportScrollArea
);
641 // Create the selection container. This needs to be added before the
642 // rowContainer as the selection must be below the text.
643 this.selectionContainer
= document
.createElement('div');
644 this.selectionContainer
.classList
.add('xterm-selection');
645 this.element
.appendChild(this.selectionContainer
);
647 // Create the container that will hold the lines of the terminal and then
648 // produce the lines the lines.
649 this.rowContainer
= document
.createElement('div');
650 this.rowContainer
.classList
.add('xterm-rows');
651 this.element
.appendChild(this.rowContainer
);
653 this.linkifier
.attachToDom(document
, this.children
);
655 // Create the container that will hold helpers like the textarea for
656 // capturing DOM Events. Then produce the helpers.
657 this.helperContainer
= document
.createElement('div');
658 this.helperContainer
.classList
.add('xterm-helpers');
659 // TODO: This should probably be inserted once it's filled to prevent an additional layout
660 this.element
.appendChild(this.helperContainer
);
661 this.textarea
= document
.createElement('textarea');
662 this.textarea
.classList
.add('xterm-helper-textarea');
663 this.textarea
.setAttribute('autocorrect', 'off');
664 this.textarea
.setAttribute('autocapitalize', 'off');
665 this.textarea
.setAttribute('spellcheck', 'false');
666 this.textarea
.tabIndex
= 0;
667 this.textarea
.addEventListener('focus', function() {
668 self
.emit('focus', {terminal
: self
});
670 this.textarea
.addEventListener('blur', function() {
671 self
.emit('blur', {terminal
: self
});
673 this.helperContainer
.appendChild(this.textarea
);
675 this.compositionView
= document
.createElement('div');
676 this.compositionView
.classList
.add('composition-view');
677 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
678 this.helperContainer
.appendChild(this.compositionView
);
680 this.charSizeStyleElement
= document
.createElement('style');
681 this.helperContainer
.appendChild(this.charSizeStyleElement
);
683 for (; i
< this.rows
; i
++) {
686 this.parent
.appendChild(this.element
);
688 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
689 this.charMeasure
.on('charsizechanged', function () {
690 self
.updateCharSizeCSS();
692 this.charMeasure
.measure();
694 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
695 this.renderer
= new Renderer(this);
696 this.selectionManager
= new SelectionManager(this, this.lines
, this.rowContainer
, this.charMeasure
);
697 this.selectionManager
.on('refresh', data
=> this.renderer
.refreshSelection(data
.start
, data
.end
));
698 this.on('scroll', () => this.selectionManager
.refresh());
699 this.viewportElement
.addEventListener('scroll', () => this.selectionManager
.refresh());
701 // Setup loop that draws to screen
702 this.refresh(0, this.rows
- 1);
704 // Initialize global actions that
705 // need to be taken on the document.
709 * Automatic focus functionality.
710 * TODO: Default to `false` starting with xterm.js 3.0.
712 if (typeof focus
== 'undefined') {
713 let message
= 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
715 message
+= 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
716 message
+= 'it will default to `false`.';
718 console
.warn(message
);
726 on(this.element
, 'click', function() {
727 var selection
= document
.getSelection(),
728 collapsed
= selection
.isCollapsed
,
729 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
735 // Listen for mouse events and translate
736 // them into terminal mouse protocols.
740 * This event is emitted when terminal has completed opening.
749 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
750 * @param {string} addon The name of the addon to load
753 Terminal
.loadAddon = function(addon
, callback
) {
754 if (typeof exports
=== 'object' && typeof module
=== 'object') {
756 return require('./addons/' + addon
+ '/' + addon
);
757 } else if (typeof define
== 'function') {
759 return require(['./addons/' + addon
+ '/' + addon
], callback
);
761 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
767 * Updates the helper CSS class with any changes necessary after the terminal's
768 * character width has been changed.
770 Terminal
.prototype.updateCharSizeCSS = function() {
771 this.charSizeStyleElement
.textContent
=
772 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
773 `.xterm-normal-char{width:${this.charMeasure.width}px;}`
778 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
779 * To better understand these
780 * the xterm code is very helpful:
782 * button.c, charproc.c, misc.c
783 * Relevant functions in xterm/button.c:
784 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
786 Terminal
.prototype.bindMouse = function() {
787 var el
= this.element
, self
= this, pressed
= 32;
789 // mouseup, mousedown, wheel
790 // left click: ^[[M 3<^[[M#3<
792 function sendButton(ev
) {
796 // get the xterm-style button
797 button
= getButton(ev
);
799 // get mouse coordinates
800 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
803 sendEvent(button
, pos
);
805 switch (ev
.overrideType
|| ev
.type
) {
810 // keep it at the left
811 // button, just in case.
822 // motion example of a left click:
823 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
824 function sendMove(ev
) {
828 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
831 // buttons marked as motions
832 // are incremented by 32
835 sendEvent(button
, pos
);
839 // position to characters
840 function encode(data
, ch
) {
841 if (!self
.utfMouse
) {
842 if (ch
=== 255) return data
.push(0);
843 if (ch
> 127) ch
= 127;
846 if (ch
=== 2047) return data
.push(0);
850 if (ch
> 2047) ch
= 2047;
851 data
.push(0xC0 | (ch
>> 6));
852 data
.push(0x80 | (ch
& 0x3F));
857 // send a mouse event:
858 // regular/utf8: ^[[M Cb Cx Cy
859 // urxvt: ^[[ Cb ; Cx ; Cy M
860 // sgr: ^[[ Cb ; Cx ; Cy M/m
861 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
862 // locator: CSI P e ; P b ; P r ; P c ; P p & w
863 function sendEvent(button
, pos
) {
864 // self.emit('mouse', {
870 if (self
.vt300Mouse
) {
872 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
876 var data
= C0
.ESC
+ '[24';
877 if (button
=== 0) data
+= '1';
878 else if (button
=== 1) data
+= '3';
879 else if (button
=== 2) data
+= '5';
880 else if (button
=== 3) return;
882 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
887 if (self
.decLocator
) {
892 if (button
=== 0) button
= 2;
893 else if (button
=== 1) button
= 4;
894 else if (button
=== 2) button
= 6;
895 else if (button
=== 3) button
= 3;
896 self
.send(C0
.ESC
+ '['
899 + (button
=== 3 ? 4 : 0)
910 if (self
.urxvtMouse
) {
915 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
922 self
.send(C0
.ESC
+ '[<'
923 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
928 + ((button
& 3) === 3 ? 'm' : 'M'));
934 encode(data
, button
);
938 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
941 function getButton(ev
) {
954 // 1, and 2 - with 64 added
955 switch (ev
.overrideType
|| ev
.type
) {
957 button
= ev
.button
!= null
963 if (self
.browser
.isMSIE
) {
964 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
970 case 'DOMMouseScroll':
971 button
= ev
.detail
< 0
976 button
= ev
.wheelDeltaY
> 0
982 // next three bits are the modifiers:
983 // 4 = shift, 8 = meta, 16 = control
984 shift
= ev
.shiftKey
? 4 : 0;
985 meta
= ev
.metaKey
? 8 : 0;
986 ctrl
= ev
.ctrlKey
? 16 : 0;
987 mod
= shift
| meta
| ctrl
;
990 if (self
.vt200Mouse
) {
993 } else if (!self
.normalMouse
) {
998 button
= (32 + (mod
<< 2)) + button
;
1003 on(el
, 'mousedown', function(ev
) {
1004 if (!self
.mouseEvents
) return;
1013 //if (self.vt200Mouse && !self.normalMouse) {
1014 if (self
.vt200Mouse
) {
1015 ev
.overrideType
= 'mouseup';
1017 return self
.cancel(ev
);
1021 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1023 // x10 compatibility mode can't send button releases
1024 if (!self
.x10Mouse
) {
1025 on(self
.document
, 'mouseup', function up(ev
) {
1027 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1028 off(self
.document
, 'mouseup', up
);
1029 return self
.cancel(ev
);
1033 return self
.cancel(ev
);
1036 //if (self.normalMouse) {
1037 // on(self.document, 'mousemove', sendMove);
1040 on(el
, 'wheel', function(ev
) {
1041 if (!self
.mouseEvents
) return;
1044 || self
.decLocator
) return;
1046 return self
.cancel(ev
);
1049 // allow wheel scrolling in
1050 // the shell for example
1051 on(el
, 'wheel', function(ev
) {
1052 if (self
.mouseEvents
) return;
1053 self
.viewport
.onWheel(ev
);
1054 return self
.cancel(ev
);
1059 * Destroys the terminal.
1061 Terminal
.prototype.destroy = function() {
1062 this.readable
= false;
1063 this.writable
= false;
1065 this.handler = function() {};
1066 this.write = function() {};
1067 if (this.element
&& this.element
.parentNode
) {
1068 this.element
.parentNode
.removeChild(this.element
);
1070 //this.emit('close');
1074 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1076 * @param {number} start The row to start from (between 0 and this.rows - 1).
1077 * @param {number} end The row to end at (between start and this.rows - 1).
1079 Terminal
.prototype.refresh = function(start
, end
) {
1080 if (this.renderer
) {
1081 this.renderer
.queueRefresh(start
, end
);
1086 * Queues linkification for the specified rows.
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.queueLinkification = function(start
, end
) {
1091 if (this.linkifier
) {
1092 for (let i
= start
; i
<= end
; i
++) {
1093 this.linkifier
.linkifyRow(i
);
1099 * Display the cursor element
1101 Terminal
.prototype.showCursor = function() {
1102 if (!this.cursorState
) {
1103 this.cursorState
= 1;
1104 this.refresh(this.y
, this.y
);
1109 * Scroll the terminal down 1 row, creating a blank line.
1111 Terminal
.prototype.scroll = function() {
1114 // Make room for the new row in lines
1115 if (this.lines
.length
=== this.lines
.maxLength
) {
1116 this.lines
.trimStart(1);
1118 if (this.ydisp
!== 0) {
1125 // TODO: Why is this done twice?
1126 if (!this.userScrolling
) {
1127 this.ydisp
= this.ybase
;
1131 row
= this.ybase
+ this.rows
- 1;
1133 // subtract the bottom scroll region
1134 row
-= this.rows
- 1 - this.scrollBottom
;
1136 if (row
=== this.lines
.length
) {
1137 // Optimization: pushing is faster than splicing when they amount to the same behavior
1138 this.lines
.push(this.blankLine());
1141 this.lines
.splice(row
, 0, this.blankLine());
1144 if (this.scrollTop
!== 0) {
1145 if (this.ybase
!== 0) {
1147 if (!this.userScrolling
) {
1148 this.ydisp
= this.ybase
;
1151 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1155 this.updateRange(this.scrollTop
);
1156 this.updateRange(this.scrollBottom
);
1159 * This event is emitted whenever the terminal is scrolled.
1160 * The one parameter passed is the new y display position.
1164 this.emit('scroll', this.ydisp
);
1168 * Scroll the display of the terminal
1169 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1170 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1171 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1172 * viewport originally.
1174 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1176 if (this.ydisp
=== 0) {
1179 this.userScrolling
= true;
1180 } else if (disp
+ this.ydisp
>= this.ybase
) {
1181 this.userScrolling
= false;
1186 if (this.ydisp
> this.ybase
) {
1187 this.ydisp
= this.ybase
;
1188 } else if (this.ydisp
< 0) {
1192 if (!suppressScrollEvent
) {
1193 this.emit('scroll', this.ydisp
);
1196 this.refresh(0, this.rows
- 1);
1200 * Scroll the display of the terminal by a number of pages.
1201 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1203 Terminal
.prototype.scrollPages = function(pageCount
) {
1204 this.scrollDisp(pageCount
* (this.rows
- 1));
1208 * Scrolls the display of the terminal to the top.
1210 Terminal
.prototype.scrollToTop = function() {
1211 this.scrollDisp(-this.ydisp
);
1215 * Scrolls the display of the terminal to the bottom.
1217 Terminal
.prototype.scrollToBottom = function() {
1218 this.scrollDisp(this.ybase
- this.ydisp
);
1222 * Writes text to the terminal.
1223 * @param {string} text The text to write to the terminal.
1225 Terminal
.prototype.write = function(data
) {
1226 this.writeBuffer
.push(data
);
1228 // Send XOFF to pause the pty process if the write buffer becomes too large so
1229 // xterm.js can catch up before more data is sent. This is necessary in order
1230 // to keep signals such as ^C responsive.
1231 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1232 // XOFF - stop pty pipe
1233 // XON will be triggered by emulator before processing data chunk
1235 this.xoffSentToCatchUp
= true;
1238 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1239 // Kick off a write which will write all data in sequence recursively
1240 this.writeInProgress
= true;
1241 // Kick off an async innerWrite so more writes can come in while processing data
1243 setTimeout(function () {
1249 Terminal
.prototype.innerWrite = function() {
1250 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1251 while (writeBatch
.length
> 0) {
1252 var data
= writeBatch
.shift();
1253 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1255 // If XOFF was sent in order to catch up with the pty process, resume it if
1256 // the writeBuffer is empty to allow more data to come in.
1257 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1259 this.xoffSentToCatchUp
= false;
1262 this.refreshStart
= this.y
;
1263 this.refreshEnd
= this.y
;
1265 // HACK: Set the parser state based on it's state at the time of return.
1266 // This works around the bug #662 which saw the parser state reset in the
1267 // middle of parsing escape sequence in two chunks. For some reason the
1268 // state of the parser resets to 0 after exiting parser.parse. This change
1269 // just sets the state back based on the correct return statement.
1270 var state
= this.parser
.parse(data
);
1271 this.parser
.setState(state
);
1273 this.updateRange(this.y
);
1274 this.refresh(this.refreshStart
, this.refreshEnd
);
1276 if (this.writeBuffer
.length
> 0) {
1277 // Allow renderer to catch up before processing the next batch
1279 setTimeout(function () {
1283 this.writeInProgress
= false;
1288 * Writes text to the terminal, followed by a break line character (\n).
1289 * @param {string} text The text to write to the terminal.
1291 Terminal
.prototype.writeln = function(data
) {
1292 this.write(data
+ '\r\n');
1296 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1297 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1299 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1300 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1301 * the default action. The function returns whether the event should be processed by xterm.js.
1303 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1304 this.customKeydownHandler
= customKeydownHandler
;
1308 * Attaches a http(s) link handler, forcing web links to behave differently to
1309 * regular <a> tags. This will trigger a refresh as links potentially need to be
1310 * reconstructed. Calling this with null will remove the handler.
1311 * @param {LinkHandler} handler The handler callback function.
1313 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1314 if (!this.linkifier
) {
1315 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1317 this.linkifier
.setHypertextLinkHandler(handler
);
1318 // Refresh to force links to refresh
1319 this.refresh(0, this.rows
- 1);
1323 * Attaches a validation callback for hypertext links. This is useful to use
1324 * validation logic or to do something with the link's element and url.
1325 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1326 * be cleared with null.
1328 Terminal
.prototype.setHypertextValidationCallback = function(handler
) {
1329 if (!this.linkifier
) {
1330 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1332 this.linkifier
.setHypertextValidationCallback(handler
);
1333 // Refresh to force links to refresh
1334 this.refresh(0, this.rows
- 1);
1338 * Registers a link matcher, allowing custom link patterns to be matched and
1340 * @param {RegExp} regex The regular expression to search for, specifically
1341 * this searches the textContent of the rows. You will want to use \s to match
1342 * a space ' ' character for example.
1343 * @param {LinkHandler} handler The callback when the link is called.
1344 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1345 * @return {number} The ID of the new matcher, this can be used to deregister.
1347 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1348 if (this.linkifier
) {
1349 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1350 this.refresh(0, this.rows
- 1);
1356 * Deregisters a link matcher if it has been registered.
1357 * @param {number} matcherId The link matcher's ID (returned after register)
1359 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1360 if (this.linkifier
) {
1361 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1362 this.refresh(0, this.rows
- 1);
1368 * Selects all text within the terminal.
1370 Terminal
.prototype.selectAll = function() {
1371 this.selectionManager
.selectAll();
1375 * Handle a keydown event
1377 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1378 * @param {KeyboardEvent} ev The keydown event to be handled.
1380 Terminal
.prototype.keyDown = function(ev
) {
1381 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1385 this.restartCursorBlinking();
1387 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1388 if (this.ybase
!== this.ydisp
) {
1389 this.scrollToBottom();
1395 var result
= this.evaluateKeyEscapeSequence(ev
);
1397 if (result
.key
=== C0
.DC3
) { // XOFF
1398 this.writeStopped
= true;
1399 } else if (result
.key
=== C0
.DC1
) { // XON
1400 this.writeStopped
= false;
1403 if (result
.scrollDisp
) {
1404 this.scrollDisp(result
.scrollDisp
);
1405 return this.cancel(ev
, true);
1408 if (isThirdLevelShift(this, ev
)) {
1412 if (result
.cancel
) {
1413 // The event is canceled at the end already, is this necessary?
1414 this.cancel(ev
, true);
1421 this.emit('keydown', ev
);
1422 this.emit('key', result
.key
, ev
);
1424 this.handler(result
.key
);
1426 return this.cancel(ev
, true);
1430 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1431 * returned value is the new key code to pass to the PTY.
1433 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1434 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1436 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1438 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1439 // canceled at the end of keyDown
1441 // The new key even to emit
1443 // The number of characters to scroll, if this is defined it will cancel the event
1444 scrollDisp
: undefined
1446 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1447 switch (ev
.keyCode
) {
1451 result
.key
= C0
.BS
; // ^H
1454 result
.key
= C0
.DEL
; // ^?
1459 result
.key
= C0
.ESC
+ '[Z';
1463 result
.cancel
= true;
1468 result
.cancel
= true;
1472 result
.key
= C0
.ESC
;
1473 result
.cancel
= true;
1478 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1479 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1480 // http://unix.stackexchange.com/a/108106
1481 // macOS uses different escape sequences than linux
1482 if (result
.key
== C0
.ESC
+ '[1;3D') {
1483 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1485 } else if (this.applicationCursor
) {
1486 result
.key
= C0
.ESC
+ 'OD';
1488 result
.key
= C0
.ESC
+ '[D';
1494 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1495 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1496 // http://unix.stackexchange.com/a/108106
1497 // macOS uses different escape sequences than linux
1498 if (result
.key
== C0
.ESC
+ '[1;3C') {
1499 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1501 } else if (this.applicationCursor
) {
1502 result
.key
= C0
.ESC
+ 'OC';
1504 result
.key
= C0
.ESC
+ '[C';
1510 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1511 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1512 // http://unix.stackexchange.com/a/108106
1513 if (result
.key
== C0
.ESC
+ '[1;3A') {
1514 result
.key
= C0
.ESC
+ '[1;5A';
1516 } else if (this.applicationCursor
) {
1517 result
.key
= C0
.ESC
+ 'OA';
1519 result
.key
= C0
.ESC
+ '[A';
1525 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1526 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1527 // http://unix.stackexchange.com/a/108106
1528 if (result
.key
== C0
.ESC
+ '[1;3B') {
1529 result
.key
= C0
.ESC
+ '[1;5B';
1531 } else if (this.applicationCursor
) {
1532 result
.key
= C0
.ESC
+ 'OB';
1534 result
.key
= C0
.ESC
+ '[B';
1539 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1540 // <Ctrl> or <Shift> + <Insert> are used to
1541 // copy-paste on some systems.
1542 result
.key
= C0
.ESC
+ '[2~';
1548 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1550 result
.key
= C0
.ESC
+ '[3~';
1556 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1557 else if (this.applicationCursor
)
1558 result
.key
= C0
.ESC
+ 'OH';
1560 result
.key
= C0
.ESC
+ '[H';
1565 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1566 else if (this.applicationCursor
)
1567 result
.key
= C0
.ESC
+ 'OF';
1569 result
.key
= C0
.ESC
+ '[F';
1574 result
.scrollDisp
= -(this.rows
- 1);
1576 result
.key
= C0
.ESC
+ '[5~';
1582 result
.scrollDisp
= this.rows
- 1;
1584 result
.key
= C0
.ESC
+ '[6~';
1590 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1592 result
.key
= C0
.ESC
+ 'OP';
1597 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1599 result
.key
= C0
.ESC
+ 'OQ';
1604 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1606 result
.key
= C0
.ESC
+ 'OR';
1611 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1613 result
.key
= C0
.ESC
+ 'OS';
1618 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1620 result
.key
= C0
.ESC
+ '[15~';
1625 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1627 result
.key
= C0
.ESC
+ '[17~';
1632 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1634 result
.key
= C0
.ESC
+ '[18~';
1639 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1641 result
.key
= C0
.ESC
+ '[19~';
1646 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1648 result
.key
= C0
.ESC
+ '[20~';
1653 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1655 result
.key
= C0
.ESC
+ '[21~';
1660 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1662 result
.key
= C0
.ESC
+ '[23~';
1667 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1669 result
.key
= C0
.ESC
+ '[24~';
1674 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1675 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1676 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1677 } else if (ev
.keyCode
=== 32) {
1679 result
.key
= String
.fromCharCode(0);
1680 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1681 // escape, file sep, group sep, record sep, unit sep
1682 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1683 } else if (ev
.keyCode
=== 56) {
1685 result
.key
= String
.fromCharCode(127);
1686 } else if (ev
.keyCode
=== 219) {
1687 // ^[ - Control Sequence Introducer (CSI)
1688 result
.key
= String
.fromCharCode(27);
1689 } else if (ev
.keyCode
=== 220) {
1690 // ^\ - String Terminator (ST)
1691 result
.key
= String
.fromCharCode(28);
1692 } else if (ev
.keyCode
=== 221) {
1693 // ^] - Operating System Command (OSC)
1694 result
.key
= String
.fromCharCode(29);
1696 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1697 // On Mac this is a third level shift. Use <Esc> instead.
1698 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1699 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1700 } else if (ev
.keyCode
=== 192) {
1701 result
.key
= C0
.ESC
+ '`';
1702 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1703 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1705 } else if (this.browser
.isMac
&& !ev
.altKey
&& !ev
.ctrlKey
&& ev
.metaKey
) {
1706 if (ev
.keyCode
=== 65) { // cmd + a
1717 * Set the G level of the terminal
1720 Terminal
.prototype.setgLevel = function(g
) {
1722 this.charset
= this.charsets
[g
];
1726 * Set the charset for the given G level of the terminal
1730 Terminal
.prototype.setgCharset = function(g
, charset
) {
1731 this.charsets
[g
] = charset
;
1732 if (this.glevel
=== g
) {
1733 this.charset
= charset
;
1738 * Handle a keypress event.
1740 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1741 * @param {KeyboardEvent} ev The keypress event to be handled.
1743 Terminal
.prototype.keyPress = function(ev
) {
1750 } else if (ev
.which
== null) {
1752 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1759 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1764 key
= String
.fromCharCode(key
);
1766 this.emit('keypress', key
, ev
);
1767 this.emit('key', key
, ev
);
1775 * Send data for handling to the terminal
1776 * @param {string} data
1778 Terminal
.prototype.send = function(data
) {
1782 setTimeout(function() {
1783 self
.handler(self
.queue
);
1793 * Note: We could do sweet things with webaudio here
1795 Terminal
.prototype.bell = function() {
1796 if (!this.visualBell
) return;
1798 this.element
.style
.borderColor
= 'white';
1799 setTimeout(function() {
1800 self
.element
.style
.borderColor
= '';
1802 if (this.popOnBell
) this.focus();
1806 * Log the current state to the console.
1808 Terminal
.prototype.log = function() {
1809 if (!this.debug
) return;
1810 if (!this.context
.console
|| !this.context
.console
.log
) return;
1811 var args
= Array
.prototype.slice
.call(arguments
);
1812 this.context
.console
.log
.apply(this.context
.console
, args
);
1816 * Log the current state as error to the console.
1818 Terminal
.prototype.error = function() {
1819 if (!this.debug
) return;
1820 if (!this.context
.console
|| !this.context
.console
.error
) return;
1821 var args
= Array
.prototype.slice
.call(arguments
);
1822 this.context
.console
.error
.apply(this.context
.console
, args
);
1826 * Resizes the terminal.
1828 * @param {number} x The number of columns to resize to.
1829 * @param {number} y The number of rows to resize to.
1831 Terminal
.prototype.resize = function(x
, y
) {
1832 if (isNaN(x
) || isNaN(y
)) {
1843 if (x
=== this.cols
&& y
=== this.rows
) {
1853 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1854 i
= this.lines
.length
;
1856 while (this.lines
.get(i
).length
< x
) {
1857 this.lines
.get(i
).push(ch
);
1863 this.setupStops(this.cols
);
1871 // y is rows, not this.y
1872 if (this.lines
.length
< y
+ this.ybase
) {
1873 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
1874 // There is room above the buffer and there are no empty elements below the line,
1878 if (this.ydisp
> 0) {
1879 // Viewport is at the top of the buffer, must increase downwards
1883 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1884 // are blank lines after the cursor
1885 this.lines
.push(this.blankLine());
1888 if (this.children
.length
< y
) {
1894 if (this.lines
.length
> y
+ this.ybase
) {
1895 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
1896 // The line is a blank line below the cursor, remove it
1899 // The line is the cursor, scroll down
1904 if (this.children
.length
> y
) {
1905 el
= this.children
.shift();
1907 el
.parentNode
.removeChild(el
);
1913 // Make sure that the cursor stays on screen
1926 this.scrollBottom
= y
- 1;
1928 this.charMeasure
.measure();
1930 this.refresh(0, this.rows
- 1);
1934 this.geometry
= [this.cols
, this.rows
];
1935 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
1939 * Updates the range of rows to refresh
1940 * @param {number} y The number of rows to refresh next.
1942 Terminal
.prototype.updateRange = function(y
) {
1943 if (y
< this.refreshStart
) this.refreshStart
= y
;
1944 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
1945 // if (y > this.refreshEnd) {
1946 // this.refreshEnd = y;
1947 // if (y > this.rows - 1) {
1948 // this.refreshEnd = this.rows - 1;
1954 * Set the range of refreshing to the maximum value
1956 Terminal
.prototype.maxRange = function() {
1957 this.refreshStart
= 0;
1958 this.refreshEnd
= this.rows
- 1;
1964 * Setup the tab stops.
1967 Terminal
.prototype.setupStops = function(i
) {
1969 if (!this.tabs
[i
]) {
1970 i
= this.prevStop(i
);
1977 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
1978 this.tabs
[i
] = true;
1984 * Move the cursor to the previous tab stop from the given position (default is current).
1985 * @param {number} x The position to move the cursor to the previous tab stop.
1987 Terminal
.prototype.prevStop = function(x
) {
1988 if (x
== null) x
= this.x
;
1989 while (!this.tabs
[--x
] && x
> 0);
1990 return x
>= this.cols
1997 * Move the cursor one tab stop forward from the given position (default is current).
1998 * @param {number} x The position to move the cursor one tab stop forward.
2000 Terminal
.prototype.nextStop = function(x
) {
2001 if (x
== null) x
= this.x
;
2002 while (!this.tabs
[++x
] && x
< this.cols
);
2003 return x
>= this.cols
2010 * Erase in the identified line everything from "x" to the end of the line (right).
2011 * @param {number} x The column from which to start erasing to the end of the line.
2012 * @param {number} y The line in which to operate.
2014 Terminal
.prototype.eraseRight = function(x
, y
) {
2015 var line
= this.lines
.get(this.ybase
+ y
);
2019 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2020 for (; x
< this.cols
; x
++) {
2023 this.updateRange(y
);
2029 * Erase in the identified line everything from "x" to the start of the line (left).
2030 * @param {number} x The column from which to start erasing to the start of the line.
2031 * @param {number} y The line in which to operate.
2033 Terminal
.prototype.eraseLeft = function(x
, y
) {
2034 var line
= this.lines
.get(this.ybase
+ y
);
2038 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2043 this.updateRange(y
);
2047 * Clears the entire buffer, making the prompt line the new first line.
2049 Terminal
.prototype.clear = function() {
2050 if (this.ybase
=== 0 && this.y
=== 0) {
2051 // Don't clear if it's already clear
2054 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2055 this.lines
.length
= 1;
2059 for (var i
= 1; i
< this.rows
; i
++) {
2060 this.lines
.push(this.blankLine());
2062 this.refresh(0, this.rows
- 1);
2063 this.emit('scroll', this.ydisp
);
2067 * Erase all content in the given line
2068 * @param {number} y The line to erase all of its contents.
2070 Terminal
.prototype.eraseLine = function(y
) {
2071 this.eraseRight(0, y
);
2076 * Return the data array of a blank line
2077 * @param {number} cur First bunch of data for each "blank" character.
2079 Terminal
.prototype.blankLine = function(cur
) {
2084 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2088 for (; i
< this.cols
; i
++) {
2097 * If cur return the back color xterm feature attribute. Else return defAttr.
2098 * @param {object} cur
2100 Terminal
.prototype.ch = function(cur
) {
2102 ? [this.eraseAttr(), ' ', 1]
2103 : [this.defAttr
, ' ', 1];
2108 * Evaluate if the current erminal is the given argument.
2109 * @param {object} term The terminal to evaluate
2111 Terminal
.prototype.is = function(term
) {
2112 var name
= this.termName
;
2113 return (name
+ '').indexOf(term
) === 0;
2118 * Emit the 'data' event and populate the given data.
2119 * @param {string} data The data to populate in the event.
2121 Terminal
.prototype.handler = function(data
) {
2122 // Prevents all events to pty process if stdin is disabled
2123 if (this.options
.disableStdin
) {
2127 // Input is being sent to the terminal, the terminal should focus the prompt.
2128 if (this.ybase
!== this.ydisp
) {
2129 this.scrollToBottom();
2131 this.emit('data', data
);
2136 * Emit the 'title' event and populate the given title.
2137 * @param {string} title The title to populate in the event.
2139 Terminal
.prototype.handleTitle = function(title
) {
2141 * This event is emitted when the title of the terminal is changed
2142 * from inside the terminal. The parameter is the new title.
2146 this.emit('title', title
);
2155 * ESC D Index (IND is 0x84).
2157 Terminal
.prototype.index = function() {
2159 if (this.y
> this.scrollBottom
) {
2163 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2164 if (this.x
>= this.cols
) {
2171 * ESC M Reverse Index (RI is 0x8d).
2173 * Move the cursor up one row, inserting a new blank line if necessary.
2175 Terminal
.prototype.reverseIndex = function() {
2177 if (this.y
=== this.scrollTop
) {
2178 // possibly move the code below to term.reverseScroll();
2179 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2180 // blankLine(true) is xterm/linux behavior
2181 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2182 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2183 this.updateRange(this.scrollTop
);
2184 this.updateRange(this.scrollBottom
);
2192 * ESC c Full Reset (RIS).
2194 Terminal
.prototype.reset = function() {
2195 this.options
.rows
= this.rows
;
2196 this.options
.cols
= this.cols
;
2197 var customKeydownHandler
= this.customKeydownHandler
;
2198 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2199 Terminal
.call(this, this.options
);
2200 this.customKeydownHandler
= customKeydownHandler
;
2201 this.cursorBlinkInterval
= cursorBlinkInterval
;
2202 this.refresh(0, this.rows
- 1);
2203 this.viewport
.syncScrollArea();
2208 * ESC H Tab Set (HTS is 0x88).
2210 Terminal
.prototype.tabSet = function() {
2211 this.tabs
[this.x
] = true;
2218 function on(el
, type
, handler
, capture
) {
2219 if (!Array
.isArray(el
)) {
2222 el
.forEach(function (element
) {
2223 element
.addEventListener(type
, handler
, capture
|| false);
2227 function off(el
, type
, handler
, capture
) {
2228 el
.removeEventListener(type
, handler
, capture
|| false);
2231 function cancel(ev
, force
) {
2232 if (!this.cancelEvents
&& !force
) {
2235 ev
.preventDefault();
2236 ev
.stopPropagation();
2240 function inherits(child
, parent
) {
2242 this.constructor = child
;
2244 f
.prototype = parent
.prototype;
2245 child
.prototype = new f
;
2248 function indexOf(obj
, el
) {
2251 if (obj
[i
] === el
) return i
;
2256 function isThirdLevelShift(term
, ev
) {
2258 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2259 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2261 if (ev
.type
== 'keypress') {
2262 return thirdLevelKey
;
2265 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2266 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2269 // Expose to InputHandler (temporary)
2270 Terminal
.prototype.matchColor
= matchColor
;
2272 function matchColor(r1
, g1
, b1
) {
2273 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2275 if (matchColor
._cache
[hash
] != null) {
2276 return matchColor
._cache
[hash
];
2279 var ldiff
= Infinity
2288 for (; i
< Terminal
.vcolors
.length
; i
++) {
2289 c
= Terminal
.vcolors
[i
];
2294 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2307 return matchColor
._cache
[hash
] = li
;
2310 matchColor
._cache
= {};
2312 // http://stackoverflow.com/questions/1633828
2313 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2314 return Math
.pow(30 * (r1
- r2
), 2)
2315 + Math
.pow(59 * (g1
- g2
), 2)
2316 + Math
.pow(11 * (b1
- b2
), 2);
2319 function each(obj
, iter
, con
) {
2320 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2321 for (var i
= 0; i
< obj
.length
; i
++) {
2322 iter
.call(con
, obj
[i
], i
, obj
);
2326 function wasMondifierKeyOnlyEvent(ev
) {
2327 return ev
.keyCode
=== 16 || // Shift
2328 ev
.keyCode
=== 17 || // Ctrl
2329 ev
.keyCode
=== 18; // Alt
2332 function keys(obj
) {
2333 if (Object
.keys
) return Object
.keys(obj
);
2336 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2347 Terminal
.EventEmitter
= EventEmitter
;
2348 Terminal
.inherits
= inherits
;
2351 * Adds an event listener to the terminal.
2353 * @param {string} event The name of the event. TODO: Document all event types
2354 * @param {function} callback The function to call when the event is triggered.
2358 Terminal
.cancel
= cancel
;
2360 module
.exports
= Terminal
;