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;
225 this.refreshAnimationFrame
= null;
228 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
229 * This is a distinct state from writeStopped so that if the user requested
230 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
233 this.xoffSentToCatchUp
= false;
235 /** Whether writing has been stopped as a result of XOFF */
236 this.writeStopped
= false;
238 // leftover surrogate high from previous write invocation
239 this.surrogate_high
= '';
242 * An array of all lines in the entire buffer, including the prompt. The lines are array of
243 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
245 this.lines
= new CircularList(this.scrollback
);
248 this.lines
.push(this.blankLine());
254 // Store if user went browsing history in scrollback
255 this.userScrolling
= false;
258 inherits(Terminal
, EventEmitter
);
261 * back_color_erase feature for xterm.
263 Terminal
.prototype.eraseAttr = function() {
264 // if (this.is('screen')) return this.defAttr;
265 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
273 Terminal
.tangoColors
= [
294 // Colors 0-15 + 16-255
295 // Much thanks to TooTallNate for writing this.
296 Terminal
.colors
= (function() {
297 var colors
= Terminal
.tangoColors
.slice()
298 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
303 for (; i
< 216; i
++) {
304 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
309 for (; i
< 24; i
++) {
314 function out(r
, g
, b
) {
315 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
320 return c
.length
< 2 ? '0' + c
: c
;
326 Terminal
._colors
= Terminal
.colors
.slice();
328 Terminal
.vcolors
= (function() {
330 , colors
= Terminal
.colors
334 for (; i
< 256; i
++) {
335 color
= parseInt(colors
[i
].substring(1), 16);
337 (color
>> 16) & 0xff,
350 Terminal
.defaults
= {
351 colors
: Terminal
.colors
,
357 cursorStyle
: 'block',
365 useFlowControl
: false,
367 // programFeatures: false,
371 Terminal
.options
= {};
373 Terminal
.focus
= null;
375 each(keys(Terminal
.defaults
), function(key
) {
376 Terminal
[key
] = Terminal
.defaults
[key
];
377 Terminal
.options
[key
] = Terminal
.defaults
[key
];
381 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
383 Terminal
.prototype.focus = function() {
384 return this.textarea
.focus();
388 * Retrieves an option's value from the terminal.
389 * @param {string} key The option key.
391 Terminal
.prototype.getOption = function(key
, value
) {
392 if (!(key
in Terminal
.defaults
)) {
393 throw new Error('No option with key "' + key
+ '"');
396 if (typeof this.options
[key
] !== 'undefined') {
397 return this.options
[key
];
404 * Sets an option on the terminal.
405 * @param {string} key The option key.
406 * @param {string} value The option value.
408 Terminal
.prototype.setOption = function(key
, value
) {
409 if (!(key
in Terminal
.defaults
)) {
410 throw new Error('No option with key "' + key
+ '"');
414 if (this.options
[key
] !== value
) {
415 if (this.lines
.length
> value
) {
416 const amountToTrim
= this.lines
.length
- value
;
417 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
418 this.lines
.trimStart(amountToTrim
);
419 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
420 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
422 this.refresh(0, this.rows
- 1);
425 this.lines
.maxLength
= value
;
426 this.viewport
.syncScrollArea();
431 this.options
[key
] = value
;
433 case 'cursorBlink': this.element
.classList
.toggle('xterm-cursor-blink', value
); break;
435 // Style 'block' applies with no class
436 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
437 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
439 case 'tabStopWidth': this.setupStops(); break;
444 * Binds the desired focus behavior on a given terminal object.
448 Terminal
.bindFocus = function (term
) {
449 on(term
.textarea
, 'focus', function (ev
) {
450 if (term
.sendFocus
) {
451 term
.send(C0
.ESC
+ '[I');
453 term
.element
.classList
.add('focus');
455 Terminal
.focus
= term
;
456 term
.emit('focus', {terminal
: term
});
461 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
463 Terminal
.prototype.blur = function() {
464 return this.textarea
.blur();
468 * Binds the desired blur behavior on a given terminal object.
472 Terminal
.bindBlur = function (term
) {
473 on(term
.textarea
, 'blur', function (ev
) {
474 term
.queueRefresh(term
.y
, term
.y
);
475 if (term
.sendFocus
) {
476 term
.send(C0
.ESC
+ '[O');
478 term
.element
.classList
.remove('focus');
479 Terminal
.focus
= null;
480 term
.emit('blur', {terminal
: term
});
485 * Initialize default behavior
487 Terminal
.prototype.initGlobal = function() {
490 Terminal
.bindKeys(this);
491 Terminal
.bindFocus(this);
492 Terminal
.bindBlur(this);
494 // Bind clipboard functionality
495 on(this.element
, 'copy', function (ev
) {
496 copyHandler
.call(this, ev
, term
);
498 on(this.textarea
, 'paste', function (ev
) {
499 pasteHandler
.call(this, ev
, term
);
501 on(this.element
, 'paste', function (ev
) {
502 pasteHandler
.call(this, ev
, term
);
505 function rightClickHandlerWrapper (ev
) {
506 rightClickHandler
.call(this, ev
, term
);
509 if (term
.browser
.isFirefox
) {
510 on(this.element
, 'mousedown', function (ev
) {
511 if (ev
.button
== 2) {
512 rightClickHandlerWrapper(ev
);
516 on(this.element
, 'contextmenu', rightClickHandlerWrapper
);
521 * Apply key handling to the terminal
523 Terminal
.bindKeys = function(term
) {
524 on(term
.element
, 'keydown', function(ev
) {
525 if (document
.activeElement
!= this) {
531 on(term
.element
, 'keypress', function(ev
) {
532 if (document
.activeElement
!= this) {
538 on(term
.element
, 'keyup', function(ev
) {
539 if (!wasMondifierKeyOnlyEvent(ev
)) {
544 on(term
.textarea
, 'keydown', function(ev
) {
548 on(term
.textarea
, 'keypress', function(ev
) {
550 // Truncate the textarea's value, since it is not needed
554 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
555 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
556 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
557 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
562 * Insert the given row to the terminal or produce a new one
563 * if no row argument is passed. Return the inserted row.
564 * @param {HTMLElement} row (optional) The row to append to the terminal.
566 Terminal
.prototype.insertRow = function (row
) {
567 if (typeof row
!= 'object') {
568 row
= document
.createElement('div');
571 this.rowContainer
.appendChild(row
);
572 this.children
.push(row
);
578 * Opens the terminal within an element.
580 * @param {HTMLElement} parent The element to create the terminal within.
582 Terminal
.prototype.open = function(parent
) {
583 var self
=this, i
=0, div
;
585 this.parent
= parent
|| this.parent
;
588 throw new Error('Terminal requires a parent element.');
591 // Grab global elements
592 this.context
= this.parent
.ownerDocument
.defaultView
;
593 this.document
= this.parent
.ownerDocument
;
594 this.body
= this.document
.getElementsByTagName('body')[0];
596 //Create main element container
597 this.element
= this.document
.createElement('div');
598 this.element
.classList
.add('terminal');
599 this.element
.classList
.add('xterm');
600 this.element
.classList
.add('xterm-theme-' + this.theme
);
601 this.element
.classList
.toggle('xterm-cursor-blink', this.options
.cursorBlink
);
603 this.element
.style
.height
604 this.element
.setAttribute('tabindex', 0);
606 this.viewportElement
= document
.createElement('div');
607 this.viewportElement
.classList
.add('xterm-viewport');
608 this.element
.appendChild(this.viewportElement
);
609 this.viewportScrollArea
= document
.createElement('div');
610 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
611 this.viewportElement
.appendChild(this.viewportScrollArea
);
613 // Create the container that will hold the lines of the terminal and then
614 // produce the lines the lines.
615 this.rowContainer
= document
.createElement('div');
616 this.rowContainer
.classList
.add('xterm-rows');
617 this.element
.appendChild(this.rowContainer
);
620 // Create the container that will hold helpers like the textarea for
621 // capturing DOM Events. Then produce the helpers.
622 this.helperContainer
= document
.createElement('div');
623 this.helperContainer
.classList
.add('xterm-helpers');
624 // TODO: This should probably be inserted once it's filled to prevent an additional layout
625 this.element
.appendChild(this.helperContainer
);
626 this.textarea
= document
.createElement('textarea');
627 this.textarea
.classList
.add('xterm-helper-textarea');
628 this.textarea
.setAttribute('autocorrect', 'off');
629 this.textarea
.setAttribute('autocapitalize', 'off');
630 this.textarea
.setAttribute('spellcheck', 'false');
631 this.textarea
.tabIndex
= 0;
632 this.textarea
.addEventListener('focus', function() {
633 self
.emit('focus', {terminal
: self
});
635 this.textarea
.addEventListener('blur', function() {
636 self
.emit('blur', {terminal
: self
});
638 this.helperContainer
.appendChild(this.textarea
);
640 this.compositionView
= document
.createElement('div');
641 this.compositionView
.classList
.add('composition-view');
642 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
643 this.helperContainer
.appendChild(this.compositionView
);
645 this.charSizeStyleElement
= document
.createElement('style');
646 this.helperContainer
.appendChild(this.charSizeStyleElement
);
648 for (; i
< this.rows
; i
++) {
651 this.parent
.appendChild(this.element
);
653 this.charMeasure
= new CharMeasure(this.helperContainer
);
654 this.charMeasure
.on('charsizechanged', function () {
655 self
.updateCharSizeCSS();
657 this.charMeasure
.measure();
659 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
661 // Setup loop that draws to screen
662 this.queueRefresh(0, this.rows
- 1);
664 // Initialize global actions that
665 // need to be taken on the document.
668 // Ensure there is a Terminal.focus.
671 on(this.element
, 'click', function() {
672 var selection
= document
.getSelection(),
673 collapsed
= selection
.isCollapsed
,
674 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
680 // Listen for mouse events and translate
681 // them into terminal mouse protocols.
684 // Figure out whether boldness affects
685 // the character width of monospace fonts.
686 if (Terminal
.brokenBold
== null) {
687 Terminal
.brokenBold
= isBoldBroken(this.document
);
691 * This event is emitted when terminal has completed opening.
700 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
701 * @param {string} addon The name of the addon to load
704 Terminal
.loadAddon = function(addon
, callback
) {
705 if (typeof exports
=== 'object' && typeof module
=== 'object') {
707 return require('./addons/' + addon
+ '/' + addon
);
708 } else if (typeof define
== 'function') {
710 return require(['./addons/' + addon
+ '/' + addon
], callback
);
712 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
718 * Updates the helper CSS class with any changes necessary after the terminal's
719 * character width has been changed.
721 Terminal
.prototype.updateCharSizeCSS = function() {
722 this.charSizeStyleElement
.textContent
= '.xterm-wide-char{width:' + (this.charMeasure
.width
* 2) + 'px;}';
727 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
728 * To better understand these
729 * the xterm code is very helpful:
731 * button.c, charproc.c, misc.c
732 * Relevant functions in xterm/button.c:
733 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
735 Terminal
.prototype.bindMouse = function() {
736 var el
= this.element
, self
= this, pressed
= 32;
738 // mouseup, mousedown, wheel
739 // left click: ^[[M 3<^[[M#3<
741 function sendButton(ev
) {
745 // get the xterm-style button
746 button
= getButton(ev
);
748 // get mouse coordinates
752 sendEvent(button
, pos
);
754 switch (ev
.overrideType
|| ev
.type
) {
759 // keep it at the left
760 // button, just in case.
771 // motion example of a left click:
772 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
773 function sendMove(ev
) {
780 // buttons marked as motions
781 // are incremented by 32
784 sendEvent(button
, pos
);
788 // position to characters
789 function encode(data
, ch
) {
790 if (!self
.utfMouse
) {
791 if (ch
=== 255) return data
.push(0);
792 if (ch
> 127) ch
= 127;
795 if (ch
=== 2047) return data
.push(0);
799 if (ch
> 2047) ch
= 2047;
800 data
.push(0xC0 | (ch
>> 6));
801 data
.push(0x80 | (ch
& 0x3F));
806 // send a mouse event:
807 // regular/utf8: ^[[M Cb Cx Cy
808 // urxvt: ^[[ Cb ; Cx ; Cy M
809 // sgr: ^[[ Cb ; Cx ; Cy M/m
810 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
811 // locator: CSI P e ; P b ; P r ; P c ; P p & w
812 function sendEvent(button
, pos
) {
813 // self.emit('mouse', {
819 if (self
.vt300Mouse
) {
821 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
825 var data
= C0
.ESC
+ '[24';
826 if (button
=== 0) data
+= '1';
827 else if (button
=== 1) data
+= '3';
828 else if (button
=== 2) data
+= '5';
829 else if (button
=== 3) return;
831 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
836 if (self
.decLocator
) {
841 if (button
=== 0) button
= 2;
842 else if (button
=== 1) button
= 4;
843 else if (button
=== 2) button
= 6;
844 else if (button
=== 3) button
= 3;
845 self
.send(C0
.ESC
+ '['
848 + (button
=== 3 ? 4 : 0)
859 if (self
.urxvtMouse
) {
864 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
871 self
.send(C0
.ESC
+ '[<'
872 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
877 + ((button
& 3) === 3 ? 'm' : 'M'));
883 encode(data
, button
);
887 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
890 function getButton(ev
) {
903 // 1, and 2 - with 64 added
904 switch (ev
.overrideType
|| ev
.type
) {
906 button
= ev
.button
!= null
912 if (self
.browser
.isMSIE
) {
913 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
919 case 'DOMMouseScroll':
920 button
= ev
.detail
< 0
925 button
= ev
.wheelDeltaY
> 0
931 // next three bits are the modifiers:
932 // 4 = shift, 8 = meta, 16 = control
933 shift
= ev
.shiftKey
? 4 : 0;
934 meta
= ev
.metaKey
? 8 : 0;
935 ctrl
= ev
.ctrlKey
? 16 : 0;
936 mod
= shift
| meta
| ctrl
;
939 if (self
.vt200Mouse
) {
942 } else if (!self
.normalMouse
) {
947 button
= (32 + (mod
<< 2)) + button
;
952 // mouse coordinates measured in cols/rows
953 function getCoords(ev
) {
956 // ignore browsers without pageX for now
957 if (ev
.pageX
== null) return;
963 // should probably check offsetParent
964 // but this is more portable
965 while (el
&& el
!== self
.document
.documentElement
) {
968 el
= 'offsetParent' in el
973 // convert to cols/rows
974 w
= self
.element
.clientWidth
;
975 h
= self
.element
.clientHeight
;
976 x
= Math
.ceil((x
/ w
) * self
.cols
);
977 y
= Math
.ceil((y
/ h
) * self
.rows
);
979 // be sure to avoid sending
980 // bad positions to the program
982 if (x
> self
.cols
) x
= self
.cols
;
984 if (y
> self
.rows
) y
= self
.rows
;
986 // xterm sends raw bytes and
987 // starts at 32 (SP) for each.
998 on(el
, 'mousedown', function(ev
) {
999 if (!self
.mouseEvents
) return;
1008 //if (self.vt200Mouse && !self.normalMouse) {
1009 if (self
.vt200Mouse
) {
1010 ev
.overrideType
= 'mouseup';
1012 return self
.cancel(ev
);
1016 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1018 // x10 compatibility mode can't send button releases
1019 if (!self
.x10Mouse
) {
1020 on(self
.document
, 'mouseup', function up(ev
) {
1022 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1023 off(self
.document
, 'mouseup', up
);
1024 return self
.cancel(ev
);
1028 return self
.cancel(ev
);
1031 //if (self.normalMouse) {
1032 // on(self.document, 'mousemove', sendMove);
1035 on(el
, 'wheel', function(ev
) {
1036 if (!self
.mouseEvents
) return;
1039 || self
.decLocator
) return;
1041 return self
.cancel(ev
);
1044 // allow wheel scrolling in
1045 // the shell for example
1046 on(el
, 'wheel', function(ev
) {
1047 if (self
.mouseEvents
) return;
1048 self
.viewport
.onWheel(ev
);
1049 return self
.cancel(ev
);
1054 * Destroys the terminal.
1056 Terminal
.prototype.destroy = function() {
1057 this.readable
= false;
1058 this.writable
= false;
1060 this.handler = function() {};
1061 this.write = function() {};
1062 if (this.element
.parentNode
) {
1063 this.element
.parentNode
.removeChild(this.element
);
1065 //this.emit('close');
1070 * Flags used to render terminal text properly
1081 * Queues a refresh between two rows (inclusive), to be done on next animation
1083 * @param {number} start The start row.
1084 * @param {number} end The end row.
1086 Terminal
.prototype.queueRefresh = function(start
, end
) {
1087 this.refreshRowsQueue
.push({ start
: start
, end
: end
});
1088 if (!this.refreshAnimationFrame
) {
1089 this.refreshAnimationFrame
= window
.requestAnimationFrame(this.refreshLoop
.bind(this));
1094 * Performs the refresh loop callback, calling refresh only if a refresh is
1095 * necessary before queueing up the next one.
1097 Terminal
.prototype.refreshLoop = function() {
1098 // Skip MAX_REFRESH_FRAME_SKIP frames if the writeBuffer is non-empty as it
1099 // will need to be immediately refreshed anyway. This saves a lot of
1100 // rendering time as the viewport DOM does not need to be refreshed, no
1101 // scroll events, no layouts, etc.
1102 var skipFrame
= this.writeBuffer
.length
> 0 && this.refreshFramesSkipped
++ <= MAX_REFRESH_FRAME_SKIP
;
1104 this.refreshAnimationFrame
= window
.requestAnimationFrame(this.refreshLoop
.bind(this));
1108 this.refreshFramesSkipped
= 0;
1111 if (this.refreshRowsQueue
.length
> 4) {
1112 // Just do a full refresh when 5+ refreshes are queued
1114 end
= this.rows
- 1;
1116 // Get start and end rows that need refreshing
1117 start
= this.refreshRowsQueue
[0].start
;
1118 end
= this.refreshRowsQueue
[0].end
;
1119 for (var i
= 1; i
< this.refreshRowsQueue
.length
; i
++) {
1120 if (this.refreshRowsQueue
[i
].start
< start
) {
1121 start
= this.refreshRowsQueue
[i
].start
;
1123 if (this.refreshRowsQueue
[i
].end
> end
) {
1124 end
= this.refreshRowsQueue
[i
].end
;
1128 this.refreshRowsQueue
= [];
1129 this.refreshAnimationFrame
= null;
1130 this.refresh(start
, end
);
1134 * Refreshes (re-renders) terminal content within two rows (inclusive)
1138 * In the screen buffer, each character is stored as a an array with a character
1139 * and a 32-bit integer:
1140 * - First value: a utf-16 character.
1142 * - Next 9 bits: background color (0-511).
1143 * - Next 9 bits: foreground color (0-511).
1144 * - Next 14 bits: a mask for misc. flags:
1151 * @param {number} start The row to start from (between 0 and terminal's height terminal - 1)
1152 * @param {number} end The row to end at (between fromRow and terminal's height terminal - 1)
1154 Terminal
.prototype.refresh = function(start
, end
) {
1157 var x
, y
, i
, line
, out
, ch
, ch_width
, width
, data
, attr
, bg
, fg
, flags
, row
, parent
, focused
= document
.activeElement
;
1159 // If this is a big refresh, remove the terminal rows from the DOM for faster calculations
1160 if (end
- start
>= this.rows
/ 2) {
1161 parent
= this.element
.parentNode
;
1163 this.element
.removeChild(this.rowContainer
);
1170 if (end
>= this.rows
.length
) {
1171 this.log('`end` is too large. Most likely a bad CSR.');
1172 end
= this.rows
.length
- 1;
1175 for (; y
<= end
; y
++) {
1176 row
= y
+ this.ydisp
;
1178 line
= this.lines
.get(row
);
1179 if (!line
|| !this.children
[y
]) {
1180 // Continue if the line is not available, this means a resize is currently in progress
1185 if (this.y
=== y
- (this.ybase
- this.ydisp
)
1187 && !this.cursorHidden
) {
1193 attr
= this.defAttr
;
1196 for (; i
< width
; i
++) {
1198 // Continue if the character is not available, this means a resize is currently in progress
1203 ch_width
= line
[i
][2];
1207 if (i
=== x
) data
= -1;
1209 if (data
!== attr
) {
1210 if (attr
!== this.defAttr
) {
1213 if (data
!== this.defAttr
) {
1215 out
+= '<span class="reverse-video terminal-cursor">';
1217 var classNames
= [];
1220 fg
= (data
>> 9) & 0x1ff;
1223 if (flags
& Terminal
.flags
.BOLD
) {
1224 if (!Terminal
.brokenBold
) {
1225 classNames
.push('xterm-bold');
1227 // See: XTerm*boldColors
1228 if (fg
< 8) fg
+= 8;
1231 if (flags
& Terminal
.flags
.UNDERLINE
) {
1232 classNames
.push('xterm-underline');
1235 if (flags
& Terminal
.flags
.BLINK
) {
1236 classNames
.push('xterm-blink');
1239 // If inverse flag is on, then swap the foreground and background variables.
1240 if (flags
& Terminal
.flags
.INVERSE
) {
1241 /* One-line variable swap in JavaScript: http://stackoverflow.com/a/16201730 */
1242 bg = [fg, fg = bg][0];
1243 // Should inverse just be before the
1244 // above boldColors effect instead?
1245 if ((flags & 1) && fg < 8) fg += 8;
1248 if (flags & Terminal.flags.INVISIBLE) {
1249 classNames.push('xterm-hidden');
1253 * Weird situation: Invert flag used black foreground and white background results
1254 * in invalid background color, positioned at the 256 index of the 256 terminal
1255 * color map. Pin the colors manually in such a case.
1257 * Source: https://github.com/sourcelair/xterm.js/issues/57
1259 if (flags
& Terminal
.flags
.INVERSE
) {
1269 classNames
.push('xterm-bg-color-' + bg
);
1273 classNames
.push('xterm-color-' + fg
);
1277 if (classNames
.length
) {
1278 out
+= ' class="' + classNames
.join(' ') + '"';
1285 if (ch_width
=== 2) {
1286 out
+= '<span class="xterm-wide-char">';
1306 if (ch_width
=== 2) {
1313 if (attr
!== this.defAttr
) {
1317 this.children
[y
].innerHTML
= out
;
1321 this.element
.appendChild(this.rowContainer
);
1324 this.emit('refresh', {element
: this.element
, start
: start
, end
: end
});
1328 * Display the cursor element
1330 Terminal
.prototype.showCursor = function() {
1331 if (!this.cursorState
) {
1332 this.cursorState
= 1;
1333 this.queueRefresh(this.y
, this.y
);
1338 * Scroll the terminal down 1 row, creating a blank line.
1340 Terminal
.prototype.scroll = function() {
1343 // Make room for the new row in lines
1344 if (this.lines
.length
=== this.lines
.maxLength
) {
1345 this.lines
.trimStart(1);
1347 if (this.ydisp
!== 0) {
1354 // TODO: Why is this done twice?
1355 if (!this.userScrolling
) {
1356 this.ydisp
= this.ybase
;
1360 row
= this.ybase
+ this.rows
- 1;
1362 // subtract the bottom scroll region
1363 row
-= this.rows
- 1 - this.scrollBottom
;
1365 if (row
=== this.lines
.length
) {
1366 // Optimization: pushing is faster than splicing when they amount to the same behavior
1367 this.lines
.push(this.blankLine());
1370 this.lines
.splice(row
, 0, this.blankLine());
1373 if (this.scrollTop
!== 0) {
1374 if (this.ybase
!== 0) {
1376 if (!this.userScrolling
) {
1377 this.ydisp
= this.ybase
;
1380 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1384 this.updateRange(this.scrollTop
);
1385 this.updateRange(this.scrollBottom
);
1388 * This event is emitted whenever the terminal is scrolled.
1389 * The one parameter passed is the new y display position.
1393 this.emit('scroll', this.ydisp
);
1397 * Scroll the display of the terminal
1398 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1399 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1400 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1401 * viewport originally.
1403 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1405 this.userScrolling
= true;
1406 } else if (disp
+ this.ydisp
>= this.ybase
) {
1407 this.userScrolling
= false;
1412 if (this.ydisp
> this.ybase
) {
1413 this.ydisp
= this.ybase
;
1414 } else if (this.ydisp
< 0) {
1418 if (!suppressScrollEvent
) {
1419 this.emit('scroll', this.ydisp
);
1422 this.queueRefresh(0, this.rows
- 1);
1426 * Scroll the display of the terminal by a number of pages.
1427 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1429 Terminal
.prototype.scrollPages = function(pageCount
) {
1430 this.scrollDisp(pageCount
* (this.rows
- 1));
1434 * Scrolls the display of the terminal to the top.
1436 Terminal
.prototype.scrollToTop = function() {
1437 this.scrollDisp(-this.ydisp
);
1441 * Scrolls the display of the terminal to the bottom.
1443 Terminal
.prototype.scrollToBottom = function() {
1444 this.scrollDisp(this.ybase
- this.ydisp
);
1448 * Writes text to the terminal.
1449 * @param {string} text The text to write to the terminal.
1451 Terminal
.prototype.write = function(data
) {
1452 this.writeBuffer
.push(data
);
1454 // Send XOFF to pause the pty process if the write buffer becomes too large so
1455 // xterm.js can catch up before more data is sent. This is necessary in order
1456 // to keep signals such as ^C responsive.
1457 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1458 // XOFF - stop pty pipe
1459 // XON will be triggered by emulator before processing data chunk
1461 this.xoffSentToCatchUp
= true;
1464 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1465 // Kick off a write which will write all data in sequence recursively
1466 this.writeInProgress
= true;
1467 // Kick off an async innerWrite so more writes can come in while processing data
1469 setTimeout(function () {
1475 Terminal
.prototype.innerWrite = function() {
1476 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1477 while (writeBatch
.length
> 0) {
1478 var data
= writeBatch
.shift();
1479 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1481 // If XOFF was sent in order to catch up with the pty process, resume it if
1482 // the writeBuffer is empty to allow more data to come in.
1483 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1485 this.xoffSentToCatchUp
= false;
1488 this.refreshStart
= this.y
;
1489 this.refreshEnd
= this.y
;
1491 this.parser
.parse(data
);
1493 this.updateRange(this.y
);
1494 this.queueRefresh(this.refreshStart
, this.refreshEnd
);
1496 if (this.writeBuffer
.length
> 0) {
1497 // Allow renderer to catch up before processing the next batch
1499 setTimeout(function () {
1503 this.writeInProgress
= false;
1508 * Writes text to the terminal, followed by a break line character (\n).
1509 * @param {string} text The text to write to the terminal.
1511 Terminal
.prototype.writeln = function(data
) {
1512 this.write(data
+ '\r\n');
1516 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1517 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1519 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1520 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1521 * the default action. The function returns whether the event should be processed by xterm.js.
1523 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1524 this.customKeydownHandler
= customKeydownHandler
;
1528 * Handle a keydown event
1530 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1531 * @param {KeyboardEvent} ev The keydown event to be handled.
1533 Terminal
.prototype.keyDown = function(ev
) {
1534 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1538 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1539 if (this.ybase
!== this.ydisp
) {
1540 this.scrollToBottom();
1546 var result
= this.evaluateKeyEscapeSequence(ev
);
1548 if (result
.key
=== C0
.DC3
) { // XOFF
1549 this.writeStopped
= true;
1550 } else if (result
.key
=== C0
.DC1
) { // XON
1551 this.writeStopped
= false;
1554 if (result
.scrollDisp
) {
1555 this.scrollDisp(result
.scrollDisp
);
1556 return this.cancel(ev
, true);
1559 if (isThirdLevelShift(this, ev
)) {
1563 if (result
.cancel
) {
1564 // The event is canceled at the end already, is this necessary?
1565 this.cancel(ev
, true);
1572 this.emit('keydown', ev
);
1573 this.emit('key', result
.key
, ev
);
1575 this.handler(result
.key
);
1577 return this.cancel(ev
, true);
1581 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1582 * returned value is the new key code to pass to the PTY.
1584 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1585 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1587 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1589 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1590 // canceled at the end of keyDown
1592 // The new key even to emit
1594 // The number of characters to scroll, if this is defined it will cancel the event
1595 scrollDisp
: undefined
1597 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1598 switch (ev
.keyCode
) {
1602 result
.key
= C0
.BS
; // ^H
1605 result
.key
= C0
.DEL
; // ^?
1610 result
.key
= C0
.ESC
+ '[Z';
1614 result
.cancel
= true;
1619 result
.cancel
= true;
1623 result
.key
= C0
.ESC
;
1624 result
.cancel
= true;
1629 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1630 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1631 // http://unix.stackexchange.com/a/108106
1632 // macOS uses different escape sequences than linux
1633 if (result
.key
== C0
.ESC
+ '[1;3D') {
1634 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1636 } else if (this.applicationCursor
) {
1637 result
.key
= C0
.ESC
+ 'OD';
1639 result
.key
= C0
.ESC
+ '[D';
1645 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1646 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1647 // http://unix.stackexchange.com/a/108106
1648 // macOS uses different escape sequences than linux
1649 if (result
.key
== C0
.ESC
+ '[1;3C') {
1650 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1652 } else if (this.applicationCursor
) {
1653 result
.key
= C0
.ESC
+ 'OC';
1655 result
.key
= C0
.ESC
+ '[C';
1661 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1662 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1663 // http://unix.stackexchange.com/a/108106
1664 if (result
.key
== C0
.ESC
+ '[1;3A') {
1665 result
.key
= C0
.ESC
+ '[1;5A';
1667 } else if (this.applicationCursor
) {
1668 result
.key
= C0
.ESC
+ 'OA';
1670 result
.key
= C0
.ESC
+ '[A';
1676 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1677 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1678 // http://unix.stackexchange.com/a/108106
1679 if (result
.key
== C0
.ESC
+ '[1;3B') {
1680 result
.key
= C0
.ESC
+ '[1;5B';
1682 } else if (this.applicationCursor
) {
1683 result
.key
= C0
.ESC
+ 'OB';
1685 result
.key
= C0
.ESC
+ '[B';
1690 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1691 // <Ctrl> or <Shift> + <Insert> are used to
1692 // copy-paste on some systems.
1693 result
.key
= C0
.ESC
+ '[2~';
1699 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1701 result
.key
= C0
.ESC
+ '[3~';
1707 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1708 else if (this.applicationCursor
)
1709 result
.key
= C0
.ESC
+ 'OH';
1711 result
.key
= C0
.ESC
+ '[H';
1716 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1717 else if (this.applicationCursor
)
1718 result
.key
= C0
.ESC
+ 'OF';
1720 result
.key
= C0
.ESC
+ '[F';
1725 result
.scrollDisp
= -(this.rows
- 1);
1727 result
.key
= C0
.ESC
+ '[5~';
1733 result
.scrollDisp
= this.rows
- 1;
1735 result
.key
= C0
.ESC
+ '[6~';
1741 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1743 result
.key
= C0
.ESC
+ 'OP';
1748 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1750 result
.key
= C0
.ESC
+ 'OQ';
1755 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1757 result
.key
= C0
.ESC
+ 'OR';
1762 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1764 result
.key
= C0
.ESC
+ 'OS';
1769 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1771 result
.key
= C0
.ESC
+ '[15~';
1776 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1778 result
.key
= C0
.ESC
+ '[17~';
1783 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1785 result
.key
= C0
.ESC
+ '[18~';
1790 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1792 result
.key
= C0
.ESC
+ '[19~';
1797 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1799 result
.key
= C0
.ESC
+ '[20~';
1804 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1806 result
.key
= C0
.ESC
+ '[21~';
1811 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1813 result
.key
= C0
.ESC
+ '[23~';
1818 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1820 result
.key
= C0
.ESC
+ '[24~';
1825 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1826 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1827 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1828 } else if (ev
.keyCode
=== 32) {
1830 result
.key
= String
.fromCharCode(0);
1831 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1832 // escape, file sep, group sep, record sep, unit sep
1833 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1834 } else if (ev
.keyCode
=== 56) {
1836 result
.key
= String
.fromCharCode(127);
1837 } else if (ev
.keyCode
=== 219) {
1838 // ^[ - Control Sequence Introducer (CSI)
1839 result
.key
= String
.fromCharCode(27);
1840 } else if (ev
.keyCode
=== 220) {
1841 // ^\ - String Terminator (ST)
1842 result
.key
= String
.fromCharCode(28);
1843 } else if (ev
.keyCode
=== 221) {
1844 // ^] - Operating System Command (OSC)
1845 result
.key
= String
.fromCharCode(29);
1847 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1848 // On Mac this is a third level shift. Use <Esc> instead.
1849 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1850 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1851 } else if (ev
.keyCode
=== 192) {
1852 result
.key
= C0
.ESC
+ '`';
1853 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1854 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1864 * Set the G level of the terminal
1867 Terminal
.prototype.setgLevel = function(g
) {
1869 this.charset
= this.charsets
[g
];
1873 * Set the charset for the given G level of the terminal
1877 Terminal
.prototype.setgCharset = function(g
, charset
) {
1878 this.charsets
[g
] = charset
;
1879 if (this.glevel
=== g
) {
1880 this.charset
= charset
;
1885 * Handle a keypress event.
1887 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1888 * @param {KeyboardEvent} ev The keypress event to be handled.
1890 Terminal
.prototype.keyPress = function(ev
) {
1897 } else if (ev
.which
== null) {
1899 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1906 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1911 key
= String
.fromCharCode(key
);
1913 this.emit('keypress', key
, ev
);
1914 this.emit('key', key
, ev
);
1922 * Send data for handling to the terminal
1923 * @param {string} data
1925 Terminal
.prototype.send = function(data
) {
1929 setTimeout(function() {
1930 self
.handler(self
.queue
);
1940 * Note: We could do sweet things with webaudio here
1942 Terminal
.prototype.bell = function() {
1943 if (!this.visualBell
) return;
1945 this.element
.style
.borderColor
= 'white';
1946 setTimeout(function() {
1947 self
.element
.style
.borderColor
= '';
1949 if (this.popOnBell
) this.focus();
1953 * Log the current state to the console.
1955 Terminal
.prototype.log = function() {
1956 if (!this.debug
) return;
1957 if (!this.context
.console
|| !this.context
.console
.log
) return;
1958 var args
= Array
.prototype.slice
.call(arguments
);
1959 this.context
.console
.log
.apply(this.context
.console
, args
);
1963 * Log the current state as error to the console.
1965 Terminal
.prototype.error = function() {
1966 if (!this.debug
) return;
1967 if (!this.context
.console
|| !this.context
.console
.error
) return;
1968 var args
= Array
.prototype.slice
.call(arguments
);
1969 this.context
.console
.error
.apply(this.context
.console
, args
);
1973 * Resizes the terminal.
1975 * @param {number} x The number of columns to resize to.
1976 * @param {number} y The number of rows to resize to.
1978 Terminal
.prototype.resize = function(x
, y
) {
1986 if (x
=== this.cols
&& y
=== this.rows
) {
1996 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1997 i
= this.lines
.length
;
1999 while (this.lines
.get(i
).length
< x
) {
2000 this.lines
.get(i
).push(ch
);
2004 i
= this.lines
.length
;
2006 while (this.lines
.get(i
).length
> x
) {
2007 this.lines
.get(i
).pop();
2012 this.setupStops(this.cols
);
2020 // y is rows, not this.y
2021 if (this.lines
.length
< y
+ this.ybase
) {
2022 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
2023 // There is room above the buffer and there are no empty elements below the line,
2027 if (this.ydisp
> 0) {
2028 // Viewport is at the top of the buffer, must increase downwards
2032 // Add a blank line if there is no buffer left at the top to scroll to, or if there
2033 // are blank lines after the cursor
2034 this.lines
.push(this.blankLine());
2037 if (this.children
.length
< y
) {
2043 if (this.lines
.length
> y
+ this.ybase
) {
2044 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
2045 // The line is a blank line below the cursor, remove it
2048 // The line is the cursor, scroll down
2053 if (this.children
.length
> y
) {
2054 el
= this.children
.shift();
2056 el
.parentNode
.removeChild(el
);
2062 // Make sure that the cursor stays on screen
2075 this.scrollBottom
= y
- 1;
2077 this.charMeasure
.measure();
2079 this.queueRefresh(0, this.rows
- 1);
2083 this.geometry
= [this.cols
, this.rows
];
2084 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
2088 * Updates the range of rows to refresh
2089 * @param {number} y The number of rows to refresh next.
2091 Terminal
.prototype.updateRange = function(y
) {
2092 if (y
< this.refreshStart
) this.refreshStart
= y
;
2093 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
2094 // if (y > this.refreshEnd) {
2095 // this.refreshEnd = y;
2096 // if (y > this.rows - 1) {
2097 // this.refreshEnd = this.rows - 1;
2103 * Set the range of refreshing to the maximum value
2105 Terminal
.prototype.maxRange = function() {
2106 this.refreshStart
= 0;
2107 this.refreshEnd
= this.rows
- 1;
2113 * Setup the tab stops.
2116 Terminal
.prototype.setupStops = function(i
) {
2118 if (!this.tabs
[i
]) {
2119 i
= this.prevStop(i
);
2126 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
2127 this.tabs
[i
] = true;
2133 * Move the cursor to the previous tab stop from the given position (default is current).
2134 * @param {number} x The position to move the cursor to the previous tab stop.
2136 Terminal
.prototype.prevStop = function(x
) {
2137 if (x
== null) x
= this.x
;
2138 while (!this.tabs
[--x
] && x
> 0);
2139 return x
>= this.cols
2146 * Move the cursor one tab stop forward from the given position (default is current).
2147 * @param {number} x The position to move the cursor one tab stop forward.
2149 Terminal
.prototype.nextStop = function(x
) {
2150 if (x
== null) x
= this.x
;
2151 while (!this.tabs
[++x
] && x
< this.cols
);
2152 return x
>= this.cols
2159 * Erase in the identified line everything from "x" to the end of the line (right).
2160 * @param {number} x The column from which to start erasing to the end of the line.
2161 * @param {number} y The line in which to operate.
2163 Terminal
.prototype.eraseRight = function(x
, y
) {
2164 var line
= this.lines
.get(this.ybase
+ y
);
2168 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2169 for (; x
< this.cols
; x
++) {
2172 this.updateRange(y
);
2178 * Erase in the identified line everything from "x" to the start of the line (left).
2179 * @param {number} x The column from which to start erasing to the start of the line.
2180 * @param {number} y The line in which to operate.
2182 Terminal
.prototype.eraseLeft = function(x
, y
) {
2183 var line
= this.lines
.get(this.ybase
+ y
);
2187 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2192 this.updateRange(y
);
2196 * Clears the entire buffer, making the prompt line the new first line.
2198 Terminal
.prototype.clear = function() {
2199 if (this.ybase
=== 0 && this.y
=== 0) {
2200 // Don't clear if it's already clear
2203 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2204 this.lines
.length
= 1;
2208 for (var i
= 1; i
< this.rows
; i
++) {
2209 this.lines
.push(this.blankLine());
2211 this.queueRefresh(0, this.rows
- 1);
2212 this.emit('scroll', this.ydisp
);
2216 * Erase all content in the given line
2217 * @param {number} y The line to erase all of its contents.
2219 Terminal
.prototype.eraseLine = function(y
) {
2220 this.eraseRight(0, y
);
2225 * Return the data array of a blank line
2226 * @param {number} cur First bunch of data for each "blank" character.
2228 Terminal
.prototype.blankLine = function(cur
) {
2233 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2237 for (; i
< this.cols
; i
++) {
2246 * If cur return the back color xterm feature attribute. Else return defAttr.
2247 * @param {object} cur
2249 Terminal
.prototype.ch = function(cur
) {
2251 ? [this.eraseAttr(), ' ', 1]
2252 : [this.defAttr
, ' ', 1];
2257 * Evaluate if the current erminal is the given argument.
2258 * @param {object} term The terminal to evaluate
2260 Terminal
.prototype.is = function(term
) {
2261 var name
= this.termName
;
2262 return (name
+ '').indexOf(term
) === 0;
2267 * Emit the 'data' event and populate the given data.
2268 * @param {string} data The data to populate in the event.
2270 Terminal
.prototype.handler = function(data
) {
2271 // Prevents all events to pty process if stdin is disabled
2272 if (this.options
.disableStdin
) {
2276 // Input is being sent to the terminal, the terminal should focus the prompt.
2277 if (this.ybase
!== this.ydisp
) {
2278 this.scrollToBottom();
2280 this.emit('data', data
);
2285 * Emit the 'title' event and populate the given title.
2286 * @param {string} title The title to populate in the event.
2288 Terminal
.prototype.handleTitle = function(title
) {
2290 * This event is emitted when the title of the terminal is changed
2291 * from inside the terminal. The parameter is the new title.
2295 this.emit('title', title
);
2304 * ESC D Index (IND is 0x84).
2306 Terminal
.prototype.index = function() {
2308 if (this.y
> this.scrollBottom
) {
2312 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2313 if (this.x
>= this.cols
) {
2320 * ESC M Reverse Index (RI is 0x8d).
2322 * Move the cursor up one row, inserting a new blank line if necessary.
2324 Terminal
.prototype.reverseIndex = function() {
2326 if (this.y
=== this.scrollTop
) {
2327 // possibly move the code below to term.reverseScroll();
2328 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2329 // blankLine(true) is xterm/linux behavior
2330 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2331 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2332 this.updateRange(this.scrollTop
);
2333 this.updateRange(this.scrollBottom
);
2341 * ESC c Full Reset (RIS).
2343 Terminal
.prototype.reset = function() {
2344 this.options
.rows
= this.rows
;
2345 this.options
.cols
= this.cols
;
2346 var customKeydownHandler
= this.customKeydownHandler
;
2347 Terminal
.call(this, this.options
);
2348 this.customKeydownHandler
= customKeydownHandler
;
2349 this.queueRefresh(0, this.rows
- 1);
2350 this.viewport
.syncScrollArea();
2355 * ESC H Tab Set (HTS is 0x88).
2357 Terminal
.prototype.tabSet = function() {
2358 this.tabs
[this.x
] = true;
2365 function on(el
, type
, handler
, capture
) {
2366 if (!Array
.isArray(el
)) {
2369 el
.forEach(function (element
) {
2370 element
.addEventListener(type
, handler
, capture
|| false);
2374 function off(el
, type
, handler
, capture
) {
2375 el
.removeEventListener(type
, handler
, capture
|| false);
2378 function cancel(ev
, force
) {
2379 if (!this.cancelEvents
&& !force
) {
2382 ev
.preventDefault();
2383 ev
.stopPropagation();
2387 function inherits(child
, parent
) {
2389 this.constructor = child
;
2391 f
.prototype = parent
.prototype;
2392 child
.prototype = new f
;
2395 // if bold is broken, we can't
2396 // use it in the terminal.
2397 function isBoldBroken(document
) {
2398 var body
= document
.getElementsByTagName('body')[0];
2399 var el
= document
.createElement('span');
2400 el
.innerHTML
= 'hello world';
2401 body
.appendChild(el
);
2402 var w1
= el
.scrollWidth
;
2403 el
.style
.fontWeight
= 'bold';
2404 var w2
= el
.scrollWidth
;
2405 body
.removeChild(el
);
2409 function indexOf(obj
, el
) {
2412 if (obj
[i
] === el
) return i
;
2417 function isThirdLevelShift(term
, ev
) {
2419 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2420 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2422 if (ev
.type
== 'keypress') {
2423 return thirdLevelKey
;
2426 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2427 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2430 // Expose to InputHandler (temporary)
2431 Terminal
.prototype.matchColor
= matchColor
;
2433 function matchColor(r1
, g1
, b1
) {
2434 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2436 if (matchColor
._cache
[hash
] != null) {
2437 return matchColor
._cache
[hash
];
2440 var ldiff
= Infinity
2449 for (; i
< Terminal
.vcolors
.length
; i
++) {
2450 c
= Terminal
.vcolors
[i
];
2455 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2468 return matchColor
._cache
[hash
] = li
;
2471 matchColor
._cache
= {};
2473 // http://stackoverflow.com/questions/1633828
2474 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2475 return Math
.pow(30 * (r1
- r2
), 2)
2476 + Math
.pow(59 * (g1
- g2
), 2)
2477 + Math
.pow(11 * (b1
- b2
), 2);
2480 function each(obj
, iter
, con
) {
2481 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2482 for (var i
= 0; i
< obj
.length
; i
++) {
2483 iter
.call(con
, obj
[i
], i
, obj
);
2487 function wasMondifierKeyOnlyEvent(ev
) {
2488 return ev
.keyCode
=== 16 || // Shift
2489 ev
.keyCode
=== 17 || // Ctrl
2490 ev
.keyCode
=== 18; // Alt
2493 function keys(obj
) {
2494 if (Object
.keys
) return Object
.keys(obj
);
2497 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2508 Terminal
.EventEmitter
= EventEmitter
;
2509 Terminal
.inherits
= inherits
;
2512 * Adds an event listener to the terminal.
2514 * @param {string} event The name of the event. TODO: Document all event types
2515 * @param {function} callback The function to call when the event is triggered.
2519 Terminal
.cancel
= cancel
;
2521 module
.exports
= Terminal
;