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',
364 // programFeatures: false,
368 Terminal
.options
= {};
370 Terminal
.focus
= null;
372 each(keys(Terminal
.defaults
), function(key
) {
373 Terminal
[key
] = Terminal
.defaults
[key
];
374 Terminal
.options
[key
] = Terminal
.defaults
[key
];
378 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
380 Terminal
.prototype.focus = function() {
381 return this.textarea
.focus();
385 * Retrieves an option's value from the terminal.
386 * @param {string} key The option key.
388 Terminal
.prototype.getOption = function(key
, value
) {
389 if (!(key
in Terminal
.defaults
)) {
390 throw new Error('No option with key "' + key
+ '"');
393 if (typeof this.options
[key
] !== 'undefined') {
394 return this.options
[key
];
401 * Sets an option on the terminal.
402 * @param {string} key The option key.
403 * @param {string} value The option value.
405 Terminal
.prototype.setOption = function(key
, value
) {
406 if (!(key
in Terminal
.defaults
)) {
407 throw new Error('No option with key "' + key
+ '"');
411 if (this.options
[key
] !== value
) {
412 if (this.lines
.length
> value
) {
413 const amountToTrim
= this.lines
.length
- value
;
414 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
415 this.lines
.trimStart(amountToTrim
);
416 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
417 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
419 this.refresh(0, this.rows
- 1);
422 this.lines
.maxLength
= value
;
423 this.viewport
.syncScrollArea();
428 this.options
[key
] = value
;
430 case 'cursorBlink': this.element
.classList
.toggle('xterm-cursor-blink', value
); break;
432 // Style 'block' applies with no class
433 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
434 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
440 * Binds the desired focus behavior on a given terminal object.
444 Terminal
.bindFocus = function (term
) {
445 on(term
.textarea
, 'focus', function (ev
) {
446 if (term
.sendFocus
) {
447 term
.send(C0
.ESC
+ '[I');
449 term
.element
.classList
.add('focus');
451 Terminal
.focus
= term
;
452 term
.emit('focus', {terminal
: term
});
457 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
459 Terminal
.prototype.blur = function() {
460 return this.textarea
.blur();
464 * Binds the desired blur behavior on a given terminal object.
468 Terminal
.bindBlur = function (term
) {
469 on(term
.textarea
, 'blur', function (ev
) {
470 term
.queueRefresh(term
.y
, term
.y
);
471 if (term
.sendFocus
) {
472 term
.send(C0
.ESC
+ '[O');
474 term
.element
.classList
.remove('focus');
475 Terminal
.focus
= null;
476 term
.emit('blur', {terminal
: term
});
481 * Initialize default behavior
483 Terminal
.prototype.initGlobal = function() {
486 Terminal
.bindKeys(this);
487 Terminal
.bindFocus(this);
488 Terminal
.bindBlur(this);
490 // Bind clipboard functionality
491 on(this.element
, 'copy', function (ev
) {
492 copyHandler
.call(this, ev
, term
);
494 on(this.textarea
, 'paste', function (ev
) {
495 pasteHandler
.call(this, ev
, term
);
497 on(this.element
, 'paste', function (ev
) {
498 pasteHandler
.call(this, ev
, term
);
501 function rightClickHandlerWrapper (ev
) {
502 rightClickHandler
.call(this, ev
, term
);
505 if (term
.browser
.isFirefox
) {
506 on(this.element
, 'mousedown', function (ev
) {
507 if (ev
.button
== 2) {
508 rightClickHandlerWrapper(ev
);
512 on(this.element
, 'contextmenu', rightClickHandlerWrapper
);
517 * Apply key handling to the terminal
519 Terminal
.bindKeys = function(term
) {
520 on(term
.element
, 'keydown', function(ev
) {
521 if (document
.activeElement
!= this) {
527 on(term
.element
, 'keypress', function(ev
) {
528 if (document
.activeElement
!= this) {
534 on(term
.element
, 'keyup', function(ev
) {
535 if (!wasMondifierKeyOnlyEvent(ev
)) {
540 on(term
.textarea
, 'keydown', function(ev
) {
544 on(term
.textarea
, 'keypress', function(ev
) {
546 // Truncate the textarea's value, since it is not needed
550 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
551 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
552 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
553 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
558 * Insert the given row to the terminal or produce a new one
559 * if no row argument is passed. Return the inserted row.
560 * @param {HTMLElement} row (optional) The row to append to the terminal.
562 Terminal
.prototype.insertRow = function (row
) {
563 if (typeof row
!= 'object') {
564 row
= document
.createElement('div');
567 this.rowContainer
.appendChild(row
);
568 this.children
.push(row
);
574 * Opens the terminal within an element.
576 * @param {HTMLElement} parent The element to create the terminal within.
578 Terminal
.prototype.open = function(parent
) {
579 var self
=this, i
=0, div
;
581 this.parent
= parent
|| this.parent
;
584 throw new Error('Terminal requires a parent element.');
587 // Grab global elements
588 this.context
= this.parent
.ownerDocument
.defaultView
;
589 this.document
= this.parent
.ownerDocument
;
590 this.body
= this.document
.getElementsByTagName('body')[0];
592 //Create main element container
593 this.element
= this.document
.createElement('div');
594 this.element
.classList
.add('terminal');
595 this.element
.classList
.add('xterm');
596 this.element
.classList
.add('xterm-theme-' + this.theme
);
597 this.element
.classList
.toggle('xterm-cursor-blink', this.options
.cursorBlink
);
599 this.element
.style
.height
600 this.element
.setAttribute('tabindex', 0);
602 this.viewportElement
= document
.createElement('div');
603 this.viewportElement
.classList
.add('xterm-viewport');
604 this.element
.appendChild(this.viewportElement
);
605 this.viewportScrollArea
= document
.createElement('div');
606 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
607 this.viewportElement
.appendChild(this.viewportScrollArea
);
609 // Create the container that will hold the lines of the terminal and then
610 // produce the lines the lines.
611 this.rowContainer
= document
.createElement('div');
612 this.rowContainer
.classList
.add('xterm-rows');
613 this.element
.appendChild(this.rowContainer
);
616 // Create the container that will hold helpers like the textarea for
617 // capturing DOM Events. Then produce the helpers.
618 this.helperContainer
= document
.createElement('div');
619 this.helperContainer
.classList
.add('xterm-helpers');
620 // TODO: This should probably be inserted once it's filled to prevent an additional layout
621 this.element
.appendChild(this.helperContainer
);
622 this.textarea
= document
.createElement('textarea');
623 this.textarea
.classList
.add('xterm-helper-textarea');
624 this.textarea
.setAttribute('autocorrect', 'off');
625 this.textarea
.setAttribute('autocapitalize', 'off');
626 this.textarea
.setAttribute('spellcheck', 'false');
627 this.textarea
.tabIndex
= 0;
628 this.textarea
.addEventListener('focus', function() {
629 self
.emit('focus', {terminal
: self
});
631 this.textarea
.addEventListener('blur', function() {
632 self
.emit('blur', {terminal
: self
});
634 this.helperContainer
.appendChild(this.textarea
);
636 this.compositionView
= document
.createElement('div');
637 this.compositionView
.classList
.add('composition-view');
638 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
639 this.helperContainer
.appendChild(this.compositionView
);
641 this.charSizeStyleElement
= document
.createElement('style');
642 this.helperContainer
.appendChild(this.charSizeStyleElement
);
644 for (; i
< this.rows
; i
++) {
647 this.parent
.appendChild(this.element
);
649 this.charMeasure
= new CharMeasure(this.helperContainer
);
650 this.charMeasure
.on('charsizechanged', function () {
651 self
.updateCharSizeCSS();
653 this.charMeasure
.measure();
655 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
657 // Setup loop that draws to screen
658 this.queueRefresh(0, this.rows
- 1);
661 // Initialize global actions that
662 // need to be taken on the document.
665 // Ensure there is a Terminal.focus.
668 on(this.element
, 'click', function() {
669 var selection
= document
.getSelection(),
670 collapsed
= selection
.isCollapsed
,
671 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
677 // Listen for mouse events and translate
678 // them into terminal mouse protocols.
681 // Figure out whether boldness affects
682 // the character width of monospace fonts.
683 if (Terminal
.brokenBold
== null) {
684 Terminal
.brokenBold
= isBoldBroken(this.document
);
688 * This event is emitted when terminal has completed opening.
697 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
698 * @param {string} addon The name of the addon to load
701 Terminal
.loadAddon = function(addon
, callback
) {
702 if (typeof exports
=== 'object' && typeof module
=== 'object') {
704 return require('./addons/' + addon
+ '/' + addon
);
705 } else if (typeof define
== 'function') {
707 return require(['./addons/' + addon
+ '/' + addon
], callback
);
709 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
715 * Updates the helper CSS class with any changes necessary after the terminal's
716 * character width has been changed.
718 Terminal
.prototype.updateCharSizeCSS = function() {
719 this.charSizeStyleElement
.textContent
= '.xterm-wide-char{width:' + (this.charMeasure
.width
* 2) + 'px;}';
724 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
725 * To better understand these
726 * the xterm code is very helpful:
728 * button.c, charproc.c, misc.c
729 * Relevant functions in xterm/button.c:
730 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
732 Terminal
.prototype.bindMouse = function() {
733 var el
= this.element
, self
= this, pressed
= 32;
735 // mouseup, mousedown, wheel
736 // left click: ^[[M 3<^[[M#3<
738 function sendButton(ev
) {
742 // get the xterm-style button
743 button
= getButton(ev
);
745 // get mouse coordinates
749 sendEvent(button
, pos
);
751 switch (ev
.overrideType
|| ev
.type
) {
756 // keep it at the left
757 // button, just in case.
768 // motion example of a left click:
769 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
770 function sendMove(ev
) {
777 // buttons marked as motions
778 // are incremented by 32
781 sendEvent(button
, pos
);
785 // position to characters
786 function encode(data
, ch
) {
787 if (!self
.utfMouse
) {
788 if (ch
=== 255) return data
.push(0);
789 if (ch
> 127) ch
= 127;
792 if (ch
=== 2047) return data
.push(0);
796 if (ch
> 2047) ch
= 2047;
797 data
.push(0xC0 | (ch
>> 6));
798 data
.push(0x80 | (ch
& 0x3F));
803 // send a mouse event:
804 // regular/utf8: ^[[M Cb Cx Cy
805 // urxvt: ^[[ Cb ; Cx ; Cy M
806 // sgr: ^[[ Cb ; Cx ; Cy M/m
807 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
808 // locator: CSI P e ; P b ; P r ; P c ; P p & w
809 function sendEvent(button
, pos
) {
810 // self.emit('mouse', {
816 if (self
.vt300Mouse
) {
818 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
822 var data
= C0
.ESC
+ '[24';
823 if (button
=== 0) data
+= '1';
824 else if (button
=== 1) data
+= '3';
825 else if (button
=== 2) data
+= '5';
826 else if (button
=== 3) return;
828 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
833 if (self
.decLocator
) {
838 if (button
=== 0) button
= 2;
839 else if (button
=== 1) button
= 4;
840 else if (button
=== 2) button
= 6;
841 else if (button
=== 3) button
= 3;
842 self
.send(C0
.ESC
+ '['
845 + (button
=== 3 ? 4 : 0)
856 if (self
.urxvtMouse
) {
861 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
868 self
.send(C0
.ESC
+ '[<'
869 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
874 + ((button
& 3) === 3 ? 'm' : 'M'));
880 encode(data
, button
);
884 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
887 function getButton(ev
) {
900 // 1, and 2 - with 64 added
901 switch (ev
.overrideType
|| ev
.type
) {
903 button
= ev
.button
!= null
909 if (self
.browser
.isMSIE
) {
910 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
916 case 'DOMMouseScroll':
917 button
= ev
.detail
< 0
922 button
= ev
.wheelDeltaY
> 0
928 // next three bits are the modifiers:
929 // 4 = shift, 8 = meta, 16 = control
930 shift
= ev
.shiftKey
? 4 : 0;
931 meta
= ev
.metaKey
? 8 : 0;
932 ctrl
= ev
.ctrlKey
? 16 : 0;
933 mod
= shift
| meta
| ctrl
;
936 if (self
.vt200Mouse
) {
939 } else if (!self
.normalMouse
) {
944 button
= (32 + (mod
<< 2)) + button
;
949 // mouse coordinates measured in cols/rows
950 function getCoords(ev
) {
953 // ignore browsers without pageX for now
954 if (ev
.pageX
== null) return;
960 // should probably check offsetParent
961 // but this is more portable
962 while (el
&& el
!== self
.document
.documentElement
) {
965 el
= 'offsetParent' in el
970 // convert to cols/rows
971 w
= self
.element
.clientWidth
;
972 h
= self
.element
.clientHeight
;
973 x
= Math
.ceil((x
/ w
) * self
.cols
);
974 y
= Math
.ceil((y
/ h
) * self
.rows
);
976 // be sure to avoid sending
977 // bad positions to the program
979 if (x
> self
.cols
) x
= self
.cols
;
981 if (y
> self
.rows
) y
= self
.rows
;
983 // xterm sends raw bytes and
984 // starts at 32 (SP) for each.
995 on(el
, 'mousedown', function(ev
) {
996 if (!self
.mouseEvents
) return;
1005 //if (self.vt200Mouse && !self.normalMouse) {
1006 if (self
.vt200Mouse
) {
1007 ev
.overrideType
= 'mouseup';
1009 return self
.cancel(ev
);
1013 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1015 // x10 compatibility mode can't send button releases
1016 if (!self
.x10Mouse
) {
1017 on(self
.document
, 'mouseup', function up(ev
) {
1019 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1020 off(self
.document
, 'mouseup', up
);
1021 return self
.cancel(ev
);
1025 return self
.cancel(ev
);
1028 //if (self.normalMouse) {
1029 // on(self.document, 'mousemove', sendMove);
1032 on(el
, 'wheel', function(ev
) {
1033 if (!self
.mouseEvents
) return;
1036 || self
.decLocator
) return;
1038 return self
.cancel(ev
);
1041 // allow wheel scrolling in
1042 // the shell for example
1043 on(el
, 'wheel', function(ev
) {
1044 if (self
.mouseEvents
) return;
1045 self
.viewport
.onWheel(ev
);
1046 return self
.cancel(ev
);
1051 * Destroys the terminal.
1053 Terminal
.prototype.destroy = function() {
1054 this.readable
= false;
1055 this.writable
= false;
1057 this.handler = function() {};
1058 this.write = function() {};
1059 if (this.element
.parentNode
) {
1060 this.element
.parentNode
.removeChild(this.element
);
1062 //this.emit('close');
1067 * Flags used to render terminal text properly
1078 * Queues a refresh between two rows (inclusive), to be done on next animation
1080 * @param {number} start The start row.
1081 * @param {number} end The end row.
1083 Terminal
.prototype.queueRefresh = function(start
, end
) {
1084 this.refreshRowsQueue
.push({ start
: start
, end
: end
});
1088 * Performs the refresh loop callback, calling refresh only if a refresh is
1089 * necessary before queueing up the next one.
1091 Terminal
.prototype.refreshLoop = function() {
1092 // Don't refresh if there were no row changes
1093 if (this.refreshRowsQueue
.length
> 0) {
1094 // Skip MAX_REFRESH_FRAME_SKIP frames if the writeBuffer is non-empty as it
1095 // will need to be immediately refreshed anyway. This saves a lot of
1096 // rendering time as the viewport DOM does not need to be refreshed, no
1097 // scroll events, no layouts, etc.
1098 var skipFrame
= this.writeBuffer
.length
> 0 && this.refreshFramesSkipped
++ <= MAX_REFRESH_FRAME_SKIP
;
1101 this.refreshFramesSkipped
= 0;
1104 if (this.refreshRowsQueue
.length
> 4) {
1105 // Just do a full refresh when 5+ refreshes are queued
1107 end
= this.rows
- 1;
1109 // Get start and end rows that need refreshing
1110 start
= this.refreshRowsQueue
[0].start
;
1111 end
= this.refreshRowsQueue
[0].end
;
1112 for (var i
= 1; i
< this.refreshRowsQueue
.length
; i
++) {
1113 if (this.refreshRowsQueue
[i
].start
< start
) {
1114 start
= this.refreshRowsQueue
[i
].start
;
1116 if (this.refreshRowsQueue
[i
].end
> end
) {
1117 end
= this.refreshRowsQueue
[i
].end
;
1121 this.refreshRowsQueue
= [];
1122 this.refresh(start
, end
);
1125 window
.requestAnimationFrame(this.refreshLoop
.bind(this));
1129 * Refreshes (re-renders) terminal content within two rows (inclusive)
1133 * In the screen buffer, each character is stored as a an array with a character
1134 * and a 32-bit integer:
1135 * - First value: a utf-16 character.
1137 * - Next 9 bits: background color (0-511).
1138 * - Next 9 bits: foreground color (0-511).
1139 * - Next 14 bits: a mask for misc. flags:
1146 * @param {number} start The row to start from (between 0 and terminal's height terminal - 1)
1147 * @param {number} end The row to end at (between fromRow and terminal's height terminal - 1)
1149 Terminal
.prototype.refresh = function(start
, end
) {
1152 var x
, y
, i
, line
, out
, ch
, ch_width
, width
, data
, attr
, bg
, fg
, flags
, row
, parent
, focused
= document
.activeElement
;
1154 // If this is a big refresh, remove the terminal rows from the DOM for faster calculations
1155 if (end
- start
>= this.rows
/ 2) {
1156 parent
= this.element
.parentNode
;
1158 this.element
.removeChild(this.rowContainer
);
1165 if (end
>= this.rows
.length
) {
1166 this.log('`end` is too large. Most likely a bad CSR.');
1167 end
= this.rows
.length
- 1;
1170 for (; y
<= end
; y
++) {
1171 row
= y
+ this.ydisp
;
1173 line
= this.lines
.get(row
);
1174 if (!line
|| !this.children
[y
]) {
1175 // Continue if the line is not available, this means a resize is currently in progress
1180 if (this.y
=== y
- (this.ybase
- this.ydisp
)
1182 && !this.cursorHidden
) {
1188 attr
= this.defAttr
;
1191 for (; i
< width
; i
++) {
1193 // Continue if the character is not available, this means a resize is currently in progress
1198 ch_width
= line
[i
][2];
1202 if (i
=== x
) data
= -1;
1204 if (data
!== attr
) {
1205 if (attr
!== this.defAttr
) {
1208 if (data
!== this.defAttr
) {
1210 out
+= '<span class="reverse-video terminal-cursor">';
1212 var classNames
= [];
1215 fg
= (data
>> 9) & 0x1ff;
1218 if (flags
& Terminal
.flags
.BOLD
) {
1219 if (!Terminal
.brokenBold
) {
1220 classNames
.push('xterm-bold');
1222 // See: XTerm*boldColors
1223 if (fg
< 8) fg
+= 8;
1226 if (flags
& Terminal
.flags
.UNDERLINE
) {
1227 classNames
.push('xterm-underline');
1230 if (flags
& Terminal
.flags
.BLINK
) {
1231 classNames
.push('xterm-blink');
1234 // If inverse flag is on, then swap the foreground and background variables.
1235 if (flags
& Terminal
.flags
.INVERSE
) {
1236 /* One-line variable swap in JavaScript: http://stackoverflow.com/a/16201730 */
1237 bg = [fg, fg = bg][0];
1238 // Should inverse just be before the
1239 // above boldColors effect instead?
1240 if ((flags & 1) && fg < 8) fg += 8;
1243 if (flags & Terminal.flags.INVISIBLE) {
1244 classNames.push('xterm-hidden');
1248 * Weird situation: Invert flag used black foreground and white background results
1249 * in invalid background color, positioned at the 256 index of the 256 terminal
1250 * color map. Pin the colors manually in such a case.
1252 * Source: https://github.com/sourcelair/xterm.js/issues/57
1254 if (flags
& Terminal
.flags
.INVERSE
) {
1264 classNames
.push('xterm-bg-color-' + bg
);
1268 classNames
.push('xterm-color-' + fg
);
1272 if (classNames
.length
) {
1273 out
+= ' class="' + classNames
.join(' ') + '"';
1280 if (ch_width
=== 2) {
1281 out
+= '<span class="xterm-wide-char">';
1301 if (ch_width
=== 2) {
1308 if (attr
!== this.defAttr
) {
1312 this.children
[y
].innerHTML
= out
;
1316 this.element
.appendChild(this.rowContainer
);
1319 this.emit('refresh', {element
: this.element
, start
: start
, end
: end
});
1323 * Display the cursor element
1325 Terminal
.prototype.showCursor = function() {
1326 if (!this.cursorState
) {
1327 this.cursorState
= 1;
1328 this.queueRefresh(this.y
, this.y
);
1333 * Scroll the terminal down 1 row, creating a blank line.
1335 Terminal
.prototype.scroll = function() {
1338 // Make room for the new row in lines
1339 if (this.lines
.length
=== this.lines
.maxLength
) {
1340 this.lines
.trimStart(1);
1342 if (this.ydisp
!== 0) {
1349 // TODO: Why is this done twice?
1350 if (!this.userScrolling
) {
1351 this.ydisp
= this.ybase
;
1355 row
= this.ybase
+ this.rows
- 1;
1357 // subtract the bottom scroll region
1358 row
-= this.rows
- 1 - this.scrollBottom
;
1360 if (row
=== this.lines
.length
) {
1361 // Optimization: pushing is faster than splicing when they amount to the same behavior
1362 this.lines
.push(this.blankLine());
1365 this.lines
.splice(row
, 0, this.blankLine());
1368 if (this.scrollTop
!== 0) {
1369 if (this.ybase
!== 0) {
1371 if (!this.userScrolling
) {
1372 this.ydisp
= this.ybase
;
1375 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1379 this.updateRange(this.scrollTop
);
1380 this.updateRange(this.scrollBottom
);
1383 * This event is emitted whenever the terminal is scrolled.
1384 * The one parameter passed is the new y display position.
1388 this.emit('scroll', this.ydisp
);
1392 * Scroll the display of the terminal
1393 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1394 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1395 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1396 * viewport originally.
1398 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1400 this.userScrolling
= true;
1401 } else if (disp
+ this.ydisp
>= this.ybase
) {
1402 this.userScrolling
= false;
1407 if (this.ydisp
> this.ybase
) {
1408 this.ydisp
= this.ybase
;
1409 } else if (this.ydisp
< 0) {
1413 if (!suppressScrollEvent
) {
1414 this.emit('scroll', this.ydisp
);
1417 this.queueRefresh(0, this.rows
- 1);
1421 * Scroll the display of the terminal by a number of pages.
1422 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1424 Terminal
.prototype.scrollPages = function(pageCount
) {
1425 this.scrollDisp(pageCount
* (this.rows
- 1));
1429 * Scrolls the display of the terminal to the top.
1431 Terminal
.prototype.scrollToTop = function() {
1432 this.scrollDisp(-this.ydisp
);
1436 * Scrolls the display of the terminal to the bottom.
1438 Terminal
.prototype.scrollToBottom = function() {
1439 this.scrollDisp(this.ybase
- this.ydisp
);
1443 * Writes text to the terminal.
1444 * @param {string} text The text to write to the terminal.
1446 Terminal
.prototype.write = function(data
) {
1447 this.writeBuffer
.push(data
);
1449 // Send XOFF to pause the pty process if the write buffer becomes too large so
1450 // xterm.js can catch up before more data is sent. This is necessary in order
1451 // to keep signals such as ^C responsive.
1452 if (!this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1453 // XOFF - stop pty pipe
1454 // XON will be triggered by emulator before processing data chunk
1456 this.xoffSentToCatchUp
= true;
1459 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1460 // Kick off a write which will write all data in sequence recursively
1461 this.writeInProgress
= true;
1462 // Kick off an async innerWrite so more writes can come in while processing data
1464 setTimeout(function () {
1470 Terminal
.prototype.innerWrite = function() {
1471 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1472 while (writeBatch
.length
> 0) {
1473 var data
= writeBatch
.shift();
1474 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1476 // If XOFF was sent in order to catch up with the pty process, resume it if
1477 // the writeBuffer is empty to allow more data to come in.
1478 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1480 this.xoffSentToCatchUp
= false;
1483 this.refreshStart
= this.y
;
1484 this.refreshEnd
= this.y
;
1486 this.parser
.parse(data
);
1488 this.updateRange(this.y
);
1489 this.queueRefresh(this.refreshStart
, this.refreshEnd
);
1491 if (this.writeBuffer
.length
> 0) {
1492 // Allow renderer to catch up before processing the next batch
1494 setTimeout(function () {
1498 this.writeInProgress
= false;
1503 * Writes text to the terminal, followed by a break line character (\n).
1504 * @param {string} text The text to write to the terminal.
1506 Terminal
.prototype.writeln = function(data
) {
1507 this.write(data
+ '\r\n');
1511 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1512 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1514 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1515 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1516 * the default action. The function returns whether the event should be processed by xterm.js.
1518 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1519 this.customKeydownHandler
= customKeydownHandler
;
1523 * Handle a keydown event
1525 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1526 * @param {KeyboardEvent} ev The keydown event to be handled.
1528 Terminal
.prototype.keyDown = function(ev
) {
1529 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1533 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1534 if (this.ybase
!== this.ydisp
) {
1535 this.scrollToBottom();
1541 var result
= this.evaluateKeyEscapeSequence(ev
);
1543 if (result
.key
=== C0
.DC3
) { // XOFF
1544 this.writeStopped
= true;
1545 } else if (result
.key
=== C0
.DC1
) { // XON
1546 this.writeStopped
= false;
1549 if (result
.scrollDisp
) {
1550 this.scrollDisp(result
.scrollDisp
);
1551 return this.cancel(ev
, true);
1554 if (isThirdLevelShift(this, ev
)) {
1558 if (result
.cancel
) {
1559 // The event is canceled at the end already, is this necessary?
1560 this.cancel(ev
, true);
1567 this.emit('keydown', ev
);
1568 this.emit('key', result
.key
, ev
);
1570 this.handler(result
.key
);
1572 return this.cancel(ev
, true);
1576 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1577 * returned value is the new key code to pass to the PTY.
1579 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1580 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1582 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1584 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1585 // canceled at the end of keyDown
1587 // The new key even to emit
1589 // The number of characters to scroll, if this is defined it will cancel the event
1590 scrollDisp
: undefined
1592 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1593 switch (ev
.keyCode
) {
1597 result
.key
= C0
.BS
; // ^H
1600 result
.key
= C0
.DEL
; // ^?
1605 result
.key
= C0
.ESC
+ '[Z';
1609 result
.cancel
= true;
1614 result
.cancel
= true;
1618 result
.key
= C0
.ESC
;
1619 result
.cancel
= true;
1624 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1625 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1626 // http://unix.stackexchange.com/a/108106
1627 // macOS uses different escape sequences than linux
1628 if (result
.key
== C0
.ESC
+ '[1;3D') {
1629 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1631 } else if (this.applicationCursor
) {
1632 result
.key
= C0
.ESC
+ 'OD';
1634 result
.key
= C0
.ESC
+ '[D';
1640 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1641 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1642 // http://unix.stackexchange.com/a/108106
1643 // macOS uses different escape sequences than linux
1644 if (result
.key
== C0
.ESC
+ '[1;3C') {
1645 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1647 } else if (this.applicationCursor
) {
1648 result
.key
= C0
.ESC
+ 'OC';
1650 result
.key
= C0
.ESC
+ '[C';
1656 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1657 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1658 // http://unix.stackexchange.com/a/108106
1659 if (result
.key
== C0
.ESC
+ '[1;3A') {
1660 result
.key
= C0
.ESC
+ '[1;5A';
1662 } else if (this.applicationCursor
) {
1663 result
.key
= C0
.ESC
+ 'OA';
1665 result
.key
= C0
.ESC
+ '[A';
1671 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1672 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1673 // http://unix.stackexchange.com/a/108106
1674 if (result
.key
== C0
.ESC
+ '[1;3B') {
1675 result
.key
= C0
.ESC
+ '[1;5B';
1677 } else if (this.applicationCursor
) {
1678 result
.key
= C0
.ESC
+ 'OB';
1680 result
.key
= C0
.ESC
+ '[B';
1685 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1686 // <Ctrl> or <Shift> + <Insert> are used to
1687 // copy-paste on some systems.
1688 result
.key
= C0
.ESC
+ '[2~';
1694 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1696 result
.key
= C0
.ESC
+ '[3~';
1702 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1703 else if (this.applicationCursor
)
1704 result
.key
= C0
.ESC
+ 'OH';
1706 result
.key
= C0
.ESC
+ '[H';
1711 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1712 else if (this.applicationCursor
)
1713 result
.key
= C0
.ESC
+ 'OF';
1715 result
.key
= C0
.ESC
+ '[F';
1720 result
.scrollDisp
= -(this.rows
- 1);
1722 result
.key
= C0
.ESC
+ '[5~';
1728 result
.scrollDisp
= this.rows
- 1;
1730 result
.key
= C0
.ESC
+ '[6~';
1736 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1738 result
.key
= C0
.ESC
+ 'OP';
1743 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1745 result
.key
= C0
.ESC
+ 'OQ';
1750 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1752 result
.key
= C0
.ESC
+ 'OR';
1757 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1759 result
.key
= C0
.ESC
+ 'OS';
1764 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1766 result
.key
= C0
.ESC
+ '[15~';
1771 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1773 result
.key
= C0
.ESC
+ '[17~';
1778 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1780 result
.key
= C0
.ESC
+ '[18~';
1785 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1787 result
.key
= C0
.ESC
+ '[19~';
1792 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1794 result
.key
= C0
.ESC
+ '[20~';
1799 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1801 result
.key
= C0
.ESC
+ '[21~';
1806 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1808 result
.key
= C0
.ESC
+ '[23~';
1813 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1815 result
.key
= C0
.ESC
+ '[24~';
1820 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1821 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1822 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1823 } else if (ev
.keyCode
=== 32) {
1825 result
.key
= String
.fromCharCode(0);
1826 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1827 // escape, file sep, group sep, record sep, unit sep
1828 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1829 } else if (ev
.keyCode
=== 56) {
1831 result
.key
= String
.fromCharCode(127);
1832 } else if (ev
.keyCode
=== 219) {
1833 // ^[ - Control Sequence Introducer (CSI)
1834 result
.key
= String
.fromCharCode(27);
1835 } else if (ev
.keyCode
=== 220) {
1836 // ^\ - String Terminator (ST)
1837 result
.key
= String
.fromCharCode(28);
1838 } else if (ev
.keyCode
=== 221) {
1839 // ^] - Operating System Command (OSC)
1840 result
.key
= String
.fromCharCode(29);
1842 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1843 // On Mac this is a third level shift. Use <Esc> instead.
1844 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1845 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1846 } else if (ev
.keyCode
=== 192) {
1847 result
.key
= C0
.ESC
+ '`';
1848 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1849 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1859 * Set the G level of the terminal
1862 Terminal
.prototype.setgLevel = function(g
) {
1864 this.charset
= this.charsets
[g
];
1868 * Set the charset for the given G level of the terminal
1872 Terminal
.prototype.setgCharset = function(g
, charset
) {
1873 this.charsets
[g
] = charset
;
1874 if (this.glevel
=== g
) {
1875 this.charset
= charset
;
1880 * Handle a keypress event.
1882 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1883 * @param {KeyboardEvent} ev The keypress event to be handled.
1885 Terminal
.prototype.keyPress = function(ev
) {
1892 } else if (ev
.which
== null) {
1894 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1901 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1906 key
= String
.fromCharCode(key
);
1908 this.emit('keypress', key
, ev
);
1909 this.emit('key', key
, ev
);
1917 * Send data for handling to the terminal
1918 * @param {string} data
1920 Terminal
.prototype.send = function(data
) {
1924 setTimeout(function() {
1925 self
.handler(self
.queue
);
1935 * Note: We could do sweet things with webaudio here
1937 Terminal
.prototype.bell = function() {
1938 if (!this.visualBell
) return;
1940 this.element
.style
.borderColor
= 'white';
1941 setTimeout(function() {
1942 self
.element
.style
.borderColor
= '';
1944 if (this.popOnBell
) this.focus();
1948 * Log the current state to the console.
1950 Terminal
.prototype.log = function() {
1951 if (!this.debug
) return;
1952 if (!this.context
.console
|| !this.context
.console
.log
) return;
1953 var args
= Array
.prototype.slice
.call(arguments
);
1954 this.context
.console
.log
.apply(this.context
.console
, args
);
1958 * Log the current state as error to the console.
1960 Terminal
.prototype.error = function() {
1961 if (!this.debug
) return;
1962 if (!this.context
.console
|| !this.context
.console
.error
) return;
1963 var args
= Array
.prototype.slice
.call(arguments
);
1964 this.context
.console
.error
.apply(this.context
.console
, args
);
1968 * Resizes the terminal.
1970 * @param {number} x The number of columns to resize to.
1971 * @param {number} y The number of rows to resize to.
1973 Terminal
.prototype.resize = function(x
, y
) {
1981 if (x
=== this.cols
&& y
=== this.rows
) {
1991 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1992 i
= this.lines
.length
;
1994 while (this.lines
.get(i
).length
< x
) {
1995 this.lines
.get(i
).push(ch
);
1999 i
= this.lines
.length
;
2001 while (this.lines
.get(i
).length
> x
) {
2002 this.lines
.get(i
).pop();
2015 // y is rows, not this.y
2016 if (this.lines
.length
< y
+ this.ybase
) {
2017 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
2018 // There is room above the buffer and there are no empty elements below the line,
2022 if (this.ydisp
> 0) {
2023 // Viewport is at the top of the buffer, must increase downwards
2027 // Add a blank line if there is no buffer left at the top to scroll to, or if there
2028 // are blank lines after the cursor
2029 this.lines
.push(this.blankLine());
2032 if (this.children
.length
< y
) {
2038 if (this.lines
.length
> y
+ this.ybase
) {
2039 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
2040 // The line is a blank line below the cursor, remove it
2043 // The line is the cursor, scroll down
2048 if (this.children
.length
> y
) {
2049 el
= this.children
.shift();
2051 el
.parentNode
.removeChild(el
);
2057 // Make sure that the cursor stays on screen
2070 this.scrollBottom
= y
- 1;
2072 this.charMeasure
.measure();
2074 this.queueRefresh(0, this.rows
- 1);
2078 this.geometry
= [this.cols
, this.rows
];
2079 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
2083 * Updates the range of rows to refresh
2084 * @param {number} y The number of rows to refresh next.
2086 Terminal
.prototype.updateRange = function(y
) {
2087 if (y
< this.refreshStart
) this.refreshStart
= y
;
2088 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
2089 // if (y > this.refreshEnd) {
2090 // this.refreshEnd = y;
2091 // if (y > this.rows - 1) {
2092 // this.refreshEnd = this.rows - 1;
2098 * Set the range of refreshing to the maximum value
2100 Terminal
.prototype.maxRange = function() {
2101 this.refreshStart
= 0;
2102 this.refreshEnd
= this.rows
- 1;
2108 * Setup the tab stops.
2111 Terminal
.prototype.setupStops = function(i
) {
2113 if (!this.tabs
[i
]) {
2114 i
= this.prevStop(i
);
2121 for (; i
< this.cols
; i
+= 8) {
2122 this.tabs
[i
] = true;
2128 * Move the cursor to the previous tab stop from the given position (default is current).
2129 * @param {number} x The position to move the cursor to the previous tab stop.
2131 Terminal
.prototype.prevStop = function(x
) {
2132 if (x
== null) x
= this.x
;
2133 while (!this.tabs
[--x
] && x
> 0);
2134 return x
>= this.cols
2141 * Move the cursor one tab stop forward from the given position (default is current).
2142 * @param {number} x The position to move the cursor one tab stop forward.
2144 Terminal
.prototype.nextStop = function(x
) {
2145 if (x
== null) x
= this.x
;
2146 while (!this.tabs
[++x
] && x
< this.cols
);
2147 return x
>= this.cols
2154 * Erase in the identified line everything from "x" to the end of the line (right).
2155 * @param {number} x The column from which to start erasing to the end of the line.
2156 * @param {number} y The line in which to operate.
2158 Terminal
.prototype.eraseRight = function(x
, y
) {
2159 var line
= this.lines
.get(this.ybase
+ y
)
2160 , ch
= [this.eraseAttr(), ' ', 1]; // xterm
2163 for (; x
< this.cols
; x
++) {
2167 this.updateRange(y
);
2173 * Erase in the identified line everything from "x" to the start of the line (left).
2174 * @param {number} x The column from which to start erasing to the start of the line.
2175 * @param {number} y The line in which to operate.
2177 Terminal
.prototype.eraseLeft = function(x
, y
) {
2178 var line
= this.lines
.get(this.ybase
+ y
)
2179 , ch
= [this.eraseAttr(), ' ', 1]; // xterm
2182 while (x
--) line
[x
] = ch
;
2184 this.updateRange(y
);
2188 * Clears the entire buffer, making the prompt line the new first line.
2190 Terminal
.prototype.clear = function() {
2191 if (this.ybase
=== 0 && this.y
=== 0) {
2192 // Don't clear if it's already clear
2195 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2196 this.lines
.length
= 1;
2200 for (var i
= 1; i
< this.rows
; i
++) {
2201 this.lines
.push(this.blankLine());
2203 this.queueRefresh(0, this.rows
- 1);
2204 this.emit('scroll', this.ydisp
);
2208 * Erase all content in the given line
2209 * @param {number} y The line to erase all of its contents.
2211 Terminal
.prototype.eraseLine = function(y
) {
2212 this.eraseRight(0, y
);
2217 * Return the data array of a blank line
2218 * @param {number} cur First bunch of data for each "blank" character.
2220 Terminal
.prototype.blankLine = function(cur
) {
2225 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2229 for (; i
< this.cols
; i
++) {
2238 * If cur return the back color xterm feature attribute. Else return defAttr.
2239 * @param {object} cur
2241 Terminal
.prototype.ch = function(cur
) {
2243 ? [this.eraseAttr(), ' ', 1]
2244 : [this.defAttr
, ' ', 1];
2249 * Evaluate if the current erminal is the given argument.
2250 * @param {object} term The terminal to evaluate
2252 Terminal
.prototype.is = function(term
) {
2253 var name
= this.termName
;
2254 return (name
+ '').indexOf(term
) === 0;
2259 * Emit the 'data' event and populate the given data.
2260 * @param {string} data The data to populate in the event.
2262 Terminal
.prototype.handler = function(data
) {
2263 // Prevents all events to pty process if stdin is disabled
2264 if (this.options
.disableStdin
) {
2268 // Input is being sent to the terminal, the terminal should focus the prompt.
2269 if (this.ybase
!== this.ydisp
) {
2270 this.scrollToBottom();
2272 this.emit('data', data
);
2277 * Emit the 'title' event and populate the given title.
2278 * @param {string} title The title to populate in the event.
2280 Terminal
.prototype.handleTitle = function(title
) {
2282 * This event is emitted when the title of the terminal is changed
2283 * from inside the terminal. The parameter is the new title.
2287 this.emit('title', title
);
2296 * ESC D Index (IND is 0x84).
2298 Terminal
.prototype.index = function() {
2300 if (this.y
> this.scrollBottom
) {
2308 * ESC M Reverse Index (RI is 0x8d).
2310 * Move the cursor up one row, inserting a new blank line if necessary.
2312 Terminal
.prototype.reverseIndex = function() {
2314 if (this.y
=== this.scrollTop
) {
2315 // possibly move the code below to term.reverseScroll();
2316 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2317 // blankLine(true) is xterm/linux behavior
2318 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2319 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2320 this.updateRange(this.scrollTop
);
2321 this.updateRange(this.scrollBottom
);
2329 * ESC c Full Reset (RIS).
2331 Terminal
.prototype.reset = function() {
2332 this.options
.rows
= this.rows
;
2333 this.options
.cols
= this.cols
;
2334 var customKeydownHandler
= this.customKeydownHandler
;
2335 Terminal
.call(this, this.options
);
2336 this.customKeydownHandler
= customKeydownHandler
;
2337 this.queueRefresh(0, this.rows
- 1);
2338 this.viewport
.syncScrollArea();
2343 * ESC H Tab Set (HTS is 0x88).
2345 Terminal
.prototype.tabSet = function() {
2346 this.tabs
[this.x
] = true;
2353 function on(el
, type
, handler
, capture
) {
2354 if (!Array
.isArray(el
)) {
2357 el
.forEach(function (element
) {
2358 element
.addEventListener(type
, handler
, capture
|| false);
2362 function off(el
, type
, handler
, capture
) {
2363 el
.removeEventListener(type
, handler
, capture
|| false);
2366 function cancel(ev
, force
) {
2367 if (!this.cancelEvents
&& !force
) {
2370 ev
.preventDefault();
2371 ev
.stopPropagation();
2375 function inherits(child
, parent
) {
2377 this.constructor = child
;
2379 f
.prototype = parent
.prototype;
2380 child
.prototype = new f
;
2383 // if bold is broken, we can't
2384 // use it in the terminal.
2385 function isBoldBroken(document
) {
2386 var body
= document
.getElementsByTagName('body')[0];
2387 var el
= document
.createElement('span');
2388 el
.innerHTML
= 'hello world';
2389 body
.appendChild(el
);
2390 var w1
= el
.scrollWidth
;
2391 el
.style
.fontWeight
= 'bold';
2392 var w2
= el
.scrollWidth
;
2393 body
.removeChild(el
);
2397 function indexOf(obj
, el
) {
2400 if (obj
[i
] === el
) return i
;
2405 function isThirdLevelShift(term
, ev
) {
2407 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2408 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2410 if (ev
.type
== 'keypress') {
2411 return thirdLevelKey
;
2414 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2415 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2418 // Expose to InputHandler (temporary)
2419 Terminal
.prototype.matchColor
= matchColor
;
2421 function matchColor(r1
, g1
, b1
) {
2422 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2424 if (matchColor
._cache
[hash
] != null) {
2425 return matchColor
._cache
[hash
];
2428 var ldiff
= Infinity
2437 for (; i
< Terminal
.vcolors
.length
; i
++) {
2438 c
= Terminal
.vcolors
[i
];
2443 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2456 return matchColor
._cache
[hash
] = li
;
2459 matchColor
._cache
= {};
2461 // http://stackoverflow.com/questions/1633828
2462 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2463 return Math
.pow(30 * (r1
- r2
), 2)
2464 + Math
.pow(59 * (g1
- g2
), 2)
2465 + Math
.pow(11 * (b1
- b2
), 2);
2468 function each(obj
, iter
, con
) {
2469 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2470 for (var i
= 0; i
< obj
.length
; i
++) {
2471 iter
.call(con
, obj
[i
], i
, obj
);
2475 function wasMondifierKeyOnlyEvent(ev
) {
2476 return ev
.keyCode
=== 16 || // Shift
2477 ev
.keyCode
=== 17 || // Ctrl
2478 ev
.keyCode
=== 18; // Alt
2481 function keys(obj
) {
2482 if (Object
.keys
) return Object
.keys(obj
);
2485 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2496 Terminal
.EventEmitter
= EventEmitter
;
2497 Terminal
.inherits
= inherits
;
2500 * Adds an event listener to the terminal.
2502 * @param {string} event The name of the event. TODO: Document all event types
2503 * @param {function} callback The function to call when the event is triggered.
2507 Terminal
.cancel
= cancel
;
2509 module
.exports
= Terminal
;