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;}` +
767 `.xterm-rows > div{height:${this.charMeasure.height}px;}`;
772 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
773 * To better understand these
774 * the xterm code is very helpful:
776 * button.c, charproc.c, misc.c
777 * Relevant functions in xterm/button.c:
778 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
780 Terminal
.prototype.bindMouse = function() {
781 var el
= this.element
, self
= this, pressed
= 32;
783 // mouseup, mousedown, wheel
784 // left click: ^[[M 3<^[[M#3<
786 function sendButton(ev
) {
790 // get the xterm-style button
791 button
= getButton(ev
);
793 // get mouse coordinates
794 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
797 sendEvent(button
, pos
);
799 switch (ev
.overrideType
|| ev
.type
) {
804 // keep it at the left
805 // button, just in case.
816 // motion example of a left click:
817 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
818 function sendMove(ev
) {
822 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
825 // buttons marked as motions
826 // are incremented by 32
829 sendEvent(button
, pos
);
833 // position to characters
834 function encode(data
, ch
) {
835 if (!self
.utfMouse
) {
836 if (ch
=== 255) return data
.push(0);
837 if (ch
> 127) ch
= 127;
840 if (ch
=== 2047) return data
.push(0);
844 if (ch
> 2047) ch
= 2047;
845 data
.push(0xC0 | (ch
>> 6));
846 data
.push(0x80 | (ch
& 0x3F));
851 // send a mouse event:
852 // regular/utf8: ^[[M Cb Cx Cy
853 // urxvt: ^[[ Cb ; Cx ; Cy M
854 // sgr: ^[[ Cb ; Cx ; Cy M/m
855 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
856 // locator: CSI P e ; P b ; P r ; P c ; P p & w
857 function sendEvent(button
, pos
) {
858 // self.emit('mouse', {
864 if (self
.vt300Mouse
) {
866 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
870 var data
= C0
.ESC
+ '[24';
871 if (button
=== 0) data
+= '1';
872 else if (button
=== 1) data
+= '3';
873 else if (button
=== 2) data
+= '5';
874 else if (button
=== 3) return;
876 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
881 if (self
.decLocator
) {
886 if (button
=== 0) button
= 2;
887 else if (button
=== 1) button
= 4;
888 else if (button
=== 2) button
= 6;
889 else if (button
=== 3) button
= 3;
890 self
.send(C0
.ESC
+ '['
893 + (button
=== 3 ? 4 : 0)
904 if (self
.urxvtMouse
) {
909 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
916 self
.send(C0
.ESC
+ '[<'
917 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
922 + ((button
& 3) === 3 ? 'm' : 'M'));
928 encode(data
, button
);
932 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
935 function getButton(ev
) {
948 // 1, and 2 - with 64 added
949 switch (ev
.overrideType
|| ev
.type
) {
951 button
= ev
.button
!= null
957 if (self
.browser
.isMSIE
) {
958 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
964 case 'DOMMouseScroll':
965 button
= ev
.detail
< 0
970 button
= ev
.wheelDeltaY
> 0
976 // next three bits are the modifiers:
977 // 4 = shift, 8 = meta, 16 = control
978 shift
= ev
.shiftKey
? 4 : 0;
979 meta
= ev
.metaKey
? 8 : 0;
980 ctrl
= ev
.ctrlKey
? 16 : 0;
981 mod
= shift
| meta
| ctrl
;
984 if (self
.vt200Mouse
) {
987 } else if (!self
.normalMouse
) {
992 button
= (32 + (mod
<< 2)) + button
;
997 on(el
, 'mousedown', function(ev
) {
998 if (!self
.mouseEvents
) return;
1007 //if (self.vt200Mouse && !self.normalMouse) {
1008 if (self
.vt200Mouse
) {
1009 ev
.overrideType
= 'mouseup';
1011 return self
.cancel(ev
);
1015 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1017 // x10 compatibility mode can't send button releases
1018 if (!self
.x10Mouse
) {
1019 on(self
.document
, 'mouseup', function up(ev
) {
1021 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1022 off(self
.document
, 'mouseup', up
);
1023 return self
.cancel(ev
);
1027 return self
.cancel(ev
);
1030 //if (self.normalMouse) {
1031 // on(self.document, 'mousemove', sendMove);
1034 on(el
, 'wheel', function(ev
) {
1035 if (!self
.mouseEvents
) return;
1038 || self
.decLocator
) return;
1040 return self
.cancel(ev
);
1043 // allow wheel scrolling in
1044 // the shell for example
1045 on(el
, 'wheel', function(ev
) {
1046 if (self
.mouseEvents
) return;
1047 self
.viewport
.onWheel(ev
);
1048 return self
.cancel(ev
);
1053 * Destroys the terminal.
1055 Terminal
.prototype.destroy = function() {
1056 this.readable
= false;
1057 this.writable
= false;
1059 this.handler = function() {};
1060 this.write = function() {};
1061 if (this.element
&& this.element
.parentNode
) {
1062 this.element
.parentNode
.removeChild(this.element
);
1064 //this.emit('close');
1068 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1070 * @param {number} start The row to start from (between 0 and this.rows - 1).
1071 * @param {number} end The row to end at (between start and this.rows - 1).
1073 Terminal
.prototype.refresh = function(start
, end
) {
1074 if (this.renderer
) {
1075 this.renderer
.queueRefresh(start
, end
);
1080 * Queues linkification for the specified rows.
1081 * @param {number} start The row to start from (between 0 and this.rows - 1).
1082 * @param {number} end The row to end at (between start and this.rows - 1).
1084 Terminal
.prototype.queueLinkification = function(start
, end
) {
1085 if (this.linkifier
) {
1086 for (let i
= start
; i
<= end
; i
++) {
1087 this.linkifier
.linkifyRow(i
);
1093 * Display the cursor element
1095 Terminal
.prototype.showCursor = function() {
1096 if (!this.cursorState
) {
1097 this.cursorState
= 1;
1098 this.refresh(this.y
, this.y
);
1103 * Scroll the terminal down 1 row, creating a blank line.
1105 Terminal
.prototype.scroll = function() {
1108 // Make room for the new row in lines
1109 if (this.lines
.length
=== this.lines
.maxLength
) {
1110 this.lines
.trimStart(1);
1112 if (this.ydisp
!== 0) {
1119 // TODO: Why is this done twice?
1120 if (!this.userScrolling
) {
1121 this.ydisp
= this.ybase
;
1125 row
= this.ybase
+ this.rows
- 1;
1127 // subtract the bottom scroll region
1128 row
-= this.rows
- 1 - this.scrollBottom
;
1130 if (row
=== this.lines
.length
) {
1131 // Optimization: pushing is faster than splicing when they amount to the same behavior
1132 this.lines
.push(this.blankLine());
1135 this.lines
.splice(row
, 0, this.blankLine());
1138 if (this.scrollTop
!== 0) {
1139 if (this.ybase
!== 0) {
1141 if (!this.userScrolling
) {
1142 this.ydisp
= this.ybase
;
1145 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1149 this.updateRange(this.scrollTop
);
1150 this.updateRange(this.scrollBottom
);
1153 * This event is emitted whenever the terminal is scrolled.
1154 * The one parameter passed is the new y display position.
1158 this.emit('scroll', this.ydisp
);
1162 * Scroll the display of the terminal
1163 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1164 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1165 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1166 * viewport originally.
1168 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1170 this.userScrolling
= true;
1171 } else if (disp
+ this.ydisp
>= this.ybase
) {
1172 this.userScrolling
= false;
1177 if (this.ydisp
> this.ybase
) {
1178 this.ydisp
= this.ybase
;
1179 } else if (this.ydisp
< 0) {
1183 if (!suppressScrollEvent
) {
1184 this.emit('scroll', this.ydisp
);
1187 this.refresh(0, this.rows
- 1);
1191 * Scroll the display of the terminal by a number of pages.
1192 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1194 Terminal
.prototype.scrollPages = function(pageCount
) {
1195 this.scrollDisp(pageCount
* (this.rows
- 1));
1199 * Scrolls the display of the terminal to the top.
1201 Terminal
.prototype.scrollToTop = function() {
1202 this.scrollDisp(-this.ydisp
);
1206 * Scrolls the display of the terminal to the bottom.
1208 Terminal
.prototype.scrollToBottom = function() {
1209 this.scrollDisp(this.ybase
- this.ydisp
);
1213 * Writes text to the terminal.
1214 * @param {string} text The text to write to the terminal.
1216 Terminal
.prototype.write = function(data
) {
1217 this.writeBuffer
.push(data
);
1219 // Send XOFF to pause the pty process if the write buffer becomes too large so
1220 // xterm.js can catch up before more data is sent. This is necessary in order
1221 // to keep signals such as ^C responsive.
1222 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1223 // XOFF - stop pty pipe
1224 // XON will be triggered by emulator before processing data chunk
1226 this.xoffSentToCatchUp
= true;
1229 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1230 // Kick off a write which will write all data in sequence recursively
1231 this.writeInProgress
= true;
1232 // Kick off an async innerWrite so more writes can come in while processing data
1234 setTimeout(function () {
1240 Terminal
.prototype.innerWrite = function() {
1241 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1242 while (writeBatch
.length
> 0) {
1243 var data
= writeBatch
.shift();
1244 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1246 // If XOFF was sent in order to catch up with the pty process, resume it if
1247 // the writeBuffer is empty to allow more data to come in.
1248 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1250 this.xoffSentToCatchUp
= false;
1253 this.refreshStart
= this.y
;
1254 this.refreshEnd
= this.y
;
1256 // HACK: Set the parser state based on it's state at the time of return.
1257 // This works around the bug #662 which saw the parser state reset in the
1258 // middle of parsing escape sequence in two chunks. For some reason the
1259 // state of the parser resets to 0 after exiting parser.parse. This change
1260 // just sets the state back based on the correct return statement.
1261 var state
= this.parser
.parse(data
);
1262 this.parser
.setState(state
);
1264 this.updateRange(this.y
);
1265 this.refresh(this.refreshStart
, this.refreshEnd
);
1267 if (this.writeBuffer
.length
> 0) {
1268 // Allow renderer to catch up before processing the next batch
1270 setTimeout(function () {
1274 this.writeInProgress
= false;
1279 * Writes text to the terminal, followed by a break line character (\n).
1280 * @param {string} text The text to write to the terminal.
1282 Terminal
.prototype.writeln = function(data
) {
1283 this.write(data
+ '\r\n');
1287 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1288 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1290 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1291 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1292 * the default action. The function returns whether the event should be processed by xterm.js.
1294 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1295 this.customKeydownHandler
= customKeydownHandler
;
1299 * Attaches a http(s) link handler, forcing web links to behave differently to
1300 * regular <a> tags. This will trigger a refresh as links potentially need to be
1301 * reconstructed. Calling this with null will remove the handler.
1302 * @param {LinkHandler} handler The handler callback function.
1304 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1305 if (!this.linkifier
) {
1306 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1308 this.linkifier
.setHypertextLinkHandler(handler
);
1309 // Refresh to force links to refresh
1310 this.refresh(0, this.rows
- 1);
1314 * Attaches a validation callback for hypertext links. This is useful to use
1315 * validation logic or to do something with the link's element and url.
1316 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1317 * be cleared with null.
1319 Terminal
.prototype.setHypertextValidationCallback = function(handler
) {
1320 if (!this.linkifier
) {
1321 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1323 this.linkifier
.setHypertextValidationCallback(handler
);
1324 // Refresh to force links to refresh
1325 this.refresh(0, this.rows
- 1);
1329 * Registers a link matcher, allowing custom link patterns to be matched and
1331 * @param {RegExp} regex The regular expression to search for, specifically
1332 * this searches the textContent of the rows. You will want to use \s to match
1333 * a space ' ' character for example.
1334 * @param {LinkHandler} handler The callback when the link is called.
1335 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1336 * @return {number} The ID of the new matcher, this can be used to deregister.
1338 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1339 if (this.linkifier
) {
1340 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1341 this.refresh(0, this.rows
- 1);
1347 * Deregisters a link matcher if it has been registered.
1348 * @param {number} matcherId The link matcher's ID (returned after register)
1350 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1351 if (this.linkifier
) {
1352 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1353 this.refresh(0, this.rows
- 1);
1359 * Handle a keydown event
1361 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1362 * @param {KeyboardEvent} ev The keydown event to be handled.
1364 Terminal
.prototype.keyDown = function(ev
) {
1365 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1369 this.restartCursorBlinking();
1371 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1372 if (this.ybase
!== this.ydisp
) {
1373 this.scrollToBottom();
1379 var result
= this.evaluateKeyEscapeSequence(ev
);
1381 if (result
.key
=== C0
.DC3
) { // XOFF
1382 this.writeStopped
= true;
1383 } else if (result
.key
=== C0
.DC1
) { // XON
1384 this.writeStopped
= false;
1387 if (result
.scrollDisp
) {
1388 this.scrollDisp(result
.scrollDisp
);
1389 return this.cancel(ev
, true);
1392 if (isThirdLevelShift(this, ev
)) {
1396 if (result
.cancel
) {
1397 // The event is canceled at the end already, is this necessary?
1398 this.cancel(ev
, true);
1405 this.emit('keydown', ev
);
1406 this.emit('key', result
.key
, ev
);
1408 this.handler(result
.key
);
1410 return this.cancel(ev
, true);
1414 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1415 * returned value is the new key code to pass to the PTY.
1417 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1418 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1420 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1422 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1423 // canceled at the end of keyDown
1425 // The new key even to emit
1427 // The number of characters to scroll, if this is defined it will cancel the event
1428 scrollDisp
: undefined
1430 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1431 switch (ev
.keyCode
) {
1435 result
.key
= C0
.BS
; // ^H
1438 result
.key
= C0
.DEL
; // ^?
1443 result
.key
= C0
.ESC
+ '[Z';
1447 result
.cancel
= true;
1452 result
.cancel
= true;
1456 result
.key
= C0
.ESC
;
1457 result
.cancel
= true;
1462 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1463 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1464 // http://unix.stackexchange.com/a/108106
1465 // macOS uses different escape sequences than linux
1466 if (result
.key
== C0
.ESC
+ '[1;3D') {
1467 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1469 } else if (this.applicationCursor
) {
1470 result
.key
= C0
.ESC
+ 'OD';
1472 result
.key
= C0
.ESC
+ '[D';
1478 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1479 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1480 // http://unix.stackexchange.com/a/108106
1481 // macOS uses different escape sequences than linux
1482 if (result
.key
== C0
.ESC
+ '[1;3C') {
1483 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1485 } else if (this.applicationCursor
) {
1486 result
.key
= C0
.ESC
+ 'OC';
1488 result
.key
= C0
.ESC
+ '[C';
1494 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1495 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1496 // http://unix.stackexchange.com/a/108106
1497 if (result
.key
== C0
.ESC
+ '[1;3A') {
1498 result
.key
= C0
.ESC
+ '[1;5A';
1500 } else if (this.applicationCursor
) {
1501 result
.key
= C0
.ESC
+ 'OA';
1503 result
.key
= C0
.ESC
+ '[A';
1509 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1510 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1511 // http://unix.stackexchange.com/a/108106
1512 if (result
.key
== C0
.ESC
+ '[1;3B') {
1513 result
.key
= C0
.ESC
+ '[1;5B';
1515 } else if (this.applicationCursor
) {
1516 result
.key
= C0
.ESC
+ 'OB';
1518 result
.key
= C0
.ESC
+ '[B';
1523 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1524 // <Ctrl> or <Shift> + <Insert> are used to
1525 // copy-paste on some systems.
1526 result
.key
= C0
.ESC
+ '[2~';
1532 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1534 result
.key
= C0
.ESC
+ '[3~';
1540 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1541 else if (this.applicationCursor
)
1542 result
.key
= C0
.ESC
+ 'OH';
1544 result
.key
= C0
.ESC
+ '[H';
1549 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1550 else if (this.applicationCursor
)
1551 result
.key
= C0
.ESC
+ 'OF';
1553 result
.key
= C0
.ESC
+ '[F';
1558 result
.scrollDisp
= -(this.rows
- 1);
1560 result
.key
= C0
.ESC
+ '[5~';
1566 result
.scrollDisp
= this.rows
- 1;
1568 result
.key
= C0
.ESC
+ '[6~';
1574 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1576 result
.key
= C0
.ESC
+ 'OP';
1581 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1583 result
.key
= C0
.ESC
+ 'OQ';
1588 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1590 result
.key
= C0
.ESC
+ 'OR';
1595 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1597 result
.key
= C0
.ESC
+ 'OS';
1602 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1604 result
.key
= C0
.ESC
+ '[15~';
1609 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1611 result
.key
= C0
.ESC
+ '[17~';
1616 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1618 result
.key
= C0
.ESC
+ '[18~';
1623 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1625 result
.key
= C0
.ESC
+ '[19~';
1630 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1632 result
.key
= C0
.ESC
+ '[20~';
1637 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1639 result
.key
= C0
.ESC
+ '[21~';
1644 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1646 result
.key
= C0
.ESC
+ '[23~';
1651 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1653 result
.key
= C0
.ESC
+ '[24~';
1658 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1659 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1660 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1661 } else if (ev
.keyCode
=== 32) {
1663 result
.key
= String
.fromCharCode(0);
1664 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1665 // escape, file sep, group sep, record sep, unit sep
1666 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1667 } else if (ev
.keyCode
=== 56) {
1669 result
.key
= String
.fromCharCode(127);
1670 } else if (ev
.keyCode
=== 219) {
1671 // ^[ - Control Sequence Introducer (CSI)
1672 result
.key
= String
.fromCharCode(27);
1673 } else if (ev
.keyCode
=== 220) {
1674 // ^\ - String Terminator (ST)
1675 result
.key
= String
.fromCharCode(28);
1676 } else if (ev
.keyCode
=== 221) {
1677 // ^] - Operating System Command (OSC)
1678 result
.key
= String
.fromCharCode(29);
1680 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1681 // On Mac this is a third level shift. Use <Esc> instead.
1682 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1683 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1684 } else if (ev
.keyCode
=== 192) {
1685 result
.key
= C0
.ESC
+ '`';
1686 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1687 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1697 * Set the G level of the terminal
1700 Terminal
.prototype.setgLevel = function(g
) {
1702 this.charset
= this.charsets
[g
];
1706 * Set the charset for the given G level of the terminal
1710 Terminal
.prototype.setgCharset = function(g
, charset
) {
1711 this.charsets
[g
] = charset
;
1712 if (this.glevel
=== g
) {
1713 this.charset
= charset
;
1718 * Handle a keypress event.
1720 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1721 * @param {KeyboardEvent} ev The keypress event to be handled.
1723 Terminal
.prototype.keyPress = function(ev
) {
1730 } else if (ev
.which
== null) {
1732 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1739 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1744 key
= String
.fromCharCode(key
);
1746 this.emit('keypress', key
, ev
);
1747 this.emit('key', key
, ev
);
1755 * Send data for handling to the terminal
1756 * @param {string} data
1758 Terminal
.prototype.send = function(data
) {
1762 setTimeout(function() {
1763 self
.handler(self
.queue
);
1773 * Note: We could do sweet things with webaudio here
1775 Terminal
.prototype.bell = function() {
1776 if (!this.visualBell
) return;
1778 this.element
.style
.borderColor
= 'white';
1779 setTimeout(function() {
1780 self
.element
.style
.borderColor
= '';
1782 if (this.popOnBell
) this.focus();
1786 * Log the current state to the console.
1788 Terminal
.prototype.log = function() {
1789 if (!this.debug
) return;
1790 if (!this.context
.console
|| !this.context
.console
.log
) return;
1791 var args
= Array
.prototype.slice
.call(arguments
);
1792 this.context
.console
.log
.apply(this.context
.console
, args
);
1796 * Log the current state as error to the console.
1798 Terminal
.prototype.error = function() {
1799 if (!this.debug
) return;
1800 if (!this.context
.console
|| !this.context
.console
.error
) return;
1801 var args
= Array
.prototype.slice
.call(arguments
);
1802 this.context
.console
.error
.apply(this.context
.console
, args
);
1806 * Resizes the terminal.
1808 * @param {number} x The number of columns to resize to.
1809 * @param {number} y The number of rows to resize to.
1811 Terminal
.prototype.resize = function(x
, y
) {
1812 if (isNaN(x
) || isNaN(y
)) {
1823 if (x
=== this.cols
&& y
=== this.rows
) {
1833 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1834 i
= this.lines
.length
;
1836 while (this.lines
.get(i
).length
< x
) {
1837 this.lines
.get(i
).push(ch
);
1843 this.setupStops(this.cols
);
1851 // y is rows, not this.y
1852 if (this.lines
.length
< y
+ this.ybase
) {
1853 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
1854 // There is room above the buffer and there are no empty elements below the line,
1858 if (this.ydisp
> 0) {
1859 // Viewport is at the top of the buffer, must increase downwards
1863 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1864 // are blank lines after the cursor
1865 this.lines
.push(this.blankLine());
1868 if (this.children
.length
< y
) {
1874 if (this.lines
.length
> y
+ this.ybase
) {
1875 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
1876 // The line is a blank line below the cursor, remove it
1879 // The line is the cursor, scroll down
1884 if (this.children
.length
> y
) {
1885 el
= this.children
.shift();
1887 el
.parentNode
.removeChild(el
);
1893 // Make sure that the cursor stays on screen
1906 this.scrollBottom
= y
- 1;
1908 this.charMeasure
.measure();
1910 this.refresh(0, this.rows
- 1);
1914 this.geometry
= [this.cols
, this.rows
];
1915 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
1919 * Updates the range of rows to refresh
1920 * @param {number} y The number of rows to refresh next.
1922 Terminal
.prototype.updateRange = function(y
) {
1923 if (y
< this.refreshStart
) this.refreshStart
= y
;
1924 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
1925 // if (y > this.refreshEnd) {
1926 // this.refreshEnd = y;
1927 // if (y > this.rows - 1) {
1928 // this.refreshEnd = this.rows - 1;
1934 * Set the range of refreshing to the maximum value
1936 Terminal
.prototype.maxRange = function() {
1937 this.refreshStart
= 0;
1938 this.refreshEnd
= this.rows
- 1;
1944 * Setup the tab stops.
1947 Terminal
.prototype.setupStops = function(i
) {
1949 if (!this.tabs
[i
]) {
1950 i
= this.prevStop(i
);
1957 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
1958 this.tabs
[i
] = true;
1964 * Move the cursor to the previous tab stop from the given position (default is current).
1965 * @param {number} x The position to move the cursor to the previous tab stop.
1967 Terminal
.prototype.prevStop = function(x
) {
1968 if (x
== null) x
= this.x
;
1969 while (!this.tabs
[--x
] && x
> 0);
1970 return x
>= this.cols
1977 * Move the cursor one tab stop forward from the given position (default is current).
1978 * @param {number} x The position to move the cursor one tab stop forward.
1980 Terminal
.prototype.nextStop = function(x
) {
1981 if (x
== null) x
= this.x
;
1982 while (!this.tabs
[++x
] && x
< this.cols
);
1983 return x
>= this.cols
1990 * Erase in the identified line everything from "x" to the end of the line (right).
1991 * @param {number} x The column from which to start erasing to the end of the line.
1992 * @param {number} y The line in which to operate.
1994 Terminal
.prototype.eraseRight = function(x
, y
) {
1995 var line
= this.lines
.get(this.ybase
+ y
);
1999 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2000 for (; x
< this.cols
; x
++) {
2003 this.updateRange(y
);
2009 * Erase in the identified line everything from "x" to the start of the line (left).
2010 * @param {number} x The column from which to start erasing to the start of the line.
2011 * @param {number} y The line in which to operate.
2013 Terminal
.prototype.eraseLeft = function(x
, y
) {
2014 var line
= this.lines
.get(this.ybase
+ y
);
2018 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2023 this.updateRange(y
);
2027 * Clears the entire buffer, making the prompt line the new first line.
2029 Terminal
.prototype.clear = function() {
2030 if (this.ybase
=== 0 && this.y
=== 0) {
2031 // Don't clear if it's already clear
2034 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2035 this.lines
.length
= 1;
2039 for (var i
= 1; i
< this.rows
; i
++) {
2040 this.lines
.push(this.blankLine());
2042 this.refresh(0, this.rows
- 1);
2043 this.emit('scroll', this.ydisp
);
2047 * Erase all content in the given line
2048 * @param {number} y The line to erase all of its contents.
2050 Terminal
.prototype.eraseLine = function(y
) {
2051 this.eraseRight(0, y
);
2056 * Return the data array of a blank line
2057 * @param {number} cur First bunch of data for each "blank" character.
2059 Terminal
.prototype.blankLine = function(cur
) {
2064 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2068 for (; i
< this.cols
; i
++) {
2077 * If cur return the back color xterm feature attribute. Else return defAttr.
2078 * @param {object} cur
2080 Terminal
.prototype.ch = function(cur
) {
2082 ? [this.eraseAttr(), ' ', 1]
2083 : [this.defAttr
, ' ', 1];
2088 * Evaluate if the current erminal is the given argument.
2089 * @param {object} term The terminal to evaluate
2091 Terminal
.prototype.is = function(term
) {
2092 var name
= this.termName
;
2093 return (name
+ '').indexOf(term
) === 0;
2098 * Emit the 'data' event and populate the given data.
2099 * @param {string} data The data to populate in the event.
2101 Terminal
.prototype.handler = function(data
) {
2102 // Prevents all events to pty process if stdin is disabled
2103 if (this.options
.disableStdin
) {
2107 // Input is being sent to the terminal, the terminal should focus the prompt.
2108 if (this.ybase
!== this.ydisp
) {
2109 this.scrollToBottom();
2111 this.emit('data', data
);
2116 * Emit the 'title' event and populate the given title.
2117 * @param {string} title The title to populate in the event.
2119 Terminal
.prototype.handleTitle = function(title
) {
2121 * This event is emitted when the title of the terminal is changed
2122 * from inside the terminal. The parameter is the new title.
2126 this.emit('title', title
);
2135 * ESC D Index (IND is 0x84).
2137 Terminal
.prototype.index = function() {
2139 if (this.y
> this.scrollBottom
) {
2143 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2144 if (this.x
>= this.cols
) {
2151 * ESC M Reverse Index (RI is 0x8d).
2153 * Move the cursor up one row, inserting a new blank line if necessary.
2155 Terminal
.prototype.reverseIndex = function() {
2157 if (this.y
=== this.scrollTop
) {
2158 // possibly move the code below to term.reverseScroll();
2159 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2160 // blankLine(true) is xterm/linux behavior
2161 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2162 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2163 this.updateRange(this.scrollTop
);
2164 this.updateRange(this.scrollBottom
);
2172 * ESC c Full Reset (RIS).
2174 Terminal
.prototype.reset = function() {
2175 this.options
.rows
= this.rows
;
2176 this.options
.cols
= this.cols
;
2177 var customKeydownHandler
= this.customKeydownHandler
;
2178 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2179 Terminal
.call(this, this.options
);
2180 this.customKeydownHandler
= customKeydownHandler
;
2181 this.cursorBlinkInterval
= cursorBlinkInterval
;
2182 this.refresh(0, this.rows
- 1);
2183 this.viewport
.syncScrollArea();
2188 * ESC H Tab Set (HTS is 0x88).
2190 Terminal
.prototype.tabSet = function() {
2191 this.tabs
[this.x
] = true;
2198 function on(el
, type
, handler
, capture
) {
2199 if (!Array
.isArray(el
)) {
2202 el
.forEach(function (element
) {
2203 element
.addEventListener(type
, handler
, capture
|| false);
2207 function off(el
, type
, handler
, capture
) {
2208 el
.removeEventListener(type
, handler
, capture
|| false);
2211 function cancel(ev
, force
) {
2212 if (!this.cancelEvents
&& !force
) {
2215 ev
.preventDefault();
2216 ev
.stopPropagation();
2220 function inherits(child
, parent
) {
2222 this.constructor = child
;
2224 f
.prototype = parent
.prototype;
2225 child
.prototype = new f
;
2228 function indexOf(obj
, el
) {
2231 if (obj
[i
] === el
) return i
;
2236 function isThirdLevelShift(term
, ev
) {
2238 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2239 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2241 if (ev
.type
== 'keypress') {
2242 return thirdLevelKey
;
2245 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2246 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2249 // Expose to InputHandler (temporary)
2250 Terminal
.prototype.matchColor
= matchColor
;
2252 function matchColor(r1
, g1
, b1
) {
2253 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2255 if (matchColor
._cache
[hash
] != null) {
2256 return matchColor
._cache
[hash
];
2259 var ldiff
= Infinity
2268 for (; i
< Terminal
.vcolors
.length
; i
++) {
2269 c
= Terminal
.vcolors
[i
];
2274 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2287 return matchColor
._cache
[hash
] = li
;
2290 matchColor
._cache
= {};
2292 // http://stackoverflow.com/questions/1633828
2293 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2294 return Math
.pow(30 * (r1
- r2
), 2)
2295 + Math
.pow(59 * (g1
- g2
), 2)
2296 + Math
.pow(11 * (b1
- b2
), 2);
2299 function each(obj
, iter
, con
) {
2300 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2301 for (var i
= 0; i
< obj
.length
; i
++) {
2302 iter
.call(con
, obj
[i
], i
, obj
);
2306 function wasMondifierKeyOnlyEvent(ev
) {
2307 return ev
.keyCode
=== 16 || // Shift
2308 ev
.keyCode
=== 17 || // Ctrl
2309 ev
.keyCode
=== 18; // Alt
2312 function keys(obj
) {
2313 if (Object
.keys
) return Object
.keys(obj
);
2316 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2327 Terminal
.EventEmitter
= EventEmitter
;
2328 Terminal
.inherits
= inherits
;
2331 * Adds an event listener to the terminal.
2333 * @param {string} event The name of the event. TODO: Document all event types
2334 * @param {function} callback The function to call when the event is triggered.
2338 Terminal
.cancel
= cancel
;
2340 module
.exports
= Terminal
;