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';
27 import { getRawByteCoords
} from './utils/Mouse';
30 * Terminal Emulation References:
32 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
33 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
34 * http://invisible-island.net/vttest/
35 * http://www.inwap.com/pdp10/ansicode.txt
36 * http://linux.die.net/man/4/console_codes
37 * http://linux.die.net/man/7/urxvt
40 // Let it work inside Node.js for automated testing purposes.
41 var document
= (typeof window
!= 'undefined') ? window
.document
: null;
44 * The amount of write requests to queue before sending an XOFF signal to the
45 * pty process. This number must be small in order for ^C and similar sequences
48 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
51 * The number of writes to perform in a single batch before allowing the
52 * renderer to catch up with a 0ms setTimeout.
54 var WRITE_BATCH_SIZE
= 300;
57 * The time between cursor blinks. This is driven by JS rather than a CSS
58 * animation due to a bug in Chromium that causes it to use excessive CPU time.
59 * See https://github.com/Microsoft/vscode/issues/22900
61 var CURSOR_BLINK_INTERVAL
= 600;
68 * Creates a new `Terminal` object.
70 * @param {object} options An object containing a set of options, the available options are:
71 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
72 * - `cols` (number): The number of columns of the terminal (horizontal size)
73 * - `rows` (number): The number of rows of the terminal (vertical size)
77 * @alias module:xterm/src/xterm
79 function Terminal(options
) {
82 if (!(this instanceof Terminal
)) {
83 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
86 self
.browser
= Browser
;
87 self
.cancel
= Terminal
.cancel
;
89 EventEmitter
.call(this);
91 if (typeof options
=== 'number') {
99 options
= options
|| {};
102 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
103 if (options
[key
] == null) {
104 options
[key
] = Terminal
.options
[key
];
106 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
107 options
[key
] = Terminal
[key
];
110 self
[key
] = options
[key
];
113 if (options
.colors
.length
=== 8) {
114 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
115 } else if (options
.colors
.length
=== 16) {
116 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
117 } else if (options
.colors
.length
=== 10) {
118 options
.colors
= options
.colors
.slice(0, -2).concat(
119 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
120 } else if (options
.colors
.length
=== 18) {
121 options
.colors
= options
.colors
.concat(
122 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
124 this.colors
= options
.colors
;
126 this.options
= options
;
128 // this.context = options.context || window;
129 // this.document = options.document || document;
130 this.parent
= options
.body
|| options
.parent
|| (
131 document
? document
.getElementsByTagName('body')[0] : null
134 this.cols
= options
.cols
|| options
.geometry
[0];
135 this.rows
= options
.rows
|| options
.geometry
[1];
136 this.geometry
= [this.cols
, this.rows
];
138 if (options
.handler
) {
139 this.on('data', options
.handler
);
143 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
149 * The scroll position of the viewport
154 * The cursor's x position after ybase
159 * The cursor's y position after ybase
163 this.cursorState
= 0;
164 this.cursorHidden
= false;
168 this.scrollBottom
= this.rows
- 1;
169 this.customKeydownHandler
= null;
170 this.cursorBlinkInterval
= null;
173 this.applicationKeypad
= false;
174 this.applicationCursor
= false;
175 this.originMode
= false;
176 this.insertMode
= false;
177 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
182 this.gcharset
= null;
184 this.charsets
= [null];
208 this.readable
= true;
209 this.writable
= true;
211 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
212 this.curAttr
= this.defAttr
;
215 this.currentParam
= 0;
219 this.inputHandler
= new InputHandler(this);
220 this.parser
= new Parser(this.inputHandler
, this);
221 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
222 this.renderer
= this.renderer
|| null;
223 this.linkifier
= this.linkifier
|| new Linkifier();
226 this.writeBuffer
= [];
227 this.writeInProgress
= false;
230 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
231 * This is a distinct state from writeStopped so that if the user requested
232 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
235 this.xoffSentToCatchUp
= false;
237 /** Whether writing has been stopped as a result of XOFF */
238 this.writeStopped
= false;
240 // leftover surrogate high from previous write invocation
241 this.surrogate_high
= '';
244 * An array of all lines in the entire buffer, including the prompt. The lines are array of
245 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
247 this.lines
= new CircularList(this.scrollback
);
250 this.lines
.push(this.blankLine());
256 // Store if user went browsing history in scrollback
257 this.userScrolling
= false;
260 inherits(Terminal
, EventEmitter
);
263 * back_color_erase feature for xterm.
265 Terminal
.prototype.eraseAttr = function() {
266 // if (this.is('screen')) return this.defAttr;
267 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
275 Terminal
.tangoColors
= [
296 // Colors 0-15 + 16-255
297 // Much thanks to TooTallNate for writing this.
298 Terminal
.colors
= (function() {
299 var colors
= Terminal
.tangoColors
.slice()
300 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
305 for (; i
< 216; i
++) {
306 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
311 for (; i
< 24; i
++) {
316 function out(r
, g
, b
) {
317 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
322 return c
.length
< 2 ? '0' + c
: c
;
328 Terminal
._colors
= Terminal
.colors
.slice();
330 Terminal
.vcolors
= (function() {
332 , colors
= Terminal
.colors
336 for (; i
< 256; i
++) {
337 color
= parseInt(colors
[i
].substring(1), 16);
339 (color
>> 16) & 0xff,
352 Terminal
.defaults
= {
353 colors
: Terminal
.colors
,
359 cursorStyle
: 'block',
367 useFlowControl
: false,
369 // programFeatures: false,
373 Terminal
.options
= {};
375 Terminal
.focus
= null;
377 each(keys(Terminal
.defaults
), function(key
) {
378 Terminal
[key
] = Terminal
.defaults
[key
];
379 Terminal
.options
[key
] = Terminal
.defaults
[key
];
383 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
385 Terminal
.prototype.focus = function() {
386 return this.textarea
.focus();
390 * Retrieves an option's value from the terminal.
391 * @param {string} key The option key.
393 Terminal
.prototype.getOption = function(key
, value
) {
394 if (!(key
in Terminal
.defaults
)) {
395 throw new Error('No option with key "' + key
+ '"');
398 if (typeof this.options
[key
] !== 'undefined') {
399 return this.options
[key
];
406 * Sets an option on the terminal.
407 * @param {string} key The option key.
408 * @param {string} value The option value.
410 Terminal
.prototype.setOption = function(key
, value
) {
411 if (!(key
in Terminal
.defaults
)) {
412 throw new Error('No option with key "' + key
+ '"');
416 if (this.options
[key
] !== value
) {
417 if (this.lines
.length
> value
) {
418 const amountToTrim
= this.lines
.length
- value
;
419 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
420 this.lines
.trimStart(amountToTrim
);
421 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
422 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
424 this.refresh(0, this.rows
- 1);
427 this.lines
.maxLength
= value
;
428 this.viewport
.syncScrollArea();
433 this.options
[key
] = value
;
435 case 'cursorBlink': this.setCursorBlinking(value
); break;
437 // Style 'block' applies with no class
438 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
439 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
441 case 'tabStopWidth': this.setupStops(); break;
445 Terminal
.prototype.restartCursorBlinking = function () {
446 this.setCursorBlinking(this.options
.cursorBlink
);
449 Terminal
.prototype.setCursorBlinking = function (enabled
) {
450 this.element
.classList
.toggle('xterm-cursor-blink', enabled
);
451 this.clearCursorBlinkingInterval();
454 this.cursorBlinkInterval
= setInterval(function () {
455 self
.element
.classList
.toggle('xterm-cursor-blink-on');
456 }, CURSOR_BLINK_INTERVAL
);
460 Terminal
.prototype.clearCursorBlinkingInterval = function () {
461 this.element
.classList
.remove('xterm-cursor-blink-on');
462 if (this.cursorBlinkInterval
) {
463 clearInterval(this.cursorBlinkInterval
);
464 this.cursorBlinkInterval
= null;
469 * Binds the desired focus behavior on a given terminal object.
473 Terminal
.bindFocus = function (term
) {
474 on(term
.textarea
, 'focus', function (ev
) {
475 if (term
.sendFocus
) {
476 term
.send(C0
.ESC
+ '[I');
478 term
.element
.classList
.add('focus');
480 term
.restartCursorBlinking
.apply(term
);
481 Terminal
.focus
= term
;
482 term
.emit('focus', {terminal
: term
});
487 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
489 Terminal
.prototype.blur = function() {
490 return this.textarea
.blur();
494 * Binds the desired blur behavior on a given terminal object.
498 Terminal
.bindBlur = function (term
) {
499 on(term
.textarea
, 'blur', function (ev
) {
500 term
.refresh(term
.y
, term
.y
);
501 if (term
.sendFocus
) {
502 term
.send(C0
.ESC
+ '[O');
504 term
.element
.classList
.remove('focus');
505 term
.clearCursorBlinkingInterval
.apply(term
);
506 Terminal
.focus
= null;
507 term
.emit('blur', {terminal
: term
});
512 * Initialize default behavior
514 Terminal
.prototype.initGlobal = function() {
517 Terminal
.bindKeys(this);
518 Terminal
.bindFocus(this);
519 Terminal
.bindBlur(this);
521 // Bind clipboard functionality
522 on(this.element
, 'copy', function (ev
) {
523 copyHandler
.call(this, ev
, term
);
525 on(this.textarea
, 'paste', function (ev
) {
526 pasteHandler
.call(this, ev
, term
);
528 on(this.element
, 'paste', function (ev
) {
529 pasteHandler
.call(this, ev
, term
);
532 function rightClickHandlerWrapper (ev
) {
533 rightClickHandler
.call(this, ev
, term
);
536 if (term
.browser
.isFirefox
) {
537 on(this.element
, 'mousedown', function (ev
) {
538 if (ev
.button
== 2) {
539 rightClickHandlerWrapper(ev
);
543 on(this.element
, 'contextmenu', rightClickHandlerWrapper
);
548 * Apply key handling to the terminal
550 Terminal
.bindKeys = function(term
) {
551 on(term
.element
, 'keydown', function(ev
) {
552 if (document
.activeElement
!= this) {
558 on(term
.element
, 'keypress', function(ev
) {
559 if (document
.activeElement
!= this) {
565 on(term
.element
, 'keyup', function(ev
) {
566 if (!wasMondifierKeyOnlyEvent(ev
)) {
571 on(term
.textarea
, 'keydown', function(ev
) {
575 on(term
.textarea
, 'keypress', function(ev
) {
577 // Truncate the textarea's value, since it is not needed
581 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
582 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
583 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
584 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
585 term
.on('refresh', function (data
) {
586 term
.queueLinkification(data
.start
, data
.end
)
592 * Insert the given row to the terminal or produce a new one
593 * if no row argument is passed. Return the inserted row.
594 * @param {HTMLElement} row (optional) The row to append to the terminal.
596 Terminal
.prototype.insertRow = function (row
) {
597 if (typeof row
!= 'object') {
598 row
= document
.createElement('div');
601 this.rowContainer
.appendChild(row
);
602 this.children
.push(row
);
608 * Opens the terminal within an element.
610 * @param {HTMLElement} parent The element to create the terminal within.
611 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
613 Terminal
.prototype.open = function(parent
, focus
) {
614 var self
=this, i
=0, div
;
616 this.parent
= parent
|| this.parent
;
619 throw new Error('Terminal requires a parent element.');
622 // Grab global elements
623 this.context
= this.parent
.ownerDocument
.defaultView
;
624 this.document
= this.parent
.ownerDocument
;
625 this.body
= this.document
.getElementsByTagName('body')[0];
627 //Create main element container
628 this.element
= this.document
.createElement('div');
629 this.element
.classList
.add('terminal');
630 this.element
.classList
.add('xterm');
631 this.element
.classList
.add('xterm-theme-' + this.theme
);
632 this.setCursorBlinking(this.options
.cursorBlink
);
634 this.element
.style
.height
;
635 this.element
.setAttribute('tabindex', 0);
637 this.viewportElement
= document
.createElement('div');
638 this.viewportElement
.classList
.add('xterm-viewport');
639 this.element
.appendChild(this.viewportElement
);
640 this.viewportScrollArea
= document
.createElement('div');
641 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
642 this.viewportElement
.appendChild(this.viewportScrollArea
);
644 // Create the container that will hold the lines of the terminal and then
645 // produce the lines the lines.
646 this.rowContainer
= document
.createElement('div');
647 this.rowContainer
.classList
.add('xterm-rows');
648 this.element
.appendChild(this.rowContainer
);
650 this.linkifier
.attachToDom(document
, this.children
);
652 // Create the container that will hold helpers like the textarea for
653 // capturing DOM Events. Then produce the helpers.
654 this.helperContainer
= document
.createElement('div');
655 this.helperContainer
.classList
.add('xterm-helpers');
656 // TODO: This should probably be inserted once it's filled to prevent an additional layout
657 this.element
.appendChild(this.helperContainer
);
658 this.textarea
= document
.createElement('textarea');
659 this.textarea
.classList
.add('xterm-helper-textarea');
660 this.textarea
.setAttribute('autocorrect', 'off');
661 this.textarea
.setAttribute('autocapitalize', 'off');
662 this.textarea
.setAttribute('spellcheck', 'false');
663 this.textarea
.tabIndex
= 0;
664 this.textarea
.addEventListener('focus', function() {
665 self
.emit('focus', {terminal
: self
});
667 this.textarea
.addEventListener('blur', function() {
668 self
.emit('blur', {terminal
: self
});
670 this.helperContainer
.appendChild(this.textarea
);
672 this.compositionView
= document
.createElement('div');
673 this.compositionView
.classList
.add('composition-view');
674 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
675 this.helperContainer
.appendChild(this.compositionView
);
677 this.charSizeStyleElement
= document
.createElement('style');
678 this.helperContainer
.appendChild(this.charSizeStyleElement
);
680 for (; i
< this.rows
; i
++) {
683 this.parent
.appendChild(this.element
);
685 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
686 this.charMeasure
.on('charsizechanged', function () {
687 self
.updateCharSizeCSS();
689 this.charMeasure
.measure();
691 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
692 this.renderer
= new Renderer(this);
694 // Setup loop that draws to screen
695 this.refresh(0, this.rows
- 1);
697 // Initialize global actions that
698 // need to be taken on the document.
702 * Automatic focus functionality.
703 * TODO: Default to `false` starting with xterm.js 3.0.
705 if (typeof focus
== 'undefined') {
706 let message
= 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
708 message
+= 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
709 message
+= 'it will default to `false`.';
711 console
.warn(message
);
719 on(this.element
, 'click', function() {
720 var selection
= document
.getSelection(),
721 collapsed
= selection
.isCollapsed
,
722 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
728 // Listen for mouse events and translate
729 // them into terminal mouse protocols.
733 * This event is emitted when terminal has completed opening.
742 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
743 * @param {string} addon The name of the addon to load
746 Terminal
.loadAddon = function(addon
, callback
) {
747 if (typeof exports
=== 'object' && typeof module
=== 'object') {
749 return require('./addons/' + addon
+ '/' + addon
);
750 } else if (typeof define
== 'function') {
752 return require(['./addons/' + addon
+ '/' + addon
], callback
);
754 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
760 * Updates the helper CSS class with any changes necessary after the terminal's
761 * character width has been changed.
763 Terminal
.prototype.updateCharSizeCSS = function() {
764 this.charSizeStyleElement
.textContent
=
765 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
766 `.xterm-normal-char{width:${this.charMeasure.width}px;}`
771 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
772 * To better understand these
773 * the xterm code is very helpful:
775 * button.c, charproc.c, misc.c
776 * Relevant functions in xterm/button.c:
777 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
779 Terminal
.prototype.bindMouse = function() {
780 var el
= this.element
, self
= this, pressed
= 32;
782 // mouseup, mousedown, wheel
783 // left click: ^[[M 3<^[[M#3<
785 function sendButton(ev
) {
789 // get the xterm-style button
790 button
= getButton(ev
);
792 // get mouse coordinates
793 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
796 sendEvent(button
, pos
);
798 switch (ev
.overrideType
|| ev
.type
) {
803 // keep it at the left
804 // button, just in case.
815 // motion example of a left click:
816 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
817 function sendMove(ev
) {
821 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
824 // buttons marked as motions
825 // are incremented by 32
828 sendEvent(button
, pos
);
832 // position to characters
833 function encode(data
, ch
) {
834 if (!self
.utfMouse
) {
835 if (ch
=== 255) return data
.push(0);
836 if (ch
> 127) ch
= 127;
839 if (ch
=== 2047) return data
.push(0);
843 if (ch
> 2047) ch
= 2047;
844 data
.push(0xC0 | (ch
>> 6));
845 data
.push(0x80 | (ch
& 0x3F));
850 // send a mouse event:
851 // regular/utf8: ^[[M Cb Cx Cy
852 // urxvt: ^[[ Cb ; Cx ; Cy M
853 // sgr: ^[[ Cb ; Cx ; Cy M/m
854 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
855 // locator: CSI P e ; P b ; P r ; P c ; P p & w
856 function sendEvent(button
, pos
) {
857 // self.emit('mouse', {
863 if (self
.vt300Mouse
) {
865 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
869 var data
= C0
.ESC
+ '[24';
870 if (button
=== 0) data
+= '1';
871 else if (button
=== 1) data
+= '3';
872 else if (button
=== 2) data
+= '5';
873 else if (button
=== 3) return;
875 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
880 if (self
.decLocator
) {
885 if (button
=== 0) button
= 2;
886 else if (button
=== 1) button
= 4;
887 else if (button
=== 2) button
= 6;
888 else if (button
=== 3) button
= 3;
889 self
.send(C0
.ESC
+ '['
892 + (button
=== 3 ? 4 : 0)
903 if (self
.urxvtMouse
) {
908 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
915 self
.send(C0
.ESC
+ '[<'
916 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
921 + ((button
& 3) === 3 ? 'm' : 'M'));
927 encode(data
, button
);
931 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
934 function getButton(ev
) {
947 // 1, and 2 - with 64 added
948 switch (ev
.overrideType
|| ev
.type
) {
950 button
= ev
.button
!= null
956 if (self
.browser
.isMSIE
) {
957 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
963 case 'DOMMouseScroll':
964 button
= ev
.detail
< 0
969 button
= ev
.wheelDeltaY
> 0
975 // next three bits are the modifiers:
976 // 4 = shift, 8 = meta, 16 = control
977 shift
= ev
.shiftKey
? 4 : 0;
978 meta
= ev
.metaKey
? 8 : 0;
979 ctrl
= ev
.ctrlKey
? 16 : 0;
980 mod
= shift
| meta
| ctrl
;
983 if (self
.vt200Mouse
) {
986 } else if (!self
.normalMouse
) {
991 button
= (32 + (mod
<< 2)) + button
;
996 on(el
, 'mousedown', function(ev
) {
997 if (!self
.mouseEvents
) return;
1006 //if (self.vt200Mouse && !self.normalMouse) {
1007 if (self
.vt200Mouse
) {
1008 ev
.overrideType
= 'mouseup';
1010 return self
.cancel(ev
);
1014 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1016 // x10 compatibility mode can't send button releases
1017 if (!self
.x10Mouse
) {
1018 on(self
.document
, 'mouseup', function up(ev
) {
1020 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1021 off(self
.document
, 'mouseup', up
);
1022 return self
.cancel(ev
);
1026 return self
.cancel(ev
);
1029 //if (self.normalMouse) {
1030 // on(self.document, 'mousemove', sendMove);
1033 on(el
, 'wheel', function(ev
) {
1034 if (!self
.mouseEvents
) return;
1037 || self
.decLocator
) return;
1039 return self
.cancel(ev
);
1042 // allow wheel scrolling in
1043 // the shell for example
1044 on(el
, 'wheel', function(ev
) {
1045 if (self
.mouseEvents
) return;
1046 self
.viewport
.onWheel(ev
);
1047 return self
.cancel(ev
);
1052 * Destroys the terminal.
1054 Terminal
.prototype.destroy = function() {
1055 this.readable
= false;
1056 this.writable
= false;
1058 this.handler = function() {};
1059 this.write = function() {};
1060 if (this.element
&& this.element
.parentNode
) {
1061 this.element
.parentNode
.removeChild(this.element
);
1063 //this.emit('close');
1067 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1069 * @param {number} start The row to start from (between 0 and this.rows - 1).
1070 * @param {number} end The row to end at (between start and this.rows - 1).
1072 Terminal
.prototype.refresh = function(start
, end
) {
1073 if (this.renderer
) {
1074 this.renderer
.queueRefresh(start
, end
);
1079 * Queues linkification for the specified rows.
1080 * @param {number} start The row to start from (between 0 and this.rows - 1).
1081 * @param {number} end The row to end at (between start and this.rows - 1).
1083 Terminal
.prototype.queueLinkification = function(start
, end
) {
1084 if (this.linkifier
) {
1085 for (let i
= start
; i
<= end
; i
++) {
1086 this.linkifier
.linkifyRow(i
);
1092 * Display the cursor element
1094 Terminal
.prototype.showCursor = function() {
1095 if (!this.cursorState
) {
1096 this.cursorState
= 1;
1097 this.refresh(this.y
, this.y
);
1102 * Scroll the terminal down 1 row, creating a blank line.
1104 Terminal
.prototype.scroll = function() {
1107 // Make room for the new row in lines
1108 if (this.lines
.length
=== this.lines
.maxLength
) {
1109 this.lines
.trimStart(1);
1111 if (this.ydisp
!== 0) {
1118 // TODO: Why is this done twice?
1119 if (!this.userScrolling
) {
1120 this.ydisp
= this.ybase
;
1124 row
= this.ybase
+ this.rows
- 1;
1126 // subtract the bottom scroll region
1127 row
-= this.rows
- 1 - this.scrollBottom
;
1129 if (row
=== this.lines
.length
) {
1130 // Optimization: pushing is faster than splicing when they amount to the same behavior
1131 this.lines
.push(this.blankLine());
1134 this.lines
.splice(row
, 0, this.blankLine());
1137 if (this.scrollTop
!== 0) {
1138 if (this.ybase
!== 0) {
1140 if (!this.userScrolling
) {
1141 this.ydisp
= this.ybase
;
1144 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1148 this.updateRange(this.scrollTop
);
1149 this.updateRange(this.scrollBottom
);
1152 * This event is emitted whenever the terminal is scrolled.
1153 * The one parameter passed is the new y display position.
1157 this.emit('scroll', this.ydisp
);
1161 * Scroll the display of the terminal
1162 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1163 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1164 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1165 * viewport originally.
1167 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1169 this.userScrolling
= true;
1170 } else if (disp
+ this.ydisp
>= this.ybase
) {
1171 this.userScrolling
= false;
1176 if (this.ydisp
> this.ybase
) {
1177 this.ydisp
= this.ybase
;
1178 } else if (this.ydisp
< 0) {
1182 if (!suppressScrollEvent
) {
1183 this.emit('scroll', this.ydisp
);
1186 this.refresh(0, this.rows
- 1);
1190 * Scroll the display of the terminal by a number of pages.
1191 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1193 Terminal
.prototype.scrollPages = function(pageCount
) {
1194 this.scrollDisp(pageCount
* (this.rows
- 1));
1198 * Scrolls the display of the terminal to the top.
1200 Terminal
.prototype.scrollToTop = function() {
1201 this.scrollDisp(-this.ydisp
);
1205 * Scrolls the display of the terminal to the bottom.
1207 Terminal
.prototype.scrollToBottom = function() {
1208 this.scrollDisp(this.ybase
- this.ydisp
);
1212 * Writes text to the terminal.
1213 * @param {string} text The text to write to the terminal.
1215 Terminal
.prototype.write = function(data
) {
1216 this.writeBuffer
.push(data
);
1218 // Send XOFF to pause the pty process if the write buffer becomes too large so
1219 // xterm.js can catch up before more data is sent. This is necessary in order
1220 // to keep signals such as ^C responsive.
1221 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1222 // XOFF - stop pty pipe
1223 // XON will be triggered by emulator before processing data chunk
1225 this.xoffSentToCatchUp
= true;
1228 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1229 // Kick off a write which will write all data in sequence recursively
1230 this.writeInProgress
= true;
1231 // Kick off an async innerWrite so more writes can come in while processing data
1233 setTimeout(function () {
1239 Terminal
.prototype.innerWrite = function() {
1240 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1241 while (writeBatch
.length
> 0) {
1242 var data
= writeBatch
.shift();
1243 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1245 // If XOFF was sent in order to catch up with the pty process, resume it if
1246 // the writeBuffer is empty to allow more data to come in.
1247 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1249 this.xoffSentToCatchUp
= false;
1252 this.refreshStart
= this.y
;
1253 this.refreshEnd
= this.y
;
1255 this.parser
.parse(data
);
1257 this.updateRange(this.y
);
1258 this.refresh(this.refreshStart
, this.refreshEnd
);
1260 if (this.writeBuffer
.length
> 0) {
1261 // Allow renderer to catch up before processing the next batch
1263 setTimeout(function () {
1267 this.writeInProgress
= false;
1272 * Writes text to the terminal, followed by a break line character (\n).
1273 * @param {string} text The text to write to the terminal.
1275 Terminal
.prototype.writeln = function(data
) {
1276 this.write(data
+ '\r\n');
1280 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1281 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1283 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1284 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1285 * the default action. The function returns whether the event should be processed by xterm.js.
1287 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1288 this.customKeydownHandler
= customKeydownHandler
;
1292 * Attaches a http(s) link handler, forcing web links to behave differently to
1293 * regular <a> tags. This will trigger a refresh as links potentially need to be
1294 * reconstructed. Calling this with null will remove the handler.
1295 * @param {LinkHandler} handler The handler callback function.
1297 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1298 if (!this.linkifier
) {
1299 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1301 this.linkifier
.setHypertextLinkHandler(handler
);
1302 // Refresh to force links to refresh
1303 this.refresh(0, this.rows
- 1);
1307 * Attaches a validation callback for hypertext links. This is useful to use
1308 * validation logic or to do something with the link's element and url.
1309 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1310 * be cleared with null.
1312 Terminal
.prototype.setHypertextValidationCallback = function(handler
) {
1313 if (!this.linkifier
) {
1314 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1316 this.linkifier
.setHypertextValidationCallback(handler
);
1317 // Refresh to force links to refresh
1318 this.refresh(0, this.rows
- 1);
1322 * Registers a link matcher, allowing custom link patterns to be matched and
1324 * @param {RegExp} regex The regular expression to search for, specifically
1325 * this searches the textContent of the rows. You will want to use \s to match
1326 * a space ' ' character for example.
1327 * @param {LinkHandler} handler The callback when the link is called.
1328 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1329 * @return {number} The ID of the new matcher, this can be used to deregister.
1331 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1332 if (this.linkifier
) {
1333 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1334 this.refresh(0, this.rows
- 1);
1340 * Deregisters a link matcher if it has been registered.
1341 * @param {number} matcherId The link matcher's ID (returned after register)
1343 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1344 if (this.linkifier
) {
1345 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1346 this.refresh(0, this.rows
- 1);
1352 * Handle a keydown event
1354 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1355 * @param {KeyboardEvent} ev The keydown event to be handled.
1357 Terminal
.prototype.keyDown = function(ev
) {
1358 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1362 this.restartCursorBlinking();
1364 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1365 if (this.ybase
!== this.ydisp
) {
1366 this.scrollToBottom();
1372 var result
= this.evaluateKeyEscapeSequence(ev
);
1374 if (result
.key
=== C0
.DC3
) { // XOFF
1375 this.writeStopped
= true;
1376 } else if (result
.key
=== C0
.DC1
) { // XON
1377 this.writeStopped
= false;
1380 if (result
.scrollDisp
) {
1381 this.scrollDisp(result
.scrollDisp
);
1382 return this.cancel(ev
, true);
1385 if (isThirdLevelShift(this, ev
)) {
1389 if (result
.cancel
) {
1390 // The event is canceled at the end already, is this necessary?
1391 this.cancel(ev
, true);
1398 this.emit('keydown', ev
);
1399 this.emit('key', result
.key
, ev
);
1401 this.handler(result
.key
);
1403 return this.cancel(ev
, true);
1407 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1408 * returned value is the new key code to pass to the PTY.
1410 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1411 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1413 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1415 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1416 // canceled at the end of keyDown
1418 // The new key even to emit
1420 // The number of characters to scroll, if this is defined it will cancel the event
1421 scrollDisp
: undefined
1423 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1424 switch (ev
.keyCode
) {
1428 result
.key
= C0
.BS
; // ^H
1431 result
.key
= C0
.DEL
; // ^?
1436 result
.key
= C0
.ESC
+ '[Z';
1440 result
.cancel
= true;
1445 result
.cancel
= true;
1449 result
.key
= C0
.ESC
;
1450 result
.cancel
= true;
1455 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1456 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1457 // http://unix.stackexchange.com/a/108106
1458 // macOS uses different escape sequences than linux
1459 if (result
.key
== C0
.ESC
+ '[1;3D') {
1460 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1462 } else if (this.applicationCursor
) {
1463 result
.key
= C0
.ESC
+ 'OD';
1465 result
.key
= C0
.ESC
+ '[D';
1471 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1472 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1473 // http://unix.stackexchange.com/a/108106
1474 // macOS uses different escape sequences than linux
1475 if (result
.key
== C0
.ESC
+ '[1;3C') {
1476 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1478 } else if (this.applicationCursor
) {
1479 result
.key
= C0
.ESC
+ 'OC';
1481 result
.key
= C0
.ESC
+ '[C';
1487 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1488 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1489 // http://unix.stackexchange.com/a/108106
1490 if (result
.key
== C0
.ESC
+ '[1;3A') {
1491 result
.key
= C0
.ESC
+ '[1;5A';
1493 } else if (this.applicationCursor
) {
1494 result
.key
= C0
.ESC
+ 'OA';
1496 result
.key
= C0
.ESC
+ '[A';
1502 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1503 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1504 // http://unix.stackexchange.com/a/108106
1505 if (result
.key
== C0
.ESC
+ '[1;3B') {
1506 result
.key
= C0
.ESC
+ '[1;5B';
1508 } else if (this.applicationCursor
) {
1509 result
.key
= C0
.ESC
+ 'OB';
1511 result
.key
= C0
.ESC
+ '[B';
1516 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1517 // <Ctrl> or <Shift> + <Insert> are used to
1518 // copy-paste on some systems.
1519 result
.key
= C0
.ESC
+ '[2~';
1525 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1527 result
.key
= C0
.ESC
+ '[3~';
1533 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1534 else if (this.applicationCursor
)
1535 result
.key
= C0
.ESC
+ 'OH';
1537 result
.key
= C0
.ESC
+ '[H';
1542 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1543 else if (this.applicationCursor
)
1544 result
.key
= C0
.ESC
+ 'OF';
1546 result
.key
= C0
.ESC
+ '[F';
1551 result
.scrollDisp
= -(this.rows
- 1);
1553 result
.key
= C0
.ESC
+ '[5~';
1559 result
.scrollDisp
= this.rows
- 1;
1561 result
.key
= C0
.ESC
+ '[6~';
1567 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1569 result
.key
= C0
.ESC
+ 'OP';
1574 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1576 result
.key
= C0
.ESC
+ 'OQ';
1581 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1583 result
.key
= C0
.ESC
+ 'OR';
1588 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1590 result
.key
= C0
.ESC
+ 'OS';
1595 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1597 result
.key
= C0
.ESC
+ '[15~';
1602 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1604 result
.key
= C0
.ESC
+ '[17~';
1609 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1611 result
.key
= C0
.ESC
+ '[18~';
1616 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1618 result
.key
= C0
.ESC
+ '[19~';
1623 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1625 result
.key
= C0
.ESC
+ '[20~';
1630 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1632 result
.key
= C0
.ESC
+ '[21~';
1637 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1639 result
.key
= C0
.ESC
+ '[23~';
1644 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1646 result
.key
= C0
.ESC
+ '[24~';
1651 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1652 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1653 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1654 } else if (ev
.keyCode
=== 32) {
1656 result
.key
= String
.fromCharCode(0);
1657 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1658 // escape, file sep, group sep, record sep, unit sep
1659 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1660 } else if (ev
.keyCode
=== 56) {
1662 result
.key
= String
.fromCharCode(127);
1663 } else if (ev
.keyCode
=== 219) {
1664 // ^[ - Control Sequence Introducer (CSI)
1665 result
.key
= String
.fromCharCode(27);
1666 } else if (ev
.keyCode
=== 220) {
1667 // ^\ - String Terminator (ST)
1668 result
.key
= String
.fromCharCode(28);
1669 } else if (ev
.keyCode
=== 221) {
1670 // ^] - Operating System Command (OSC)
1671 result
.key
= String
.fromCharCode(29);
1673 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1674 // On Mac this is a third level shift. Use <Esc> instead.
1675 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1676 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1677 } else if (ev
.keyCode
=== 192) {
1678 result
.key
= C0
.ESC
+ '`';
1679 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1680 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1690 * Set the G level of the terminal
1693 Terminal
.prototype.setgLevel = function(g
) {
1695 this.charset
= this.charsets
[g
];
1699 * Set the charset for the given G level of the terminal
1703 Terminal
.prototype.setgCharset = function(g
, charset
) {
1704 this.charsets
[g
] = charset
;
1705 if (this.glevel
=== g
) {
1706 this.charset
= charset
;
1711 * Handle a keypress event.
1713 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1714 * @param {KeyboardEvent} ev The keypress event to be handled.
1716 Terminal
.prototype.keyPress = function(ev
) {
1723 } else if (ev
.which
== null) {
1725 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1732 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1737 key
= String
.fromCharCode(key
);
1739 this.emit('keypress', key
, ev
);
1740 this.emit('key', key
, ev
);
1748 * Send data for handling to the terminal
1749 * @param {string} data
1751 Terminal
.prototype.send = function(data
) {
1755 setTimeout(function() {
1756 self
.handler(self
.queue
);
1766 * Note: We could do sweet things with webaudio here
1768 Terminal
.prototype.bell = function() {
1769 if (!this.visualBell
) return;
1771 this.element
.style
.borderColor
= 'white';
1772 setTimeout(function() {
1773 self
.element
.style
.borderColor
= '';
1775 if (this.popOnBell
) this.focus();
1779 * Log the current state to the console.
1781 Terminal
.prototype.log = function() {
1782 if (!this.debug
) return;
1783 if (!this.context
.console
|| !this.context
.console
.log
) return;
1784 var args
= Array
.prototype.slice
.call(arguments
);
1785 this.context
.console
.log
.apply(this.context
.console
, args
);
1789 * Log the current state as error to the console.
1791 Terminal
.prototype.error = function() {
1792 if (!this.debug
) return;
1793 if (!this.context
.console
|| !this.context
.console
.error
) return;
1794 var args
= Array
.prototype.slice
.call(arguments
);
1795 this.context
.console
.error
.apply(this.context
.console
, args
);
1799 * Resizes the terminal.
1801 * @param {number} x The number of columns to resize to.
1802 * @param {number} y The number of rows to resize to.
1804 Terminal
.prototype.resize = function(x
, y
) {
1805 if (isNaN(x
) || isNaN(y
)) {
1816 if (x
=== this.cols
&& y
=== this.rows
) {
1826 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1827 i
= this.lines
.length
;
1829 while (this.lines
.get(i
).length
< x
) {
1830 this.lines
.get(i
).push(ch
);
1836 this.setupStops(this.cols
);
1844 // y is rows, not this.y
1845 if (this.lines
.length
< y
+ this.ybase
) {
1846 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
1847 // There is room above the buffer and there are no empty elements below the line,
1851 if (this.ydisp
> 0) {
1852 // Viewport is at the top of the buffer, must increase downwards
1856 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1857 // are blank lines after the cursor
1858 this.lines
.push(this.blankLine());
1861 if (this.children
.length
< y
) {
1867 if (this.lines
.length
> y
+ this.ybase
) {
1868 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
1869 // The line is a blank line below the cursor, remove it
1872 // The line is the cursor, scroll down
1877 if (this.children
.length
> y
) {
1878 el
= this.children
.shift();
1880 el
.parentNode
.removeChild(el
);
1886 // Make sure that the cursor stays on screen
1899 this.scrollBottom
= y
- 1;
1901 this.charMeasure
.measure();
1903 this.refresh(0, this.rows
- 1);
1907 this.geometry
= [this.cols
, this.rows
];
1908 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
1912 * Updates the range of rows to refresh
1913 * @param {number} y The number of rows to refresh next.
1915 Terminal
.prototype.updateRange = function(y
) {
1916 if (y
< this.refreshStart
) this.refreshStart
= y
;
1917 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
1918 // if (y > this.refreshEnd) {
1919 // this.refreshEnd = y;
1920 // if (y > this.rows - 1) {
1921 // this.refreshEnd = this.rows - 1;
1927 * Set the range of refreshing to the maximum value
1929 Terminal
.prototype.maxRange = function() {
1930 this.refreshStart
= 0;
1931 this.refreshEnd
= this.rows
- 1;
1937 * Setup the tab stops.
1940 Terminal
.prototype.setupStops = function(i
) {
1942 if (!this.tabs
[i
]) {
1943 i
= this.prevStop(i
);
1950 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
1951 this.tabs
[i
] = true;
1957 * Move the cursor to the previous tab stop from the given position (default is current).
1958 * @param {number} x The position to move the cursor to the previous tab stop.
1960 Terminal
.prototype.prevStop = function(x
) {
1961 if (x
== null) x
= this.x
;
1962 while (!this.tabs
[--x
] && x
> 0);
1963 return x
>= this.cols
1970 * Move the cursor one tab stop forward from the given position (default is current).
1971 * @param {number} x The position to move the cursor one tab stop forward.
1973 Terminal
.prototype.nextStop = function(x
) {
1974 if (x
== null) x
= this.x
;
1975 while (!this.tabs
[++x
] && x
< this.cols
);
1976 return x
>= this.cols
1983 * Erase in the identified line everything from "x" to the end of the line (right).
1984 * @param {number} x The column from which to start erasing to the end of the line.
1985 * @param {number} y The line in which to operate.
1987 Terminal
.prototype.eraseRight = function(x
, y
) {
1988 var line
= this.lines
.get(this.ybase
+ y
);
1992 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
1993 for (; x
< this.cols
; x
++) {
1996 this.updateRange(y
);
2002 * Erase in the identified line everything from "x" to the start of the line (left).
2003 * @param {number} x The column from which to start erasing to the start of the line.
2004 * @param {number} y The line in which to operate.
2006 Terminal
.prototype.eraseLeft = function(x
, y
) {
2007 var line
= this.lines
.get(this.ybase
+ y
);
2011 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2016 this.updateRange(y
);
2020 * Clears the entire buffer, making the prompt line the new first line.
2022 Terminal
.prototype.clear = function() {
2023 if (this.ybase
=== 0 && this.y
=== 0) {
2024 // Don't clear if it's already clear
2027 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2028 this.lines
.length
= 1;
2032 for (var i
= 1; i
< this.rows
; i
++) {
2033 this.lines
.push(this.blankLine());
2035 this.refresh(0, this.rows
- 1);
2036 this.emit('scroll', this.ydisp
);
2040 * Erase all content in the given line
2041 * @param {number} y The line to erase all of its contents.
2043 Terminal
.prototype.eraseLine = function(y
) {
2044 this.eraseRight(0, y
);
2049 * Return the data array of a blank line
2050 * @param {number} cur First bunch of data for each "blank" character.
2052 Terminal
.prototype.blankLine = function(cur
) {
2057 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2061 for (; i
< this.cols
; i
++) {
2070 * If cur return the back color xterm feature attribute. Else return defAttr.
2071 * @param {object} cur
2073 Terminal
.prototype.ch = function(cur
) {
2075 ? [this.eraseAttr(), ' ', 1]
2076 : [this.defAttr
, ' ', 1];
2081 * Evaluate if the current erminal is the given argument.
2082 * @param {object} term The terminal to evaluate
2084 Terminal
.prototype.is = function(term
) {
2085 var name
= this.termName
;
2086 return (name
+ '').indexOf(term
) === 0;
2091 * Emit the 'data' event and populate the given data.
2092 * @param {string} data The data to populate in the event.
2094 Terminal
.prototype.handler = function(data
) {
2095 // Prevents all events to pty process if stdin is disabled
2096 if (this.options
.disableStdin
) {
2100 // Input is being sent to the terminal, the terminal should focus the prompt.
2101 if (this.ybase
!== this.ydisp
) {
2102 this.scrollToBottom();
2104 this.emit('data', data
);
2109 * Emit the 'title' event and populate the given title.
2110 * @param {string} title The title to populate in the event.
2112 Terminal
.prototype.handleTitle = function(title
) {
2114 * This event is emitted when the title of the terminal is changed
2115 * from inside the terminal. The parameter is the new title.
2119 this.emit('title', title
);
2128 * ESC D Index (IND is 0x84).
2130 Terminal
.prototype.index = function() {
2132 if (this.y
> this.scrollBottom
) {
2136 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2137 if (this.x
>= this.cols
) {
2144 * ESC M Reverse Index (RI is 0x8d).
2146 * Move the cursor up one row, inserting a new blank line if necessary.
2148 Terminal
.prototype.reverseIndex = function() {
2150 if (this.y
=== this.scrollTop
) {
2151 // possibly move the code below to term.reverseScroll();
2152 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2153 // blankLine(true) is xterm/linux behavior
2154 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2155 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2156 this.updateRange(this.scrollTop
);
2157 this.updateRange(this.scrollBottom
);
2165 * ESC c Full Reset (RIS).
2167 Terminal
.prototype.reset = function() {
2168 this.options
.rows
= this.rows
;
2169 this.options
.cols
= this.cols
;
2170 var customKeydownHandler
= this.customKeydownHandler
;
2171 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2172 Terminal
.call(this, this.options
);
2173 this.customKeydownHandler
= customKeydownHandler
;
2174 this.cursorBlinkInterval
= cursorBlinkInterval
;
2175 this.refresh(0, this.rows
- 1);
2176 this.viewport
.syncScrollArea();
2181 * ESC H Tab Set (HTS is 0x88).
2183 Terminal
.prototype.tabSet = function() {
2184 this.tabs
[this.x
] = true;
2191 function on(el
, type
, handler
, capture
) {
2192 if (!Array
.isArray(el
)) {
2195 el
.forEach(function (element
) {
2196 element
.addEventListener(type
, handler
, capture
|| false);
2200 function off(el
, type
, handler
, capture
) {
2201 el
.removeEventListener(type
, handler
, capture
|| false);
2204 function cancel(ev
, force
) {
2205 if (!this.cancelEvents
&& !force
) {
2208 ev
.preventDefault();
2209 ev
.stopPropagation();
2213 function inherits(child
, parent
) {
2215 this.constructor = child
;
2217 f
.prototype = parent
.prototype;
2218 child
.prototype = new f
;
2221 function indexOf(obj
, el
) {
2224 if (obj
[i
] === el
) return i
;
2229 function isThirdLevelShift(term
, ev
) {
2231 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2232 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2234 if (ev
.type
== 'keypress') {
2235 return thirdLevelKey
;
2238 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2239 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2242 // Expose to InputHandler (temporary)
2243 Terminal
.prototype.matchColor
= matchColor
;
2245 function matchColor(r1
, g1
, b1
) {
2246 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2248 if (matchColor
._cache
[hash
] != null) {
2249 return matchColor
._cache
[hash
];
2252 var ldiff
= Infinity
2261 for (; i
< Terminal
.vcolors
.length
; i
++) {
2262 c
= Terminal
.vcolors
[i
];
2267 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2280 return matchColor
._cache
[hash
] = li
;
2283 matchColor
._cache
= {};
2285 // http://stackoverflow.com/questions/1633828
2286 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2287 return Math
.pow(30 * (r1
- r2
), 2)
2288 + Math
.pow(59 * (g1
- g2
), 2)
2289 + Math
.pow(11 * (b1
- b2
), 2);
2292 function each(obj
, iter
, con
) {
2293 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2294 for (var i
= 0; i
< obj
.length
; i
++) {
2295 iter
.call(con
, obj
[i
], i
, obj
);
2299 function wasMondifierKeyOnlyEvent(ev
) {
2300 return ev
.keyCode
=== 16 || // Shift
2301 ev
.keyCode
=== 17 || // Ctrl
2302 ev
.keyCode
=== 18; // Alt
2305 function keys(obj
) {
2306 if (Object
.keys
) return Object
.keys(obj
);
2309 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2320 Terminal
.EventEmitter
= EventEmitter
;
2321 Terminal
.inherits
= inherits
;
2324 * Adds an event listener to the terminal.
2326 * @param {string} event The name of the event. TODO: Document all event types
2327 * @param {function} callback The function to call when the event is triggered.
2331 Terminal
.cancel
= cancel
;
2333 module
.exports
= Terminal
;