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 { CharMeasure
} from './utils/CharMeasure';
24 import * as Browser
from './utils/Browser';
25 import * as Keyboard
from './utils/Keyboard';
26 import { CHARSETS
} from './Charsets';
29 * Terminal Emulation References:
31 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
32 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
33 * http://invisible-island.net/vttest/
34 * http://www.inwap.com/pdp10/ansicode.txt
35 * http://linux.die.net/man/4/console_codes
36 * http://linux.die.net/man/7/urxvt
39 // Let it work inside Node.js for automated testing purposes.
40 var document
= (typeof window
!= 'undefined') ? window
.document
: null;
43 * The amount of write requests to queue before sending an XOFF signal to the
44 * pty process. This number must be small in order for ^C and similar sequences
47 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
50 * The number of writes to perform in a single batch before allowing the
51 * renderer to catch up with a 0ms setTimeout.
53 var WRITE_BATCH_SIZE
= 300;
56 * The time between cursor blinks. This is driven by JS rather than a CSS
57 * animation due to a bug in Chromium that causes it to use excessive CPU time.
58 * See https://github.com/Microsoft/vscode/issues/22900
60 var CURSOR_BLINK_INTERVAL
= 600;
67 * Creates a new `Terminal` object.
69 * @param {object} options An object containing a set of options, the available options are:
70 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
71 * - `cols` (number): The number of columns of the terminal (horizontal size)
72 * - `rows` (number): The number of rows of the terminal (vertical size)
76 * @alias module:xterm/src/xterm
78 function Terminal(options
) {
81 if (!(this instanceof Terminal
)) {
82 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
85 self
.browser
= Browser
;
86 self
.cancel
= Terminal
.cancel
;
88 EventEmitter
.call(this);
90 if (typeof options
=== 'number') {
98 options
= options
|| {};
101 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
102 if (options
[key
] == null) {
103 options
[key
] = Terminal
.options
[key
];
105 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
106 options
[key
] = Terminal
[key
];
109 self
[key
] = options
[key
];
112 if (options
.colors
.length
=== 8) {
113 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
114 } else if (options
.colors
.length
=== 16) {
115 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
116 } else if (options
.colors
.length
=== 10) {
117 options
.colors
= options
.colors
.slice(0, -2).concat(
118 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
119 } else if (options
.colors
.length
=== 18) {
120 options
.colors
= options
.colors
.concat(
121 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
123 this.colors
= options
.colors
;
125 this.options
= options
;
127 // this.context = options.context || window;
128 // this.document = options.document || document;
129 this.parent
= options
.body
|| options
.parent
|| (
130 document
? document
.getElementsByTagName('body')[0] : null
133 this.cols
= options
.cols
|| options
.geometry
[0];
134 this.rows
= options
.rows
|| options
.geometry
[1];
135 this.geometry
= [this.cols
, this.rows
];
137 if (options
.handler
) {
138 this.on('data', options
.handler
);
142 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
148 * The scroll position of the viewport
153 * The cursor's x position after ybase
158 * The cursor's y position after ybase
162 this.cursorState
= 0;
163 this.cursorHidden
= false;
167 this.scrollBottom
= this.rows
- 1;
168 this.customKeydownHandler
= null;
169 this.cursorBlinkInterval
= null;
172 this.applicationKeypad
= false;
173 this.applicationCursor
= false;
174 this.originMode
= false;
175 this.insertMode
= false;
176 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
181 this.gcharset
= null;
183 this.charsets
= [null];
207 this.readable
= true;
208 this.writable
= true;
210 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
211 this.curAttr
= this.defAttr
;
214 this.currentParam
= 0;
218 this.inputHandler
= new InputHandler(this);
219 this.parser
= new Parser(this.inputHandler
, this);
220 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
221 this.renderer
= this.renderer
|| null;
222 this.linkifier
= this.linkifier
|| new Linkifier();
225 this.writeBuffer
= [];
226 this.writeInProgress
= false;
229 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
230 * This is a distinct state from writeStopped so that if the user requested
231 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
234 this.xoffSentToCatchUp
= false;
236 /** Whether writing has been stopped as a result of XOFF */
237 this.writeStopped
= false;
239 // leftover surrogate high from previous write invocation
240 this.surrogate_high
= '';
243 * An array of all lines in the entire buffer, including the prompt. The lines are array of
244 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
246 this.lines
= new CircularList(this.scrollback
);
249 this.lines
.push(this.blankLine());
255 // Store if user went browsing history in scrollback
256 this.userScrolling
= false;
259 inherits(Terminal
, EventEmitter
);
262 * back_color_erase feature for xterm.
264 Terminal
.prototype.eraseAttr = function() {
265 // if (this.is('screen')) return this.defAttr;
266 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
274 Terminal
.tangoColors
= [
295 // Colors 0-15 + 16-255
296 // Much thanks to TooTallNate for writing this.
297 Terminal
.colors
= (function() {
298 var colors
= Terminal
.tangoColors
.slice()
299 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
304 for (; i
< 216; i
++) {
305 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
310 for (; i
< 24; i
++) {
315 function out(r
, g
, b
) {
316 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
321 return c
.length
< 2 ? '0' + c
: c
;
327 Terminal
._colors
= Terminal
.colors
.slice();
329 Terminal
.vcolors
= (function() {
331 , colors
= Terminal
.colors
335 for (; i
< 256; i
++) {
336 color
= parseInt(colors
[i
].substring(1), 16);
338 (color
>> 16) & 0xff,
351 Terminal
.defaults
= {
352 colors
: Terminal
.colors
,
358 cursorStyle
: 'block',
366 useFlowControl
: false,
368 // programFeatures: false,
372 Terminal
.options
= {};
374 Terminal
.focus
= null;
376 each(keys(Terminal
.defaults
), function(key
) {
377 Terminal
[key
] = Terminal
.defaults
[key
];
378 Terminal
.options
[key
] = Terminal
.defaults
[key
];
382 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
384 Terminal
.prototype.focus = function() {
385 return this.textarea
.focus();
389 * Retrieves an option's value from the terminal.
390 * @param {string} key The option key.
392 Terminal
.prototype.getOption = function(key
, value
) {
393 if (!(key
in Terminal
.defaults
)) {
394 throw new Error('No option with key "' + key
+ '"');
397 if (typeof this.options
[key
] !== 'undefined') {
398 return this.options
[key
];
405 * Sets an option on the terminal.
406 * @param {string} key The option key.
407 * @param {string} value The option value.
409 Terminal
.prototype.setOption = function(key
, value
) {
410 if (!(key
in Terminal
.defaults
)) {
411 throw new Error('No option with key "' + key
+ '"');
415 if (this.options
[key
] !== value
) {
416 if (this.lines
.length
> value
) {
417 const amountToTrim
= this.lines
.length
- value
;
418 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
419 this.lines
.trimStart(amountToTrim
);
420 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
421 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
423 this.refresh(0, this.rows
- 1);
426 this.lines
.maxLength
= value
;
427 this.viewport
.syncScrollArea();
432 this.options
[key
] = value
;
434 case 'cursorBlink': this.setCursorBlinking(value
); break;
436 // Style 'block' applies with no class
437 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
438 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
440 case 'tabStopWidth': this.setupStops(); break;
444 Terminal
.prototype.restartCursorBlinking = function () {
445 this.setCursorBlinking(this.options
.cursorBlink
);
448 Terminal
.prototype.setCursorBlinking = function (enabled
) {
449 this.element
.classList
.toggle('xterm-cursor-blink', enabled
);
450 this.clearCursorBlinkingInterval();
453 this.cursorBlinkInterval
= setInterval(function () {
454 self
.element
.classList
.toggle('xterm-cursor-blink-on');
455 }, CURSOR_BLINK_INTERVAL
);
459 Terminal
.prototype.clearCursorBlinkingInterval = function () {
460 this.element
.classList
.remove('xterm-cursor-blink-on');
461 if (this.cursorBlinkInterval
) {
462 clearInterval(this.cursorBlinkInterval
);
463 this.cursorBlinkInterval
= null;
468 * Binds the desired focus behavior on a given terminal object.
472 Terminal
.bindFocus = function (term
) {
473 on(term
.textarea
, 'focus', function (ev
) {
474 if (term
.sendFocus
) {
475 term
.send(C0
.ESC
+ '[I');
477 term
.element
.classList
.add('focus');
479 term
.restartCursorBlinking
.apply(term
);
480 Terminal
.focus
= term
;
481 term
.emit('focus', {terminal
: term
});
486 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
488 Terminal
.prototype.blur = function() {
489 return this.textarea
.blur();
493 * Binds the desired blur behavior on a given terminal object.
497 Terminal
.bindBlur = function (term
) {
498 on(term
.textarea
, 'blur', function (ev
) {
499 term
.refresh(term
.y
, term
.y
);
500 if (term
.sendFocus
) {
501 term
.send(C0
.ESC
+ '[O');
503 term
.element
.classList
.remove('focus');
504 term
.clearCursorBlinkingInterval
.apply(term
);
505 Terminal
.focus
= null;
506 term
.emit('blur', {terminal
: term
});
511 * Initialize default behavior
513 Terminal
.prototype.initGlobal = function() {
516 Terminal
.bindKeys(this);
517 Terminal
.bindFocus(this);
518 Terminal
.bindBlur(this);
520 // Bind clipboard functionality
521 on(this.element
, 'copy', function (ev
) {
522 copyHandler
.call(this, ev
, term
);
524 on(this.textarea
, 'paste', function (ev
) {
525 pasteHandler
.call(this, ev
, term
);
527 on(this.element
, 'paste', function (ev
) {
528 pasteHandler
.call(this, ev
, term
);
531 function rightClickHandlerWrapper (ev
) {
532 rightClickHandler
.call(this, ev
, term
);
535 if (term
.browser
.isFirefox
) {
536 on(this.element
, 'mousedown', function (ev
) {
537 if (ev
.button
== 2) {
538 rightClickHandlerWrapper(ev
);
542 on(this.element
, 'contextmenu', rightClickHandlerWrapper
);
547 * Apply key handling to the terminal
549 Terminal
.bindKeys = function(term
) {
550 on(term
.element
, 'keydown', function(ev
) {
551 if (document
.activeElement
!= this) {
557 on(term
.element
, 'keypress', function(ev
) {
558 if (document
.activeElement
!= this) {
564 on(term
.element
, 'keyup', function(ev
) {
565 if (!wasMondifierKeyOnlyEvent(ev
)) {
570 on(term
.textarea
, 'keydown', function(ev
) {
574 on(term
.textarea
, 'keypress', function(ev
) {
576 // Truncate the textarea's value, since it is not needed
580 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
581 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
582 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
583 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
584 term
.on('refresh', function (data
) {
585 term
.queueLinkification(data
.start
, data
.end
)
591 * Insert the given row to the terminal or produce a new one
592 * if no row argument is passed. Return the inserted row.
593 * @param {HTMLElement} row (optional) The row to append to the terminal.
595 Terminal
.prototype.insertRow = function (row
) {
596 if (typeof row
!= 'object') {
597 row
= document
.createElement('div');
600 this.rowContainer
.appendChild(row
);
601 this.children
.push(row
);
607 * Opens the terminal within an element.
609 * @param {HTMLElement} parent The element to create the terminal within.
611 Terminal
.prototype.open = function(parent
) {
612 var self
=this, i
=0, div
;
614 this.parent
= parent
|| this.parent
;
617 throw new Error('Terminal requires a parent element.');
620 // Grab global elements
621 this.context
= this.parent
.ownerDocument
.defaultView
;
622 this.document
= this.parent
.ownerDocument
;
623 this.body
= this.document
.getElementsByTagName('body')[0];
625 //Create main element container
626 this.element
= this.document
.createElement('div');
627 this.element
.classList
.add('terminal');
628 this.element
.classList
.add('xterm');
629 this.element
.classList
.add('xterm-theme-' + this.theme
);
630 this.setCursorBlinking(this.options
.cursorBlink
);
632 this.element
.style
.height
633 this.element
.setAttribute('tabindex', 0);
635 this.viewportElement
= document
.createElement('div');
636 this.viewportElement
.classList
.add('xterm-viewport');
637 this.element
.appendChild(this.viewportElement
);
638 this.viewportScrollArea
= document
.createElement('div');
639 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
640 this.viewportElement
.appendChild(this.viewportScrollArea
);
642 // Create the container that will hold the lines of the terminal and then
643 // produce the lines the lines.
644 this.rowContainer
= document
.createElement('div');
645 this.rowContainer
.classList
.add('xterm-rows');
646 this.element
.appendChild(this.rowContainer
);
648 this.linkifier
.attachToDom(document
, this.children
);
650 // Create the container that will hold helpers like the textarea for
651 // capturing DOM Events. Then produce the helpers.
652 this.helperContainer
= document
.createElement('div');
653 this.helperContainer
.classList
.add('xterm-helpers');
654 // TODO: This should probably be inserted once it's filled to prevent an additional layout
655 this.element
.appendChild(this.helperContainer
);
656 this.textarea
= document
.createElement('textarea');
657 this.textarea
.classList
.add('xterm-helper-textarea');
658 this.textarea
.setAttribute('autocorrect', 'off');
659 this.textarea
.setAttribute('autocapitalize', 'off');
660 this.textarea
.setAttribute('spellcheck', 'false');
661 this.textarea
.tabIndex
= 0;
662 this.textarea
.addEventListener('focus', function() {
663 self
.emit('focus', {terminal
: self
});
665 this.textarea
.addEventListener('blur', function() {
666 self
.emit('blur', {terminal
: self
});
668 this.helperContainer
.appendChild(this.textarea
);
670 this.compositionView
= document
.createElement('div');
671 this.compositionView
.classList
.add('composition-view');
672 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
673 this.helperContainer
.appendChild(this.compositionView
);
675 this.charSizeStyleElement
= document
.createElement('style');
676 this.helperContainer
.appendChild(this.charSizeStyleElement
);
678 for (; i
< this.rows
; i
++) {
681 this.parent
.appendChild(this.element
);
683 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
684 this.charMeasure
.on('charsizechanged', function () {
685 self
.updateCharSizeCSS();
687 this.charMeasure
.measure();
689 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
690 this.renderer
= new Renderer(this);
692 // Setup loop that draws to screen
693 this.refresh(0, this.rows
- 1);
695 // Initialize global actions that
696 // need to be taken on the document.
699 // Ensure there is a Terminal.focus.
702 on(this.element
, 'click', function() {
703 var selection
= document
.getSelection(),
704 collapsed
= selection
.isCollapsed
,
705 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
711 // Listen for mouse events and translate
712 // them into terminal mouse protocols.
716 * This event is emitted when terminal has completed opening.
725 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
726 * @param {string} addon The name of the addon to load
729 Terminal
.loadAddon = function(addon
, callback
) {
730 if (typeof exports
=== 'object' && typeof module
=== 'object') {
732 return require('./addons/' + addon
+ '/' + addon
);
733 } else if (typeof define
== 'function') {
735 return require(['./addons/' + addon
+ '/' + addon
], callback
);
737 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
743 * Updates the helper CSS class with any changes necessary after the terminal's
744 * character width has been changed.
746 Terminal
.prototype.updateCharSizeCSS = function() {
747 this.charSizeStyleElement
.textContent
= '.xterm-wide-char{width:' + (this.charMeasure
.width
* 2) + 'px;}';
752 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
753 * To better understand these
754 * the xterm code is very helpful:
756 * button.c, charproc.c, misc.c
757 * Relevant functions in xterm/button.c:
758 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
760 Terminal
.prototype.bindMouse = function() {
761 var el
= this.element
, self
= this, pressed
= 32;
763 // mouseup, mousedown, wheel
764 // left click: ^[[M 3<^[[M#3<
766 function sendButton(ev
) {
770 // get the xterm-style button
771 button
= getButton(ev
);
773 // get mouse coordinates
777 sendEvent(button
, pos
);
779 switch (ev
.overrideType
|| ev
.type
) {
784 // keep it at the left
785 // button, just in case.
796 // motion example of a left click:
797 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
798 function sendMove(ev
) {
805 // buttons marked as motions
806 // are incremented by 32
809 sendEvent(button
, pos
);
813 // position to characters
814 function encode(data
, ch
) {
815 if (!self
.utfMouse
) {
816 if (ch
=== 255) return data
.push(0);
817 if (ch
> 127) ch
= 127;
820 if (ch
=== 2047) return data
.push(0);
824 if (ch
> 2047) ch
= 2047;
825 data
.push(0xC0 | (ch
>> 6));
826 data
.push(0x80 | (ch
& 0x3F));
831 // send a mouse event:
832 // regular/utf8: ^[[M Cb Cx Cy
833 // urxvt: ^[[ Cb ; Cx ; Cy M
834 // sgr: ^[[ Cb ; Cx ; Cy M/m
835 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
836 // locator: CSI P e ; P b ; P r ; P c ; P p & w
837 function sendEvent(button
, pos
) {
838 // self.emit('mouse', {
844 if (self
.vt300Mouse
) {
846 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
850 var data
= C0
.ESC
+ '[24';
851 if (button
=== 0) data
+= '1';
852 else if (button
=== 1) data
+= '3';
853 else if (button
=== 2) data
+= '5';
854 else if (button
=== 3) return;
856 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
861 if (self
.decLocator
) {
866 if (button
=== 0) button
= 2;
867 else if (button
=== 1) button
= 4;
868 else if (button
=== 2) button
= 6;
869 else if (button
=== 3) button
= 3;
870 self
.send(C0
.ESC
+ '['
873 + (button
=== 3 ? 4 : 0)
884 if (self
.urxvtMouse
) {
889 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
896 self
.send(C0
.ESC
+ '[<'
897 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
902 + ((button
& 3) === 3 ? 'm' : 'M'));
908 encode(data
, button
);
912 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
915 function getButton(ev
) {
928 // 1, and 2 - with 64 added
929 switch (ev
.overrideType
|| ev
.type
) {
931 button
= ev
.button
!= null
937 if (self
.browser
.isMSIE
) {
938 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
944 case 'DOMMouseScroll':
945 button
= ev
.detail
< 0
950 button
= ev
.wheelDeltaY
> 0
956 // next three bits are the modifiers:
957 // 4 = shift, 8 = meta, 16 = control
958 shift
= ev
.shiftKey
? 4 : 0;
959 meta
= ev
.metaKey
? 8 : 0;
960 ctrl
= ev
.ctrlKey
? 16 : 0;
961 mod
= shift
| meta
| ctrl
;
964 if (self
.vt200Mouse
) {
967 } else if (!self
.normalMouse
) {
972 button
= (32 + (mod
<< 2)) + button
;
977 // mouse coordinates measured in cols/rows
978 function getCoords(ev
) {
981 // ignore browsers without pageX for now
982 if (ev
.pageX
== null) return;
988 // should probably check offsetParent
989 // but this is more portable
990 while (el
&& el
!== self
.document
.documentElement
) {
993 el
= 'offsetParent' in el
998 // convert to cols/rows
999 x
= Math
.ceil(x
/ self
.charMeasure
.width
);
1000 y
= Math
.ceil(y
/ self
.charMeasure
.height
);
1002 // be sure to avoid sending
1003 // bad positions to the program
1005 if (x
> self
.cols
) x
= self
.cols
;
1007 if (y
> self
.rows
) y
= self
.rows
;
1009 // xterm sends raw bytes and
1010 // starts at 32 (SP) for each.
1021 on(el
, 'mousedown', function(ev
) {
1022 if (!self
.mouseEvents
) return;
1031 //if (self.vt200Mouse && !self.normalMouse) {
1032 if (self
.vt200Mouse
) {
1033 ev
.overrideType
= 'mouseup';
1035 return self
.cancel(ev
);
1039 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1041 // x10 compatibility mode can't send button releases
1042 if (!self
.x10Mouse
) {
1043 on(self
.document
, 'mouseup', function up(ev
) {
1045 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1046 off(self
.document
, 'mouseup', up
);
1047 return self
.cancel(ev
);
1051 return self
.cancel(ev
);
1054 //if (self.normalMouse) {
1055 // on(self.document, 'mousemove', sendMove);
1058 on(el
, 'wheel', function(ev
) {
1059 if (!self
.mouseEvents
) return;
1062 || self
.decLocator
) return;
1064 return self
.cancel(ev
);
1067 // allow wheel scrolling in
1068 // the shell for example
1069 on(el
, 'wheel', function(ev
) {
1070 if (self
.mouseEvents
) return;
1071 self
.viewport
.onWheel(ev
);
1072 return self
.cancel(ev
);
1077 * Destroys the terminal.
1079 Terminal
.prototype.destroy = function() {
1080 this.readable
= false;
1081 this.writable
= false;
1083 this.handler = function() {};
1084 this.write = function() {};
1085 if (this.element
&& this.element
.parentNode
) {
1086 this.element
.parentNode
.removeChild(this.element
);
1088 //this.emit('close');
1092 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1094 * @param {number} start The row to start from (between 0 and this.rows - 1).
1095 * @param {number} end The row to end at (between start and this.rows - 1).
1097 Terminal
.prototype.refresh = function(start
, end
) {
1098 if (this.renderer
) {
1099 this.renderer
.queueRefresh(start
, end
);
1104 * Queues linkification for the specified rows.
1105 * @param {number} start The row to start from (between 0 and this.rows - 1).
1106 * @param {number} end The row to end at (between start and this.rows - 1).
1108 Terminal
.prototype.queueLinkification = function(start
, end
) {
1109 if (this.linkifier
) {
1110 for (let i
= start
; i
<= end
; i
++) {
1111 this.linkifier
.linkifyRow(i
);
1117 * Display the cursor element
1119 Terminal
.prototype.showCursor = function() {
1120 if (!this.cursorState
) {
1121 this.cursorState
= 1;
1122 this.refresh(this.y
, this.y
);
1127 * Scroll the terminal down 1 row, creating a blank line.
1129 Terminal
.prototype.scroll = function() {
1132 // Make room for the new row in lines
1133 if (this.lines
.length
=== this.lines
.maxLength
) {
1134 this.lines
.trimStart(1);
1136 if (this.ydisp
!== 0) {
1143 // TODO: Why is this done twice?
1144 if (!this.userScrolling
) {
1145 this.ydisp
= this.ybase
;
1149 row
= this.ybase
+ this.rows
- 1;
1151 // subtract the bottom scroll region
1152 row
-= this.rows
- 1 - this.scrollBottom
;
1154 if (row
=== this.lines
.length
) {
1155 // Optimization: pushing is faster than splicing when they amount to the same behavior
1156 this.lines
.push(this.blankLine());
1159 this.lines
.splice(row
, 0, this.blankLine());
1162 if (this.scrollTop
!== 0) {
1163 if (this.ybase
!== 0) {
1165 if (!this.userScrolling
) {
1166 this.ydisp
= this.ybase
;
1169 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1173 this.updateRange(this.scrollTop
);
1174 this.updateRange(this.scrollBottom
);
1177 * This event is emitted whenever the terminal is scrolled.
1178 * The one parameter passed is the new y display position.
1182 this.emit('scroll', this.ydisp
);
1186 * Scroll the display of the terminal
1187 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1188 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1189 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1190 * viewport originally.
1192 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1194 this.userScrolling
= true;
1195 } else if (disp
+ this.ydisp
>= this.ybase
) {
1196 this.userScrolling
= false;
1201 if (this.ydisp
> this.ybase
) {
1202 this.ydisp
= this.ybase
;
1203 } else if (this.ydisp
< 0) {
1207 if (!suppressScrollEvent
) {
1208 this.emit('scroll', this.ydisp
);
1211 this.refresh(0, this.rows
- 1);
1215 * Scroll the display of the terminal by a number of pages.
1216 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1218 Terminal
.prototype.scrollPages = function(pageCount
) {
1219 this.scrollDisp(pageCount
* (this.rows
- 1));
1223 * Scrolls the display of the terminal to the top.
1225 Terminal
.prototype.scrollToTop = function() {
1226 this.scrollDisp(-this.ydisp
);
1230 * Scrolls the display of the terminal to the bottom.
1232 Terminal
.prototype.scrollToBottom = function() {
1233 this.scrollDisp(this.ybase
- this.ydisp
);
1237 * Writes text to the terminal.
1238 * @param {string} text The text to write to the terminal.
1240 Terminal
.prototype.write = function(data
) {
1241 this.writeBuffer
.push(data
);
1243 // Send XOFF to pause the pty process if the write buffer becomes too large so
1244 // xterm.js can catch up before more data is sent. This is necessary in order
1245 // to keep signals such as ^C responsive.
1246 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1247 // XOFF - stop pty pipe
1248 // XON will be triggered by emulator before processing data chunk
1250 this.xoffSentToCatchUp
= true;
1253 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1254 // Kick off a write which will write all data in sequence recursively
1255 this.writeInProgress
= true;
1256 // Kick off an async innerWrite so more writes can come in while processing data
1258 setTimeout(function () {
1264 Terminal
.prototype.innerWrite = function() {
1265 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1266 while (writeBatch
.length
> 0) {
1267 var data
= writeBatch
.shift();
1268 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1270 // If XOFF was sent in order to catch up with the pty process, resume it if
1271 // the writeBuffer is empty to allow more data to come in.
1272 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1274 this.xoffSentToCatchUp
= false;
1277 this.refreshStart
= this.y
;
1278 this.refreshEnd
= this.y
;
1280 this.parser
.parse(data
);
1282 this.updateRange(this.y
);
1283 this.refresh(this.refreshStart
, this.refreshEnd
);
1285 if (this.writeBuffer
.length
> 0) {
1286 // Allow renderer to catch up before processing the next batch
1288 setTimeout(function () {
1292 this.writeInProgress
= false;
1297 * Writes text to the terminal, followed by a break line character (\n).
1298 * @param {string} text The text to write to the terminal.
1300 Terminal
.prototype.writeln = function(data
) {
1301 this.write(data
+ '\r\n');
1305 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1306 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1308 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1309 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1310 * the default action. The function returns whether the event should be processed by xterm.js.
1312 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1313 this.customKeydownHandler
= customKeydownHandler
;
1317 * Attaches a http(s) link handler, forcing web links to behave differently to
1318 * regular <a> tags. This will trigger a refresh as links potentially need to be
1319 * reconstructed. Calling this with null will remove the handler.
1320 * @param {LinkHandler} handler The handler callback function.
1322 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1323 if (!this.linkifier
) {
1324 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1326 this.linkifier
.setHypertextLinkHandler(handler
);
1327 // Refresh to force links to refresh
1328 this.refresh(0, this.rows
- 1);
1332 * Attaches a validation callback for hypertext links. This is useful to use
1333 * validation logic or to do something with the link's element and url.
1334 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1335 * be cleared with null.
1337 Terminal
.prototype.setHypertextValidationCallback = function(handler
) {
1338 if (!this.linkifier
) {
1339 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1341 this.linkifier
.setHypertextValidationCallback(handler
);
1342 // Refresh to force links to refresh
1343 this.refresh(0, this.rows
- 1);
1347 * Registers a link matcher, allowing custom link patterns to be matched and
1349 * @param {RegExp} regex The regular expression to search for, specifically
1350 * this searches the textContent of the rows. You will want to use \s to match
1351 * a space ' ' character for example.
1352 * @param {LinkHandler} handler The callback when the link is called.
1353 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1354 * @return {number} The ID of the new matcher, this can be used to deregister.
1356 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1357 if (this.linkifier
) {
1358 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1359 this.refresh(0, this.rows
- 1);
1365 * Deregisters a link matcher if it has been registered.
1366 * @param {number} matcherId The link matcher's ID (returned after register)
1368 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1369 if (this.linkifier
) {
1370 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1371 this.refresh(0, this.rows
- 1);
1377 * Handle a keydown event
1379 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1380 * @param {KeyboardEvent} ev The keydown event to be handled.
1382 Terminal
.prototype.keyDown = function(ev
) {
1383 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1387 this.restartCursorBlinking();
1389 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1390 if (this.ybase
!== this.ydisp
) {
1391 this.scrollToBottom();
1397 var result
= this.evaluateKeyEscapeSequence(ev
);
1399 if (result
.key
=== C0
.DC3
) { // XOFF
1400 this.writeStopped
= true;
1401 } else if (result
.key
=== C0
.DC1
) { // XON
1402 this.writeStopped
= false;
1405 if (result
.scrollDisp
) {
1406 this.scrollDisp(result
.scrollDisp
);
1407 return this.cancel(ev
, true);
1410 if (isThirdLevelShift(this, ev
)) {
1414 if (result
.cancel
) {
1415 // The event is canceled at the end already, is this necessary?
1416 this.cancel(ev
, true);
1423 this.emit('keydown', ev
);
1424 this.emit('key', result
.key
, ev
);
1426 this.handler(result
.key
);
1428 return this.cancel(ev
, true);
1432 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1433 * returned value is the new key code to pass to the PTY.
1435 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1436 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1438 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1440 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1441 // canceled at the end of keyDown
1443 // The new key even to emit
1445 // The number of characters to scroll, if this is defined it will cancel the event
1446 scrollDisp
: undefined
1448 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1449 switch (ev
.keyCode
) {
1453 result
.key
= C0
.BS
; // ^H
1456 result
.key
= C0
.DEL
; // ^?
1461 result
.key
= C0
.ESC
+ '[Z';
1465 result
.cancel
= true;
1470 result
.cancel
= true;
1474 result
.key
= C0
.ESC
;
1475 result
.cancel
= true;
1480 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1481 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1482 // http://unix.stackexchange.com/a/108106
1483 // macOS uses different escape sequences than linux
1484 if (result
.key
== C0
.ESC
+ '[1;3D') {
1485 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1487 } else if (this.applicationCursor
) {
1488 result
.key
= C0
.ESC
+ 'OD';
1490 result
.key
= C0
.ESC
+ '[D';
1496 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1497 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1498 // http://unix.stackexchange.com/a/108106
1499 // macOS uses different escape sequences than linux
1500 if (result
.key
== C0
.ESC
+ '[1;3C') {
1501 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1503 } else if (this.applicationCursor
) {
1504 result
.key
= C0
.ESC
+ 'OC';
1506 result
.key
= C0
.ESC
+ '[C';
1512 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1513 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1514 // http://unix.stackexchange.com/a/108106
1515 if (result
.key
== C0
.ESC
+ '[1;3A') {
1516 result
.key
= C0
.ESC
+ '[1;5A';
1518 } else if (this.applicationCursor
) {
1519 result
.key
= C0
.ESC
+ 'OA';
1521 result
.key
= C0
.ESC
+ '[A';
1527 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1528 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1529 // http://unix.stackexchange.com/a/108106
1530 if (result
.key
== C0
.ESC
+ '[1;3B') {
1531 result
.key
= C0
.ESC
+ '[1;5B';
1533 } else if (this.applicationCursor
) {
1534 result
.key
= C0
.ESC
+ 'OB';
1536 result
.key
= C0
.ESC
+ '[B';
1541 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1542 // <Ctrl> or <Shift> + <Insert> are used to
1543 // copy-paste on some systems.
1544 result
.key
= C0
.ESC
+ '[2~';
1550 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1552 result
.key
= C0
.ESC
+ '[3~';
1558 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1559 else if (this.applicationCursor
)
1560 result
.key
= C0
.ESC
+ 'OH';
1562 result
.key
= C0
.ESC
+ '[H';
1567 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1568 else if (this.applicationCursor
)
1569 result
.key
= C0
.ESC
+ 'OF';
1571 result
.key
= C0
.ESC
+ '[F';
1576 result
.scrollDisp
= -(this.rows
- 1);
1578 result
.key
= C0
.ESC
+ '[5~';
1584 result
.scrollDisp
= this.rows
- 1;
1586 result
.key
= C0
.ESC
+ '[6~';
1592 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1594 result
.key
= C0
.ESC
+ 'OP';
1599 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1601 result
.key
= C0
.ESC
+ 'OQ';
1606 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1608 result
.key
= C0
.ESC
+ 'OR';
1613 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1615 result
.key
= C0
.ESC
+ 'OS';
1620 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1622 result
.key
= C0
.ESC
+ '[15~';
1627 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1629 result
.key
= C0
.ESC
+ '[17~';
1634 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1636 result
.key
= C0
.ESC
+ '[18~';
1641 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1643 result
.key
= C0
.ESC
+ '[19~';
1648 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1650 result
.key
= C0
.ESC
+ '[20~';
1655 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1657 result
.key
= C0
.ESC
+ '[21~';
1662 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1664 result
.key
= C0
.ESC
+ '[23~';
1669 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1671 result
.key
= C0
.ESC
+ '[24~';
1676 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1677 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1678 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1679 } else if (ev
.keyCode
=== 32) {
1681 result
.key
= String
.fromCharCode(0);
1682 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1683 // escape, file sep, group sep, record sep, unit sep
1684 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1685 } else if (ev
.keyCode
=== 56) {
1687 result
.key
= String
.fromCharCode(127);
1688 } else if (ev
.keyCode
=== 219) {
1689 // ^[ - Control Sequence Introducer (CSI)
1690 result
.key
= String
.fromCharCode(27);
1691 } else if (ev
.keyCode
=== 220) {
1692 // ^\ - String Terminator (ST)
1693 result
.key
= String
.fromCharCode(28);
1694 } else if (ev
.keyCode
=== 221) {
1695 // ^] - Operating System Command (OSC)
1696 result
.key
= String
.fromCharCode(29);
1698 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1699 // On Mac this is a third level shift. Use <Esc> instead.
1700 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1701 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1702 } else if (ev
.keyCode
=== 192) {
1703 result
.key
= C0
.ESC
+ '`';
1704 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1705 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1715 * Set the G level of the terminal
1718 Terminal
.prototype.setgLevel = function(g
) {
1720 this.charset
= this.charsets
[g
];
1724 * Set the charset for the given G level of the terminal
1728 Terminal
.prototype.setgCharset = function(g
, charset
) {
1729 this.charsets
[g
] = charset
;
1730 if (this.glevel
=== g
) {
1731 this.charset
= charset
;
1736 * Handle a keypress event.
1738 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1739 * @param {KeyboardEvent} ev The keypress event to be handled.
1741 Terminal
.prototype.keyPress = function(ev
) {
1748 } else if (ev
.which
== null) {
1750 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1757 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1762 key
= String
.fromCharCode(key
);
1764 this.emit('keypress', key
, ev
);
1765 this.emit('key', key
, ev
);
1773 * Send data for handling to the terminal
1774 * @param {string} data
1776 Terminal
.prototype.send = function(data
) {
1780 setTimeout(function() {
1781 self
.handler(self
.queue
);
1791 * Note: We could do sweet things with webaudio here
1793 Terminal
.prototype.bell = function() {
1794 if (!this.visualBell
) return;
1796 this.element
.style
.borderColor
= 'white';
1797 setTimeout(function() {
1798 self
.element
.style
.borderColor
= '';
1800 if (this.popOnBell
) this.focus();
1804 * Log the current state to the console.
1806 Terminal
.prototype.log = function() {
1807 if (!this.debug
) return;
1808 if (!this.context
.console
|| !this.context
.console
.log
) return;
1809 var args
= Array
.prototype.slice
.call(arguments
);
1810 this.context
.console
.log
.apply(this.context
.console
, args
);
1814 * Log the current state as error to the console.
1816 Terminal
.prototype.error = function() {
1817 if (!this.debug
) return;
1818 if (!this.context
.console
|| !this.context
.console
.error
) return;
1819 var args
= Array
.prototype.slice
.call(arguments
);
1820 this.context
.console
.error
.apply(this.context
.console
, args
);
1824 * Resizes the terminal.
1826 * @param {number} x The number of columns to resize to.
1827 * @param {number} y The number of rows to resize to.
1829 Terminal
.prototype.resize = function(x
, y
) {
1830 if (isNaN(x
) || isNaN(y
)) {
1841 if (x
=== this.cols
&& y
=== this.rows
) {
1851 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1852 i
= this.lines
.length
;
1854 while (this.lines
.get(i
).length
< x
) {
1855 this.lines
.get(i
).push(ch
);
1861 this.setupStops(this.cols
);
1869 // y is rows, not this.y
1870 if (this.lines
.length
< y
+ this.ybase
) {
1871 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
1872 // There is room above the buffer and there are no empty elements below the line,
1876 if (this.ydisp
> 0) {
1877 // Viewport is at the top of the buffer, must increase downwards
1881 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1882 // are blank lines after the cursor
1883 this.lines
.push(this.blankLine());
1886 if (this.children
.length
< y
) {
1892 if (this.lines
.length
> y
+ this.ybase
) {
1893 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
1894 // The line is a blank line below the cursor, remove it
1897 // The line is the cursor, scroll down
1902 if (this.children
.length
> y
) {
1903 el
= this.children
.shift();
1905 el
.parentNode
.removeChild(el
);
1911 // Make sure that the cursor stays on screen
1924 this.scrollBottom
= y
- 1;
1926 this.charMeasure
.measure();
1928 this.refresh(0, this.rows
- 1);
1932 this.geometry
= [this.cols
, this.rows
];
1933 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
1937 * Updates the range of rows to refresh
1938 * @param {number} y The number of rows to refresh next.
1940 Terminal
.prototype.updateRange = function(y
) {
1941 if (y
< this.refreshStart
) this.refreshStart
= y
;
1942 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
1943 // if (y > this.refreshEnd) {
1944 // this.refreshEnd = y;
1945 // if (y > this.rows - 1) {
1946 // this.refreshEnd = this.rows - 1;
1952 * Set the range of refreshing to the maximum value
1954 Terminal
.prototype.maxRange = function() {
1955 this.refreshStart
= 0;
1956 this.refreshEnd
= this.rows
- 1;
1962 * Setup the tab stops.
1965 Terminal
.prototype.setupStops = function(i
) {
1967 if (!this.tabs
[i
]) {
1968 i
= this.prevStop(i
);
1975 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
1976 this.tabs
[i
] = true;
1982 * Move the cursor to the previous tab stop from the given position (default is current).
1983 * @param {number} x The position to move the cursor to the previous tab stop.
1985 Terminal
.prototype.prevStop = function(x
) {
1986 if (x
== null) x
= this.x
;
1987 while (!this.tabs
[--x
] && x
> 0);
1988 return x
>= this.cols
1995 * Move the cursor one tab stop forward from the given position (default is current).
1996 * @param {number} x The position to move the cursor one tab stop forward.
1998 Terminal
.prototype.nextStop = function(x
) {
1999 if (x
== null) x
= this.x
;
2000 while (!this.tabs
[++x
] && x
< this.cols
);
2001 return x
>= this.cols
2008 * Erase in the identified line everything from "x" to the end of the line (right).
2009 * @param {number} x The column from which to start erasing to the end of the line.
2010 * @param {number} y The line in which to operate.
2012 Terminal
.prototype.eraseRight = function(x
, y
) {
2013 var line
= this.lines
.get(this.ybase
+ y
);
2017 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2018 for (; x
< this.cols
; x
++) {
2021 this.updateRange(y
);
2027 * Erase in the identified line everything from "x" to the start of the line (left).
2028 * @param {number} x The column from which to start erasing to the start of the line.
2029 * @param {number} y The line in which to operate.
2031 Terminal
.prototype.eraseLeft = function(x
, y
) {
2032 var line
= this.lines
.get(this.ybase
+ y
);
2036 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2041 this.updateRange(y
);
2045 * Clears the entire buffer, making the prompt line the new first line.
2047 Terminal
.prototype.clear = function() {
2048 if (this.ybase
=== 0 && this.y
=== 0) {
2049 // Don't clear if it's already clear
2052 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2053 this.lines
.length
= 1;
2057 for (var i
= 1; i
< this.rows
; i
++) {
2058 this.lines
.push(this.blankLine());
2060 this.refresh(0, this.rows
- 1);
2061 this.emit('scroll', this.ydisp
);
2065 * Erase all content in the given line
2066 * @param {number} y The line to erase all of its contents.
2068 Terminal
.prototype.eraseLine = function(y
) {
2069 this.eraseRight(0, y
);
2074 * Return the data array of a blank line
2075 * @param {number} cur First bunch of data for each "blank" character.
2077 Terminal
.prototype.blankLine = function(cur
) {
2082 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2086 for (; i
< this.cols
; i
++) {
2095 * If cur return the back color xterm feature attribute. Else return defAttr.
2096 * @param {object} cur
2098 Terminal
.prototype.ch = function(cur
) {
2100 ? [this.eraseAttr(), ' ', 1]
2101 : [this.defAttr
, ' ', 1];
2106 * Evaluate if the current erminal is the given argument.
2107 * @param {object} term The terminal to evaluate
2109 Terminal
.prototype.is = function(term
) {
2110 var name
= this.termName
;
2111 return (name
+ '').indexOf(term
) === 0;
2116 * Emit the 'data' event and populate the given data.
2117 * @param {string} data The data to populate in the event.
2119 Terminal
.prototype.handler = function(data
) {
2120 // Prevents all events to pty process if stdin is disabled
2121 if (this.options
.disableStdin
) {
2125 // Input is being sent to the terminal, the terminal should focus the prompt.
2126 if (this.ybase
!== this.ydisp
) {
2127 this.scrollToBottom();
2129 this.emit('data', data
);
2134 * Emit the 'title' event and populate the given title.
2135 * @param {string} title The title to populate in the event.
2137 Terminal
.prototype.handleTitle = function(title
) {
2139 * This event is emitted when the title of the terminal is changed
2140 * from inside the terminal. The parameter is the new title.
2144 this.emit('title', title
);
2153 * ESC D Index (IND is 0x84).
2155 Terminal
.prototype.index = function() {
2157 if (this.y
> this.scrollBottom
) {
2161 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2162 if (this.x
>= this.cols
) {
2169 * ESC M Reverse Index (RI is 0x8d).
2171 * Move the cursor up one row, inserting a new blank line if necessary.
2173 Terminal
.prototype.reverseIndex = function() {
2175 if (this.y
=== this.scrollTop
) {
2176 // possibly move the code below to term.reverseScroll();
2177 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2178 // blankLine(true) is xterm/linux behavior
2179 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2180 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2181 this.updateRange(this.scrollTop
);
2182 this.updateRange(this.scrollBottom
);
2190 * ESC c Full Reset (RIS).
2192 Terminal
.prototype.reset = function() {
2193 this.options
.rows
= this.rows
;
2194 this.options
.cols
= this.cols
;
2195 var customKeydownHandler
= this.customKeydownHandler
;
2196 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2197 Terminal
.call(this, this.options
);
2198 this.customKeydownHandler
= customKeydownHandler
;
2199 this.cursorBlinkInterval
= cursorBlinkInterval
;
2200 this.refresh(0, this.rows
- 1);
2201 this.viewport
.syncScrollArea();
2206 * ESC H Tab Set (HTS is 0x88).
2208 Terminal
.prototype.tabSet = function() {
2209 this.tabs
[this.x
] = true;
2216 function on(el
, type
, handler
, capture
) {
2217 if (!Array
.isArray(el
)) {
2220 el
.forEach(function (element
) {
2221 element
.addEventListener(type
, handler
, capture
|| false);
2225 function off(el
, type
, handler
, capture
) {
2226 el
.removeEventListener(type
, handler
, capture
|| false);
2229 function cancel(ev
, force
) {
2230 if (!this.cancelEvents
&& !force
) {
2233 ev
.preventDefault();
2234 ev
.stopPropagation();
2238 function inherits(child
, parent
) {
2240 this.constructor = child
;
2242 f
.prototype = parent
.prototype;
2243 child
.prototype = new f
;
2246 function indexOf(obj
, el
) {
2249 if (obj
[i
] === el
) return i
;
2254 function isThirdLevelShift(term
, ev
) {
2256 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2257 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2259 if (ev
.type
== 'keypress') {
2260 return thirdLevelKey
;
2263 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2264 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2267 // Expose to InputHandler (temporary)
2268 Terminal
.prototype.matchColor
= matchColor
;
2270 function matchColor(r1
, g1
, b1
) {
2271 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2273 if (matchColor
._cache
[hash
] != null) {
2274 return matchColor
._cache
[hash
];
2277 var ldiff
= Infinity
2286 for (; i
< Terminal
.vcolors
.length
; i
++) {
2287 c
= Terminal
.vcolors
[i
];
2292 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2305 return matchColor
._cache
[hash
] = li
;
2308 matchColor
._cache
= {};
2310 // http://stackoverflow.com/questions/1633828
2311 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2312 return Math
.pow(30 * (r1
- r2
), 2)
2313 + Math
.pow(59 * (g1
- g2
), 2)
2314 + Math
.pow(11 * (b1
- b2
), 2);
2317 function each(obj
, iter
, con
) {
2318 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2319 for (var i
= 0; i
< obj
.length
; i
++) {
2320 iter
.call(con
, obj
[i
], i
, obj
);
2324 function wasMondifierKeyOnlyEvent(ev
) {
2325 return ev
.keyCode
=== 16 || // Shift
2326 ev
.keyCode
=== 17 || // Ctrl
2327 ev
.keyCode
=== 18; // Alt
2330 function keys(obj
) {
2331 if (Object
.keys
) return Object
.keys(obj
);
2334 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2345 Terminal
.EventEmitter
= EventEmitter
;
2346 Terminal
.inherits
= inherits
;
2349 * Adds an event listener to the terminal.
2351 * @param {string} event The name of the event. TODO: Document all event types
2352 * @param {function} callback The function to call when the event is triggered.
2356 Terminal
.cancel
= cancel
;
2358 module
.exports
= Terminal
;