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 { Renderer
} from './Renderer';
22 import { Linkifier
} from './Linkifier';
23 import { CharMeasure
} from './utils/CharMeasure';
24 import * as Browser
from './utils/Browser';
25 import * as Keyboard
from './utils/Keyboard';
26 import { CHARSETS
} from './Charsets';
29 * Terminal Emulation References:
31 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
32 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
33 * http://invisible-island.net/vttest/
34 * http://www.inwap.com/pdp10/ansicode.txt
35 * http://linux.die.net/man/4/console_codes
36 * http://linux.die.net/man/7/urxvt
39 // Let it work inside Node.js for automated testing purposes.
40 var document
= (typeof window
!= 'undefined') ? window
.document
: null;
43 * The amount of write requests to queue before sending an XOFF signal to the
44 * pty process. This number must be small in order for ^C and similar sequences
47 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
50 * The number of writes to perform in a single batch before allowing the
51 * renderer to catch up with a 0ms setTimeout.
53 var WRITE_BATCH_SIZE
= 300;
60 * Creates a new `Terminal` object.
62 * @param {object} options An object containing a set of options, the available options are:
63 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
64 * - `cols` (number): The number of columns of the terminal (horizontal size)
65 * - `rows` (number): The number of rows of the terminal (vertical size)
69 * @alias module:xterm/src/xterm
71 function Terminal(options
) {
74 if (!(this instanceof Terminal
)) {
75 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
78 self
.browser
= Browser
;
79 self
.cancel
= Terminal
.cancel
;
81 EventEmitter
.call(this);
83 if (typeof options
=== 'number') {
91 options
= options
|| {};
94 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
95 if (options
[key
] == null) {
96 options
[key
] = Terminal
.options
[key
];
98 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
99 options
[key
] = Terminal
[key
];
102 self
[key
] = options
[key
];
105 if (options
.colors
.length
=== 8) {
106 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
107 } else if (options
.colors
.length
=== 16) {
108 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
109 } else if (options
.colors
.length
=== 10) {
110 options
.colors
= options
.colors
.slice(0, -2).concat(
111 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
112 } else if (options
.colors
.length
=== 18) {
113 options
.colors
= options
.colors
.concat(
114 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
116 this.colors
= options
.colors
;
118 this.options
= options
;
120 // this.context = options.context || window;
121 // this.document = options.document || document;
122 this.parent
= options
.body
|| options
.parent
|| (
123 document
? document
.getElementsByTagName('body')[0] : null
126 this.cols
= options
.cols
|| options
.geometry
[0];
127 this.rows
= options
.rows
|| options
.geometry
[1];
128 this.geometry
= [this.cols
, this.rows
];
130 if (options
.handler
) {
131 this.on('data', options
.handler
);
135 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
141 * The scroll position of the viewport
146 * The cursor's x position after ybase
151 * The cursor's y position after ybase
155 this.cursorState
= 0;
156 this.cursorHidden
= false;
160 this.scrollBottom
= this.rows
- 1;
161 this.customKeydownHandler
= null;
164 this.applicationKeypad
= false;
165 this.applicationCursor
= false;
166 this.originMode
= false;
167 this.insertMode
= false;
168 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
173 this.gcharset
= null;
175 this.charsets
= [null];
199 this.readable
= true;
200 this.writable
= true;
202 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
203 this.curAttr
= this.defAttr
;
206 this.currentParam
= 0;
210 this.inputHandler
= new InputHandler(this);
211 this.parser
= new Parser(this.inputHandler
, this);
212 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
213 this.renderer
= this.renderer
|| null;
214 this.linkifier
= this.linkifier
|| null;;
217 this.writeBuffer
= [];
218 this.writeInProgress
= false;
221 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
222 * This is a distinct state from writeStopped so that if the user requested
223 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
226 this.xoffSentToCatchUp
= false;
228 /** Whether writing has been stopped as a result of XOFF */
229 this.writeStopped
= false;
231 // leftover surrogate high from previous write invocation
232 this.surrogate_high
= '';
235 * An array of all lines in the entire buffer, including the prompt. The lines are array of
236 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
238 this.lines
= new CircularList(this.scrollback
);
241 this.lines
.push(this.blankLine());
247 // Store if user went browsing history in scrollback
248 this.userScrolling
= false;
251 inherits(Terminal
, EventEmitter
);
254 * back_color_erase feature for xterm.
256 Terminal
.prototype.eraseAttr = function() {
257 // if (this.is('screen')) return this.defAttr;
258 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
266 Terminal
.tangoColors
= [
287 // Colors 0-15 + 16-255
288 // Much thanks to TooTallNate for writing this.
289 Terminal
.colors
= (function() {
290 var colors
= Terminal
.tangoColors
.slice()
291 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
296 for (; i
< 216; i
++) {
297 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
302 for (; i
< 24; i
++) {
307 function out(r
, g
, b
) {
308 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
313 return c
.length
< 2 ? '0' + c
: c
;
319 Terminal
._colors
= Terminal
.colors
.slice();
321 Terminal
.vcolors
= (function() {
323 , colors
= Terminal
.colors
327 for (; i
< 256; i
++) {
328 color
= parseInt(colors
[i
].substring(1), 16);
330 (color
>> 16) & 0xff,
343 Terminal
.defaults
= {
344 colors
: Terminal
.colors
,
350 cursorStyle
: 'block',
358 useFlowControl
: false,
360 // programFeatures: false,
364 Terminal
.options
= {};
366 Terminal
.focus
= null;
368 each(keys(Terminal
.defaults
), function(key
) {
369 Terminal
[key
] = Terminal
.defaults
[key
];
370 Terminal
.options
[key
] = Terminal
.defaults
[key
];
374 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
376 Terminal
.prototype.focus = function() {
377 return this.textarea
.focus();
381 * Retrieves an option's value from the terminal.
382 * @param {string} key The option key.
384 Terminal
.prototype.getOption = function(key
, value
) {
385 if (!(key
in Terminal
.defaults
)) {
386 throw new Error('No option with key "' + key
+ '"');
389 if (typeof this.options
[key
] !== 'undefined') {
390 return this.options
[key
];
397 * Sets an option on the terminal.
398 * @param {string} key The option key.
399 * @param {string} value The option value.
401 Terminal
.prototype.setOption = function(key
, value
) {
402 if (!(key
in Terminal
.defaults
)) {
403 throw new Error('No option with key "' + key
+ '"');
407 if (this.options
[key
] !== value
) {
408 if (this.lines
.length
> value
) {
409 const amountToTrim
= this.lines
.length
- value
;
410 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
411 this.lines
.trimStart(amountToTrim
);
412 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
413 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
415 this.refresh(0, this.rows
- 1);
418 this.lines
.maxLength
= value
;
419 this.viewport
.syncScrollArea();
424 this.options
[key
] = value
;
426 case 'cursorBlink': this.element
.classList
.toggle('xterm-cursor-blink', value
); break;
428 // Style 'block' applies with no class
429 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
430 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
432 case 'tabStopWidth': this.setupStops(); break;
437 * Binds the desired focus behavior on a given terminal object.
441 Terminal
.bindFocus = function (term
) {
442 on(term
.textarea
, 'focus', function (ev
) {
443 if (term
.sendFocus
) {
444 term
.send(C0
.ESC
+ '[I');
446 term
.element
.classList
.add('focus');
448 Terminal
.focus
= term
;
449 term
.emit('focus', {terminal
: term
});
454 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
456 Terminal
.prototype.blur = function() {
457 return this.textarea
.blur();
461 * Binds the desired blur behavior on a given terminal object.
465 Terminal
.bindBlur = function (term
) {
466 on(term
.textarea
, 'blur', function (ev
) {
467 term
.refresh(term
.y
, term
.y
);
468 if (term
.sendFocus
) {
469 term
.send(C0
.ESC
+ '[O');
471 term
.element
.classList
.remove('focus');
472 Terminal
.focus
= null;
473 term
.emit('blur', {terminal
: term
});
478 * Initialize default behavior
480 Terminal
.prototype.initGlobal = function() {
483 Terminal
.bindKeys(this);
484 Terminal
.bindFocus(this);
485 Terminal
.bindBlur(this);
487 // Bind clipboard functionality
488 on(this.element
, 'copy', function (ev
) {
489 copyHandler
.call(this, ev
, term
);
491 on(this.textarea
, 'paste', function (ev
) {
492 pasteHandler
.call(this, ev
, term
);
494 on(this.element
, 'paste', function (ev
) {
495 pasteHandler
.call(this, ev
, term
);
498 function rightClickHandlerWrapper (ev
) {
499 rightClickHandler
.call(this, ev
, term
);
502 if (term
.browser
.isFirefox
) {
503 on(this.element
, 'mousedown', function (ev
) {
504 if (ev
.button
== 2) {
505 rightClickHandlerWrapper(ev
);
509 on(this.element
, 'contextmenu', rightClickHandlerWrapper
);
514 * Apply key handling to the terminal
516 Terminal
.bindKeys = function(term
) {
517 on(term
.element
, 'keydown', function(ev
) {
518 if (document
.activeElement
!= this) {
524 on(term
.element
, 'keypress', function(ev
) {
525 if (document
.activeElement
!= this) {
531 on(term
.element
, 'keyup', function(ev
) {
532 if (!wasMondifierKeyOnlyEvent(ev
)) {
537 on(term
.textarea
, 'keydown', function(ev
) {
541 on(term
.textarea
, 'keypress', function(ev
) {
543 // Truncate the textarea's value, since it is not needed
547 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
548 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
549 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
550 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
551 term
.on('refresh', function (data
) {
552 term
.queueLinkification(data
.start
, data
.end
)
558 * Insert the given row to the terminal or produce a new one
559 * if no row argument is passed. Return the inserted row.
560 * @param {HTMLElement} row (optional) The row to append to the terminal.
562 Terminal
.prototype.insertRow = function (row
) {
563 if (typeof row
!= 'object') {
564 row
= document
.createElement('div');
567 this.rowContainer
.appendChild(row
);
568 this.children
.push(row
);
574 * Opens the terminal within an element.
576 * @param {HTMLElement} parent The element to create the terminal within.
578 Terminal
.prototype.open = function(parent
) {
579 var self
=this, i
=0, div
;
581 this.parent
= parent
|| this.parent
;
584 throw new Error('Terminal requires a parent element.');
587 // Grab global elements
588 this.context
= this.parent
.ownerDocument
.defaultView
;
589 this.document
= this.parent
.ownerDocument
;
590 this.body
= this.document
.getElementsByTagName('body')[0];
592 //Create main element container
593 this.element
= this.document
.createElement('div');
594 this.element
.classList
.add('terminal');
595 this.element
.classList
.add('xterm');
596 this.element
.classList
.add('xterm-theme-' + this.theme
);
597 this.element
.classList
.toggle('xterm-cursor-blink', this.options
.cursorBlink
);
599 this.element
.style
.height
600 this.element
.setAttribute('tabindex', 0);
602 this.viewportElement
= document
.createElement('div');
603 this.viewportElement
.classList
.add('xterm-viewport');
604 this.element
.appendChild(this.viewportElement
);
605 this.viewportScrollArea
= document
.createElement('div');
606 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
607 this.viewportElement
.appendChild(this.viewportScrollArea
);
609 // Create the container that will hold the lines of the terminal and then
610 // produce the lines the lines.
611 this.rowContainer
= document
.createElement('div');
612 this.rowContainer
.classList
.add('xterm-rows');
613 this.element
.appendChild(this.rowContainer
);
615 this.linkifier
= new Linkifier(document
, this.children
);
617 // Create the container that will hold helpers like the textarea for
618 // capturing DOM Events. Then produce the helpers.
619 this.helperContainer
= document
.createElement('div');
620 this.helperContainer
.classList
.add('xterm-helpers');
621 // TODO: This should probably be inserted once it's filled to prevent an additional layout
622 this.element
.appendChild(this.helperContainer
);
623 this.textarea
= document
.createElement('textarea');
624 this.textarea
.classList
.add('xterm-helper-textarea');
625 this.textarea
.setAttribute('autocorrect', 'off');
626 this.textarea
.setAttribute('autocapitalize', 'off');
627 this.textarea
.setAttribute('spellcheck', 'false');
628 this.textarea
.tabIndex
= 0;
629 this.textarea
.addEventListener('focus', function() {
630 self
.emit('focus', {terminal
: self
});
632 this.textarea
.addEventListener('blur', function() {
633 self
.emit('blur', {terminal
: self
});
635 this.helperContainer
.appendChild(this.textarea
);
637 this.compositionView
= document
.createElement('div');
638 this.compositionView
.classList
.add('composition-view');
639 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
640 this.helperContainer
.appendChild(this.compositionView
);
642 this.charSizeStyleElement
= document
.createElement('style');
643 this.helperContainer
.appendChild(this.charSizeStyleElement
);
645 for (; i
< this.rows
; i
++) {
648 this.parent
.appendChild(this.element
);
650 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
651 this.charMeasure
.on('charsizechanged', function () {
652 self
.updateCharSizeCSS();
654 this.charMeasure
.measure();
656 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
657 this.renderer
= new Renderer(this);
659 // Setup loop that draws to screen
660 this.refresh(0, this.rows
- 1);
662 // Initialize global actions that
663 // need to be taken on the document.
666 // Ensure there is a Terminal.focus.
669 on(this.element
, 'click', function() {
670 var selection
= document
.getSelection(),
671 collapsed
= selection
.isCollapsed
,
672 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
678 // Listen for mouse events and translate
679 // them into terminal mouse protocols.
683 * This event is emitted when terminal has completed opening.
692 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
693 * @param {string} addon The name of the addon to load
696 Terminal
.loadAddon = function(addon
, callback
) {
697 if (typeof exports
=== 'object' && typeof module
=== 'object') {
699 return require('./addons/' + addon
+ '/' + addon
);
700 } else if (typeof define
== 'function') {
702 return require(['./addons/' + addon
+ '/' + addon
], callback
);
704 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
710 * Updates the helper CSS class with any changes necessary after the terminal's
711 * character width has been changed.
713 Terminal
.prototype.updateCharSizeCSS = function() {
714 this.charSizeStyleElement
.textContent
= '.xterm-wide-char{width:' + (this.charMeasure
.width
* 2) + 'px;}';
719 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
720 * To better understand these
721 * the xterm code is very helpful:
723 * button.c, charproc.c, misc.c
724 * Relevant functions in xterm/button.c:
725 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
727 Terminal
.prototype.bindMouse = function() {
728 var el
= this.element
, self
= this, pressed
= 32;
730 // mouseup, mousedown, wheel
731 // left click: ^[[M 3<^[[M#3<
733 function sendButton(ev
) {
737 // get the xterm-style button
738 button
= getButton(ev
);
740 // get mouse coordinates
744 sendEvent(button
, pos
);
746 switch (ev
.overrideType
|| ev
.type
) {
751 // keep it at the left
752 // button, just in case.
763 // motion example of a left click:
764 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
765 function sendMove(ev
) {
772 // buttons marked as motions
773 // are incremented by 32
776 sendEvent(button
, pos
);
780 // position to characters
781 function encode(data
, ch
) {
782 if (!self
.utfMouse
) {
783 if (ch
=== 255) return data
.push(0);
784 if (ch
> 127) ch
= 127;
787 if (ch
=== 2047) return data
.push(0);
791 if (ch
> 2047) ch
= 2047;
792 data
.push(0xC0 | (ch
>> 6));
793 data
.push(0x80 | (ch
& 0x3F));
798 // send a mouse event:
799 // regular/utf8: ^[[M Cb Cx Cy
800 // urxvt: ^[[ Cb ; Cx ; Cy M
801 // sgr: ^[[ Cb ; Cx ; Cy M/m
802 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
803 // locator: CSI P e ; P b ; P r ; P c ; P p & w
804 function sendEvent(button
, pos
) {
805 // self.emit('mouse', {
811 if (self
.vt300Mouse
) {
813 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
817 var data
= C0
.ESC
+ '[24';
818 if (button
=== 0) data
+= '1';
819 else if (button
=== 1) data
+= '3';
820 else if (button
=== 2) data
+= '5';
821 else if (button
=== 3) return;
823 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
828 if (self
.decLocator
) {
833 if (button
=== 0) button
= 2;
834 else if (button
=== 1) button
= 4;
835 else if (button
=== 2) button
= 6;
836 else if (button
=== 3) button
= 3;
837 self
.send(C0
.ESC
+ '['
840 + (button
=== 3 ? 4 : 0)
851 if (self
.urxvtMouse
) {
856 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
863 self
.send(C0
.ESC
+ '[<'
864 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
869 + ((button
& 3) === 3 ? 'm' : 'M'));
875 encode(data
, button
);
879 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
882 function getButton(ev
) {
895 // 1, and 2 - with 64 added
896 switch (ev
.overrideType
|| ev
.type
) {
898 button
= ev
.button
!= null
904 if (self
.browser
.isMSIE
) {
905 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
911 case 'DOMMouseScroll':
912 button
= ev
.detail
< 0
917 button
= ev
.wheelDeltaY
> 0
923 // next three bits are the modifiers:
924 // 4 = shift, 8 = meta, 16 = control
925 shift
= ev
.shiftKey
? 4 : 0;
926 meta
= ev
.metaKey
? 8 : 0;
927 ctrl
= ev
.ctrlKey
? 16 : 0;
928 mod
= shift
| meta
| ctrl
;
931 if (self
.vt200Mouse
) {
934 } else if (!self
.normalMouse
) {
939 button
= (32 + (mod
<< 2)) + button
;
944 // mouse coordinates measured in cols/rows
945 function getCoords(ev
) {
948 // ignore browsers without pageX for now
949 if (ev
.pageX
== null) return;
955 // should probably check offsetParent
956 // but this is more portable
957 while (el
&& el
!== self
.document
.documentElement
) {
960 el
= 'offsetParent' in el
965 // convert to cols/rows
966 x
= Math
.ceil(x
/ self
.charMeasure
.width
);
967 y
= Math
.ceil(y
/ self
.charMeasure
.height
);
969 // be sure to avoid sending
970 // bad positions to the program
972 if (x
> self
.cols
) x
= self
.cols
;
974 if (y
> self
.rows
) y
= self
.rows
;
976 // xterm sends raw bytes and
977 // starts at 32 (SP) for each.
988 on(el
, 'mousedown', function(ev
) {
989 if (!self
.mouseEvents
) return;
998 //if (self.vt200Mouse && !self.normalMouse) {
999 if (self
.vt200Mouse
) {
1000 ev
.overrideType
= 'mouseup';
1002 return self
.cancel(ev
);
1006 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1008 // x10 compatibility mode can't send button releases
1009 if (!self
.x10Mouse
) {
1010 on(self
.document
, 'mouseup', function up(ev
) {
1012 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1013 off(self
.document
, 'mouseup', up
);
1014 return self
.cancel(ev
);
1018 return self
.cancel(ev
);
1021 //if (self.normalMouse) {
1022 // on(self.document, 'mousemove', sendMove);
1025 on(el
, 'wheel', function(ev
) {
1026 if (!self
.mouseEvents
) return;
1029 || self
.decLocator
) return;
1031 return self
.cancel(ev
);
1034 // allow wheel scrolling in
1035 // the shell for example
1036 on(el
, 'wheel', function(ev
) {
1037 if (self
.mouseEvents
) return;
1038 self
.viewport
.onWheel(ev
);
1039 return self
.cancel(ev
);
1044 * Destroys the terminal.
1046 Terminal
.prototype.destroy = function() {
1047 this.readable
= false;
1048 this.writable
= false;
1050 this.handler = function() {};
1051 this.write = function() {};
1052 if (this.element
&& this.element
.parentNode
) {
1053 this.element
.parentNode
.removeChild(this.element
);
1055 //this.emit('close');
1059 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1061 * @param {number} start The row to start from (between 0 and this.rows - 1).
1062 * @param {number} end The row to end at (between start and this.rows - 1).
1064 Terminal
.prototype.refresh = function(start
, end
) {
1065 if (this.renderer
) {
1066 this.renderer
.queueRefresh(start
, end
);
1071 * Queues linkification for the specified rows.
1072 * @param {number} start The row to start from (between 0 and this.rows - 1).
1073 * @param {number} end The row to end at (between start and this.rows - 1).
1075 Terminal
.prototype.queueLinkification = function(start
, end
) {
1076 if (this.linkifier
) {
1077 for (let i
= start
; i
<= end
; i
++) {
1078 this.linkifier
.linkifyRow(i
);
1084 * Display the cursor element
1086 Terminal
.prototype.showCursor = function() {
1087 if (!this.cursorState
) {
1088 this.cursorState
= 1;
1089 this.refresh(this.y
, this.y
);
1094 * Scroll the terminal down 1 row, creating a blank line.
1096 Terminal
.prototype.scroll = function() {
1099 // Make room for the new row in lines
1100 if (this.lines
.length
=== this.lines
.maxLength
) {
1101 this.lines
.trimStart(1);
1103 if (this.ydisp
!== 0) {
1110 // TODO: Why is this done twice?
1111 if (!this.userScrolling
) {
1112 this.ydisp
= this.ybase
;
1116 row
= this.ybase
+ this.rows
- 1;
1118 // subtract the bottom scroll region
1119 row
-= this.rows
- 1 - this.scrollBottom
;
1121 if (row
=== this.lines
.length
) {
1122 // Optimization: pushing is faster than splicing when they amount to the same behavior
1123 this.lines
.push(this.blankLine());
1126 this.lines
.splice(row
, 0, this.blankLine());
1129 if (this.scrollTop
!== 0) {
1130 if (this.ybase
!== 0) {
1132 if (!this.userScrolling
) {
1133 this.ydisp
= this.ybase
;
1136 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1140 this.updateRange(this.scrollTop
);
1141 this.updateRange(this.scrollBottom
);
1144 * This event is emitted whenever the terminal is scrolled.
1145 * The one parameter passed is the new y display position.
1149 this.emit('scroll', this.ydisp
);
1153 * Scroll the display of the terminal
1154 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1155 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1156 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1157 * viewport originally.
1159 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1161 this.userScrolling
= true;
1162 } else if (disp
+ this.ydisp
>= this.ybase
) {
1163 this.userScrolling
= false;
1168 if (this.ydisp
> this.ybase
) {
1169 this.ydisp
= this.ybase
;
1170 } else if (this.ydisp
< 0) {
1174 if (!suppressScrollEvent
) {
1175 this.emit('scroll', this.ydisp
);
1178 this.refresh(0, this.rows
- 1);
1182 * Scroll the display of the terminal by a number of pages.
1183 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1185 Terminal
.prototype.scrollPages = function(pageCount
) {
1186 this.scrollDisp(pageCount
* (this.rows
- 1));
1190 * Scrolls the display of the terminal to the top.
1192 Terminal
.prototype.scrollToTop = function() {
1193 this.scrollDisp(-this.ydisp
);
1197 * Scrolls the display of the terminal to the bottom.
1199 Terminal
.prototype.scrollToBottom = function() {
1200 this.scrollDisp(this.ybase
- this.ydisp
);
1204 * Writes text to the terminal.
1205 * @param {string} text The text to write to the terminal.
1207 Terminal
.prototype.write = function(data
) {
1208 this.writeBuffer
.push(data
);
1210 // Send XOFF to pause the pty process if the write buffer becomes too large so
1211 // xterm.js can catch up before more data is sent. This is necessary in order
1212 // to keep signals such as ^C responsive.
1213 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1214 // XOFF - stop pty pipe
1215 // XON will be triggered by emulator before processing data chunk
1217 this.xoffSentToCatchUp
= true;
1220 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1221 // Kick off a write which will write all data in sequence recursively
1222 this.writeInProgress
= true;
1223 // Kick off an async innerWrite so more writes can come in while processing data
1225 setTimeout(function () {
1231 Terminal
.prototype.innerWrite = function() {
1232 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1233 while (writeBatch
.length
> 0) {
1234 var data
= writeBatch
.shift();
1235 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1237 // If XOFF was sent in order to catch up with the pty process, resume it if
1238 // the writeBuffer is empty to allow more data to come in.
1239 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1241 this.xoffSentToCatchUp
= false;
1244 this.refreshStart
= this.y
;
1245 this.refreshEnd
= this.y
;
1247 this.parser
.parse(data
);
1249 this.updateRange(this.y
);
1250 this.refresh(this.refreshStart
, this.refreshEnd
);
1252 if (this.writeBuffer
.length
> 0) {
1253 // Allow renderer to catch up before processing the next batch
1255 setTimeout(function () {
1259 this.writeInProgress
= false;
1264 * Writes text to the terminal, followed by a break line character (\n).
1265 * @param {string} text The text to write to the terminal.
1267 Terminal
.prototype.writeln = function(data
) {
1268 this.write(data
+ '\r\n');
1272 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1273 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1275 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1276 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1277 * the default action. The function returns whether the event should be processed by xterm.js.
1279 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1280 this.customKeydownHandler
= customKeydownHandler
;
1284 * Attaches a http(s) link handler, forcing web links to behave differently to
1285 * regular <a> tags. This will trigger a refresh as links potentially need to be
1286 * reconstructed. Calling this with null will remove the handler.
1287 * @param {LinkHandler} handler The handler callback function.
1289 Terminal
.prototype.attachHypertextLinkHandler = function(handler
) {
1290 if (!this.linkifier
) {
1291 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1293 this.linkifier
.attachHypertextLinkHandler(handler
);
1294 // Refresh to force links to refresh
1295 this.refresh(0, this.rows
- 1);
1300 * Registers a link matcher, allowing custom link patterns to be matched and
1302 * @param {RegExp} regex The regular expression to search for, specifically
1303 * this searches the textContent of the rows. You will want to use \s to match
1304 * a space ' ' character for example.
1305 * @param {LinkHandler} handler The callback when the link is called.
1306 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1307 * @return {number} The ID of the new matcher, this can be used to deregister.
1309 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1310 if (this.linkifier
) {
1311 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1312 this.refresh(0, this.rows
- 1);
1318 * Deregisters a link matcher if it has been registered.
1319 * @param {number} matcherId The link matcher's ID (returned after register)
1321 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1322 if (this.linkifier
) {
1323 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1324 this.refresh(0, this.rows
- 1);
1330 * Handle a keydown event
1332 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1333 * @param {KeyboardEvent} ev The keydown event to be handled.
1335 Terminal
.prototype.keyDown = function(ev
) {
1336 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1340 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1341 if (this.ybase
!== this.ydisp
) {
1342 this.scrollToBottom();
1348 var result
= this.evaluateKeyEscapeSequence(ev
);
1350 if (result
.key
=== C0
.DC3
) { // XOFF
1351 this.writeStopped
= true;
1352 } else if (result
.key
=== C0
.DC1
) { // XON
1353 this.writeStopped
= false;
1356 if (result
.scrollDisp
) {
1357 this.scrollDisp(result
.scrollDisp
);
1358 return this.cancel(ev
, true);
1361 if (isThirdLevelShift(this, ev
)) {
1365 if (result
.cancel
) {
1366 // The event is canceled at the end already, is this necessary?
1367 this.cancel(ev
, true);
1374 this.emit('keydown', ev
);
1375 this.emit('key', result
.key
, ev
);
1377 this.handler(result
.key
);
1379 return this.cancel(ev
, true);
1383 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1384 * returned value is the new key code to pass to the PTY.
1386 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1387 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1389 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1391 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1392 // canceled at the end of keyDown
1394 // The new key even to emit
1396 // The number of characters to scroll, if this is defined it will cancel the event
1397 scrollDisp
: undefined
1399 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1400 switch (ev
.keyCode
) {
1404 result
.key
= C0
.BS
; // ^H
1407 result
.key
= C0
.DEL
; // ^?
1412 result
.key
= C0
.ESC
+ '[Z';
1416 result
.cancel
= true;
1421 result
.cancel
= true;
1425 result
.key
= C0
.ESC
;
1426 result
.cancel
= true;
1431 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1432 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1433 // http://unix.stackexchange.com/a/108106
1434 // macOS uses different escape sequences than linux
1435 if (result
.key
== C0
.ESC
+ '[1;3D') {
1436 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1438 } else if (this.applicationCursor
) {
1439 result
.key
= C0
.ESC
+ 'OD';
1441 result
.key
= C0
.ESC
+ '[D';
1447 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1448 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1449 // http://unix.stackexchange.com/a/108106
1450 // macOS uses different escape sequences than linux
1451 if (result
.key
== C0
.ESC
+ '[1;3C') {
1452 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1454 } else if (this.applicationCursor
) {
1455 result
.key
= C0
.ESC
+ 'OC';
1457 result
.key
= C0
.ESC
+ '[C';
1463 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1464 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1465 // http://unix.stackexchange.com/a/108106
1466 if (result
.key
== C0
.ESC
+ '[1;3A') {
1467 result
.key
= C0
.ESC
+ '[1;5A';
1469 } else if (this.applicationCursor
) {
1470 result
.key
= C0
.ESC
+ 'OA';
1472 result
.key
= C0
.ESC
+ '[A';
1478 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1479 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1480 // http://unix.stackexchange.com/a/108106
1481 if (result
.key
== C0
.ESC
+ '[1;3B') {
1482 result
.key
= C0
.ESC
+ '[1;5B';
1484 } else if (this.applicationCursor
) {
1485 result
.key
= C0
.ESC
+ 'OB';
1487 result
.key
= C0
.ESC
+ '[B';
1492 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1493 // <Ctrl> or <Shift> + <Insert> are used to
1494 // copy-paste on some systems.
1495 result
.key
= C0
.ESC
+ '[2~';
1501 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1503 result
.key
= C0
.ESC
+ '[3~';
1509 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1510 else if (this.applicationCursor
)
1511 result
.key
= C0
.ESC
+ 'OH';
1513 result
.key
= C0
.ESC
+ '[H';
1518 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1519 else if (this.applicationCursor
)
1520 result
.key
= C0
.ESC
+ 'OF';
1522 result
.key
= C0
.ESC
+ '[F';
1527 result
.scrollDisp
= -(this.rows
- 1);
1529 result
.key
= C0
.ESC
+ '[5~';
1535 result
.scrollDisp
= this.rows
- 1;
1537 result
.key
= C0
.ESC
+ '[6~';
1543 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1545 result
.key
= C0
.ESC
+ 'OP';
1550 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1552 result
.key
= C0
.ESC
+ 'OQ';
1557 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1559 result
.key
= C0
.ESC
+ 'OR';
1564 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1566 result
.key
= C0
.ESC
+ 'OS';
1571 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1573 result
.key
= C0
.ESC
+ '[15~';
1578 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1580 result
.key
= C0
.ESC
+ '[17~';
1585 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1587 result
.key
= C0
.ESC
+ '[18~';
1592 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1594 result
.key
= C0
.ESC
+ '[19~';
1599 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1601 result
.key
= C0
.ESC
+ '[20~';
1606 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1608 result
.key
= C0
.ESC
+ '[21~';
1613 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1615 result
.key
= C0
.ESC
+ '[23~';
1620 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1622 result
.key
= C0
.ESC
+ '[24~';
1627 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1628 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1629 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1630 } else if (ev
.keyCode
=== 32) {
1632 result
.key
= String
.fromCharCode(0);
1633 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1634 // escape, file sep, group sep, record sep, unit sep
1635 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1636 } else if (ev
.keyCode
=== 56) {
1638 result
.key
= String
.fromCharCode(127);
1639 } else if (ev
.keyCode
=== 219) {
1640 // ^[ - Control Sequence Introducer (CSI)
1641 result
.key
= String
.fromCharCode(27);
1642 } else if (ev
.keyCode
=== 220) {
1643 // ^\ - String Terminator (ST)
1644 result
.key
= String
.fromCharCode(28);
1645 } else if (ev
.keyCode
=== 221) {
1646 // ^] - Operating System Command (OSC)
1647 result
.key
= String
.fromCharCode(29);
1649 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1650 // On Mac this is a third level shift. Use <Esc> instead.
1651 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1652 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1653 } else if (ev
.keyCode
=== 192) {
1654 result
.key
= C0
.ESC
+ '`';
1655 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1656 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1666 * Set the G level of the terminal
1669 Terminal
.prototype.setgLevel = function(g
) {
1671 this.charset
= this.charsets
[g
];
1675 * Set the charset for the given G level of the terminal
1679 Terminal
.prototype.setgCharset = function(g
, charset
) {
1680 this.charsets
[g
] = charset
;
1681 if (this.glevel
=== g
) {
1682 this.charset
= charset
;
1687 * Handle a keypress event.
1689 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1690 * @param {KeyboardEvent} ev The keypress event to be handled.
1692 Terminal
.prototype.keyPress = function(ev
) {
1699 } else if (ev
.which
== null) {
1701 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1708 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1713 key
= String
.fromCharCode(key
);
1715 this.emit('keypress', key
, ev
);
1716 this.emit('key', key
, ev
);
1724 * Send data for handling to the terminal
1725 * @param {string} data
1727 Terminal
.prototype.send = function(data
) {
1731 setTimeout(function() {
1732 self
.handler(self
.queue
);
1742 * Note: We could do sweet things with webaudio here
1744 Terminal
.prototype.bell = function() {
1745 if (!this.visualBell
) return;
1747 this.element
.style
.borderColor
= 'white';
1748 setTimeout(function() {
1749 self
.element
.style
.borderColor
= '';
1751 if (this.popOnBell
) this.focus();
1755 * Log the current state to the console.
1757 Terminal
.prototype.log = function() {
1758 if (!this.debug
) return;
1759 if (!this.context
.console
|| !this.context
.console
.log
) return;
1760 var args
= Array
.prototype.slice
.call(arguments
);
1761 this.context
.console
.log
.apply(this.context
.console
, args
);
1765 * Log the current state as error to the console.
1767 Terminal
.prototype.error = function() {
1768 if (!this.debug
) return;
1769 if (!this.context
.console
|| !this.context
.console
.error
) return;
1770 var args
= Array
.prototype.slice
.call(arguments
);
1771 this.context
.console
.error
.apply(this.context
.console
, args
);
1775 * Resizes the terminal.
1777 * @param {number} x The number of columns to resize to.
1778 * @param {number} y The number of rows to resize to.
1780 Terminal
.prototype.resize = function(x
, y
) {
1781 if (isNaN(x
) || isNaN(y
)) {
1792 if (x
=== this.cols
&& y
=== this.rows
) {
1802 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1803 i
= this.lines
.length
;
1805 while (this.lines
.get(i
).length
< x
) {
1806 this.lines
.get(i
).push(ch
);
1810 i
= this.lines
.length
;
1812 while (this.lines
.get(i
).length
> x
) {
1813 this.lines
.get(i
).pop();
1818 this.setupStops(this.cols
);
1826 // y is rows, not this.y
1827 if (this.lines
.length
< y
+ this.ybase
) {
1828 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
1829 // There is room above the buffer and there are no empty elements below the line,
1833 if (this.ydisp
> 0) {
1834 // Viewport is at the top of the buffer, must increase downwards
1838 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1839 // are blank lines after the cursor
1840 this.lines
.push(this.blankLine());
1843 if (this.children
.length
< y
) {
1849 if (this.lines
.length
> y
+ this.ybase
) {
1850 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
1851 // The line is a blank line below the cursor, remove it
1854 // The line is the cursor, scroll down
1859 if (this.children
.length
> y
) {
1860 el
= this.children
.shift();
1862 el
.parentNode
.removeChild(el
);
1868 // Make sure that the cursor stays on screen
1881 this.scrollBottom
= y
- 1;
1883 this.charMeasure
.measure();
1885 this.refresh(0, this.rows
- 1);
1889 this.geometry
= [this.cols
, this.rows
];
1890 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
1894 * Updates the range of rows to refresh
1895 * @param {number} y The number of rows to refresh next.
1897 Terminal
.prototype.updateRange = function(y
) {
1898 if (y
< this.refreshStart
) this.refreshStart
= y
;
1899 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
1900 // if (y > this.refreshEnd) {
1901 // this.refreshEnd = y;
1902 // if (y > this.rows - 1) {
1903 // this.refreshEnd = this.rows - 1;
1909 * Set the range of refreshing to the maximum value
1911 Terminal
.prototype.maxRange = function() {
1912 this.refreshStart
= 0;
1913 this.refreshEnd
= this.rows
- 1;
1919 * Setup the tab stops.
1922 Terminal
.prototype.setupStops = function(i
) {
1924 if (!this.tabs
[i
]) {
1925 i
= this.prevStop(i
);
1932 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
1933 this.tabs
[i
] = true;
1939 * Move the cursor to the previous tab stop from the given position (default is current).
1940 * @param {number} x The position to move the cursor to the previous tab stop.
1942 Terminal
.prototype.prevStop = function(x
) {
1943 if (x
== null) x
= this.x
;
1944 while (!this.tabs
[--x
] && x
> 0);
1945 return x
>= this.cols
1952 * Move the cursor one tab stop forward from the given position (default is current).
1953 * @param {number} x The position to move the cursor one tab stop forward.
1955 Terminal
.prototype.nextStop = function(x
) {
1956 if (x
== null) x
= this.x
;
1957 while (!this.tabs
[++x
] && x
< this.cols
);
1958 return x
>= this.cols
1965 * Erase in the identified line everything from "x" to the end of the line (right).
1966 * @param {number} x The column from which to start erasing to the end of the line.
1967 * @param {number} y The line in which to operate.
1969 Terminal
.prototype.eraseRight = function(x
, y
) {
1970 var line
= this.lines
.get(this.ybase
+ y
);
1974 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
1975 for (; x
< this.cols
; x
++) {
1978 this.updateRange(y
);
1984 * Erase in the identified line everything from "x" to the start of the line (left).
1985 * @param {number} x The column from which to start erasing to the start of the line.
1986 * @param {number} y The line in which to operate.
1988 Terminal
.prototype.eraseLeft = function(x
, y
) {
1989 var line
= this.lines
.get(this.ybase
+ y
);
1993 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
1998 this.updateRange(y
);
2002 * Clears the entire buffer, making the prompt line the new first line.
2004 Terminal
.prototype.clear = function() {
2005 if (this.ybase
=== 0 && this.y
=== 0) {
2006 // Don't clear if it's already clear
2009 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2010 this.lines
.length
= 1;
2014 for (var i
= 1; i
< this.rows
; i
++) {
2015 this.lines
.push(this.blankLine());
2017 this.refresh(0, this.rows
- 1);
2018 this.emit('scroll', this.ydisp
);
2022 * Erase all content in the given line
2023 * @param {number} y The line to erase all of its contents.
2025 Terminal
.prototype.eraseLine = function(y
) {
2026 this.eraseRight(0, y
);
2031 * Return the data array of a blank line
2032 * @param {number} cur First bunch of data for each "blank" character.
2034 Terminal
.prototype.blankLine = function(cur
) {
2039 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2043 for (; i
< this.cols
; i
++) {
2052 * If cur return the back color xterm feature attribute. Else return defAttr.
2053 * @param {object} cur
2055 Terminal
.prototype.ch = function(cur
) {
2057 ? [this.eraseAttr(), ' ', 1]
2058 : [this.defAttr
, ' ', 1];
2063 * Evaluate if the current erminal is the given argument.
2064 * @param {object} term The terminal to evaluate
2066 Terminal
.prototype.is = function(term
) {
2067 var name
= this.termName
;
2068 return (name
+ '').indexOf(term
) === 0;
2073 * Emit the 'data' event and populate the given data.
2074 * @param {string} data The data to populate in the event.
2076 Terminal
.prototype.handler = function(data
) {
2077 // Prevents all events to pty process if stdin is disabled
2078 if (this.options
.disableStdin
) {
2082 // Input is being sent to the terminal, the terminal should focus the prompt.
2083 if (this.ybase
!== this.ydisp
) {
2084 this.scrollToBottom();
2086 this.emit('data', data
);
2091 * Emit the 'title' event and populate the given title.
2092 * @param {string} title The title to populate in the event.
2094 Terminal
.prototype.handleTitle = function(title
) {
2096 * This event is emitted when the title of the terminal is changed
2097 * from inside the terminal. The parameter is the new title.
2101 this.emit('title', title
);
2110 * ESC D Index (IND is 0x84).
2112 Terminal
.prototype.index = function() {
2114 if (this.y
> this.scrollBottom
) {
2118 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2119 if (this.x
>= this.cols
) {
2126 * ESC M Reverse Index (RI is 0x8d).
2128 * Move the cursor up one row, inserting a new blank line if necessary.
2130 Terminal
.prototype.reverseIndex = function() {
2132 if (this.y
=== this.scrollTop
) {
2133 // possibly move the code below to term.reverseScroll();
2134 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2135 // blankLine(true) is xterm/linux behavior
2136 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2137 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2138 this.updateRange(this.scrollTop
);
2139 this.updateRange(this.scrollBottom
);
2147 * ESC c Full Reset (RIS).
2149 Terminal
.prototype.reset = function() {
2150 this.options
.rows
= this.rows
;
2151 this.options
.cols
= this.cols
;
2152 var customKeydownHandler
= this.customKeydownHandler
;
2153 Terminal
.call(this, this.options
);
2154 this.customKeydownHandler
= customKeydownHandler
;
2155 this.refresh(0, this.rows
- 1);
2156 this.viewport
.syncScrollArea();
2161 * ESC H Tab Set (HTS is 0x88).
2163 Terminal
.prototype.tabSet = function() {
2164 this.tabs
[this.x
] = true;
2171 function on(el
, type
, handler
, capture
) {
2172 if (!Array
.isArray(el
)) {
2175 el
.forEach(function (element
) {
2176 element
.addEventListener(type
, handler
, capture
|| false);
2180 function off(el
, type
, handler
, capture
) {
2181 el
.removeEventListener(type
, handler
, capture
|| false);
2184 function cancel(ev
, force
) {
2185 if (!this.cancelEvents
&& !force
) {
2188 ev
.preventDefault();
2189 ev
.stopPropagation();
2193 function inherits(child
, parent
) {
2195 this.constructor = child
;
2197 f
.prototype = parent
.prototype;
2198 child
.prototype = new f
;
2201 function indexOf(obj
, el
) {
2204 if (obj
[i
] === el
) return i
;
2209 function isThirdLevelShift(term
, ev
) {
2211 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2212 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2214 if (ev
.type
== 'keypress') {
2215 return thirdLevelKey
;
2218 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2219 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2222 // Expose to InputHandler (temporary)
2223 Terminal
.prototype.matchColor
= matchColor
;
2225 function matchColor(r1
, g1
, b1
) {
2226 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2228 if (matchColor
._cache
[hash
] != null) {
2229 return matchColor
._cache
[hash
];
2232 var ldiff
= Infinity
2241 for (; i
< Terminal
.vcolors
.length
; i
++) {
2242 c
= Terminal
.vcolors
[i
];
2247 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2260 return matchColor
._cache
[hash
] = li
;
2263 matchColor
._cache
= {};
2265 // http://stackoverflow.com/questions/1633828
2266 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2267 return Math
.pow(30 * (r1
- r2
), 2)
2268 + Math
.pow(59 * (g1
- g2
), 2)
2269 + Math
.pow(11 * (b1
- b2
), 2);
2272 function each(obj
, iter
, con
) {
2273 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2274 for (var i
= 0; i
< obj
.length
; i
++) {
2275 iter
.call(con
, obj
[i
], i
, obj
);
2279 function wasMondifierKeyOnlyEvent(ev
) {
2280 return ev
.keyCode
=== 16 || // Shift
2281 ev
.keyCode
=== 17 || // Ctrl
2282 ev
.keyCode
=== 18; // Alt
2285 function keys(obj
) {
2286 if (Object
.keys
) return Object
.keys(obj
);
2289 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2300 Terminal
.EventEmitter
= EventEmitter
;
2301 Terminal
.inherits
= inherits
;
2304 * Adds an event listener to the terminal.
2306 * @param {string} event The name of the event. TODO: Document all event types
2307 * @param {function} callback The function to call when the event is triggered.
2311 Terminal
.cancel
= cancel
;
2313 module
.exports
= Terminal
;