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;
43 var normal
= 0, escaped
= 1, csi
= 2, osc
= 3, charset
= 4, dcs
= 5, ignore
= 6;
46 * The amount of write requests to queue before sending an XOFF signal to the
47 * pty process. This number must be small in order for ^C and similar sequences
50 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
53 * The number of writes to perform in a single batch before allowing the
54 * renderer to catch up with a 0ms setTimeout.
56 var WRITE_BATCH_SIZE
= 300;
59 * The maximum number of refresh frames to skip when the write buffer is non-
60 * empty. Note that these frames may be intermingled with frames that are
61 * skipped via requestAnimationFrame's mechanism.
63 var MAX_REFRESH_FRAME_SKIP
= 5;
70 * Creates a new `Terminal` object.
72 * @param {object} options An object containing a set of options, the available options are:
73 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
74 * - `cols` (number): The number of columns of the terminal (horizontal size)
75 * - `rows` (number): The number of rows of the terminal (vertical size)
79 * @alias module:xterm/src/xterm
81 function Terminal(options
) {
84 if (!(this instanceof Terminal
)) {
85 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
88 self
.browser
= Browser
;
89 self
.cancel
= Terminal
.cancel
;
91 EventEmitter
.call(this);
93 if (typeof options
=== 'number') {
101 options
= options
|| {};
104 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
105 if (options
[key
] == null) {
106 options
[key
] = Terminal
.options
[key
];
108 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
109 options
[key
] = Terminal
[key
];
112 self
[key
] = options
[key
];
115 if (options
.colors
.length
=== 8) {
116 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
117 } else if (options
.colors
.length
=== 16) {
118 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
119 } else if (options
.colors
.length
=== 10) {
120 options
.colors
= options
.colors
.slice(0, -2).concat(
121 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
122 } else if (options
.colors
.length
=== 18) {
123 options
.colors
= options
.colors
.concat(
124 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
126 this.colors
= options
.colors
;
128 this.options
= options
;
130 // this.context = options.context || window;
131 // this.document = options.document || document;
132 this.parent
= options
.body
|| options
.parent
|| (
133 document
? document
.getElementsByTagName('body')[0] : null
136 this.cols
= options
.cols
|| options
.geometry
[0];
137 this.rows
= options
.rows
|| options
.geometry
[1];
138 this.geometry
= [this.cols
, this.rows
];
140 if (options
.handler
) {
141 this.on('data', options
.handler
);
145 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
151 * The scroll position of the viewport
156 * The cursor's x position after ybase
161 * The cursor's y position after ybase
165 /** A queue of the rows to be refreshed */
166 this.refreshRowsQueue
= [];
168 this.cursorState
= 0;
169 this.cursorHidden
= false;
173 this.scrollBottom
= this.rows
- 1;
174 this.customKeydownHandler
= null;
177 this.applicationKeypad
= false;
178 this.applicationCursor
= false;
179 this.originMode
= false;
180 this.insertMode
= false;
181 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
186 this.gcharset
= null;
188 this.charsets
= [null];
212 this.readable
= true;
213 this.writable
= true;
215 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
216 this.curAttr
= this.defAttr
;
219 this.currentParam
= 0;
223 this.inputHandler
= new InputHandler(this);
224 this.parser
= new Parser(this.inputHandler
, this);
227 this.writeBuffer
= [];
228 this.writeInProgress
= false;
229 this.refreshFramesSkipped
= 0;
232 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
233 * This is a distinct state from writeStopped so that if the user requested
234 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
237 this.xoffSentToCatchUp
= false;
239 /** Whether writing has been stopped as a result of XOFF */
240 this.writeStopped
= false;
242 // leftover surrogate high from previous write invocation
243 this.surrogate_high
= '';
246 * An array of all lines in the entire buffer, including the prompt. The lines are array of
247 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
249 this.lines
= new CircularList(this.scrollback
);
252 this.lines
.push(this.blankLine());
258 // Store if user went browsing history in scrollback
259 this.userScrolling
= false;
262 inherits(Terminal
, EventEmitter
);
265 * back_color_erase feature for xterm.
267 Terminal
.prototype.eraseAttr = function() {
268 // if (this.is('screen')) return this.defAttr;
269 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
277 Terminal
.tangoColors
= [
298 // Colors 0-15 + 16-255
299 // Much thanks to TooTallNate for writing this.
300 Terminal
.colors
= (function() {
301 var colors
= Terminal
.tangoColors
.slice()
302 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
307 for (; i
< 216; i
++) {
308 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
313 for (; i
< 24; i
++) {
318 function out(r
, g
, b
) {
319 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
324 return c
.length
< 2 ? '0' + c
: c
;
330 Terminal
._colors
= Terminal
.colors
.slice();
332 Terminal
.vcolors
= (function() {
334 , colors
= Terminal
.colors
338 for (; i
< 256; i
++) {
339 color
= parseInt(colors
[i
].substring(1), 16);
341 (color
>> 16) & 0xff,
354 Terminal
.defaults
= {
355 colors
: Terminal
.colors
,
368 // programFeatures: false,
372 Terminal
.options
= {};
374 Terminal
.focus
= null;
376 each(keys(Terminal
.defaults
), function(key
) {
377 Terminal
[key
] = Terminal
.defaults
[key
];
378 Terminal
.options
[key
] = Terminal
.defaults
[key
];
382 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
384 Terminal
.prototype.focus = function() {
385 return this.textarea
.focus();
389 * Retrieves an option's value from the terminal.
390 * @param {string} key The option key.
392 Terminal
.prototype.getOption = function(key
, value
) {
393 if (!(key
in Terminal
.defaults
)) {
394 throw new Error('No option with key "' + key
+ '"');
397 if (typeof this.options
[key
] !== 'undefined') {
398 return this.options
[key
];
405 * Sets an option on the terminal.
406 * @param {string} key The option key.
407 * @param {string} value The option value.
409 Terminal
.prototype.setOption = function(key
, value
) {
410 if (!(key
in Terminal
.defaults
)) {
411 throw new Error('No option with key "' + key
+ '"');
415 if (this.options
[key
] !== value
) {
416 if (this.lines
.length
> value
) {
417 const amountToTrim
= this.lines
.length
- value
;
418 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
419 this.lines
.trimStart(amountToTrim
);
420 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
421 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
423 this.refresh(0, this.rows
- 1);
426 this.lines
.maxLength
= value
;
427 this.viewport
.syncScrollArea();
432 this.options
[key
] = value
;
434 case 'cursorBlink': this.element
.classList
.toggle('xterm-cursor-blink', value
); break;
439 * Binds the desired focus behavior on a given terminal object.
443 Terminal
.bindFocus = function (term
) {
444 on(term
.textarea
, 'focus', function (ev
) {
445 if (term
.sendFocus
) {
446 term
.send(C0
.ESC
+ '[I');
448 term
.element
.classList
.add('focus');
450 Terminal
.focus
= term
;
451 term
.emit('focus', {terminal
: term
});
456 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
458 Terminal
.prototype.blur = function() {
459 return this.textarea
.blur();
463 * Binds the desired blur behavior on a given terminal object.
467 Terminal
.bindBlur = function (term
) {
468 on(term
.textarea
, 'blur', function (ev
) {
469 term
.queueRefresh(term
.y
, term
.y
);
470 if (term
.sendFocus
) {
471 term
.send(C0
.ESC
+ '[O');
473 term
.element
.classList
.remove('focus');
474 Terminal
.focus
= null;
475 term
.emit('blur', {terminal
: term
});
480 * Initialize default behavior
482 Terminal
.prototype.initGlobal = function() {
485 Terminal
.bindKeys(this);
486 Terminal
.bindFocus(this);
487 Terminal
.bindBlur(this);
489 // Bind clipboard functionality
490 on(this.element
, 'copy', function (ev
) {
491 copyHandler
.call(this, ev
, term
);
493 on(this.textarea
, 'paste', function (ev
) {
494 pasteHandler
.call(this, ev
, term
);
496 on(this.element
, 'paste', function (ev
) {
497 pasteHandler
.call(this, ev
, term
);
500 function rightClickHandlerWrapper (ev
) {
501 rightClickHandler
.call(this, ev
, term
);
504 if (term
.browser
.isFirefox
) {
505 on(this.element
, 'mousedown', function (ev
) {
506 if (ev
.button
== 2) {
507 rightClickHandlerWrapper(ev
);
511 on(this.element
, 'contextmenu', rightClickHandlerWrapper
);
516 * Apply key handling to the terminal
518 Terminal
.bindKeys = function(term
) {
519 on(term
.element
, 'keydown', function(ev
) {
520 if (document
.activeElement
!= this) {
526 on(term
.element
, 'keypress', function(ev
) {
527 if (document
.activeElement
!= this) {
533 on(term
.element
, 'keyup', function(ev
) {
534 if (!wasMondifierKeyOnlyEvent(ev
)) {
539 on(term
.textarea
, 'keydown', function(ev
) {
543 on(term
.textarea
, 'keypress', function(ev
) {
545 // Truncate the textarea's value, since it is not needed
549 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
550 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
551 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
552 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
557 * Insert the given row to the terminal or produce a new one
558 * if no row argument is passed. Return the inserted row.
559 * @param {HTMLElement} row (optional) The row to append to the terminal.
561 Terminal
.prototype.insertRow = function (row
) {
562 if (typeof row
!= 'object') {
563 row
= document
.createElement('div');
566 this.rowContainer
.appendChild(row
);
567 this.children
.push(row
);
573 * Opens the terminal within an element.
575 * @param {HTMLElement} parent The element to create the terminal within.
577 Terminal
.prototype.open = function(parent
) {
578 var self
=this, i
=0, div
;
580 this.parent
= parent
|| this.parent
;
583 throw new Error('Terminal requires a parent element.');
586 // Grab global elements
587 this.context
= this.parent
.ownerDocument
.defaultView
;
588 this.document
= this.parent
.ownerDocument
;
589 this.body
= this.document
.getElementsByTagName('body')[0];
591 //Create main element container
592 this.element
= this.document
.createElement('div');
593 this.element
.classList
.add('terminal');
594 this.element
.classList
.add('xterm');
595 this.element
.classList
.add('xterm-theme-' + this.theme
);
596 this.element
.classList
.toggle('xterm-cursor-blink', this.options
.cursorBlink
);
598 this.element
.style
.height
599 this.element
.setAttribute('tabindex', 0);
601 this.viewportElement
= document
.createElement('div');
602 this.viewportElement
.classList
.add('xterm-viewport');
603 this.element
.appendChild(this.viewportElement
);
604 this.viewportScrollArea
= document
.createElement('div');
605 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
606 this.viewportElement
.appendChild(this.viewportScrollArea
);
608 // Create the container that will hold the lines of the terminal and then
609 // produce the lines the lines.
610 this.rowContainer
= document
.createElement('div');
611 this.rowContainer
.classList
.add('xterm-rows');
612 this.element
.appendChild(this.rowContainer
);
615 // Create the container that will hold helpers like the textarea for
616 // capturing DOM Events. Then produce the helpers.
617 this.helperContainer
= document
.createElement('div');
618 this.helperContainer
.classList
.add('xterm-helpers');
619 // TODO: This should probably be inserted once it's filled to prevent an additional layout
620 this.element
.appendChild(this.helperContainer
);
621 this.textarea
= document
.createElement('textarea');
622 this.textarea
.classList
.add('xterm-helper-textarea');
623 this.textarea
.setAttribute('autocorrect', 'off');
624 this.textarea
.setAttribute('autocapitalize', 'off');
625 this.textarea
.setAttribute('spellcheck', 'false');
626 this.textarea
.tabIndex
= 0;
627 this.textarea
.addEventListener('focus', function() {
628 self
.emit('focus', {terminal
: self
});
630 this.textarea
.addEventListener('blur', function() {
631 self
.emit('blur', {terminal
: self
});
633 this.helperContainer
.appendChild(this.textarea
);
635 this.compositionView
= document
.createElement('div');
636 this.compositionView
.classList
.add('composition-view');
637 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
638 this.helperContainer
.appendChild(this.compositionView
);
640 this.charSizeStyleElement
= document
.createElement('style');
641 this.helperContainer
.appendChild(this.charSizeStyleElement
);
643 for (; i
< this.rows
; i
++) {
646 this.parent
.appendChild(this.element
);
648 this.charMeasure
= new CharMeasure(this.helperContainer
);
649 this.charMeasure
.on('charsizechanged', function () {
650 self
.updateCharSizeCSS();
652 this.charMeasure
.measure();
654 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
656 // Setup loop that draws to screen
657 this.queueRefresh(0, this.rows
- 1);
660 // Initialize global actions that
661 // need to be taken on the document.
664 // Ensure there is a Terminal.focus.
667 on(this.element
, 'click', function() {
668 var selection
= document
.getSelection(),
669 collapsed
= selection
.isCollapsed
,
670 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
676 // Listen for mouse events and translate
677 // them into terminal mouse protocols.
680 // Figure out whether boldness affects
681 // the character width of monospace fonts.
682 if (Terminal
.brokenBold
== null) {
683 Terminal
.brokenBold
= isBoldBroken(this.document
);
687 * This event is emitted when terminal has completed opening.
696 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
697 * @param {string} addon The name of the addon to load
700 Terminal
.loadAddon = function(addon
, callback
) {
701 if (typeof exports
=== 'object' && typeof module
=== 'object') {
703 return require('./addons/' + addon
+ '/' + addon
);
704 } else if (typeof define
== 'function') {
706 return require(['./addons/' + addon
+ '/' + addon
], callback
);
708 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
714 * Updates the helper CSS class with any changes necessary after the terminal's
715 * character width has been changed.
717 Terminal
.prototype.updateCharSizeCSS = function() {
718 this.charSizeStyleElement
.textContent
= '.xterm-wide-char{width:' + (this.charMeasure
.width
* 2) + 'px;}';
723 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
724 * To better understand these
725 * the xterm code is very helpful:
727 * button.c, charproc.c, misc.c
728 * Relevant functions in xterm/button.c:
729 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
731 Terminal
.prototype.bindMouse = function() {
732 var el
= this.element
, self
= this, pressed
= 32;
734 // mouseup, mousedown, wheel
735 // left click: ^[[M 3<^[[M#3<
737 function sendButton(ev
) {
741 // get the xterm-style button
742 button
= getButton(ev
);
744 // get mouse coordinates
748 sendEvent(button
, pos
);
750 switch (ev
.overrideType
|| ev
.type
) {
755 // keep it at the left
756 // button, just in case.
767 // motion example of a left click:
768 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
769 function sendMove(ev
) {
776 // buttons marked as motions
777 // are incremented by 32
780 sendEvent(button
, pos
);
784 // position to characters
785 function encode(data
, ch
) {
786 if (!self
.utfMouse
) {
787 if (ch
=== 255) return data
.push(0);
788 if (ch
> 127) ch
= 127;
791 if (ch
=== 2047) return data
.push(0);
795 if (ch
> 2047) ch
= 2047;
796 data
.push(0xC0 | (ch
>> 6));
797 data
.push(0x80 | (ch
& 0x3F));
802 // send a mouse event:
803 // regular/utf8: ^[[M Cb Cx Cy
804 // urxvt: ^[[ Cb ; Cx ; Cy M
805 // sgr: ^[[ Cb ; Cx ; Cy M/m
806 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
807 // locator: CSI P e ; P b ; P r ; P c ; P p & w
808 function sendEvent(button
, pos
) {
809 // self.emit('mouse', {
815 if (self
.vt300Mouse
) {
817 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
821 var data
= C0
.ESC
+ '[24';
822 if (button
=== 0) data
+= '1';
823 else if (button
=== 1) data
+= '3';
824 else if (button
=== 2) data
+= '5';
825 else if (button
=== 3) return;
827 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
832 if (self
.decLocator
) {
837 if (button
=== 0) button
= 2;
838 else if (button
=== 1) button
= 4;
839 else if (button
=== 2) button
= 6;
840 else if (button
=== 3) button
= 3;
841 self
.send(C0
.ESC
+ '['
844 + (button
=== 3 ? 4 : 0)
855 if (self
.urxvtMouse
) {
860 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
867 self
.send(C0
.ESC
+ '[<'
868 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
873 + ((button
& 3) === 3 ? 'm' : 'M'));
879 encode(data
, button
);
883 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
886 function getButton(ev
) {
899 // 1, and 2 - with 64 added
900 switch (ev
.overrideType
|| ev
.type
) {
902 button
= ev
.button
!= null
908 if (self
.browser
.isMSIE
) {
909 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
915 case 'DOMMouseScroll':
916 button
= ev
.detail
< 0
921 button
= ev
.wheelDeltaY
> 0
927 // next three bits are the modifiers:
928 // 4 = shift, 8 = meta, 16 = control
929 shift
= ev
.shiftKey
? 4 : 0;
930 meta
= ev
.metaKey
? 8 : 0;
931 ctrl
= ev
.ctrlKey
? 16 : 0;
932 mod
= shift
| meta
| ctrl
;
935 if (self
.vt200Mouse
) {
938 } else if (!self
.normalMouse
) {
943 button
= (32 + (mod
<< 2)) + button
;
948 // mouse coordinates measured in cols/rows
949 function getCoords(ev
) {
952 // ignore browsers without pageX for now
953 if (ev
.pageX
== null) return;
959 // should probably check offsetParent
960 // but this is more portable
961 while (el
&& el
!== self
.document
.documentElement
) {
964 el
= 'offsetParent' in el
969 // convert to cols/rows
970 w
= self
.element
.clientWidth
;
971 h
= self
.element
.clientHeight
;
972 x
= Math
.ceil((x
/ w
) * self
.cols
);
973 y
= Math
.ceil((y
/ h
) * self
.rows
);
975 // be sure to avoid sending
976 // bad positions to the program
978 if (x
> self
.cols
) x
= self
.cols
;
980 if (y
> self
.rows
) y
= self
.rows
;
982 // xterm sends raw bytes and
983 // starts at 32 (SP) for each.
994 on(el
, 'mousedown', function(ev
) {
995 if (!self
.mouseEvents
) return;
1004 //if (self.vt200Mouse && !self.normalMouse) {
1005 if (self
.vt200Mouse
) {
1006 ev
.overrideType
= 'mouseup';
1008 return self
.cancel(ev
);
1012 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1014 // x10 compatibility mode can't send button releases
1015 if (!self
.x10Mouse
) {
1016 on(self
.document
, 'mouseup', function up(ev
) {
1018 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1019 off(self
.document
, 'mouseup', up
);
1020 return self
.cancel(ev
);
1024 return self
.cancel(ev
);
1027 //if (self.normalMouse) {
1028 // on(self.document, 'mousemove', sendMove);
1031 on(el
, 'wheel', function(ev
) {
1032 if (!self
.mouseEvents
) return;
1035 || self
.decLocator
) return;
1037 return self
.cancel(ev
);
1040 // allow wheel scrolling in
1041 // the shell for example
1042 on(el
, 'wheel', function(ev
) {
1043 if (self
.mouseEvents
) return;
1044 self
.viewport
.onWheel(ev
);
1045 return self
.cancel(ev
);
1050 * Destroys the terminal.
1052 Terminal
.prototype.destroy = function() {
1053 this.readable
= false;
1054 this.writable
= false;
1056 this.handler = function() {};
1057 this.write = function() {};
1058 if (this.element
.parentNode
) {
1059 this.element
.parentNode
.removeChild(this.element
);
1061 //this.emit('close');
1066 * Flags used to render terminal text properly
1077 * Queues a refresh between two rows (inclusive), to be done on next animation
1079 * @param {number} start The start row.
1080 * @param {number} end The end row.
1082 Terminal
.prototype.queueRefresh = function(start
, end
) {
1083 this.refreshRowsQueue
.push({ start
: start
, end
: end
});
1087 * Performs the refresh loop callback, calling refresh only if a refresh is
1088 * necessary before queueing up the next one.
1090 Terminal
.prototype.refreshLoop = function() {
1091 // Don't refresh if there were no row changes
1092 if (this.refreshRowsQueue
.length
> 0) {
1093 // Skip MAX_REFRESH_FRAME_SKIP frames if the writeBuffer is non-empty as it
1094 // will need to be immediately refreshed anyway. This saves a lot of
1095 // rendering time as the viewport DOM does not need to be refreshed, no
1096 // scroll events, no layouts, etc.
1097 var skipFrame
= this.writeBuffer
.length
> 0 && this.refreshFramesSkipped
++ <= MAX_REFRESH_FRAME_SKIP
;
1100 this.refreshFramesSkipped
= 0;
1103 if (this.refreshRowsQueue
.length
> 4) {
1104 // Just do a full refresh when 5+ refreshes are queued
1106 end
= this.rows
- 1;
1108 // Get start and end rows that need refreshing
1109 start
= this.refreshRowsQueue
[0].start
;
1110 end
= this.refreshRowsQueue
[0].end
;
1111 for (var i
= 1; i
< this.refreshRowsQueue
.length
; i
++) {
1112 if (this.refreshRowsQueue
[i
].start
< start
) {
1113 start
= this.refreshRowsQueue
[i
].start
;
1115 if (this.refreshRowsQueue
[i
].end
> end
) {
1116 end
= this.refreshRowsQueue
[i
].end
;
1120 this.refreshRowsQueue
= [];
1121 this.refresh(start
, end
);
1124 window
.requestAnimationFrame(this.refreshLoop
.bind(this));
1128 * Refreshes (re-renders) terminal content within two rows (inclusive)
1132 * In the screen buffer, each character is stored as a an array with a character
1133 * and a 32-bit integer:
1134 * - First value: a utf-16 character.
1136 * - Next 9 bits: background color (0-511).
1137 * - Next 9 bits: foreground color (0-511).
1138 * - Next 14 bits: a mask for misc. flags:
1145 * @param {number} start The row to start from (between 0 and terminal's height terminal - 1)
1146 * @param {number} end The row to end at (between fromRow and terminal's height terminal - 1)
1148 Terminal
.prototype.refresh = function(start
, end
) {
1151 var x
, y
, i
, line
, out
, ch
, ch_width
, width
, data
, attr
, bg
, fg
, flags
, row
, parent
, focused
= document
.activeElement
;
1153 // If this is a big refresh, remove the terminal rows from the DOM for faster calculations
1154 if (end
- start
>= this.rows
/ 2) {
1155 parent
= this.element
.parentNode
;
1157 this.element
.removeChild(this.rowContainer
);
1164 if (end
>= this.rows
.length
) {
1165 this.log('`end` is too large. Most likely a bad CSR.');
1166 end
= this.rows
.length
- 1;
1169 for (; y
<= end
; y
++) {
1170 row
= y
+ this.ydisp
;
1172 line
= this.lines
.get(row
);
1173 if (!line
|| !this.children
[y
]) {
1174 // Continue if the line is not available, this means a resize is currently in progress
1179 if (this.y
=== y
- (this.ybase
- this.ydisp
)
1181 && !this.cursorHidden
) {
1187 attr
= this.defAttr
;
1190 for (; i
< width
; i
++) {
1192 // Continue if the character is not available, this means a resize is currently in progress
1197 ch_width
= line
[i
][2];
1201 if (i
=== x
) data
= -1;
1203 if (data
!== attr
) {
1204 if (attr
!== this.defAttr
) {
1207 if (data
!== this.defAttr
) {
1209 out
+= '<span class="reverse-video terminal-cursor">';
1211 var classNames
= [];
1214 fg
= (data
>> 9) & 0x1ff;
1217 if (flags
& Terminal
.flags
.BOLD
) {
1218 if (!Terminal
.brokenBold
) {
1219 classNames
.push('xterm-bold');
1221 // See: XTerm*boldColors
1222 if (fg
< 8) fg
+= 8;
1225 if (flags
& Terminal
.flags
.UNDERLINE
) {
1226 classNames
.push('xterm-underline');
1229 if (flags
& Terminal
.flags
.BLINK
) {
1230 classNames
.push('xterm-blink');
1233 // If inverse flag is on, then swap the foreground and background variables.
1234 if (flags
& Terminal
.flags
.INVERSE
) {
1235 /* One-line variable swap in JavaScript: http://stackoverflow.com/a/16201730 */
1236 bg = [fg, fg = bg][0];
1237 // Should inverse just be before the
1238 // above boldColors effect instead?
1239 if ((flags & 1) && fg < 8) fg += 8;
1242 if (flags & Terminal.flags.INVISIBLE) {
1243 classNames.push('xterm-hidden');
1247 * Weird situation: Invert flag used black foreground and white background results
1248 * in invalid background color, positioned at the 256 index of the 256 terminal
1249 * color map. Pin the colors manually in such a case.
1251 * Source: https://github.com/sourcelair/xterm.js/issues/57
1253 if (flags
& Terminal
.flags
.INVERSE
) {
1263 classNames
.push('xterm-bg-color-' + bg
);
1267 classNames
.push('xterm-color-' + fg
);
1271 if (classNames
.length
) {
1272 out
+= ' class="' + classNames
.join(' ') + '"';
1279 if (ch_width
=== 2) {
1280 out
+= '<span class="xterm-wide-char">';
1300 if (ch_width
=== 2) {
1307 if (attr
!== this.defAttr
) {
1311 this.children
[y
].innerHTML
= out
;
1315 this.element
.appendChild(this.rowContainer
);
1318 this.emit('refresh', {element
: this.element
, start
: start
, end
: end
});
1322 * Display the cursor element
1324 Terminal
.prototype.showCursor = function() {
1325 if (!this.cursorState
) {
1326 this.cursorState
= 1;
1327 this.queueRefresh(this.y
, this.y
);
1332 * Scroll the terminal down 1 row, creating a blank line.
1334 Terminal
.prototype.scroll = function() {
1337 // Make room for the new row in lines
1338 if (this.lines
.length
=== this.lines
.maxLength
) {
1339 this.lines
.trimStart(1);
1341 if (this.ydisp
!== 0) {
1348 // TODO: Why is this done twice?
1349 if (!this.userScrolling
) {
1350 this.ydisp
= this.ybase
;
1354 row
= this.ybase
+ this.rows
- 1;
1356 // subtract the bottom scroll region
1357 row
-= this.rows
- 1 - this.scrollBottom
;
1359 if (row
=== this.lines
.length
) {
1360 // Optimization: pushing is faster than splicing when they amount to the same behavior
1361 this.lines
.push(this.blankLine());
1364 this.lines
.splice(row
, 0, this.blankLine());
1367 if (this.scrollTop
!== 0) {
1368 if (this.ybase
!== 0) {
1370 if (!this.userScrolling
) {
1371 this.ydisp
= this.ybase
;
1374 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1378 this.updateRange(this.scrollTop
);
1379 this.updateRange(this.scrollBottom
);
1382 * This event is emitted whenever the terminal is scrolled.
1383 * The one parameter passed is the new y display position.
1387 this.emit('scroll', this.ydisp
);
1391 * Scroll the display of the terminal
1392 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1393 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1394 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1395 * viewport originally.
1397 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1399 this.userScrolling
= true;
1400 } else if (disp
+ this.ydisp
>= this.ybase
) {
1401 this.userScrolling
= false;
1406 if (this.ydisp
> this.ybase
) {
1407 this.ydisp
= this.ybase
;
1408 } else if (this.ydisp
< 0) {
1412 if (!suppressScrollEvent
) {
1413 this.emit('scroll', this.ydisp
);
1416 this.queueRefresh(0, this.rows
- 1);
1420 * Scroll the display of the terminal by a number of pages.
1421 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1423 Terminal
.prototype.scrollPages = function(pageCount
) {
1424 this.scrollDisp(pageCount
* (this.rows
- 1));
1428 * Scrolls the display of the terminal to the top.
1430 Terminal
.prototype.scrollToTop = function() {
1431 this.scrollDisp(-this.ydisp
);
1435 * Scrolls the display of the terminal to the bottom.
1437 Terminal
.prototype.scrollToBottom = function() {
1438 this.scrollDisp(this.ybase
- this.ydisp
);
1442 * Writes text to the terminal.
1443 * @param {string} text The text to write to the terminal.
1445 Terminal
.prototype.write = function(data
) {
1446 this.writeBuffer
.push(data
);
1448 // Send XOFF to pause the pty process if the write buffer becomes too large so
1449 // xterm.js can catch up before more data is sent. This is necessary in order
1450 // to keep signals such as ^C responsive.
1451 if (!this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1452 // XOFF - stop pty pipe
1453 // XON will be triggered by emulator before processing data chunk
1455 this.xoffSentToCatchUp
= true;
1458 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1459 // Kick off a write which will write all data in sequence recursively
1460 this.writeInProgress
= true;
1461 // Kick off an async innerWrite so more writes can come in while processing data
1463 setTimeout(function () {
1469 Terminal
.prototype.innerWrite = function() {
1470 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1471 while (writeBatch
.length
> 0) {
1472 var data
= writeBatch
.shift();
1473 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1475 // If XOFF was sent in order to catch up with the pty process, resume it if
1476 // the writeBuffer is empty to allow more data to come in.
1477 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1479 this.xoffSentToCatchUp
= false;
1482 this.refreshStart
= this.y
;
1483 this.refreshEnd
= this.y
;
1485 this.parser
.parse(data
);
1487 this.updateRange(this.y
);
1488 this.queueRefresh(this.refreshStart
, this.refreshEnd
);
1490 if (this.writeBuffer
.length
> 0) {
1491 // Allow renderer to catch up before processing the next batch
1493 setTimeout(function () {
1497 this.writeInProgress
= false;
1502 * Writes text to the terminal, followed by a break line character (\n).
1503 * @param {string} text The text to write to the terminal.
1505 Terminal
.prototype.writeln = function(data
) {
1506 this.write(data
+ '\r\n');
1510 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1511 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1513 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1514 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1515 * the default action. The function returns whether the event should be processed by xterm.js.
1517 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1518 this.customKeydownHandler
= customKeydownHandler
;
1522 * Handle a keydown event
1524 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1525 * @param {KeyboardEvent} ev The keydown event to be handled.
1527 Terminal
.prototype.keyDown = function(ev
) {
1528 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1532 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1533 if (this.ybase
!== this.ydisp
) {
1534 this.scrollToBottom();
1540 var result
= this.evaluateKeyEscapeSequence(ev
);
1542 if (result
.key
=== C0
.DC3
) { // XOFF
1543 this.writeStopped
= true;
1544 } else if (result
.key
=== C0
.DC1
) { // XON
1545 this.writeStopped
= false;
1548 if (result
.scrollDisp
) {
1549 this.scrollDisp(result
.scrollDisp
);
1550 return this.cancel(ev
, true);
1553 if (isThirdLevelShift(this, ev
)) {
1557 if (result
.cancel
) {
1558 // The event is canceled at the end already, is this necessary?
1559 this.cancel(ev
, true);
1566 this.emit('keydown', ev
);
1567 this.emit('key', result
.key
, ev
);
1569 this.handler(result
.key
);
1571 return this.cancel(ev
, true);
1575 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1576 * returned value is the new key code to pass to the PTY.
1578 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1579 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1581 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1583 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1584 // canceled at the end of keyDown
1586 // The new key even to emit
1588 // The number of characters to scroll, if this is defined it will cancel the event
1589 scrollDisp
: undefined
1591 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1592 switch (ev
.keyCode
) {
1596 result
.key
= C0
.BS
; // ^H
1599 result
.key
= C0
.DEL
; // ^?
1604 result
.key
= C0
.ESC
+ '[Z';
1608 result
.cancel
= true;
1613 result
.cancel
= true;
1617 result
.key
= C0
.ESC
;
1618 result
.cancel
= true;
1623 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1624 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1625 // http://unix.stackexchange.com/a/108106
1626 // macOS uses different escape sequences than linux
1627 if (result
.key
== C0
.ESC
+ '[1;3D') {
1628 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1630 } else if (this.applicationCursor
) {
1631 result
.key
= C0
.ESC
+ 'OD';
1633 result
.key
= C0
.ESC
+ '[D';
1639 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1640 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1641 // http://unix.stackexchange.com/a/108106
1642 // macOS uses different escape sequences than linux
1643 if (result
.key
== C0
.ESC
+ '[1;3C') {
1644 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1646 } else if (this.applicationCursor
) {
1647 result
.key
= C0
.ESC
+ 'OC';
1649 result
.key
= C0
.ESC
+ '[C';
1655 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1656 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1657 // http://unix.stackexchange.com/a/108106
1658 if (result
.key
== C0
.ESC
+ '[1;3A') {
1659 result
.key
= C0
.ESC
+ '[1;5A';
1661 } else if (this.applicationCursor
) {
1662 result
.key
= C0
.ESC
+ 'OA';
1664 result
.key
= C0
.ESC
+ '[A';
1670 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1671 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1672 // http://unix.stackexchange.com/a/108106
1673 if (result
.key
== C0
.ESC
+ '[1;3B') {
1674 result
.key
= C0
.ESC
+ '[1;5B';
1676 } else if (this.applicationCursor
) {
1677 result
.key
= C0
.ESC
+ 'OB';
1679 result
.key
= C0
.ESC
+ '[B';
1684 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1685 // <Ctrl> or <Shift> + <Insert> are used to
1686 // copy-paste on some systems.
1687 result
.key
= C0
.ESC
+ '[2~';
1693 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1695 result
.key
= C0
.ESC
+ '[3~';
1701 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1702 else if (this.applicationCursor
)
1703 result
.key
= C0
.ESC
+ 'OH';
1705 result
.key
= C0
.ESC
+ '[H';
1710 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1711 else if (this.applicationCursor
)
1712 result
.key
= C0
.ESC
+ 'OF';
1714 result
.key
= C0
.ESC
+ '[F';
1719 result
.scrollDisp
= -(this.rows
- 1);
1721 result
.key
= C0
.ESC
+ '[5~';
1727 result
.scrollDisp
= this.rows
- 1;
1729 result
.key
= C0
.ESC
+ '[6~';
1735 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1737 result
.key
= C0
.ESC
+ 'OP';
1742 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1744 result
.key
= C0
.ESC
+ 'OQ';
1749 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1751 result
.key
= C0
.ESC
+ 'OR';
1756 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1758 result
.key
= C0
.ESC
+ 'OS';
1763 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1765 result
.key
= C0
.ESC
+ '[15~';
1770 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1772 result
.key
= C0
.ESC
+ '[17~';
1777 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1779 result
.key
= C0
.ESC
+ '[18~';
1784 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1786 result
.key
= C0
.ESC
+ '[19~';
1791 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1793 result
.key
= C0
.ESC
+ '[20~';
1798 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1800 result
.key
= C0
.ESC
+ '[21~';
1805 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1807 result
.key
= C0
.ESC
+ '[23~';
1812 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1814 result
.key
= C0
.ESC
+ '[24~';
1819 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1820 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1821 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1822 } else if (ev
.keyCode
=== 32) {
1824 result
.key
= String
.fromCharCode(0);
1825 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1826 // escape, file sep, group sep, record sep, unit sep
1827 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1828 } else if (ev
.keyCode
=== 56) {
1830 result
.key
= String
.fromCharCode(127);
1831 } else if (ev
.keyCode
=== 219) {
1832 // ^[ - Control Sequence Introducer (CSI)
1833 result
.key
= String
.fromCharCode(27);
1834 } else if (ev
.keyCode
=== 220) {
1835 // ^\ - String Terminator (ST)
1836 result
.key
= String
.fromCharCode(28);
1837 } else if (ev
.keyCode
=== 221) {
1838 // ^] - Operating System Command (OSC)
1839 result
.key
= String
.fromCharCode(29);
1841 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1842 // On Mac this is a third level shift. Use <Esc> instead.
1843 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1844 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1845 } else if (ev
.keyCode
=== 192) {
1846 result
.key
= C0
.ESC
+ '`';
1847 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1848 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1858 * Set the G level of the terminal
1861 Terminal
.prototype.setgLevel = function(g
) {
1863 this.charset
= this.charsets
[g
];
1867 * Set the charset for the given G level of the terminal
1871 Terminal
.prototype.setgCharset = function(g
, charset
) {
1872 this.charsets
[g
] = charset
;
1873 if (this.glevel
=== g
) {
1874 this.charset
= charset
;
1879 * Handle a keypress event.
1881 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1882 * @param {KeyboardEvent} ev The keypress event to be handled.
1884 Terminal
.prototype.keyPress = function(ev
) {
1891 } else if (ev
.which
== null) {
1893 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1900 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1905 key
= String
.fromCharCode(key
);
1907 this.emit('keypress', key
, ev
);
1908 this.emit('key', key
, ev
);
1916 * Send data for handling to the terminal
1917 * @param {string} data
1919 Terminal
.prototype.send = function(data
) {
1923 setTimeout(function() {
1924 self
.handler(self
.queue
);
1934 * Note: We could do sweet things with webaudio here
1936 Terminal
.prototype.bell = function() {
1937 if (!this.visualBell
) return;
1939 this.element
.style
.borderColor
= 'white';
1940 setTimeout(function() {
1941 self
.element
.style
.borderColor
= '';
1943 if (this.popOnBell
) this.focus();
1947 * Log the current state to the console.
1949 Terminal
.prototype.log = function() {
1950 if (!this.debug
) return;
1951 if (!this.context
.console
|| !this.context
.console
.log
) return;
1952 var args
= Array
.prototype.slice
.call(arguments
);
1953 this.context
.console
.log
.apply(this.context
.console
, args
);
1957 * Log the current state as error to the console.
1959 Terminal
.prototype.error = function() {
1960 if (!this.debug
) return;
1961 if (!this.context
.console
|| !this.context
.console
.error
) return;
1962 var args
= Array
.prototype.slice
.call(arguments
);
1963 this.context
.console
.error
.apply(this.context
.console
, args
);
1967 * Resizes the terminal.
1969 * @param {number} x The number of columns to resize to.
1970 * @param {number} y The number of rows to resize to.
1972 Terminal
.prototype.resize = function(x
, y
) {
1980 if (x
=== this.cols
&& y
=== this.rows
) {
1990 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1991 i
= this.lines
.length
;
1993 while (this.lines
.get(i
).length
< x
) {
1994 this.lines
.get(i
).push(ch
);
1998 i
= this.lines
.length
;
2000 while (this.lines
.get(i
).length
> x
) {
2001 this.lines
.get(i
).pop();
2014 // y is rows, not this.y
2015 if (this.lines
.length
< y
+ this.ybase
) {
2016 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
2017 // There is room above the buffer and there are no empty elements below the line,
2021 if (this.ydisp
> 0) {
2022 // Viewport is at the top of the buffer, must increase downwards
2026 // Add a blank line if there is no buffer left at the top to scroll to, or if there
2027 // are blank lines after the cursor
2028 this.lines
.push(this.blankLine());
2031 if (this.children
.length
< y
) {
2037 if (this.lines
.length
> y
+ this.ybase
) {
2038 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
2039 // The line is a blank line below the cursor, remove it
2042 // The line is the cursor, scroll down
2047 if (this.children
.length
> y
) {
2048 el
= this.children
.shift();
2050 el
.parentNode
.removeChild(el
);
2056 // Make sure that the cursor stays on screen
2069 this.scrollBottom
= y
- 1;
2071 this.charMeasure
.measure();
2073 this.queueRefresh(0, this.rows
- 1);
2077 this.geometry
= [this.cols
, this.rows
];
2078 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
2082 * Updates the range of rows to refresh
2083 * @param {number} y The number of rows to refresh next.
2085 Terminal
.prototype.updateRange = function(y
) {
2086 if (y
< this.refreshStart
) this.refreshStart
= y
;
2087 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
2088 // if (y > this.refreshEnd) {
2089 // this.refreshEnd = y;
2090 // if (y > this.rows - 1) {
2091 // this.refreshEnd = this.rows - 1;
2097 * Set the range of refreshing to the maximum value
2099 Terminal
.prototype.maxRange = function() {
2100 this.refreshStart
= 0;
2101 this.refreshEnd
= this.rows
- 1;
2107 * Setup the tab stops.
2110 Terminal
.prototype.setupStops = function(i
) {
2112 if (!this.tabs
[i
]) {
2113 i
= this.prevStop(i
);
2120 for (; i
< this.cols
; i
+= 8) {
2121 this.tabs
[i
] = true;
2127 * Move the cursor to the previous tab stop from the given position (default is current).
2128 * @param {number} x The position to move the cursor to the previous tab stop.
2130 Terminal
.prototype.prevStop = function(x
) {
2131 if (x
== null) x
= this.x
;
2132 while (!this.tabs
[--x
] && x
> 0);
2133 return x
>= this.cols
2140 * Move the cursor one tab stop forward from the given position (default is current).
2141 * @param {number} x The position to move the cursor one tab stop forward.
2143 Terminal
.prototype.nextStop = function(x
) {
2144 if (x
== null) x
= this.x
;
2145 while (!this.tabs
[++x
] && x
< this.cols
);
2146 return x
>= this.cols
2153 * Erase in the identified line everything from "x" to the end of the line (right).
2154 * @param {number} x The column from which to start erasing to the end of the line.
2155 * @param {number} y The line in which to operate.
2157 Terminal
.prototype.eraseRight = function(x
, y
) {
2158 var line
= this.lines
.get(this.ybase
+ y
)
2159 , ch
= [this.eraseAttr(), ' ', 1]; // xterm
2162 for (; x
< this.cols
; x
++) {
2166 this.updateRange(y
);
2172 * Erase in the identified line everything from "x" to the start of the line (left).
2173 * @param {number} x The column from which to start erasing to the start of the line.
2174 * @param {number} y The line in which to operate.
2176 Terminal
.prototype.eraseLeft = function(x
, y
) {
2177 var line
= this.lines
.get(this.ybase
+ y
)
2178 , ch
= [this.eraseAttr(), ' ', 1]; // xterm
2181 while (x
--) line
[x
] = ch
;
2183 this.updateRange(y
);
2187 * Clears the entire buffer, making the prompt line the new first line.
2189 Terminal
.prototype.clear = function() {
2190 if (this.ybase
=== 0 && this.y
=== 0) {
2191 // Don't clear if it's already clear
2194 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2195 this.lines
.length
= 1;
2199 for (var i
= 1; i
< this.rows
; i
++) {
2200 this.lines
.push(this.blankLine());
2202 this.queueRefresh(0, this.rows
- 1);
2203 this.emit('scroll', this.ydisp
);
2207 * Erase all content in the given line
2208 * @param {number} y The line to erase all of its contents.
2210 Terminal
.prototype.eraseLine = function(y
) {
2211 this.eraseRight(0, y
);
2216 * Return the data array of a blank line
2217 * @param {number} cur First bunch of data for each "blank" character.
2219 Terminal
.prototype.blankLine = function(cur
) {
2224 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2228 for (; i
< this.cols
; i
++) {
2237 * If cur return the back color xterm feature attribute. Else return defAttr.
2238 * @param {object} cur
2240 Terminal
.prototype.ch = function(cur
) {
2242 ? [this.eraseAttr(), ' ', 1]
2243 : [this.defAttr
, ' ', 1];
2248 * Evaluate if the current erminal is the given argument.
2249 * @param {object} term The terminal to evaluate
2251 Terminal
.prototype.is = function(term
) {
2252 var name
= this.termName
;
2253 return (name
+ '').indexOf(term
) === 0;
2258 * Emit the 'data' event and populate the given data.
2259 * @param {string} data The data to populate in the event.
2261 Terminal
.prototype.handler = function(data
) {
2262 // Prevents all events to pty process if stdin is disabled
2263 if (this.options
.disableStdin
) {
2267 // Input is being sent to the terminal, the terminal should focus the prompt.
2268 if (this.ybase
!== this.ydisp
) {
2269 this.scrollToBottom();
2271 this.emit('data', data
);
2276 * Emit the 'title' event and populate the given title.
2277 * @param {string} title The title to populate in the event.
2279 Terminal
.prototype.handleTitle = function(title
) {
2281 * This event is emitted when the title of the terminal is changed
2282 * from inside the terminal. The parameter is the new title.
2286 this.emit('title', title
);
2295 * ESC D Index (IND is 0x84).
2297 Terminal
.prototype.index = function() {
2299 if (this.y
> this.scrollBottom
) {
2307 * ESC M Reverse Index (RI is 0x8d).
2309 * Move the cursor up one row, inserting a new blank line if necessary.
2311 Terminal
.prototype.reverseIndex = function() {
2313 if (this.y
=== this.scrollTop
) {
2314 // possibly move the code below to term.reverseScroll();
2315 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2316 // blankLine(true) is xterm/linux behavior
2317 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2318 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2319 this.updateRange(this.scrollTop
);
2320 this.updateRange(this.scrollBottom
);
2328 * ESC c Full Reset (RIS).
2330 Terminal
.prototype.reset = function() {
2331 this.options
.rows
= this.rows
;
2332 this.options
.cols
= this.cols
;
2333 var customKeydownHandler
= this.customKeydownHandler
;
2334 Terminal
.call(this, this.options
);
2335 this.customKeydownHandler
= customKeydownHandler
;
2336 this.queueRefresh(0, this.rows
- 1);
2337 this.viewport
.syncScrollArea();
2342 * ESC H Tab Set (HTS is 0x88).
2344 Terminal
.prototype.tabSet = function() {
2345 this.tabs
[this.x
] = true;
2352 function on(el
, type
, handler
, capture
) {
2353 if (!Array
.isArray(el
)) {
2356 el
.forEach(function (element
) {
2357 element
.addEventListener(type
, handler
, capture
|| false);
2361 function off(el
, type
, handler
, capture
) {
2362 el
.removeEventListener(type
, handler
, capture
|| false);
2365 function cancel(ev
, force
) {
2366 if (!this.cancelEvents
&& !force
) {
2369 ev
.preventDefault();
2370 ev
.stopPropagation();
2374 function inherits(child
, parent
) {
2376 this.constructor = child
;
2378 f
.prototype = parent
.prototype;
2379 child
.prototype = new f
;
2382 // if bold is broken, we can't
2383 // use it in the terminal.
2384 function isBoldBroken(document
) {
2385 var body
= document
.getElementsByTagName('body')[0];
2386 var el
= document
.createElement('span');
2387 el
.innerHTML
= 'hello world';
2388 body
.appendChild(el
);
2389 var w1
= el
.scrollWidth
;
2390 el
.style
.fontWeight
= 'bold';
2391 var w2
= el
.scrollWidth
;
2392 body
.removeChild(el
);
2396 function indexOf(obj
, el
) {
2399 if (obj
[i
] === el
) return i
;
2404 function isThirdLevelShift(term
, ev
) {
2406 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2407 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2409 if (ev
.type
== 'keypress') {
2410 return thirdLevelKey
;
2413 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2414 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2417 // Expose to InputHandler (temporary)
2418 Terminal
.prototype.matchColor
= matchColor
;
2420 function matchColor(r1
, g1
, b1
) {
2421 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2423 if (matchColor
._cache
[hash
] != null) {
2424 return matchColor
._cache
[hash
];
2427 var ldiff
= Infinity
2436 for (; i
< Terminal
.vcolors
.length
; i
++) {
2437 c
= Terminal
.vcolors
[i
];
2442 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2455 return matchColor
._cache
[hash
] = li
;
2458 matchColor
._cache
= {};
2460 // http://stackoverflow.com/questions/1633828
2461 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2462 return Math
.pow(30 * (r1
- r2
), 2)
2463 + Math
.pow(59 * (g1
- g2
), 2)
2464 + Math
.pow(11 * (b1
- b2
), 2);
2467 function each(obj
, iter
, con
) {
2468 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2469 for (var i
= 0; i
< obj
.length
; i
++) {
2470 iter
.call(con
, obj
[i
], i
, obj
);
2474 function wasMondifierKeyOnlyEvent(ev
) {
2475 return ev
.keyCode
=== 16 || // Shift
2476 ev
.keyCode
=== 17 || // Ctrl
2477 ev
.keyCode
=== 18; // Alt
2480 function keys(obj
) {
2481 if (Object
.keys
) return Object
.keys(obj
);
2484 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2495 Terminal
.EventEmitter
= EventEmitter
;
2496 Terminal
.inherits
= inherits
;
2499 * Adds an event listener to the terminal.
2501 * @param {string} event The name of the event. TODO: Document all event types
2502 * @param {function} callback The function to call when the event is triggered.
2506 Terminal
.cancel
= cancel
;
2508 module
.exports
= Terminal
;