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 { CharMeasure
} from './utils/CharMeasure';
22 import * as Browser
from './utils/Browser';
23 import * as Keyboard
from './utils/Keyboard';
24 import { CHARSETS
} from './Charsets';
27 * Terminal Emulation References:
29 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
30 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
31 * http://invisible-island.net/vttest/
32 * http://www.inwap.com/pdp10/ansicode.txt
33 * http://linux.die.net/man/4/console_codes
34 * http://linux.die.net/man/7/urxvt
37 // Let it work inside Node.js for automated testing purposes.
38 var document
= (typeof window
!= 'undefined') ? window
.document
: null;
41 * The amount of write requests to queue before sending an XOFF signal to the
42 * pty process. This number must be small in order for ^C and similar sequences
45 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
48 * The number of writes to perform in a single batch before allowing the
49 * renderer to catch up with a 0ms setTimeout.
51 var WRITE_BATCH_SIZE
= 300;
54 * The maximum number of refresh frames to skip when the write buffer is non-
55 * empty. Note that these frames may be intermingled with frames that are
56 * skipped via requestAnimationFrame's mechanism.
58 var MAX_REFRESH_FRAME_SKIP
= 5;
65 * Creates a new `Terminal` object.
67 * @param {object} options An object containing a set of options, the available options are:
68 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
69 * - `cols` (number): The number of columns of the terminal (horizontal size)
70 * - `rows` (number): The number of rows of the terminal (vertical size)
74 * @alias module:xterm/src/xterm
76 function Terminal(options
) {
79 if (!(this instanceof Terminal
)) {
80 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
83 self
.browser
= Browser
;
84 self
.cancel
= Terminal
.cancel
;
86 EventEmitter
.call(this);
88 if (typeof options
=== 'number') {
96 options
= options
|| {};
99 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
100 if (options
[key
] == null) {
101 options
[key
] = Terminal
.options
[key
];
103 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
104 options
[key
] = Terminal
[key
];
107 self
[key
] = options
[key
];
110 if (options
.colors
.length
=== 8) {
111 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
112 } else if (options
.colors
.length
=== 16) {
113 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
114 } else if (options
.colors
.length
=== 10) {
115 options
.colors
= options
.colors
.slice(0, -2).concat(
116 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
117 } else if (options
.colors
.length
=== 18) {
118 options
.colors
= options
.colors
.concat(
119 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
121 this.colors
= options
.colors
;
123 this.options
= options
;
125 // this.context = options.context || window;
126 // this.document = options.document || document;
127 this.parent
= options
.body
|| options
.parent
|| (
128 document
? document
.getElementsByTagName('body')[0] : null
131 this.cols
= options
.cols
|| options
.geometry
[0];
132 this.rows
= options
.rows
|| options
.geometry
[1];
133 this.geometry
= [this.cols
, this.rows
];
135 if (options
.handler
) {
136 this.on('data', options
.handler
);
140 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
146 * The scroll position of the viewport
151 * The cursor's x position after ybase
156 * The cursor's y position after ybase
160 /** A queue of the rows to be refreshed */
161 this.refreshRowsQueue
= [];
163 this.cursorState
= 0;
164 this.cursorHidden
= false;
168 this.scrollBottom
= this.rows
- 1;
169 this.customKeydownHandler
= null;
172 this.applicationKeypad
= false;
173 this.applicationCursor
= false;
174 this.originMode
= false;
175 this.insertMode
= false;
176 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
181 this.gcharset
= null;
183 this.charsets
= [null];
207 this.readable
= true;
208 this.writable
= true;
210 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
211 this.curAttr
= this.defAttr
;
214 this.currentParam
= 0;
218 this.inputHandler
= new InputHandler(this);
219 this.parser
= new Parser(this.inputHandler
, this);
222 this.writeBuffer
= [];
223 this.writeInProgress
= false;
224 this.refreshFramesSkipped
= 0;
227 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
228 * This is a distinct state from writeStopped so that if the user requested
229 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
232 this.xoffSentToCatchUp
= false;
234 /** Whether writing has been stopped as a result of XOFF */
235 this.writeStopped
= false;
237 // leftover surrogate high from previous write invocation
238 this.surrogate_high
= '';
241 * An array of all lines in the entire buffer, including the prompt. The lines are array of
242 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
244 this.lines
= new CircularList(this.scrollback
);
247 this.lines
.push(this.blankLine());
253 // Store if user went browsing history in scrollback
254 this.userScrolling
= false;
257 inherits(Terminal
, EventEmitter
);
260 * back_color_erase feature for xterm.
262 Terminal
.prototype.eraseAttr = function() {
263 // if (this.is('screen')) return this.defAttr;
264 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
272 Terminal
.tangoColors
= [
293 // Colors 0-15 + 16-255
294 // Much thanks to TooTallNate for writing this.
295 Terminal
.colors
= (function() {
296 var colors
= Terminal
.tangoColors
.slice()
297 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
302 for (; i
< 216; i
++) {
303 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
308 for (; i
< 24; i
++) {
313 function out(r
, g
, b
) {
314 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
319 return c
.length
< 2 ? '0' + c
: c
;
325 Terminal
._colors
= Terminal
.colors
.slice();
327 Terminal
.vcolors
= (function() {
329 , colors
= Terminal
.colors
333 for (; i
< 256; i
++) {
334 color
= parseInt(colors
[i
].substring(1), 16);
336 (color
>> 16) & 0xff,
349 Terminal
.defaults
= {
350 colors
: Terminal
.colors
,
356 cursorStyle
: 'block',
365 // programFeatures: false,
369 Terminal
.options
= {};
371 Terminal
.focus
= null;
373 each(keys(Terminal
.defaults
), function(key
) {
374 Terminal
[key
] = Terminal
.defaults
[key
];
375 Terminal
.options
[key
] = Terminal
.defaults
[key
];
379 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
381 Terminal
.prototype.focus = function() {
382 return this.textarea
.focus();
386 * Retrieves an option's value from the terminal.
387 * @param {string} key The option key.
389 Terminal
.prototype.getOption = function(key
, value
) {
390 if (!(key
in Terminal
.defaults
)) {
391 throw new Error('No option with key "' + key
+ '"');
394 if (typeof this.options
[key
] !== 'undefined') {
395 return this.options
[key
];
402 * Sets an option on the terminal.
403 * @param {string} key The option key.
404 * @param {string} value The option value.
406 Terminal
.prototype.setOption = function(key
, value
) {
407 if (!(key
in Terminal
.defaults
)) {
408 throw new Error('No option with key "' + key
+ '"');
412 if (this.options
[key
] !== value
) {
413 if (this.lines
.length
> value
) {
414 const amountToTrim
= this.lines
.length
- value
;
415 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
416 this.lines
.trimStart(amountToTrim
);
417 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
418 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
420 this.refresh(0, this.rows
- 1);
423 this.lines
.maxLength
= value
;
424 this.viewport
.syncScrollArea();
429 this.options
[key
] = value
;
431 case 'cursorBlink': this.element
.classList
.toggle('xterm-cursor-blink', value
); break;
433 // Style 'block' applies with no class
434 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
435 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
437 case 'tabStopWidth': this.setupStops(); break;
442 * Binds the desired focus behavior on a given terminal object.
446 Terminal
.bindFocus = function (term
) {
447 on(term
.textarea
, 'focus', function (ev
) {
448 if (term
.sendFocus
) {
449 term
.send(C0
.ESC
+ '[I');
451 term
.element
.classList
.add('focus');
453 Terminal
.focus
= term
;
454 term
.emit('focus', {terminal
: term
});
459 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
461 Terminal
.prototype.blur = function() {
462 return this.textarea
.blur();
466 * Binds the desired blur behavior on a given terminal object.
470 Terminal
.bindBlur = function (term
) {
471 on(term
.textarea
, 'blur', function (ev
) {
472 term
.queueRefresh(term
.y
, term
.y
);
473 if (term
.sendFocus
) {
474 term
.send(C0
.ESC
+ '[O');
476 term
.element
.classList
.remove('focus');
477 Terminal
.focus
= null;
478 term
.emit('blur', {terminal
: term
});
483 * Initialize default behavior
485 Terminal
.prototype.initGlobal = function() {
488 Terminal
.bindKeys(this);
489 Terminal
.bindFocus(this);
490 Terminal
.bindBlur(this);
492 // Bind clipboard functionality
493 on(this.element
, 'copy', function (ev
) {
494 copyHandler
.call(this, ev
, term
);
496 on(this.textarea
, 'paste', function (ev
) {
497 pasteHandler
.call(this, ev
, term
);
499 on(this.element
, 'paste', function (ev
) {
500 pasteHandler
.call(this, ev
, term
);
503 function rightClickHandlerWrapper (ev
) {
504 rightClickHandler
.call(this, ev
, term
);
507 if (term
.browser
.isFirefox
) {
508 on(this.element
, 'mousedown', function (ev
) {
509 if (ev
.button
== 2) {
510 rightClickHandlerWrapper(ev
);
514 on(this.element
, 'contextmenu', rightClickHandlerWrapper
);
519 * Apply key handling to the terminal
521 Terminal
.bindKeys = function(term
) {
522 on(term
.element
, 'keydown', function(ev
) {
523 if (document
.activeElement
!= this) {
529 on(term
.element
, 'keypress', function(ev
) {
530 if (document
.activeElement
!= this) {
536 on(term
.element
, 'keyup', function(ev
) {
537 if (!wasMondifierKeyOnlyEvent(ev
)) {
542 on(term
.textarea
, 'keydown', function(ev
) {
546 on(term
.textarea
, 'keypress', function(ev
) {
548 // Truncate the textarea's value, since it is not needed
552 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
553 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
554 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
555 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
560 * Insert the given row to the terminal or produce a new one
561 * if no row argument is passed. Return the inserted row.
562 * @param {HTMLElement} row (optional) The row to append to the terminal.
564 Terminal
.prototype.insertRow = function (row
) {
565 if (typeof row
!= 'object') {
566 row
= document
.createElement('div');
569 this.rowContainer
.appendChild(row
);
570 this.children
.push(row
);
576 * Opens the terminal within an element.
578 * @param {HTMLElement} parent The element to create the terminal within.
580 Terminal
.prototype.open = function(parent
) {
581 var self
=this, i
=0, div
;
583 this.parent
= parent
|| this.parent
;
586 throw new Error('Terminal requires a parent element.');
589 // Grab global elements
590 this.context
= this.parent
.ownerDocument
.defaultView
;
591 this.document
= this.parent
.ownerDocument
;
592 this.body
= this.document
.getElementsByTagName('body')[0];
594 //Create main element container
595 this.element
= this.document
.createElement('div');
596 this.element
.classList
.add('terminal');
597 this.element
.classList
.add('xterm');
598 this.element
.classList
.add('xterm-theme-' + this.theme
);
599 this.element
.classList
.toggle('xterm-cursor-blink', this.options
.cursorBlink
);
601 this.element
.style
.height
602 this.element
.setAttribute('tabindex', 0);
604 this.viewportElement
= document
.createElement('div');
605 this.viewportElement
.classList
.add('xterm-viewport');
606 this.element
.appendChild(this.viewportElement
);
607 this.viewportScrollArea
= document
.createElement('div');
608 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
609 this.viewportElement
.appendChild(this.viewportScrollArea
);
611 // Create the container that will hold the lines of the terminal and then
612 // produce the lines the lines.
613 this.rowContainer
= document
.createElement('div');
614 this.rowContainer
.classList
.add('xterm-rows');
615 this.element
.appendChild(this.rowContainer
);
618 // Create the container that will hold helpers like the textarea for
619 // capturing DOM Events. Then produce the helpers.
620 this.helperContainer
= document
.createElement('div');
621 this.helperContainer
.classList
.add('xterm-helpers');
622 // TODO: This should probably be inserted once it's filled to prevent an additional layout
623 this.element
.appendChild(this.helperContainer
);
624 this.textarea
= document
.createElement('textarea');
625 this.textarea
.classList
.add('xterm-helper-textarea');
626 this.textarea
.setAttribute('autocorrect', 'off');
627 this.textarea
.setAttribute('autocapitalize', 'off');
628 this.textarea
.setAttribute('spellcheck', 'false');
629 this.textarea
.tabIndex
= 0;
630 this.textarea
.addEventListener('focus', function() {
631 self
.emit('focus', {terminal
: self
});
633 this.textarea
.addEventListener('blur', function() {
634 self
.emit('blur', {terminal
: self
});
636 this.helperContainer
.appendChild(this.textarea
);
638 this.compositionView
= document
.createElement('div');
639 this.compositionView
.classList
.add('composition-view');
640 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
641 this.helperContainer
.appendChild(this.compositionView
);
643 this.charSizeStyleElement
= document
.createElement('style');
644 this.helperContainer
.appendChild(this.charSizeStyleElement
);
646 for (; i
< this.rows
; i
++) {
649 this.parent
.appendChild(this.element
);
651 this.charMeasure
= new CharMeasure(this.helperContainer
);
652 this.charMeasure
.on('charsizechanged', function () {
653 self
.updateCharSizeCSS();
655 this.charMeasure
.measure();
657 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
659 // Setup loop that draws to screen
660 this.queueRefresh(0, this.rows
- 1);
663 // Initialize global actions that
664 // need to be taken on the document.
667 // Ensure there is a Terminal.focus.
670 on(this.element
, 'click', function() {
671 var selection
= document
.getSelection(),
672 collapsed
= selection
.isCollapsed
,
673 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
679 // Listen for mouse events and translate
680 // them into terminal mouse protocols.
683 // Figure out whether boldness affects
684 // the character width of monospace fonts.
685 if (Terminal
.brokenBold
== null) {
686 Terminal
.brokenBold
= isBoldBroken(this.document
);
690 * This event is emitted when terminal has completed opening.
699 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
700 * @param {string} addon The name of the addon to load
703 Terminal
.loadAddon = function(addon
, callback
) {
704 if (typeof exports
=== 'object' && typeof module
=== 'object') {
706 return require('./addons/' + addon
+ '/' + addon
);
707 } else if (typeof define
== 'function') {
709 return require(['./addons/' + addon
+ '/' + addon
], callback
);
711 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
717 * Updates the helper CSS class with any changes necessary after the terminal's
718 * character width has been changed.
720 Terminal
.prototype.updateCharSizeCSS = function() {
721 this.charSizeStyleElement
.textContent
= '.xterm-wide-char{width:' + (this.charMeasure
.width
* 2) + 'px;}';
726 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
727 * To better understand these
728 * the xterm code is very helpful:
730 * button.c, charproc.c, misc.c
731 * Relevant functions in xterm/button.c:
732 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
734 Terminal
.prototype.bindMouse = function() {
735 var el
= this.element
, self
= this, pressed
= 32;
737 // mouseup, mousedown, wheel
738 // left click: ^[[M 3<^[[M#3<
740 function sendButton(ev
) {
744 // get the xterm-style button
745 button
= getButton(ev
);
747 // get mouse coordinates
751 sendEvent(button
, pos
);
753 switch (ev
.overrideType
|| ev
.type
) {
758 // keep it at the left
759 // button, just in case.
770 // motion example of a left click:
771 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
772 function sendMove(ev
) {
779 // buttons marked as motions
780 // are incremented by 32
783 sendEvent(button
, pos
);
787 // position to characters
788 function encode(data
, ch
) {
789 if (!self
.utfMouse
) {
790 if (ch
=== 255) return data
.push(0);
791 if (ch
> 127) ch
= 127;
794 if (ch
=== 2047) return data
.push(0);
798 if (ch
> 2047) ch
= 2047;
799 data
.push(0xC0 | (ch
>> 6));
800 data
.push(0x80 | (ch
& 0x3F));
805 // send a mouse event:
806 // regular/utf8: ^[[M Cb Cx Cy
807 // urxvt: ^[[ Cb ; Cx ; Cy M
808 // sgr: ^[[ Cb ; Cx ; Cy M/m
809 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
810 // locator: CSI P e ; P b ; P r ; P c ; P p & w
811 function sendEvent(button
, pos
) {
812 // self.emit('mouse', {
818 if (self
.vt300Mouse
) {
820 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
824 var data
= C0
.ESC
+ '[24';
825 if (button
=== 0) data
+= '1';
826 else if (button
=== 1) data
+= '3';
827 else if (button
=== 2) data
+= '5';
828 else if (button
=== 3) return;
830 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
835 if (self
.decLocator
) {
840 if (button
=== 0) button
= 2;
841 else if (button
=== 1) button
= 4;
842 else if (button
=== 2) button
= 6;
843 else if (button
=== 3) button
= 3;
844 self
.send(C0
.ESC
+ '['
847 + (button
=== 3 ? 4 : 0)
858 if (self
.urxvtMouse
) {
863 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
870 self
.send(C0
.ESC
+ '[<'
871 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
876 + ((button
& 3) === 3 ? 'm' : 'M'));
882 encode(data
, button
);
886 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
889 function getButton(ev
) {
902 // 1, and 2 - with 64 added
903 switch (ev
.overrideType
|| ev
.type
) {
905 button
= ev
.button
!= null
911 if (self
.browser
.isMSIE
) {
912 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
918 case 'DOMMouseScroll':
919 button
= ev
.detail
< 0
924 button
= ev
.wheelDeltaY
> 0
930 // next three bits are the modifiers:
931 // 4 = shift, 8 = meta, 16 = control
932 shift
= ev
.shiftKey
? 4 : 0;
933 meta
= ev
.metaKey
? 8 : 0;
934 ctrl
= ev
.ctrlKey
? 16 : 0;
935 mod
= shift
| meta
| ctrl
;
938 if (self
.vt200Mouse
) {
941 } else if (!self
.normalMouse
) {
946 button
= (32 + (mod
<< 2)) + button
;
951 // mouse coordinates measured in cols/rows
952 function getCoords(ev
) {
955 // ignore browsers without pageX for now
956 if (ev
.pageX
== null) return;
962 // should probably check offsetParent
963 // but this is more portable
964 while (el
&& el
!== self
.document
.documentElement
) {
967 el
= 'offsetParent' in el
972 // convert to cols/rows
973 w
= self
.element
.clientWidth
;
974 h
= self
.element
.clientHeight
;
975 x
= Math
.ceil((x
/ w
) * self
.cols
);
976 y
= Math
.ceil((y
/ h
) * self
.rows
);
978 // be sure to avoid sending
979 // bad positions to the program
981 if (x
> self
.cols
) x
= self
.cols
;
983 if (y
> self
.rows
) y
= self
.rows
;
985 // xterm sends raw bytes and
986 // starts at 32 (SP) for each.
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
.parentNode
) {
1062 this.element
.parentNode
.removeChild(this.element
);
1064 //this.emit('close');
1069 * Flags used to render terminal text properly
1080 * Queues a refresh between two rows (inclusive), to be done on next animation
1082 * @param {number} start The start row.
1083 * @param {number} end The end row.
1085 Terminal
.prototype.queueRefresh = function(start
, end
) {
1086 this.refreshRowsQueue
.push({ start
: start
, end
: end
});
1090 * Performs the refresh loop callback, calling refresh only if a refresh is
1091 * necessary before queueing up the next one.
1093 Terminal
.prototype.refreshLoop = function() {
1094 // Don't refresh if there were no row changes
1095 if (this.refreshRowsQueue
.length
> 0) {
1096 // Skip MAX_REFRESH_FRAME_SKIP frames if the writeBuffer is non-empty as it
1097 // will need to be immediately refreshed anyway. This saves a lot of
1098 // rendering time as the viewport DOM does not need to be refreshed, no
1099 // scroll events, no layouts, etc.
1100 var skipFrame
= this.writeBuffer
.length
> 0 && this.refreshFramesSkipped
++ <= MAX_REFRESH_FRAME_SKIP
;
1103 this.refreshFramesSkipped
= 0;
1106 if (this.refreshRowsQueue
.length
> 4) {
1107 // Just do a full refresh when 5+ refreshes are queued
1109 end
= this.rows
- 1;
1111 // Get start and end rows that need refreshing
1112 start
= this.refreshRowsQueue
[0].start
;
1113 end
= this.refreshRowsQueue
[0].end
;
1114 for (var i
= 1; i
< this.refreshRowsQueue
.length
; i
++) {
1115 if (this.refreshRowsQueue
[i
].start
< start
) {
1116 start
= this.refreshRowsQueue
[i
].start
;
1118 if (this.refreshRowsQueue
[i
].end
> end
) {
1119 end
= this.refreshRowsQueue
[i
].end
;
1123 this.refreshRowsQueue
= [];
1124 this.refresh(start
, end
);
1127 window
.requestAnimationFrame(this.refreshLoop
.bind(this));
1131 * Refreshes (re-renders) terminal content within two rows (inclusive)
1135 * In the screen buffer, each character is stored as a an array with a character
1136 * and a 32-bit integer:
1137 * - First value: a utf-16 character.
1139 * - Next 9 bits: background color (0-511).
1140 * - Next 9 bits: foreground color (0-511).
1141 * - Next 14 bits: a mask for misc. flags:
1148 * @param {number} start The row to start from (between 0 and terminal's height terminal - 1)
1149 * @param {number} end The row to end at (between fromRow and terminal's height terminal - 1)
1151 Terminal
.prototype.refresh = function(start
, end
) {
1154 var x
, y
, i
, line
, out
, ch
, ch_width
, width
, data
, attr
, bg
, fg
, flags
, row
, parent
, focused
= document
.activeElement
;
1156 // If this is a big refresh, remove the terminal rows from the DOM for faster calculations
1157 if (end
- start
>= this.rows
/ 2) {
1158 parent
= this.element
.parentNode
;
1160 this.element
.removeChild(this.rowContainer
);
1167 if (end
>= this.rows
.length
) {
1168 this.log('`end` is too large. Most likely a bad CSR.');
1169 end
= this.rows
.length
- 1;
1172 for (; y
<= end
; y
++) {
1173 row
= y
+ this.ydisp
;
1175 line
= this.lines
.get(row
);
1176 if (!line
|| !this.children
[y
]) {
1177 // Continue if the line is not available, this means a resize is currently in progress
1182 if (this.y
=== y
- (this.ybase
- this.ydisp
)
1184 && !this.cursorHidden
) {
1190 attr
= this.defAttr
;
1193 for (; i
< width
; i
++) {
1195 // Continue if the character is not available, this means a resize is currently in progress
1200 ch_width
= line
[i
][2];
1204 if (i
=== x
) data
= -1;
1206 if (data
!== attr
) {
1207 if (attr
!== this.defAttr
) {
1210 if (data
!== this.defAttr
) {
1212 out
+= '<span class="reverse-video terminal-cursor">';
1214 var classNames
= [];
1217 fg
= (data
>> 9) & 0x1ff;
1220 if (flags
& Terminal
.flags
.BOLD
) {
1221 if (!Terminal
.brokenBold
) {
1222 classNames
.push('xterm-bold');
1224 // See: XTerm*boldColors
1225 if (fg
< 8) fg
+= 8;
1228 if (flags
& Terminal
.flags
.UNDERLINE
) {
1229 classNames
.push('xterm-underline');
1232 if (flags
& Terminal
.flags
.BLINK
) {
1233 classNames
.push('xterm-blink');
1236 // If inverse flag is on, then swap the foreground and background variables.
1237 if (flags
& Terminal
.flags
.INVERSE
) {
1238 /* One-line variable swap in JavaScript: http://stackoverflow.com/a/16201730 */
1239 bg = [fg, fg = bg][0];
1240 // Should inverse just be before the
1241 // above boldColors effect instead?
1242 if ((flags & 1) && fg < 8) fg += 8;
1245 if (flags & Terminal.flags.INVISIBLE) {
1246 classNames.push('xterm-hidden');
1250 * Weird situation: Invert flag used black foreground and white background results
1251 * in invalid background color, positioned at the 256 index of the 256 terminal
1252 * color map. Pin the colors manually in such a case.
1254 * Source: https://github.com/sourcelair/xterm.js/issues/57
1256 if (flags
& Terminal
.flags
.INVERSE
) {
1266 classNames
.push('xterm-bg-color-' + bg
);
1270 classNames
.push('xterm-color-' + fg
);
1274 if (classNames
.length
) {
1275 out
+= ' class="' + classNames
.join(' ') + '"';
1282 if (ch_width
=== 2) {
1283 out
+= '<span class="xterm-wide-char">';
1303 if (ch_width
=== 2) {
1310 if (attr
!== this.defAttr
) {
1314 this.children
[y
].innerHTML
= out
;
1318 this.element
.appendChild(this.rowContainer
);
1321 this.emit('refresh', {element
: this.element
, start
: start
, end
: end
});
1325 * Display the cursor element
1327 Terminal
.prototype.showCursor = function() {
1328 if (!this.cursorState
) {
1329 this.cursorState
= 1;
1330 this.queueRefresh(this.y
, this.y
);
1335 * Scroll the terminal down 1 row, creating a blank line.
1337 Terminal
.prototype.scroll = function() {
1340 // Make room for the new row in lines
1341 if (this.lines
.length
=== this.lines
.maxLength
) {
1342 this.lines
.trimStart(1);
1344 if (this.ydisp
!== 0) {
1351 // TODO: Why is this done twice?
1352 if (!this.userScrolling
) {
1353 this.ydisp
= this.ybase
;
1357 row
= this.ybase
+ this.rows
- 1;
1359 // subtract the bottom scroll region
1360 row
-= this.rows
- 1 - this.scrollBottom
;
1362 if (row
=== this.lines
.length
) {
1363 // Optimization: pushing is faster than splicing when they amount to the same behavior
1364 this.lines
.push(this.blankLine());
1367 this.lines
.splice(row
, 0, this.blankLine());
1370 if (this.scrollTop
!== 0) {
1371 if (this.ybase
!== 0) {
1373 if (!this.userScrolling
) {
1374 this.ydisp
= this.ybase
;
1377 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1381 this.updateRange(this.scrollTop
);
1382 this.updateRange(this.scrollBottom
);
1385 * This event is emitted whenever the terminal is scrolled.
1386 * The one parameter passed is the new y display position.
1390 this.emit('scroll', this.ydisp
);
1394 * Scroll the display of the terminal
1395 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1396 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1397 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1398 * viewport originally.
1400 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1402 this.userScrolling
= true;
1403 } else if (disp
+ this.ydisp
>= this.ybase
) {
1404 this.userScrolling
= false;
1409 if (this.ydisp
> this.ybase
) {
1410 this.ydisp
= this.ybase
;
1411 } else if (this.ydisp
< 0) {
1415 if (!suppressScrollEvent
) {
1416 this.emit('scroll', this.ydisp
);
1419 this.queueRefresh(0, this.rows
- 1);
1423 * Scroll the display of the terminal by a number of pages.
1424 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1426 Terminal
.prototype.scrollPages = function(pageCount
) {
1427 this.scrollDisp(pageCount
* (this.rows
- 1));
1431 * Scrolls the display of the terminal to the top.
1433 Terminal
.prototype.scrollToTop = function() {
1434 this.scrollDisp(-this.ydisp
);
1438 * Scrolls the display of the terminal to the bottom.
1440 Terminal
.prototype.scrollToBottom = function() {
1441 this.scrollDisp(this.ybase
- this.ydisp
);
1445 * Writes text to the terminal.
1446 * @param {string} text The text to write to the terminal.
1448 Terminal
.prototype.write = function(data
) {
1449 this.writeBuffer
.push(data
);
1451 // Send XOFF to pause the pty process if the write buffer becomes too large so
1452 // xterm.js can catch up before more data is sent. This is necessary in order
1453 // to keep signals such as ^C responsive.
1454 if (!this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1455 // XOFF - stop pty pipe
1456 // XON will be triggered by emulator before processing data chunk
1458 this.xoffSentToCatchUp
= true;
1461 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1462 // Kick off a write which will write all data in sequence recursively
1463 this.writeInProgress
= true;
1464 // Kick off an async innerWrite so more writes can come in while processing data
1466 setTimeout(function () {
1472 Terminal
.prototype.innerWrite = function() {
1473 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1474 while (writeBatch
.length
> 0) {
1475 var data
= writeBatch
.shift();
1476 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1478 // If XOFF was sent in order to catch up with the pty process, resume it if
1479 // the writeBuffer is empty to allow more data to come in.
1480 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1482 this.xoffSentToCatchUp
= false;
1485 this.refreshStart
= this.y
;
1486 this.refreshEnd
= this.y
;
1488 this.parser
.parse(data
);
1490 this.updateRange(this.y
);
1491 this.queueRefresh(this.refreshStart
, this.refreshEnd
);
1493 if (this.writeBuffer
.length
> 0) {
1494 // Allow renderer to catch up before processing the next batch
1496 setTimeout(function () {
1500 this.writeInProgress
= false;
1505 * Writes text to the terminal, followed by a break line character (\n).
1506 * @param {string} text The text to write to the terminal.
1508 Terminal
.prototype.writeln = function(data
) {
1509 this.write(data
+ '\r\n');
1513 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1514 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1516 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1517 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1518 * the default action. The function returns whether the event should be processed by xterm.js.
1520 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1521 this.customKeydownHandler
= customKeydownHandler
;
1525 * Handle a keydown event
1527 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1528 * @param {KeyboardEvent} ev The keydown event to be handled.
1530 Terminal
.prototype.keyDown = function(ev
) {
1531 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1535 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1536 if (this.ybase
!== this.ydisp
) {
1537 this.scrollToBottom();
1543 var result
= this.evaluateKeyEscapeSequence(ev
);
1545 if (result
.key
=== C0
.DC3
) { // XOFF
1546 this.writeStopped
= true;
1547 } else if (result
.key
=== C0
.DC1
) { // XON
1548 this.writeStopped
= false;
1551 if (result
.scrollDisp
) {
1552 this.scrollDisp(result
.scrollDisp
);
1553 return this.cancel(ev
, true);
1556 if (isThirdLevelShift(this, ev
)) {
1560 if (result
.cancel
) {
1561 // The event is canceled at the end already, is this necessary?
1562 this.cancel(ev
, true);
1569 this.emit('keydown', ev
);
1570 this.emit('key', result
.key
, ev
);
1572 this.handler(result
.key
);
1574 return this.cancel(ev
, true);
1578 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1579 * returned value is the new key code to pass to the PTY.
1581 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1582 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1584 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1586 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1587 // canceled at the end of keyDown
1589 // The new key even to emit
1591 // The number of characters to scroll, if this is defined it will cancel the event
1592 scrollDisp
: undefined
1594 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1595 switch (ev
.keyCode
) {
1599 result
.key
= C0
.BS
; // ^H
1602 result
.key
= C0
.DEL
; // ^?
1607 result
.key
= C0
.ESC
+ '[Z';
1611 result
.cancel
= true;
1616 result
.cancel
= true;
1620 result
.key
= C0
.ESC
;
1621 result
.cancel
= true;
1626 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1627 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1628 // http://unix.stackexchange.com/a/108106
1629 // macOS uses different escape sequences than linux
1630 if (result
.key
== C0
.ESC
+ '[1;3D') {
1631 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1633 } else if (this.applicationCursor
) {
1634 result
.key
= C0
.ESC
+ 'OD';
1636 result
.key
= C0
.ESC
+ '[D';
1642 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1643 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1644 // http://unix.stackexchange.com/a/108106
1645 // macOS uses different escape sequences than linux
1646 if (result
.key
== C0
.ESC
+ '[1;3C') {
1647 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1649 } else if (this.applicationCursor
) {
1650 result
.key
= C0
.ESC
+ 'OC';
1652 result
.key
= C0
.ESC
+ '[C';
1658 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1659 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1660 // http://unix.stackexchange.com/a/108106
1661 if (result
.key
== C0
.ESC
+ '[1;3A') {
1662 result
.key
= C0
.ESC
+ '[1;5A';
1664 } else if (this.applicationCursor
) {
1665 result
.key
= C0
.ESC
+ 'OA';
1667 result
.key
= C0
.ESC
+ '[A';
1673 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1674 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1675 // http://unix.stackexchange.com/a/108106
1676 if (result
.key
== C0
.ESC
+ '[1;3B') {
1677 result
.key
= C0
.ESC
+ '[1;5B';
1679 } else if (this.applicationCursor
) {
1680 result
.key
= C0
.ESC
+ 'OB';
1682 result
.key
= C0
.ESC
+ '[B';
1687 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1688 // <Ctrl> or <Shift> + <Insert> are used to
1689 // copy-paste on some systems.
1690 result
.key
= C0
.ESC
+ '[2~';
1696 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1698 result
.key
= C0
.ESC
+ '[3~';
1704 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1705 else if (this.applicationCursor
)
1706 result
.key
= C0
.ESC
+ 'OH';
1708 result
.key
= C0
.ESC
+ '[H';
1713 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1714 else if (this.applicationCursor
)
1715 result
.key
= C0
.ESC
+ 'OF';
1717 result
.key
= C0
.ESC
+ '[F';
1722 result
.scrollDisp
= -(this.rows
- 1);
1724 result
.key
= C0
.ESC
+ '[5~';
1730 result
.scrollDisp
= this.rows
- 1;
1732 result
.key
= C0
.ESC
+ '[6~';
1738 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1740 result
.key
= C0
.ESC
+ 'OP';
1745 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1747 result
.key
= C0
.ESC
+ 'OQ';
1752 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1754 result
.key
= C0
.ESC
+ 'OR';
1759 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1761 result
.key
= C0
.ESC
+ 'OS';
1766 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1768 result
.key
= C0
.ESC
+ '[15~';
1773 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1775 result
.key
= C0
.ESC
+ '[17~';
1780 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1782 result
.key
= C0
.ESC
+ '[18~';
1787 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1789 result
.key
= C0
.ESC
+ '[19~';
1794 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1796 result
.key
= C0
.ESC
+ '[20~';
1801 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1803 result
.key
= C0
.ESC
+ '[21~';
1808 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1810 result
.key
= C0
.ESC
+ '[23~';
1815 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1817 result
.key
= C0
.ESC
+ '[24~';
1822 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1823 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1824 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1825 } else if (ev
.keyCode
=== 32) {
1827 result
.key
= String
.fromCharCode(0);
1828 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1829 // escape, file sep, group sep, record sep, unit sep
1830 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1831 } else if (ev
.keyCode
=== 56) {
1833 result
.key
= String
.fromCharCode(127);
1834 } else if (ev
.keyCode
=== 219) {
1835 // ^[ - Control Sequence Introducer (CSI)
1836 result
.key
= String
.fromCharCode(27);
1837 } else if (ev
.keyCode
=== 220) {
1838 // ^\ - String Terminator (ST)
1839 result
.key
= String
.fromCharCode(28);
1840 } else if (ev
.keyCode
=== 221) {
1841 // ^] - Operating System Command (OSC)
1842 result
.key
= String
.fromCharCode(29);
1844 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1845 // On Mac this is a third level shift. Use <Esc> instead.
1846 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1847 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1848 } else if (ev
.keyCode
=== 192) {
1849 result
.key
= C0
.ESC
+ '`';
1850 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1851 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1861 * Set the G level of the terminal
1864 Terminal
.prototype.setgLevel = function(g
) {
1866 this.charset
= this.charsets
[g
];
1870 * Set the charset for the given G level of the terminal
1874 Terminal
.prototype.setgCharset = function(g
, charset
) {
1875 this.charsets
[g
] = charset
;
1876 if (this.glevel
=== g
) {
1877 this.charset
= charset
;
1882 * Handle a keypress event.
1884 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1885 * @param {KeyboardEvent} ev The keypress event to be handled.
1887 Terminal
.prototype.keyPress = function(ev
) {
1894 } else if (ev
.which
== null) {
1896 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1903 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1908 key
= String
.fromCharCode(key
);
1910 this.emit('keypress', key
, ev
);
1911 this.emit('key', key
, ev
);
1919 * Send data for handling to the terminal
1920 * @param {string} data
1922 Terminal
.prototype.send = function(data
) {
1926 setTimeout(function() {
1927 self
.handler(self
.queue
);
1937 * Note: We could do sweet things with webaudio here
1939 Terminal
.prototype.bell = function() {
1940 if (!this.visualBell
) return;
1942 this.element
.style
.borderColor
= 'white';
1943 setTimeout(function() {
1944 self
.element
.style
.borderColor
= '';
1946 if (this.popOnBell
) this.focus();
1950 * Log the current state to the console.
1952 Terminal
.prototype.log = function() {
1953 if (!this.debug
) return;
1954 if (!this.context
.console
|| !this.context
.console
.log
) return;
1955 var args
= Array
.prototype.slice
.call(arguments
);
1956 this.context
.console
.log
.apply(this.context
.console
, args
);
1960 * Log the current state as error to the console.
1962 Terminal
.prototype.error = function() {
1963 if (!this.debug
) return;
1964 if (!this.context
.console
|| !this.context
.console
.error
) return;
1965 var args
= Array
.prototype.slice
.call(arguments
);
1966 this.context
.console
.error
.apply(this.context
.console
, args
);
1970 * Resizes the terminal.
1972 * @param {number} x The number of columns to resize to.
1973 * @param {number} y The number of rows to resize to.
1975 Terminal
.prototype.resize = function(x
, y
) {
1983 if (x
=== this.cols
&& y
=== this.rows
) {
1993 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1994 i
= this.lines
.length
;
1996 while (this.lines
.get(i
).length
< x
) {
1997 this.lines
.get(i
).push(ch
);
2001 i
= this.lines
.length
;
2003 while (this.lines
.get(i
).length
> x
) {
2004 this.lines
.get(i
).pop();
2009 this.setupStops(this.cols
);
2017 // y is rows, not this.y
2018 if (this.lines
.length
< y
+ this.ybase
) {
2019 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
2020 // There is room above the buffer and there are no empty elements below the line,
2024 if (this.ydisp
> 0) {
2025 // Viewport is at the top of the buffer, must increase downwards
2029 // Add a blank line if there is no buffer left at the top to scroll to, or if there
2030 // are blank lines after the cursor
2031 this.lines
.push(this.blankLine());
2034 if (this.children
.length
< y
) {
2040 if (this.lines
.length
> y
+ this.ybase
) {
2041 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
2042 // The line is a blank line below the cursor, remove it
2045 // The line is the cursor, scroll down
2050 if (this.children
.length
> y
) {
2051 el
= this.children
.shift();
2053 el
.parentNode
.removeChild(el
);
2059 // Make sure that the cursor stays on screen
2072 this.scrollBottom
= y
- 1;
2074 this.charMeasure
.measure();
2076 this.queueRefresh(0, this.rows
- 1);
2080 this.geometry
= [this.cols
, this.rows
];
2081 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
2085 * Updates the range of rows to refresh
2086 * @param {number} y The number of rows to refresh next.
2088 Terminal
.prototype.updateRange = function(y
) {
2089 if (y
< this.refreshStart
) this.refreshStart
= y
;
2090 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
2091 // if (y > this.refreshEnd) {
2092 // this.refreshEnd = y;
2093 // if (y > this.rows - 1) {
2094 // this.refreshEnd = this.rows - 1;
2100 * Set the range of refreshing to the maximum value
2102 Terminal
.prototype.maxRange = function() {
2103 this.refreshStart
= 0;
2104 this.refreshEnd
= this.rows
- 1;
2110 * Setup the tab stops.
2113 Terminal
.prototype.setupStops = function(i
) {
2115 if (!this.tabs
[i
]) {
2116 i
= this.prevStop(i
);
2123 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
2124 this.tabs
[i
] = true;
2130 * Move the cursor to the previous tab stop from the given position (default is current).
2131 * @param {number} x The position to move the cursor to the previous tab stop.
2133 Terminal
.prototype.prevStop = function(x
) {
2134 if (x
== null) x
= this.x
;
2135 while (!this.tabs
[--x
] && x
> 0);
2136 return x
>= this.cols
2143 * Move the cursor one tab stop forward from the given position (default is current).
2144 * @param {number} x The position to move the cursor one tab stop forward.
2146 Terminal
.prototype.nextStop = function(x
) {
2147 if (x
== null) x
= this.x
;
2148 while (!this.tabs
[++x
] && x
< this.cols
);
2149 return x
>= this.cols
2156 * Erase in the identified line everything from "x" to the end of the line (right).
2157 * @param {number} x The column from which to start erasing to the end of the line.
2158 * @param {number} y The line in which to operate.
2160 Terminal
.prototype.eraseRight = function(x
, y
) {
2161 var line
= this.lines
.get(this.ybase
+ y
)
2162 , ch
= [this.eraseAttr(), ' ', 1]; // xterm
2165 for (; x
< this.cols
; x
++) {
2169 this.updateRange(y
);
2175 * Erase in the identified line everything from "x" to the start of the line (left).
2176 * @param {number} x The column from which to start erasing to the start of the line.
2177 * @param {number} y The line in which to operate.
2179 Terminal
.prototype.eraseLeft = function(x
, y
) {
2180 var line
= this.lines
.get(this.ybase
+ y
)
2181 , ch
= [this.eraseAttr(), ' ', 1]; // xterm
2184 while (x
--) line
[x
] = ch
;
2186 this.updateRange(y
);
2190 * Clears the entire buffer, making the prompt line the new first line.
2192 Terminal
.prototype.clear = function() {
2193 if (this.ybase
=== 0 && this.y
=== 0) {
2194 // Don't clear if it's already clear
2197 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2198 this.lines
.length
= 1;
2202 for (var i
= 1; i
< this.rows
; i
++) {
2203 this.lines
.push(this.blankLine());
2205 this.queueRefresh(0, this.rows
- 1);
2206 this.emit('scroll', this.ydisp
);
2210 * Erase all content in the given line
2211 * @param {number} y The line to erase all of its contents.
2213 Terminal
.prototype.eraseLine = function(y
) {
2214 this.eraseRight(0, y
);
2219 * Return the data array of a blank line
2220 * @param {number} cur First bunch of data for each "blank" character.
2222 Terminal
.prototype.blankLine = function(cur
) {
2227 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2231 for (; i
< this.cols
; i
++) {
2240 * If cur return the back color xterm feature attribute. Else return defAttr.
2241 * @param {object} cur
2243 Terminal
.prototype.ch = function(cur
) {
2245 ? [this.eraseAttr(), ' ', 1]
2246 : [this.defAttr
, ' ', 1];
2251 * Evaluate if the current erminal is the given argument.
2252 * @param {object} term The terminal to evaluate
2254 Terminal
.prototype.is = function(term
) {
2255 var name
= this.termName
;
2256 return (name
+ '').indexOf(term
) === 0;
2261 * Emit the 'data' event and populate the given data.
2262 * @param {string} data The data to populate in the event.
2264 Terminal
.prototype.handler = function(data
) {
2265 // Prevents all events to pty process if stdin is disabled
2266 if (this.options
.disableStdin
) {
2270 // Input is being sent to the terminal, the terminal should focus the prompt.
2271 if (this.ybase
!== this.ydisp
) {
2272 this.scrollToBottom();
2274 this.emit('data', data
);
2279 * Emit the 'title' event and populate the given title.
2280 * @param {string} title The title to populate in the event.
2282 Terminal
.prototype.handleTitle = function(title
) {
2284 * This event is emitted when the title of the terminal is changed
2285 * from inside the terminal. The parameter is the new title.
2289 this.emit('title', title
);
2298 * ESC D Index (IND is 0x84).
2300 Terminal
.prototype.index = function() {
2302 if (this.y
> this.scrollBottom
) {
2306 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2307 if (this.x
>= this.cols
) {
2314 * ESC M Reverse Index (RI is 0x8d).
2316 * Move the cursor up one row, inserting a new blank line if necessary.
2318 Terminal
.prototype.reverseIndex = function() {
2320 if (this.y
=== this.scrollTop
) {
2321 // possibly move the code below to term.reverseScroll();
2322 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2323 // blankLine(true) is xterm/linux behavior
2324 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2325 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2326 this.updateRange(this.scrollTop
);
2327 this.updateRange(this.scrollBottom
);
2335 * ESC c Full Reset (RIS).
2337 Terminal
.prototype.reset = function() {
2338 this.options
.rows
= this.rows
;
2339 this.options
.cols
= this.cols
;
2340 var customKeydownHandler
= this.customKeydownHandler
;
2341 Terminal
.call(this, this.options
);
2342 this.customKeydownHandler
= customKeydownHandler
;
2343 this.queueRefresh(0, this.rows
- 1);
2344 this.viewport
.syncScrollArea();
2349 * ESC H Tab Set (HTS is 0x88).
2351 Terminal
.prototype.tabSet = function() {
2352 this.tabs
[this.x
] = true;
2359 function on(el
, type
, handler
, capture
) {
2360 if (!Array
.isArray(el
)) {
2363 el
.forEach(function (element
) {
2364 element
.addEventListener(type
, handler
, capture
|| false);
2368 function off(el
, type
, handler
, capture
) {
2369 el
.removeEventListener(type
, handler
, capture
|| false);
2372 function cancel(ev
, force
) {
2373 if (!this.cancelEvents
&& !force
) {
2376 ev
.preventDefault();
2377 ev
.stopPropagation();
2381 function inherits(child
, parent
) {
2383 this.constructor = child
;
2385 f
.prototype = parent
.prototype;
2386 child
.prototype = new f
;
2389 // if bold is broken, we can't
2390 // use it in the terminal.
2391 function isBoldBroken(document
) {
2392 var body
= document
.getElementsByTagName('body')[0];
2393 var el
= document
.createElement('span');
2394 el
.innerHTML
= 'hello world';
2395 body
.appendChild(el
);
2396 var w1
= el
.scrollWidth
;
2397 el
.style
.fontWeight
= 'bold';
2398 var w2
= el
.scrollWidth
;
2399 body
.removeChild(el
);
2403 function indexOf(obj
, el
) {
2406 if (obj
[i
] === el
) return i
;
2411 function isThirdLevelShift(term
, ev
) {
2413 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2414 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2416 if (ev
.type
== 'keypress') {
2417 return thirdLevelKey
;
2420 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2421 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2424 // Expose to InputHandler (temporary)
2425 Terminal
.prototype.matchColor
= matchColor
;
2427 function matchColor(r1
, g1
, b1
) {
2428 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2430 if (matchColor
._cache
[hash
] != null) {
2431 return matchColor
._cache
[hash
];
2434 var ldiff
= Infinity
2443 for (; i
< Terminal
.vcolors
.length
; i
++) {
2444 c
= Terminal
.vcolors
[i
];
2449 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2462 return matchColor
._cache
[hash
] = li
;
2465 matchColor
._cache
= {};
2467 // http://stackoverflow.com/questions/1633828
2468 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2469 return Math
.pow(30 * (r1
- r2
), 2)
2470 + Math
.pow(59 * (g1
- g2
), 2)
2471 + Math
.pow(11 * (b1
- b2
), 2);
2474 function each(obj
, iter
, con
) {
2475 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2476 for (var i
= 0; i
< obj
.length
; i
++) {
2477 iter
.call(con
, obj
[i
], i
, obj
);
2481 function wasMondifierKeyOnlyEvent(ev
) {
2482 return ev
.keyCode
=== 16 || // Shift
2483 ev
.keyCode
=== 17 || // Ctrl
2484 ev
.keyCode
=== 18; // Alt
2487 function keys(obj
) {
2488 if (Object
.keys
) return Object
.keys(obj
);
2491 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2502 Terminal
.EventEmitter
= EventEmitter
;
2503 Terminal
.inherits
= inherits
;
2506 * Adds an event listener to the terminal.
2508 * @param {string} event The name of the event. TODO: Document all event types
2509 * @param {function} callback The function to call when the event is triggered.
2513 Terminal
.cancel
= cancel
;
2515 module
.exports
= Terminal
;