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
,
363 // programFeatures: false,
367 Terminal
.options
= {};
369 Terminal
.focus
= null;
371 each(keys(Terminal
.defaults
), function(key
) {
372 Terminal
[key
] = Terminal
.defaults
[key
];
373 Terminal
.options
[key
] = Terminal
.defaults
[key
];
377 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
379 Terminal
.prototype.focus = function() {
380 return this.textarea
.focus();
384 * Retrieves an option's value from the terminal.
385 * @param {string} key The option key.
387 Terminal
.prototype.getOption = function(key
, value
) {
388 if (!(key
in Terminal
.defaults
)) {
389 throw new Error('No option with key "' + key
+ '"');
392 if (typeof this.options
[key
] !== 'undefined') {
393 return this.options
[key
];
400 * Sets an option on the terminal.
401 * @param {string} key The option key.
402 * @param {string} value The option value.
404 Terminal
.prototype.setOption = function(key
, value
) {
405 if (!(key
in Terminal
.defaults
)) {
406 throw new Error('No option with key "' + key
+ '"');
410 if (this.options
[key
] !== value
) {
411 if (this.lines
.length
> value
) {
412 const amountToTrim
= this.lines
.length
- value
;
413 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
414 this.lines
.trimStart(amountToTrim
);
415 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
416 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
418 this.refresh(0, this.rows
- 1);
421 this.lines
.maxLength
= value
;
422 this.viewport
.syncScrollArea();
427 this.options
[key
] = value
;
429 case 'cursorBlink': this.element
.classList
.toggle('xterm-cursor-blink', value
); break;
434 * Binds the desired focus behavior on a given terminal object.
438 Terminal
.bindFocus = function (term
) {
439 on(term
.textarea
, 'focus', function (ev
) {
440 if (term
.sendFocus
) {
441 term
.send(C0
.ESC
+ '[I');
443 term
.element
.classList
.add('focus');
445 Terminal
.focus
= term
;
446 term
.emit('focus', {terminal
: term
});
451 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
453 Terminal
.prototype.blur = function() {
454 return this.textarea
.blur();
458 * Binds the desired blur behavior on a given terminal object.
462 Terminal
.bindBlur = function (term
) {
463 on(term
.textarea
, 'blur', function (ev
) {
464 term
.queueRefresh(term
.y
, term
.y
);
465 if (term
.sendFocus
) {
466 term
.send(C0
.ESC
+ '[O');
468 term
.element
.classList
.remove('focus');
469 Terminal
.focus
= null;
470 term
.emit('blur', {terminal
: term
});
475 * Initialize default behavior
477 Terminal
.prototype.initGlobal = function() {
480 Terminal
.bindKeys(this);
481 Terminal
.bindFocus(this);
482 Terminal
.bindBlur(this);
484 // Bind clipboard functionality
485 on(this.element
, 'copy', function (ev
) {
486 copyHandler
.call(this, ev
, term
);
488 on(this.textarea
, 'paste', function (ev
) {
489 pasteHandler
.call(this, ev
, term
);
491 on(this.element
, 'paste', function (ev
) {
492 pasteHandler
.call(this, ev
, term
);
495 function rightClickHandlerWrapper (ev
) {
496 rightClickHandler
.call(this, ev
, term
);
499 if (term
.browser
.isFirefox
) {
500 on(this.element
, 'mousedown', function (ev
) {
501 if (ev
.button
== 2) {
502 rightClickHandlerWrapper(ev
);
506 on(this.element
, 'contextmenu', rightClickHandlerWrapper
);
511 * Apply key handling to the terminal
513 Terminal
.bindKeys = function(term
) {
514 on(term
.element
, 'keydown', function(ev
) {
515 if (document
.activeElement
!= this) {
521 on(term
.element
, 'keypress', function(ev
) {
522 if (document
.activeElement
!= this) {
528 on(term
.element
, 'keyup', function(ev
) {
529 if (!wasMondifierKeyOnlyEvent(ev
)) {
534 on(term
.textarea
, 'keydown', function(ev
) {
538 on(term
.textarea
, 'keypress', function(ev
) {
540 // Truncate the textarea's value, since it is not needed
544 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
545 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
546 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
547 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
552 * Insert the given row to the terminal or produce a new one
553 * if no row argument is passed. Return the inserted row.
554 * @param {HTMLElement} row (optional) The row to append to the terminal.
556 Terminal
.prototype.insertRow = function (row
) {
557 if (typeof row
!= 'object') {
558 row
= document
.createElement('div');
561 this.rowContainer
.appendChild(row
);
562 this.children
.push(row
);
568 * Opens the terminal within an element.
570 * @param {HTMLElement} parent The element to create the terminal within.
572 Terminal
.prototype.open = function(parent
) {
573 var self
=this, i
=0, div
;
575 this.parent
= parent
|| this.parent
;
578 throw new Error('Terminal requires a parent element.');
581 // Grab global elements
582 this.context
= this.parent
.ownerDocument
.defaultView
;
583 this.document
= this.parent
.ownerDocument
;
584 this.body
= this.document
.getElementsByTagName('body')[0];
586 //Create main element container
587 this.element
= this.document
.createElement('div');
588 this.element
.classList
.add('terminal');
589 this.element
.classList
.add('xterm');
590 this.element
.classList
.add('xterm-theme-' + this.theme
);
591 this.element
.classList
.toggle('xterm-cursor-blink', this.options
.cursorBlink
);
593 this.element
.style
.height
594 this.element
.setAttribute('tabindex', 0);
596 this.viewportElement
= document
.createElement('div');
597 this.viewportElement
.classList
.add('xterm-viewport');
598 this.element
.appendChild(this.viewportElement
);
599 this.viewportScrollArea
= document
.createElement('div');
600 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
601 this.viewportElement
.appendChild(this.viewportScrollArea
);
603 // Create the container that will hold the lines of the terminal and then
604 // produce the lines the lines.
605 this.rowContainer
= document
.createElement('div');
606 this.rowContainer
.classList
.add('xterm-rows');
607 this.element
.appendChild(this.rowContainer
);
610 // Create the container that will hold helpers like the textarea for
611 // capturing DOM Events. Then produce the helpers.
612 this.helperContainer
= document
.createElement('div');
613 this.helperContainer
.classList
.add('xterm-helpers');
614 // TODO: This should probably be inserted once it's filled to prevent an additional layout
615 this.element
.appendChild(this.helperContainer
);
616 this.textarea
= document
.createElement('textarea');
617 this.textarea
.classList
.add('xterm-helper-textarea');
618 this.textarea
.setAttribute('autocorrect', 'off');
619 this.textarea
.setAttribute('autocapitalize', 'off');
620 this.textarea
.setAttribute('spellcheck', 'false');
621 this.textarea
.tabIndex
= 0;
622 this.textarea
.addEventListener('focus', function() {
623 self
.emit('focus', {terminal
: self
});
625 this.textarea
.addEventListener('blur', function() {
626 self
.emit('blur', {terminal
: self
});
628 this.helperContainer
.appendChild(this.textarea
);
630 this.compositionView
= document
.createElement('div');
631 this.compositionView
.classList
.add('composition-view');
632 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
633 this.helperContainer
.appendChild(this.compositionView
);
635 this.charSizeStyleElement
= document
.createElement('style');
636 this.helperContainer
.appendChild(this.charSizeStyleElement
);
638 for (; i
< this.rows
; i
++) {
641 this.parent
.appendChild(this.element
);
643 this.charMeasure
= new CharMeasure(this.helperContainer
);
644 this.charMeasure
.on('charsizechanged', function () {
645 self
.updateCharSizeCSS();
647 this.charMeasure
.measure();
649 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
651 // Setup loop that draws to screen
652 this.queueRefresh(0, this.rows
- 1);
655 // Initialize global actions that
656 // need to be taken on the document.
659 // Ensure there is a Terminal.focus.
662 on(this.element
, 'click', function() {
663 var selection
= document
.getSelection(),
664 collapsed
= selection
.isCollapsed
,
665 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
671 // Listen for mouse events and translate
672 // them into terminal mouse protocols.
675 // Figure out whether boldness affects
676 // the character width of monospace fonts.
677 if (Terminal
.brokenBold
== null) {
678 Terminal
.brokenBold
= isBoldBroken(this.document
);
682 * This event is emitted when terminal has completed opening.
691 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
692 * @param {string} addon The name of the addon to load
695 Terminal
.loadAddon = function(addon
, callback
) {
696 if (typeof exports
=== 'object' && typeof module
=== 'object') {
698 return require('./addons/' + addon
+ '/' + addon
);
699 } else if (typeof define
== 'function') {
701 return require(['./addons/' + addon
+ '/' + addon
], callback
);
703 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
709 * Updates the helper CSS class with any changes necessary after the terminal's
710 * character width has been changed.
712 Terminal
.prototype.updateCharSizeCSS = function() {
713 this.charSizeStyleElement
.textContent
= '.xterm-wide-char{width:' + (this.charMeasure
.width
* 2) + 'px;}';
718 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
719 * To better understand these
720 * the xterm code is very helpful:
722 * button.c, charproc.c, misc.c
723 * Relevant functions in xterm/button.c:
724 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
726 Terminal
.prototype.bindMouse = function() {
727 var el
= this.element
, self
= this, pressed
= 32;
729 // mouseup, mousedown, wheel
730 // left click: ^[[M 3<^[[M#3<
732 function sendButton(ev
) {
736 // get the xterm-style button
737 button
= getButton(ev
);
739 // get mouse coordinates
743 sendEvent(button
, pos
);
745 switch (ev
.overrideType
|| ev
.type
) {
750 // keep it at the left
751 // button, just in case.
762 // motion example of a left click:
763 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
764 function sendMove(ev
) {
771 // buttons marked as motions
772 // are incremented by 32
775 sendEvent(button
, pos
);
779 // position to characters
780 function encode(data
, ch
) {
781 if (!self
.utfMouse
) {
782 if (ch
=== 255) return data
.push(0);
783 if (ch
> 127) ch
= 127;
786 if (ch
=== 2047) return data
.push(0);
790 if (ch
> 2047) ch
= 2047;
791 data
.push(0xC0 | (ch
>> 6));
792 data
.push(0x80 | (ch
& 0x3F));
797 // send a mouse event:
798 // regular/utf8: ^[[M Cb Cx Cy
799 // urxvt: ^[[ Cb ; Cx ; Cy M
800 // sgr: ^[[ Cb ; Cx ; Cy M/m
801 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
802 // locator: CSI P e ; P b ; P r ; P c ; P p & w
803 function sendEvent(button
, pos
) {
804 // self.emit('mouse', {
810 if (self
.vt300Mouse
) {
812 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
816 var data
= C0
.ESC
+ '[24';
817 if (button
=== 0) data
+= '1';
818 else if (button
=== 1) data
+= '3';
819 else if (button
=== 2) data
+= '5';
820 else if (button
=== 3) return;
822 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
827 if (self
.decLocator
) {
832 if (button
=== 0) button
= 2;
833 else if (button
=== 1) button
= 4;
834 else if (button
=== 2) button
= 6;
835 else if (button
=== 3) button
= 3;
836 self
.send(C0
.ESC
+ '['
839 + (button
=== 3 ? 4 : 0)
850 if (self
.urxvtMouse
) {
855 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
862 self
.send(C0
.ESC
+ '[<'
863 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
868 + ((button
& 3) === 3 ? 'm' : 'M'));
874 encode(data
, button
);
878 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
881 function getButton(ev
) {
894 // 1, and 2 - with 64 added
895 switch (ev
.overrideType
|| ev
.type
) {
897 button
= ev
.button
!= null
903 if (self
.browser
.isMSIE
) {
904 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
910 case 'DOMMouseScroll':
911 button
= ev
.detail
< 0
916 button
= ev
.wheelDeltaY
> 0
922 // next three bits are the modifiers:
923 // 4 = shift, 8 = meta, 16 = control
924 shift
= ev
.shiftKey
? 4 : 0;
925 meta
= ev
.metaKey
? 8 : 0;
926 ctrl
= ev
.ctrlKey
? 16 : 0;
927 mod
= shift
| meta
| ctrl
;
930 if (self
.vt200Mouse
) {
933 } else if (!self
.normalMouse
) {
938 button
= (32 + (mod
<< 2)) + button
;
943 // mouse coordinates measured in cols/rows
944 function getCoords(ev
) {
947 // ignore browsers without pageX for now
948 if (ev
.pageX
== null) return;
954 // should probably check offsetParent
955 // but this is more portable
956 while (el
&& el
!== self
.document
.documentElement
) {
959 el
= 'offsetParent' in el
964 // convert to cols/rows
965 w
= self
.element
.clientWidth
;
966 h
= self
.element
.clientHeight
;
967 x
= Math
.ceil((x
/ w
) * self
.cols
);
968 y
= Math
.ceil((y
/ h
) * self
.rows
);
970 // be sure to avoid sending
971 // bad positions to the program
973 if (x
> self
.cols
) x
= self
.cols
;
975 if (y
> self
.rows
) y
= self
.rows
;
977 // xterm sends raw bytes and
978 // starts at 32 (SP) for each.
989 on(el
, 'mousedown', function(ev
) {
990 if (!self
.mouseEvents
) return;
999 //if (self.vt200Mouse && !self.normalMouse) {
1000 if (self
.vt200Mouse
) {
1001 ev
.overrideType
= 'mouseup';
1003 return self
.cancel(ev
);
1007 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1009 // x10 compatibility mode can't send button releases
1010 if (!self
.x10Mouse
) {
1011 on(self
.document
, 'mouseup', function up(ev
) {
1013 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1014 off(self
.document
, 'mouseup', up
);
1015 return self
.cancel(ev
);
1019 return self
.cancel(ev
);
1022 //if (self.normalMouse) {
1023 // on(self.document, 'mousemove', sendMove);
1026 on(el
, 'wheel', function(ev
) {
1027 if (!self
.mouseEvents
) return;
1030 || self
.decLocator
) return;
1032 return self
.cancel(ev
);
1035 // allow wheel scrolling in
1036 // the shell for example
1037 on(el
, 'wheel', function(ev
) {
1038 if (self
.mouseEvents
) return;
1039 self
.viewport
.onWheel(ev
);
1040 return self
.cancel(ev
);
1045 * Destroys the terminal.
1047 Terminal
.prototype.destroy = function() {
1048 this.readable
= false;
1049 this.writable
= false;
1051 this.handler = function() {};
1052 this.write = function() {};
1053 if (this.element
.parentNode
) {
1054 this.element
.parentNode
.removeChild(this.element
);
1056 //this.emit('close');
1061 * Flags used to render terminal text properly
1072 * Queues a refresh between two rows (inclusive), to be done on next animation
1074 * @param {number} start The start row.
1075 * @param {number} end The end row.
1077 Terminal
.prototype.queueRefresh = function(start
, end
) {
1078 this.refreshRowsQueue
.push({ start
: start
, end
: end
});
1082 * Performs the refresh loop callback, calling refresh only if a refresh is
1083 * necessary before queueing up the next one.
1085 Terminal
.prototype.refreshLoop = function() {
1086 // Don't refresh if there were no row changes
1087 if (this.refreshRowsQueue
.length
> 0) {
1088 // Skip MAX_REFRESH_FRAME_SKIP frames if the writeBuffer is non-empty as it
1089 // will need to be immediately refreshed anyway. This saves a lot of
1090 // rendering time as the viewport DOM does not need to be refreshed, no
1091 // scroll events, no layouts, etc.
1092 var skipFrame
= this.writeBuffer
.length
> 0 && this.refreshFramesSkipped
++ <= MAX_REFRESH_FRAME_SKIP
;
1095 this.refreshFramesSkipped
= 0;
1098 if (this.refreshRowsQueue
.length
> 4) {
1099 // Just do a full refresh when 5+ refreshes are queued
1101 end
= this.rows
- 1;
1103 // Get start and end rows that need refreshing
1104 start
= this.refreshRowsQueue
[0].start
;
1105 end
= this.refreshRowsQueue
[0].end
;
1106 for (var i
= 1; i
< this.refreshRowsQueue
.length
; i
++) {
1107 if (this.refreshRowsQueue
[i
].start
< start
) {
1108 start
= this.refreshRowsQueue
[i
].start
;
1110 if (this.refreshRowsQueue
[i
].end
> end
) {
1111 end
= this.refreshRowsQueue
[i
].end
;
1115 this.refreshRowsQueue
= [];
1116 this.refresh(start
, end
);
1119 window
.requestAnimationFrame(this.refreshLoop
.bind(this));
1123 * Refreshes (re-renders) terminal content within two rows (inclusive)
1127 * In the screen buffer, each character is stored as a an array with a character
1128 * and a 32-bit integer:
1129 * - First value: a utf-16 character.
1131 * - Next 9 bits: background color (0-511).
1132 * - Next 9 bits: foreground color (0-511).
1133 * - Next 14 bits: a mask for misc. flags:
1140 * @param {number} start The row to start from (between 0 and terminal's height terminal - 1)
1141 * @param {number} end The row to end at (between fromRow and terminal's height terminal - 1)
1143 Terminal
.prototype.refresh = function(start
, end
) {
1146 var x
, y
, i
, line
, out
, ch
, ch_width
, width
, data
, attr
, bg
, fg
, flags
, row
, parent
, focused
= document
.activeElement
;
1148 // If this is a big refresh, remove the terminal rows from the DOM for faster calculations
1149 if (end
- start
>= this.rows
/ 2) {
1150 parent
= this.element
.parentNode
;
1152 this.element
.removeChild(this.rowContainer
);
1159 if (end
>= this.rows
.length
) {
1160 this.log('`end` is too large. Most likely a bad CSR.');
1161 end
= this.rows
.length
- 1;
1164 for (; y
<= end
; y
++) {
1165 row
= y
+ this.ydisp
;
1167 line
= this.lines
.get(row
);
1168 if (!line
|| !this.children
[y
]) {
1169 // Continue if the line is not available, this means a resize is currently in progress
1174 if (this.y
=== y
- (this.ybase
- this.ydisp
)
1176 && !this.cursorHidden
) {
1182 attr
= this.defAttr
;
1185 for (; i
< width
; i
++) {
1187 // Continue if the character is not available, this means a resize is currently in progress
1192 ch_width
= line
[i
][2];
1196 if (i
=== x
) data
= -1;
1198 if (data
!== attr
) {
1199 if (attr
!== this.defAttr
) {
1202 if (data
!== this.defAttr
) {
1204 out
+= '<span class="reverse-video terminal-cursor">';
1206 var classNames
= [];
1209 fg
= (data
>> 9) & 0x1ff;
1212 if (flags
& Terminal
.flags
.BOLD
) {
1213 if (!Terminal
.brokenBold
) {
1214 classNames
.push('xterm-bold');
1216 // See: XTerm*boldColors
1217 if (fg
< 8) fg
+= 8;
1220 if (flags
& Terminal
.flags
.UNDERLINE
) {
1221 classNames
.push('xterm-underline');
1224 if (flags
& Terminal
.flags
.BLINK
) {
1225 classNames
.push('xterm-blink');
1228 // If inverse flag is on, then swap the foreground and background variables.
1229 if (flags
& Terminal
.flags
.INVERSE
) {
1230 /* One-line variable swap in JavaScript: http://stackoverflow.com/a/16201730 */
1231 bg = [fg, fg = bg][0];
1232 // Should inverse just be before the
1233 // above boldColors effect instead?
1234 if ((flags & 1) && fg < 8) fg += 8;
1237 if (flags & Terminal.flags.INVISIBLE) {
1238 classNames.push('xterm-hidden');
1242 * Weird situation: Invert flag used black foreground and white background results
1243 * in invalid background color, positioned at the 256 index of the 256 terminal
1244 * color map. Pin the colors manually in such a case.
1246 * Source: https://github.com/sourcelair/xterm.js/issues/57
1248 if (flags
& Terminal
.flags
.INVERSE
) {
1258 classNames
.push('xterm-bg-color-' + bg
);
1262 classNames
.push('xterm-color-' + fg
);
1266 if (classNames
.length
) {
1267 out
+= ' class="' + classNames
.join(' ') + '"';
1274 if (ch_width
=== 2) {
1275 out
+= '<span class="xterm-wide-char">';
1295 if (ch_width
=== 2) {
1302 if (attr
!== this.defAttr
) {
1306 this.children
[y
].innerHTML
= out
;
1310 this.element
.appendChild(this.rowContainer
);
1313 this.emit('refresh', {element
: this.element
, start
: start
, end
: end
});
1317 * Display the cursor element
1319 Terminal
.prototype.showCursor = function() {
1320 if (!this.cursorState
) {
1321 this.cursorState
= 1;
1322 this.queueRefresh(this.y
, this.y
);
1327 * Scroll the terminal down 1 row, creating a blank line.
1329 Terminal
.prototype.scroll = function() {
1332 // Make room for the new row in lines
1333 if (this.lines
.length
=== this.lines
.maxLength
) {
1334 this.lines
.trimStart(1);
1336 if (this.ydisp
!== 0) {
1343 // TODO: Why is this done twice?
1344 if (!this.userScrolling
) {
1345 this.ydisp
= this.ybase
;
1349 row
= this.ybase
+ this.rows
- 1;
1351 // subtract the bottom scroll region
1352 row
-= this.rows
- 1 - this.scrollBottom
;
1354 if (row
=== this.lines
.length
) {
1355 // Optimization: pushing is faster than splicing when they amount to the same behavior
1356 this.lines
.push(this.blankLine());
1359 this.lines
.splice(row
, 0, this.blankLine());
1362 if (this.scrollTop
!== 0) {
1363 if (this.ybase
!== 0) {
1365 if (!this.userScrolling
) {
1366 this.ydisp
= this.ybase
;
1369 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1373 this.updateRange(this.scrollTop
);
1374 this.updateRange(this.scrollBottom
);
1377 * This event is emitted whenever the terminal is scrolled.
1378 * The one parameter passed is the new y display position.
1382 this.emit('scroll', this.ydisp
);
1386 * Scroll the display of the terminal
1387 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1388 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1389 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1390 * viewport originally.
1392 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1394 this.userScrolling
= true;
1395 } else if (disp
+ this.ydisp
>= this.ybase
) {
1396 this.userScrolling
= false;
1401 if (this.ydisp
> this.ybase
) {
1402 this.ydisp
= this.ybase
;
1403 } else if (this.ydisp
< 0) {
1407 if (!suppressScrollEvent
) {
1408 this.emit('scroll', this.ydisp
);
1411 this.queueRefresh(0, this.rows
- 1);
1415 * Scroll the display of the terminal by a number of pages.
1416 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1418 Terminal
.prototype.scrollPages = function(pageCount
) {
1419 this.scrollDisp(pageCount
* (this.rows
- 1));
1423 * Scrolls the display of the terminal to the top.
1425 Terminal
.prototype.scrollToTop = function() {
1426 this.scrollDisp(-this.ydisp
);
1430 * Scrolls the display of the terminal to the bottom.
1432 Terminal
.prototype.scrollToBottom = function() {
1433 this.scrollDisp(this.ybase
- this.ydisp
);
1437 * Writes text to the terminal.
1438 * @param {string} text The text to write to the terminal.
1440 Terminal
.prototype.write = function(data
) {
1441 this.writeBuffer
.push(data
);
1443 // Send XOFF to pause the pty process if the write buffer becomes too large so
1444 // xterm.js can catch up before more data is sent. This is necessary in order
1445 // to keep signals such as ^C responsive.
1446 if (!this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1447 // XOFF - stop pty pipe
1448 // XON will be triggered by emulator before processing data chunk
1450 this.xoffSentToCatchUp
= true;
1453 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1454 // Kick off a write which will write all data in sequence recursively
1455 this.writeInProgress
= true;
1456 // Kick off an async innerWrite so more writes can come in while processing data
1458 setTimeout(function () {
1464 Terminal
.prototype.innerWrite = function() {
1465 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1466 while (writeBatch
.length
> 0) {
1467 var data
= writeBatch
.shift();
1468 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1470 // If XOFF was sent in order to catch up with the pty process, resume it if
1471 // the writeBuffer is empty to allow more data to come in.
1472 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1474 this.xoffSentToCatchUp
= false;
1477 this.refreshStart
= this.y
;
1478 this.refreshEnd
= this.y
;
1480 this.parser
.parse(data
);
1482 this.updateRange(this.y
);
1483 this.queueRefresh(this.refreshStart
, this.refreshEnd
);
1485 if (this.writeBuffer
.length
> 0) {
1486 // Allow renderer to catch up before processing the next batch
1488 setTimeout(function () {
1492 this.writeInProgress
= false;
1497 * Writes text to the terminal, followed by a break line character (\n).
1498 * @param {string} text The text to write to the terminal.
1500 Terminal
.prototype.writeln = function(data
) {
1501 this.write(data
+ '\r\n');
1505 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1506 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1508 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1509 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1510 * the default action. The function returns whether the event should be processed by xterm.js.
1512 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1513 this.customKeydownHandler
= customKeydownHandler
;
1517 * Handle a keydown event
1519 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1520 * @param {KeyboardEvent} ev The keydown event to be handled.
1522 Terminal
.prototype.keyDown = function(ev
) {
1523 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1527 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1528 if (this.ybase
!== this.ydisp
) {
1529 this.scrollToBottom();
1535 var result
= this.evaluateKeyEscapeSequence(ev
);
1537 if (result
.key
=== C0
.DC3
) { // XOFF
1538 this.writeStopped
= true;
1539 } else if (result
.key
=== C0
.DC1
) { // XON
1540 this.writeStopped
= false;
1543 if (result
.scrollDisp
) {
1544 this.scrollDisp(result
.scrollDisp
);
1545 return this.cancel(ev
, true);
1548 if (isThirdLevelShift(this, ev
)) {
1552 if (result
.cancel
) {
1553 // The event is canceled at the end already, is this necessary?
1554 this.cancel(ev
, true);
1561 this.emit('keydown', ev
);
1562 this.emit('key', result
.key
, ev
);
1564 this.handler(result
.key
);
1566 return this.cancel(ev
, true);
1570 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1571 * returned value is the new key code to pass to the PTY.
1573 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1574 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1576 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1578 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1579 // canceled at the end of keyDown
1581 // The new key even to emit
1583 // The number of characters to scroll, if this is defined it will cancel the event
1584 scrollDisp
: undefined
1586 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1587 switch (ev
.keyCode
) {
1591 result
.key
= C0
.BS
; // ^H
1594 result
.key
= C0
.DEL
; // ^?
1599 result
.key
= C0
.ESC
+ '[Z';
1603 result
.cancel
= true;
1608 result
.cancel
= true;
1612 result
.key
= C0
.ESC
;
1613 result
.cancel
= true;
1618 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1619 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1620 // http://unix.stackexchange.com/a/108106
1621 // macOS uses different escape sequences than linux
1622 if (result
.key
== C0
.ESC
+ '[1;3D') {
1623 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1625 } else if (this.applicationCursor
) {
1626 result
.key
= C0
.ESC
+ 'OD';
1628 result
.key
= C0
.ESC
+ '[D';
1634 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1635 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1636 // http://unix.stackexchange.com/a/108106
1637 // macOS uses different escape sequences than linux
1638 if (result
.key
== C0
.ESC
+ '[1;3C') {
1639 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1641 } else if (this.applicationCursor
) {
1642 result
.key
= C0
.ESC
+ 'OC';
1644 result
.key
= C0
.ESC
+ '[C';
1650 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1651 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1652 // http://unix.stackexchange.com/a/108106
1653 if (result
.key
== C0
.ESC
+ '[1;3A') {
1654 result
.key
= C0
.ESC
+ '[1;5A';
1656 } else if (this.applicationCursor
) {
1657 result
.key
= C0
.ESC
+ 'OA';
1659 result
.key
= C0
.ESC
+ '[A';
1665 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1666 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1667 // http://unix.stackexchange.com/a/108106
1668 if (result
.key
== C0
.ESC
+ '[1;3B') {
1669 result
.key
= C0
.ESC
+ '[1;5B';
1671 } else if (this.applicationCursor
) {
1672 result
.key
= C0
.ESC
+ 'OB';
1674 result
.key
= C0
.ESC
+ '[B';
1679 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1680 // <Ctrl> or <Shift> + <Insert> are used to
1681 // copy-paste on some systems.
1682 result
.key
= C0
.ESC
+ '[2~';
1688 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1690 result
.key
= C0
.ESC
+ '[3~';
1696 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1697 else if (this.applicationCursor
)
1698 result
.key
= C0
.ESC
+ 'OH';
1700 result
.key
= C0
.ESC
+ '[H';
1705 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1706 else if (this.applicationCursor
)
1707 result
.key
= C0
.ESC
+ 'OF';
1709 result
.key
= C0
.ESC
+ '[F';
1714 result
.scrollDisp
= -(this.rows
- 1);
1716 result
.key
= C0
.ESC
+ '[5~';
1722 result
.scrollDisp
= this.rows
- 1;
1724 result
.key
= C0
.ESC
+ '[6~';
1730 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1732 result
.key
= C0
.ESC
+ 'OP';
1737 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1739 result
.key
= C0
.ESC
+ 'OQ';
1744 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1746 result
.key
= C0
.ESC
+ 'OR';
1751 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1753 result
.key
= C0
.ESC
+ 'OS';
1758 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1760 result
.key
= C0
.ESC
+ '[15~';
1765 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1767 result
.key
= C0
.ESC
+ '[17~';
1772 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1774 result
.key
= C0
.ESC
+ '[18~';
1779 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1781 result
.key
= C0
.ESC
+ '[19~';
1786 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1788 result
.key
= C0
.ESC
+ '[20~';
1793 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1795 result
.key
= C0
.ESC
+ '[21~';
1800 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1802 result
.key
= C0
.ESC
+ '[23~';
1807 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1809 result
.key
= C0
.ESC
+ '[24~';
1814 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1815 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1816 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1817 } else if (ev
.keyCode
=== 32) {
1819 result
.key
= String
.fromCharCode(0);
1820 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1821 // escape, file sep, group sep, record sep, unit sep
1822 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1823 } else if (ev
.keyCode
=== 56) {
1825 result
.key
= String
.fromCharCode(127);
1826 } else if (ev
.keyCode
=== 219) {
1827 // ^[ - Control Sequence Introducer (CSI)
1828 result
.key
= String
.fromCharCode(27);
1829 } else if (ev
.keyCode
=== 220) {
1830 // ^\ - String Terminator (ST)
1831 result
.key
= String
.fromCharCode(28);
1832 } else if (ev
.keyCode
=== 221) {
1833 // ^] - Operating System Command (OSC)
1834 result
.key
= String
.fromCharCode(29);
1836 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1837 // On Mac this is a third level shift. Use <Esc> instead.
1838 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1839 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1840 } else if (ev
.keyCode
=== 192) {
1841 result
.key
= C0
.ESC
+ '`';
1842 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1843 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1853 * Set the G level of the terminal
1856 Terminal
.prototype.setgLevel = function(g
) {
1858 this.charset
= this.charsets
[g
];
1862 * Set the charset for the given G level of the terminal
1866 Terminal
.prototype.setgCharset = function(g
, charset
) {
1867 this.charsets
[g
] = charset
;
1868 if (this.glevel
=== g
) {
1869 this.charset
= charset
;
1874 * Handle a keypress event.
1876 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1877 * @param {KeyboardEvent} ev The keypress event to be handled.
1879 Terminal
.prototype.keyPress = function(ev
) {
1886 } else if (ev
.which
== null) {
1888 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1895 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1900 key
= String
.fromCharCode(key
);
1902 this.emit('keypress', key
, ev
);
1903 this.emit('key', key
, ev
);
1911 * Send data for handling to the terminal
1912 * @param {string} data
1914 Terminal
.prototype.send = function(data
) {
1918 setTimeout(function() {
1919 self
.handler(self
.queue
);
1929 * Note: We could do sweet things with webaudio here
1931 Terminal
.prototype.bell = function() {
1932 if (!this.visualBell
) return;
1934 this.element
.style
.borderColor
= 'white';
1935 setTimeout(function() {
1936 self
.element
.style
.borderColor
= '';
1938 if (this.popOnBell
) this.focus();
1942 * Log the current state to the console.
1944 Terminal
.prototype.log = function() {
1945 if (!this.debug
) return;
1946 if (!this.context
.console
|| !this.context
.console
.log
) return;
1947 var args
= Array
.prototype.slice
.call(arguments
);
1948 this.context
.console
.log
.apply(this.context
.console
, args
);
1952 * Log the current state as error to the console.
1954 Terminal
.prototype.error = function() {
1955 if (!this.debug
) return;
1956 if (!this.context
.console
|| !this.context
.console
.error
) return;
1957 var args
= Array
.prototype.slice
.call(arguments
);
1958 this.context
.console
.error
.apply(this.context
.console
, args
);
1962 * Resizes the terminal.
1964 * @param {number} x The number of columns to resize to.
1965 * @param {number} y The number of rows to resize to.
1967 Terminal
.prototype.resize = function(x
, y
) {
1975 if (x
=== this.cols
&& y
=== this.rows
) {
1985 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1986 i
= this.lines
.length
;
1988 while (this.lines
.get(i
).length
< x
) {
1989 this.lines
.get(i
).push(ch
);
1993 i
= this.lines
.length
;
1995 while (this.lines
.get(i
).length
> x
) {
1996 this.lines
.get(i
).pop();
2009 // y is rows, not this.y
2010 if (this.lines
.length
< y
+ this.ybase
) {
2011 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
2012 // There is room above the buffer and there are no empty elements below the line,
2016 if (this.ydisp
> 0) {
2017 // Viewport is at the top of the buffer, must increase downwards
2021 // Add a blank line if there is no buffer left at the top to scroll to, or if there
2022 // are blank lines after the cursor
2023 this.lines
.push(this.blankLine());
2026 if (this.children
.length
< y
) {
2032 if (this.lines
.length
> y
+ this.ybase
) {
2033 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
2034 // The line is a blank line below the cursor, remove it
2037 // The line is the cursor, scroll down
2042 if (this.children
.length
> y
) {
2043 el
= this.children
.shift();
2045 el
.parentNode
.removeChild(el
);
2051 // Make sure that the cursor stays on screen
2064 this.scrollBottom
= y
- 1;
2066 this.charMeasure
.measure();
2068 this.queueRefresh(0, this.rows
- 1);
2072 this.geometry
= [this.cols
, this.rows
];
2073 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
2077 * Updates the range of rows to refresh
2078 * @param {number} y The number of rows to refresh next.
2080 Terminal
.prototype.updateRange = function(y
) {
2081 if (y
< this.refreshStart
) this.refreshStart
= y
;
2082 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
2083 // if (y > this.refreshEnd) {
2084 // this.refreshEnd = y;
2085 // if (y > this.rows - 1) {
2086 // this.refreshEnd = this.rows - 1;
2092 * Set the range of refreshing to the maximum value
2094 Terminal
.prototype.maxRange = function() {
2095 this.refreshStart
= 0;
2096 this.refreshEnd
= this.rows
- 1;
2102 * Setup the tab stops.
2105 Terminal
.prototype.setupStops = function(i
) {
2107 if (!this.tabs
[i
]) {
2108 i
= this.prevStop(i
);
2115 for (; i
< this.cols
; i
+= 8) {
2116 this.tabs
[i
] = true;
2122 * Move the cursor to the previous tab stop from the given position (default is current).
2123 * @param {number} x The position to move the cursor to the previous tab stop.
2125 Terminal
.prototype.prevStop = function(x
) {
2126 if (x
== null) x
= this.x
;
2127 while (!this.tabs
[--x
] && x
> 0);
2128 return x
>= this.cols
2135 * Move the cursor one tab stop forward from the given position (default is current).
2136 * @param {number} x The position to move the cursor one tab stop forward.
2138 Terminal
.prototype.nextStop = function(x
) {
2139 if (x
== null) x
= this.x
;
2140 while (!this.tabs
[++x
] && x
< this.cols
);
2141 return x
>= this.cols
2148 * Erase in the identified line everything from "x" to the end of the line (right).
2149 * @param {number} x The column from which to start erasing to the end of the line.
2150 * @param {number} y The line in which to operate.
2152 Terminal
.prototype.eraseRight = function(x
, y
) {
2153 var line
= this.lines
.get(this.ybase
+ y
)
2154 , ch
= [this.eraseAttr(), ' ', 1]; // xterm
2157 for (; x
< this.cols
; x
++) {
2161 this.updateRange(y
);
2167 * Erase in the identified line everything from "x" to the start of the line (left).
2168 * @param {number} x The column from which to start erasing to the start of the line.
2169 * @param {number} y The line in which to operate.
2171 Terminal
.prototype.eraseLeft = function(x
, y
) {
2172 var line
= this.lines
.get(this.ybase
+ y
)
2173 , ch
= [this.eraseAttr(), ' ', 1]; // xterm
2176 while (x
--) line
[x
] = ch
;
2178 this.updateRange(y
);
2182 * Clears the entire buffer, making the prompt line the new first line.
2184 Terminal
.prototype.clear = function() {
2185 if (this.ybase
=== 0 && this.y
=== 0) {
2186 // Don't clear if it's already clear
2189 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2190 this.lines
.length
= 1;
2194 for (var i
= 1; i
< this.rows
; i
++) {
2195 this.lines
.push(this.blankLine());
2197 this.queueRefresh(0, this.rows
- 1);
2198 this.emit('scroll', this.ydisp
);
2202 * Erase all content in the given line
2203 * @param {number} y The line to erase all of its contents.
2205 Terminal
.prototype.eraseLine = function(y
) {
2206 this.eraseRight(0, y
);
2211 * Return the data array of a blank line
2212 * @param {number} cur First bunch of data for each "blank" character.
2214 Terminal
.prototype.blankLine = function(cur
) {
2219 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2223 for (; i
< this.cols
; i
++) {
2232 * If cur return the back color xterm feature attribute. Else return defAttr.
2233 * @param {object} cur
2235 Terminal
.prototype.ch = function(cur
) {
2237 ? [this.eraseAttr(), ' ', 1]
2238 : [this.defAttr
, ' ', 1];
2243 * Evaluate if the current erminal is the given argument.
2244 * @param {object} term The terminal to evaluate
2246 Terminal
.prototype.is = function(term
) {
2247 var name
= this.termName
;
2248 return (name
+ '').indexOf(term
) === 0;
2253 * Emit the 'data' event and populate the given data.
2254 * @param {string} data The data to populate in the event.
2256 Terminal
.prototype.handler = function(data
) {
2257 // Prevents all events to pty process if stdin is disabled
2258 if (this.options
.disableStdin
) {
2262 // Input is being sent to the terminal, the terminal should focus the prompt.
2263 if (this.ybase
!== this.ydisp
) {
2264 this.scrollToBottom();
2266 this.emit('data', data
);
2271 * Emit the 'title' event and populate the given title.
2272 * @param {string} title The title to populate in the event.
2274 Terminal
.prototype.handleTitle = function(title
) {
2276 * This event is emitted when the title of the terminal is changed
2277 * from inside the terminal. The parameter is the new title.
2281 this.emit('title', title
);
2290 * ESC D Index (IND is 0x84).
2292 Terminal
.prototype.index = function() {
2294 if (this.y
> this.scrollBottom
) {
2302 * ESC M Reverse Index (RI is 0x8d).
2304 * Move the cursor up one row, inserting a new blank line if necessary.
2306 Terminal
.prototype.reverseIndex = function() {
2308 if (this.y
=== this.scrollTop
) {
2309 // possibly move the code below to term.reverseScroll();
2310 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2311 // blankLine(true) is xterm/linux behavior
2312 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2313 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2314 this.updateRange(this.scrollTop
);
2315 this.updateRange(this.scrollBottom
);
2323 * ESC c Full Reset (RIS).
2325 Terminal
.prototype.reset = function() {
2326 this.options
.rows
= this.rows
;
2327 this.options
.cols
= this.cols
;
2328 var customKeydownHandler
= this.customKeydownHandler
;
2329 Terminal
.call(this, this.options
);
2330 this.customKeydownHandler
= customKeydownHandler
;
2331 this.queueRefresh(0, this.rows
- 1);
2332 this.viewport
.syncScrollArea();
2337 * ESC H Tab Set (HTS is 0x88).
2339 Terminal
.prototype.tabSet = function() {
2340 this.tabs
[this.x
] = true;
2347 function on(el
, type
, handler
, capture
) {
2348 if (!Array
.isArray(el
)) {
2351 el
.forEach(function (element
) {
2352 element
.addEventListener(type
, handler
, capture
|| false);
2356 function off(el
, type
, handler
, capture
) {
2357 el
.removeEventListener(type
, handler
, capture
|| false);
2360 function cancel(ev
, force
) {
2361 if (!this.cancelEvents
&& !force
) {
2364 ev
.preventDefault();
2365 ev
.stopPropagation();
2369 function inherits(child
, parent
) {
2371 this.constructor = child
;
2373 f
.prototype = parent
.prototype;
2374 child
.prototype = new f
;
2377 // if bold is broken, we can't
2378 // use it in the terminal.
2379 function isBoldBroken(document
) {
2380 var body
= document
.getElementsByTagName('body')[0];
2381 var el
= document
.createElement('span');
2382 el
.innerHTML
= 'hello world';
2383 body
.appendChild(el
);
2384 var w1
= el
.scrollWidth
;
2385 el
.style
.fontWeight
= 'bold';
2386 var w2
= el
.scrollWidth
;
2387 body
.removeChild(el
);
2391 function indexOf(obj
, el
) {
2394 if (obj
[i
] === el
) return i
;
2399 function isThirdLevelShift(term
, ev
) {
2401 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2402 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2404 if (ev
.type
== 'keypress') {
2405 return thirdLevelKey
;
2408 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2409 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2412 // Expose to InputHandler (temporary)
2413 Terminal
.prototype.matchColor
= matchColor
;
2415 function matchColor(r1
, g1
, b1
) {
2416 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2418 if (matchColor
._cache
[hash
] != null) {
2419 return matchColor
._cache
[hash
];
2422 var ldiff
= Infinity
2431 for (; i
< Terminal
.vcolors
.length
; i
++) {
2432 c
= Terminal
.vcolors
[i
];
2437 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2450 return matchColor
._cache
[hash
] = li
;
2453 matchColor
._cache
= {};
2455 // http://stackoverflow.com/questions/1633828
2456 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2457 return Math
.pow(30 * (r1
- r2
), 2)
2458 + Math
.pow(59 * (g1
- g2
), 2)
2459 + Math
.pow(11 * (b1
- b2
), 2);
2462 function each(obj
, iter
, con
) {
2463 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2464 for (var i
= 0; i
< obj
.length
; i
++) {
2465 iter
.call(con
, obj
[i
], i
, obj
);
2469 function wasMondifierKeyOnlyEvent(ev
) {
2470 return ev
.keyCode
=== 16 || // Shift
2471 ev
.keyCode
=== 17 || // Ctrl
2472 ev
.keyCode
=== 18; // Alt
2475 function keys(obj
) {
2476 if (Object
.keys
) return Object
.keys(obj
);
2479 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2490 Terminal
.EventEmitter
= EventEmitter
;
2491 Terminal
.inherits
= inherits
;
2494 * Adds an event listener to the terminal.
2496 * @param {string} event The name of the event. TODO: Document all event types
2497 * @param {function} callback The function to call when the event is triggered.
2501 Terminal
.cancel
= cancel
;
2503 module
.exports
= Terminal
;