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 { SelectionManager
} from './SelectionManager';
24 import { CharMeasure
} from './utils/CharMeasure';
25 import * as Browser
from './utils/Browser';
26 import * as Mouse
from './utils/Mouse';
27 import { CHARSETS
} from './Charsets';
30 * Terminal Emulation References:
32 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
33 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
34 * http://invisible-island.net/vttest/
35 * http://www.inwap.com/pdp10/ansicode.txt
36 * http://linux.die.net/man/4/console_codes
37 * http://linux.die.net/man/7/urxvt
40 // Let it work inside Node.js for automated testing purposes.
41 var document
= (typeof window
!= 'undefined') ? window
.document
: null;
44 * The amount of write requests to queue before sending an XOFF signal to the
45 * pty process. This number must be small in order for ^C and similar sequences
48 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
51 * The number of writes to perform in a single batch before allowing the
52 * renderer to catch up with a 0ms setTimeout.
54 var WRITE_BATCH_SIZE
= 300;
57 * The time between cursor blinks. This is driven by JS rather than a CSS
58 * animation due to a bug in Chromium that causes it to use excessive CPU time.
59 * See https://github.com/Microsoft/vscode/issues/22900
61 var CURSOR_BLINK_INTERVAL
= 600;
68 * Creates a new `Terminal` object.
70 * @param {object} options An object containing a set of options, the available options are:
71 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
72 * - `cols` (number): The number of columns of the terminal (horizontal size)
73 * - `rows` (number): The number of rows of the terminal (vertical size)
77 * @alias module:xterm/src/xterm
79 function Terminal(options
) {
82 if (!(this instanceof Terminal
)) {
83 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
86 self
.browser
= Browser
;
87 self
.cancel
= Terminal
.cancel
;
89 EventEmitter
.call(this);
91 if (typeof options
=== 'number') {
99 options
= options
|| {};
102 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
103 if (options
[key
] == null) {
104 options
[key
] = Terminal
.options
[key
];
106 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
107 options
[key
] = Terminal
[key
];
110 self
[key
] = options
[key
];
113 if (options
.colors
.length
=== 8) {
114 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
115 } else if (options
.colors
.length
=== 16) {
116 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
117 } else if (options
.colors
.length
=== 10) {
118 options
.colors
= options
.colors
.slice(0, -2).concat(
119 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
120 } else if (options
.colors
.length
=== 18) {
121 options
.colors
= options
.colors
.concat(
122 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
124 this.colors
= options
.colors
;
126 this.options
= options
;
128 // this.context = options.context || window;
129 // this.document = options.document || document;
130 this.parent
= options
.body
|| options
.parent
|| (
131 document
? document
.getElementsByTagName('body')[0] : null
134 this.cols
= options
.cols
|| options
.geometry
[0];
135 this.rows
= options
.rows
|| options
.geometry
[1];
136 this.geometry
= [this.cols
, this.rows
];
138 if (options
.handler
) {
139 this.on('data', options
.handler
);
143 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
149 * The scroll position of the viewport
154 * The cursor's x position after ybase
159 * The cursor's y position after ybase
163 this.cursorState
= 0;
164 this.cursorHidden
= false;
168 this.scrollBottom
= this.rows
- 1;
169 this.customKeydownHandler
= null;
170 this.cursorBlinkInterval
= null;
173 this.applicationKeypad
= false;
174 this.applicationCursor
= false;
175 this.originMode
= false;
176 this.insertMode
= false;
177 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
182 this.gcharset
= null;
184 this.charsets
= [null];
208 this.readable
= true;
209 this.writable
= true;
211 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
212 this.curAttr
= this.defAttr
;
215 this.currentParam
= 0;
219 this.inputHandler
= new InputHandler(this);
220 this.parser
= new Parser(this.inputHandler
, this);
221 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
222 this.renderer
= this.renderer
|| null;
223 this.selectionManager
= this.selectionManager
|| null;
224 this.linkifier
= this.linkifier
|| new Linkifier();
227 this.writeBuffer
= [];
228 this.writeInProgress
= false;
231 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
232 * This is a distinct state from writeStopped so that if the user requested
233 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
236 this.xoffSentToCatchUp
= false;
238 /** Whether writing has been stopped as a result of XOFF */
239 this.writeStopped
= false;
241 // leftover surrogate high from previous write invocation
242 this.surrogate_high
= '';
245 * An array of all lines in the entire buffer, including the prompt. The lines are array of
246 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
248 this.lines
= new CircularList(this.scrollback
);
251 this.lines
.push(this.blankLine());
257 // Store if user went browsing history in scrollback
258 this.userScrolling
= false;
261 inherits(Terminal
, EventEmitter
);
264 * back_color_erase feature for xterm.
266 Terminal
.prototype.eraseAttr = function() {
267 // if (this.is('screen')) return this.defAttr;
268 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
276 Terminal
.tangoColors
= [
297 // Colors 0-15 + 16-255
298 // Much thanks to TooTallNate for writing this.
299 Terminal
.colors
= (function() {
300 var colors
= Terminal
.tangoColors
.slice()
301 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
306 for (; i
< 216; i
++) {
307 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
312 for (; i
< 24; i
++) {
317 function out(r
, g
, b
) {
318 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
323 return c
.length
< 2 ? '0' + c
: c
;
329 Terminal
._colors
= Terminal
.colors
.slice();
331 Terminal
.vcolors
= (function() {
333 , colors
= Terminal
.colors
337 for (; i
< 256; i
++) {
338 color
= parseInt(colors
[i
].substring(1), 16);
340 (color
>> 16) & 0xff,
353 Terminal
.defaults
= {
354 colors
: Terminal
.colors
,
360 cursorStyle
: 'block',
368 useFlowControl
: false,
370 // programFeatures: false,
374 Terminal
.options
= {};
376 Terminal
.focus
= null;
378 each(keys(Terminal
.defaults
), function(key
) {
379 Terminal
[key
] = Terminal
.defaults
[key
];
380 Terminal
.options
[key
] = Terminal
.defaults
[key
];
384 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
386 Terminal
.prototype.focus = function() {
387 return this.textarea
.focus();
391 * Retrieves an option's value from the terminal.
392 * @param {string} key The option key.
394 Terminal
.prototype.getOption = function(key
, value
) {
395 if (!(key
in Terminal
.defaults
)) {
396 throw new Error('No option with key "' + key
+ '"');
399 if (typeof this.options
[key
] !== 'undefined') {
400 return this.options
[key
];
407 * Sets an option on the terminal.
408 * @param {string} key The option key.
409 * @param {string} value The option value.
411 Terminal
.prototype.setOption = function(key
, value
) {
412 if (!(key
in Terminal
.defaults
)) {
413 throw new Error('No option with key "' + key
+ '"');
417 if (this.options
[key
] !== value
) {
418 if (this.lines
.length
> value
) {
419 const amountToTrim
= this.lines
.length
- value
;
420 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
421 this.lines
.trimStart(amountToTrim
);
422 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
423 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
425 this.refresh(0, this.rows
- 1);
428 this.lines
.maxLength
= value
;
429 this.viewport
.syncScrollArea();
434 this.options
[key
] = value
;
436 case 'cursorBlink': this.setCursorBlinking(value
); break;
438 // Style 'block' applies with no class
439 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
440 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
442 case 'tabStopWidth': this.setupStops(); break;
446 Terminal
.prototype.restartCursorBlinking = function () {
447 this.setCursorBlinking(this.options
.cursorBlink
);
450 Terminal
.prototype.setCursorBlinking = function (enabled
) {
451 this.element
.classList
.toggle('xterm-cursor-blink', enabled
);
452 this.clearCursorBlinkingInterval();
455 this.cursorBlinkInterval
= setInterval(function () {
456 self
.element
.classList
.toggle('xterm-cursor-blink-on');
457 }, CURSOR_BLINK_INTERVAL
);
461 Terminal
.prototype.clearCursorBlinkingInterval = function () {
462 this.element
.classList
.remove('xterm-cursor-blink-on');
463 if (this.cursorBlinkInterval
) {
464 clearInterval(this.cursorBlinkInterval
);
465 this.cursorBlinkInterval
= null;
470 * Binds the desired focus behavior on a given terminal object.
474 Terminal
.bindFocus = function (term
) {
475 on(term
.textarea
, 'focus', function (ev
) {
476 if (term
.sendFocus
) {
477 term
.send(C0
.ESC
+ '[I');
479 term
.element
.classList
.add('focus');
481 term
.restartCursorBlinking
.apply(term
);
482 Terminal
.focus
= term
;
483 term
.emit('focus', {terminal
: term
});
488 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
490 Terminal
.prototype.blur = function() {
491 return this.textarea
.blur();
495 * Binds the desired blur behavior on a given terminal object.
499 Terminal
.bindBlur = function (term
) {
500 on(term
.textarea
, 'blur', function (ev
) {
501 term
.refresh(term
.y
, term
.y
);
502 if (term
.sendFocus
) {
503 term
.send(C0
.ESC
+ '[O');
505 term
.element
.classList
.remove('focus');
506 term
.clearCursorBlinkingInterval
.apply(term
);
507 Terminal
.focus
= null;
508 term
.emit('blur', {terminal
: term
});
513 * Initialize default behavior
515 Terminal
.prototype.initGlobal = function() {
518 Terminal
.bindKeys(this);
519 Terminal
.bindFocus(this);
520 Terminal
.bindBlur(this);
522 // Bind clipboard functionality
523 on(this.element
, 'copy', function (ev
) {
524 copyHandler
.call(this, ev
, term
);
526 on(this.textarea
, 'paste', function (ev
) {
527 pasteHandler
.call(this, ev
, term
);
529 on(this.element
, 'paste', function (ev
) {
530 pasteHandler
.call(this, ev
, term
);
533 function rightClickHandlerWrapper (ev
) {
534 rightClickHandler
.call(this, ev
, term
);
537 if (term
.browser
.isFirefox
) {
538 on(this.element
, 'mousedown', function (ev
) {
539 if (ev
.button
== 2) {
540 rightClickHandlerWrapper(ev
);
544 on(this.element
, 'contextmenu', rightClickHandlerWrapper
);
549 * Apply key handling to the terminal
551 Terminal
.bindKeys = function(term
) {
552 on(term
.element
, 'keydown', function(ev
) {
553 if (document
.activeElement
!= this) {
559 on(term
.element
, 'keypress', function(ev
) {
560 if (document
.activeElement
!= this) {
566 on(term
.element
, 'keyup', function(ev
) {
567 if (!wasMondifierKeyOnlyEvent(ev
)) {
572 on(term
.textarea
, 'keydown', function(ev
) {
576 on(term
.textarea
, 'keypress', function(ev
) {
578 // Truncate the textarea's value, since it is not needed
582 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
583 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
584 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
585 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
586 term
.on('refresh', function (data
) {
587 term
.queueLinkification(data
.start
, data
.end
)
593 * Insert the given row to the terminal or produce a new one
594 * if no row argument is passed. Return the inserted row.
595 * @param {HTMLElement} row (optional) The row to append to the terminal.
597 Terminal
.prototype.insertRow = function (row
) {
598 if (typeof row
!= 'object') {
599 row
= document
.createElement('div');
602 this.rowContainer
.appendChild(row
);
603 this.children
.push(row
);
609 * Opens the terminal within an element.
611 * @param {HTMLElement} parent The element to create the terminal within.
612 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
614 Terminal
.prototype.open = function(parent
, focus
) {
615 var self
=this, i
=0, div
;
617 this.parent
= parent
|| this.parent
;
620 throw new Error('Terminal requires a parent element.');
623 // Grab global elements
624 this.context
= this.parent
.ownerDocument
.defaultView
;
625 this.document
= this.parent
.ownerDocument
;
626 this.body
= this.document
.getElementsByTagName('body')[0];
628 //Create main element container
629 this.element
= this.document
.createElement('div');
630 this.element
.classList
.add('terminal');
631 this.element
.classList
.add('xterm');
632 this.element
.classList
.add('xterm-theme-' + this.theme
);
633 this.setCursorBlinking(this.options
.cursorBlink
);
635 this.element
.style
.height
;
636 this.element
.setAttribute('tabindex', 0);
638 this.viewportElement
= document
.createElement('div');
639 this.viewportElement
.classList
.add('xterm-viewport');
640 this.element
.appendChild(this.viewportElement
);
641 this.viewportScrollArea
= document
.createElement('div');
642 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
643 this.viewportElement
.appendChild(this.viewportScrollArea
);
645 // Create the selection container. This needs to be added before the
646 // rowContainer as the selection must be below the text.
647 this.selectionContainer
= document
.createElement('div');
648 this.selectionContainer
.classList
.add('xterm-selection');
649 this.element
.appendChild(this.selectionContainer
);
651 // Create the container that will hold the lines of the terminal and then
652 // produce the lines the lines.
653 this.rowContainer
= document
.createElement('div');
654 this.rowContainer
.classList
.add('xterm-rows');
655 this.element
.appendChild(this.rowContainer
);
657 this.linkifier
.attachToDom(document
, this.children
);
659 // Create the container that will hold helpers like the textarea for
660 // capturing DOM Events. Then produce the helpers.
661 this.helperContainer
= document
.createElement('div');
662 this.helperContainer
.classList
.add('xterm-helpers');
663 // TODO: This should probably be inserted once it's filled to prevent an additional layout
664 this.element
.appendChild(this.helperContainer
);
665 this.textarea
= document
.createElement('textarea');
666 this.textarea
.classList
.add('xterm-helper-textarea');
667 this.textarea
.setAttribute('autocorrect', 'off');
668 this.textarea
.setAttribute('autocapitalize', 'off');
669 this.textarea
.setAttribute('spellcheck', 'false');
670 this.textarea
.tabIndex
= 0;
671 this.textarea
.addEventListener('focus', function() {
672 self
.emit('focus', {terminal
: self
});
674 this.textarea
.addEventListener('blur', function() {
675 self
.emit('blur', {terminal
: self
});
677 this.helperContainer
.appendChild(this.textarea
);
679 this.compositionView
= document
.createElement('div');
680 this.compositionView
.classList
.add('composition-view');
681 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
682 this.helperContainer
.appendChild(this.compositionView
);
684 this.charSizeStyleElement
= document
.createElement('style');
685 this.helperContainer
.appendChild(this.charSizeStyleElement
);
687 for (; i
< this.rows
; i
++) {
690 this.parent
.appendChild(this.element
);
692 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
693 this.charMeasure
.on('charsizechanged', function () {
694 self
.updateCharSizeCSS();
696 this.charMeasure
.measure();
698 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
699 this.renderer
= new Renderer(this);
700 this.selectionManager
= new SelectionManager(this, this.lines
, this.rowContainer
, this.selectionContainer
, this.charMeasure
);
701 this.selectionManager
.on('refresh', data
=> this.renderer
.refreshSelection(data
.start
, data
.end
));
702 this.on('scroll', () => this.selectionManager
.refresh());
703 this.viewportElement
.addEventListener('scroll', () => this.selectionManager
.refresh());
705 // Setup loop that draws to screen
706 this.refresh(0, this.rows
- 1);
708 // Initialize global actions that
709 // need to be taken on the document.
713 * Automatic focus functionality.
714 * TODO: Default to `false` starting with xterm.js 3.0.
716 if (typeof focus
== 'undefined') {
717 let message
= 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
719 message
+= 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
720 message
+= 'it will default to `false`.';
722 console
.warn(message
);
730 on(this.element
, 'click', function() {
731 var selection
= document
.getSelection(),
732 collapsed
= selection
.isCollapsed
,
733 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
739 // Listen for mouse events and translate
740 // them into terminal mouse protocols.
744 * This event is emitted when terminal has completed opening.
753 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
754 * @param {string} addon The name of the addon to load
757 Terminal
.loadAddon = function(addon
, callback
) {
758 if (typeof exports
=== 'object' && typeof module
=== 'object') {
760 return require('./addons/' + addon
+ '/' + addon
);
761 } else if (typeof define
== 'function') {
763 return require(['./addons/' + addon
+ '/' + addon
], callback
);
765 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
771 * Updates the helper CSS class with any changes necessary after the terminal's
772 * character width has been changed.
774 Terminal
.prototype.updateCharSizeCSS = function() {
775 this.charSizeStyleElement
.textContent
=
776 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
777 `.xterm-normal-char{width:${this.charMeasure.width}px;}`
782 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
783 * To better understand these
784 * the xterm code is very helpful:
786 * button.c, charproc.c, misc.c
787 * Relevant functions in xterm/button.c:
788 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
790 Terminal
.prototype.bindMouse = function() {
791 var el
= this.element
, self
= this, pressed
= 32;
793 // mouseup, mousedown, wheel
794 // left click: ^[[M 3<^[[M#3<
796 function sendButton(ev
) {
800 // get the xterm-style button
801 button
= getButton(ev
);
803 // get mouse coordinates
804 pos
= Mouse
.getCoords(ev
, this.rowContainer
, this.charMeasure
);
807 sendEvent(button
, pos
);
809 switch (ev
.overrideType
|| ev
.type
) {
814 // keep it at the left
815 // button, just in case.
826 // motion example of a left click:
827 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
828 function sendMove(ev
) {
832 pos
= Mouse
.getCoords(ev
, this.rowContainer
, this.charMeasure
);
835 // buttons marked as motions
836 // are incremented by 32
839 sendEvent(button
, pos
);
843 // position to characters
844 function encode(data
, ch
) {
845 if (!self
.utfMouse
) {
846 if (ch
=== 255) return data
.push(0);
847 if (ch
> 127) ch
= 127;
850 if (ch
=== 2047) return data
.push(0);
854 if (ch
> 2047) ch
= 2047;
855 data
.push(0xC0 | (ch
>> 6));
856 data
.push(0x80 | (ch
& 0x3F));
861 // send a mouse event:
862 // regular/utf8: ^[[M Cb Cx Cy
863 // urxvt: ^[[ Cb ; Cx ; Cy M
864 // sgr: ^[[ Cb ; Cx ; Cy M/m
865 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
866 // locator: CSI P e ; P b ; P r ; P c ; P p & w
867 function sendEvent(button
, pos
) {
868 // self.emit('mouse', {
874 if (self
.vt300Mouse
) {
876 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
880 var data
= C0
.ESC
+ '[24';
881 if (button
=== 0) data
+= '1';
882 else if (button
=== 1) data
+= '3';
883 else if (button
=== 2) data
+= '5';
884 else if (button
=== 3) return;
886 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
891 if (self
.decLocator
) {
896 if (button
=== 0) button
= 2;
897 else if (button
=== 1) button
= 4;
898 else if (button
=== 2) button
= 6;
899 else if (button
=== 3) button
= 3;
900 self
.send(C0
.ESC
+ '['
903 + (button
=== 3 ? 4 : 0)
914 if (self
.urxvtMouse
) {
919 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
926 self
.send(C0
.ESC
+ '[<'
927 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
932 + ((button
& 3) === 3 ? 'm' : 'M'));
938 encode(data
, button
);
942 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
945 function getButton(ev
) {
958 // 1, and 2 - with 64 added
959 switch (ev
.overrideType
|| ev
.type
) {
961 button
= ev
.button
!= null
967 if (self
.browser
.isMSIE
) {
968 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
974 case 'DOMMouseScroll':
975 button
= ev
.detail
< 0
980 button
= ev
.wheelDeltaY
> 0
986 // next three bits are the modifiers:
987 // 4 = shift, 8 = meta, 16 = control
988 shift
= ev
.shiftKey
? 4 : 0;
989 meta
= ev
.metaKey
? 8 : 0;
990 ctrl
= ev
.ctrlKey
? 16 : 0;
991 mod
= shift
| meta
| ctrl
;
994 if (self
.vt200Mouse
) {
997 } else if (!self
.normalMouse
) {
1002 button
= (32 + (mod
<< 2)) + button
;
1007 // mouse coordinates measured in cols/rows
1008 // function getCoords(ev) {
1009 // var x, y, w, h, el;
1011 // // ignore browsers without pageX for now
1012 // if (ev.pageX == null) return;
1016 // el = self.rowContainer;
1018 // // should probably check offsetParent
1019 // // but this is more portable
1020 // while (el && el !== self.document.documentElement) {
1021 // x -= el.offsetLeft;
1022 // y -= el.offsetTop;
1023 // el = 'offsetParent' in el
1024 // ? el.offsetParent
1028 // // convert to cols/rows
1029 // x = Math.ceil(x / self.charMeasure.width);
1030 // y = Math.ceil(y / self.charMeasure.height);
1032 // // be sure to avoid sending
1033 // // bad positions to the program
1034 // if (x < 0) x = 0;
1035 // if (x > self.cols) x = self.cols;
1036 // if (y < 0) y = 0;
1037 // if (y > self.rows) y = self.rows;
1039 // // xterm sends raw bytes and
1040 // // starts at 32 (SP) for each.
1051 on(el
, 'mousedown', function(ev
) {
1052 if (!self
.mouseEvents
) return;
1061 //if (self.vt200Mouse && !self.normalMouse) {
1062 if (self
.vt200Mouse
) {
1063 ev
.overrideType
= 'mouseup';
1065 return self
.cancel(ev
);
1069 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1071 // x10 compatibility mode can't send button releases
1072 if (!self
.x10Mouse
) {
1073 on(self
.document
, 'mouseup', function up(ev
) {
1075 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1076 off(self
.document
, 'mouseup', up
);
1077 return self
.cancel(ev
);
1081 return self
.cancel(ev
);
1084 //if (self.normalMouse) {
1085 // on(self.document, 'mousemove', sendMove);
1088 on(el
, 'wheel', function(ev
) {
1089 if (!self
.mouseEvents
) return;
1092 || self
.decLocator
) return;
1094 return self
.cancel(ev
);
1097 // allow wheel scrolling in
1098 // the shell for example
1099 on(el
, 'wheel', function(ev
) {
1100 if (self
.mouseEvents
) return;
1101 self
.viewport
.onWheel(ev
);
1102 return self
.cancel(ev
);
1107 * Destroys the terminal.
1109 Terminal
.prototype.destroy = function() {
1110 this.readable
= false;
1111 this.writable
= false;
1113 this.handler = function() {};
1114 this.write = function() {};
1115 if (this.element
&& this.element
.parentNode
) {
1116 this.element
.parentNode
.removeChild(this.element
);
1118 //this.emit('close');
1122 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1124 * @param {number} start The row to start from (between 0 and this.rows - 1).
1125 * @param {number} end The row to end at (between start and this.rows - 1).
1127 Terminal
.prototype.refresh = function(start
, end
) {
1128 if (this.renderer
) {
1129 this.renderer
.queueRefresh(start
, end
);
1134 * Queues linkification for the specified rows.
1135 * @param {number} start The row to start from (between 0 and this.rows - 1).
1136 * @param {number} end The row to end at (between start and this.rows - 1).
1138 Terminal
.prototype.queueLinkification = function(start
, end
) {
1139 if (this.linkifier
) {
1140 for (let i
= start
; i
<= end
; i
++) {
1141 this.linkifier
.linkifyRow(i
);
1147 * Display the cursor element
1149 Terminal
.prototype.showCursor = function() {
1150 if (!this.cursorState
) {
1151 this.cursorState
= 1;
1152 this.refresh(this.y
, this.y
);
1157 * Scroll the terminal down 1 row, creating a blank line.
1159 Terminal
.prototype.scroll = function() {
1162 // Make room for the new row in lines
1163 if (this.lines
.length
=== this.lines
.maxLength
) {
1164 this.lines
.trimStart(1);
1166 if (this.ydisp
!== 0) {
1173 // TODO: Why is this done twice?
1174 if (!this.userScrolling
) {
1175 this.ydisp
= this.ybase
;
1179 row
= this.ybase
+ this.rows
- 1;
1181 // subtract the bottom scroll region
1182 row
-= this.rows
- 1 - this.scrollBottom
;
1184 if (row
=== this.lines
.length
) {
1185 // Optimization: pushing is faster than splicing when they amount to the same behavior
1186 this.lines
.push(this.blankLine());
1189 this.lines
.splice(row
, 0, this.blankLine());
1192 if (this.scrollTop
!== 0) {
1193 if (this.ybase
!== 0) {
1195 if (!this.userScrolling
) {
1196 this.ydisp
= this.ybase
;
1199 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1203 this.updateRange(this.scrollTop
);
1204 this.updateRange(this.scrollBottom
);
1207 * This event is emitted whenever the terminal is scrolled.
1208 * The one parameter passed is the new y display position.
1212 this.emit('scroll', this.ydisp
);
1216 * Scroll the display of the terminal
1217 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1218 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1219 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1220 * viewport originally.
1222 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1224 this.userScrolling
= true;
1225 } else if (disp
+ this.ydisp
>= this.ybase
) {
1226 this.userScrolling
= false;
1231 if (this.ydisp
> this.ybase
) {
1232 this.ydisp
= this.ybase
;
1233 } else if (this.ydisp
< 0) {
1237 if (!suppressScrollEvent
) {
1238 this.emit('scroll', this.ydisp
);
1241 this.refresh(0, this.rows
- 1);
1245 * Scroll the display of the terminal by a number of pages.
1246 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1248 Terminal
.prototype.scrollPages = function(pageCount
) {
1249 this.scrollDisp(pageCount
* (this.rows
- 1));
1253 * Scrolls the display of the terminal to the top.
1255 Terminal
.prototype.scrollToTop = function() {
1256 this.scrollDisp(-this.ydisp
);
1260 * Scrolls the display of the terminal to the bottom.
1262 Terminal
.prototype.scrollToBottom = function() {
1263 this.scrollDisp(this.ybase
- this.ydisp
);
1267 * Writes text to the terminal.
1268 * @param {string} text The text to write to the terminal.
1270 Terminal
.prototype.write = function(data
) {
1271 this.writeBuffer
.push(data
);
1273 // Send XOFF to pause the pty process if the write buffer becomes too large so
1274 // xterm.js can catch up before more data is sent. This is necessary in order
1275 // to keep signals such as ^C responsive.
1276 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1277 // XOFF - stop pty pipe
1278 // XON will be triggered by emulator before processing data chunk
1280 this.xoffSentToCatchUp
= true;
1283 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1284 // Kick off a write which will write all data in sequence recursively
1285 this.writeInProgress
= true;
1286 // Kick off an async innerWrite so more writes can come in while processing data
1288 setTimeout(function () {
1294 Terminal
.prototype.innerWrite = function() {
1295 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1296 while (writeBatch
.length
> 0) {
1297 var data
= writeBatch
.shift();
1298 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1300 // If XOFF was sent in order to catch up with the pty process, resume it if
1301 // the writeBuffer is empty to allow more data to come in.
1302 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1304 this.xoffSentToCatchUp
= false;
1307 this.refreshStart
= this.y
;
1308 this.refreshEnd
= this.y
;
1310 this.parser
.parse(data
);
1312 this.updateRange(this.y
);
1313 this.refresh(this.refreshStart
, this.refreshEnd
);
1315 if (this.writeBuffer
.length
> 0) {
1316 // Allow renderer to catch up before processing the next batch
1318 setTimeout(function () {
1322 this.writeInProgress
= false;
1327 * Writes text to the terminal, followed by a break line character (\n).
1328 * @param {string} text The text to write to the terminal.
1330 Terminal
.prototype.writeln = function(data
) {
1331 this.write(data
+ '\r\n');
1335 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1336 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1338 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1339 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1340 * the default action. The function returns whether the event should be processed by xterm.js.
1342 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1343 this.customKeydownHandler
= customKeydownHandler
;
1347 * Attaches a http(s) link handler, forcing web links to behave differently to
1348 * regular <a> tags. This will trigger a refresh as links potentially need to be
1349 * reconstructed. Calling this with null will remove the handler.
1350 * @param {LinkHandler} handler The handler callback function.
1352 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1353 if (!this.linkifier
) {
1354 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1356 this.linkifier
.setHypertextLinkHandler(handler
);
1357 // Refresh to force links to refresh
1358 this.refresh(0, this.rows
- 1);
1362 * Attaches a validation callback for hypertext links. This is useful to use
1363 * validation logic or to do something with the link's element and url.
1364 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1365 * be cleared with null.
1367 Terminal
.prototype.setHypertextValidationCallback = function(handler
) {
1368 if (!this.linkifier
) {
1369 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1371 this.linkifier
.setHypertextValidationCallback(handler
);
1372 // Refresh to force links to refresh
1373 this.refresh(0, this.rows
- 1);
1377 * Registers a link matcher, allowing custom link patterns to be matched and
1379 * @param {RegExp} regex The regular expression to search for, specifically
1380 * this searches the textContent of the rows. You will want to use \s to match
1381 * a space ' ' character for example.
1382 * @param {LinkHandler} handler The callback when the link is called.
1383 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1384 * @return {number} The ID of the new matcher, this can be used to deregister.
1386 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1387 if (this.linkifier
) {
1388 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1389 this.refresh(0, this.rows
- 1);
1395 * Deregisters a link matcher if it has been registered.
1396 * @param {number} matcherId The link matcher's ID (returned after register)
1398 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1399 if (this.linkifier
) {
1400 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1401 this.refresh(0, this.rows
- 1);
1407 * Handle a keydown event
1409 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1410 * @param {KeyboardEvent} ev The keydown event to be handled.
1412 Terminal
.prototype.keyDown = function(ev
) {
1413 if (this.customKeydownHandler
&& this.customKeydownHandler(ev
) === false) {
1417 this.restartCursorBlinking();
1419 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1420 if (this.ybase
!== this.ydisp
) {
1421 this.scrollToBottom();
1427 var result
= this.evaluateKeyEscapeSequence(ev
);
1429 if (result
.key
=== C0
.DC3
) { // XOFF
1430 this.writeStopped
= true;
1431 } else if (result
.key
=== C0
.DC1
) { // XON
1432 this.writeStopped
= false;
1435 if (result
.scrollDisp
) {
1436 this.scrollDisp(result
.scrollDisp
);
1437 return this.cancel(ev
, true);
1440 if (isThirdLevelShift(this, ev
)) {
1444 if (result
.cancel
) {
1445 // The event is canceled at the end already, is this necessary?
1446 this.cancel(ev
, true);
1453 this.emit('keydown', ev
);
1454 this.emit('key', result
.key
, ev
);
1456 this.handler(result
.key
);
1458 return this.cancel(ev
, true);
1462 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1463 * returned value is the new key code to pass to the PTY.
1465 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1466 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1468 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1470 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1471 // canceled at the end of keyDown
1473 // The new key even to emit
1475 // The number of characters to scroll, if this is defined it will cancel the event
1476 scrollDisp
: undefined
1478 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1479 switch (ev
.keyCode
) {
1483 result
.key
= C0
.BS
; // ^H
1486 result
.key
= C0
.DEL
; // ^?
1491 result
.key
= C0
.ESC
+ '[Z';
1495 result
.cancel
= true;
1500 result
.cancel
= true;
1504 result
.key
= C0
.ESC
;
1505 result
.cancel
= true;
1510 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1511 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1512 // http://unix.stackexchange.com/a/108106
1513 // macOS uses different escape sequences than linux
1514 if (result
.key
== C0
.ESC
+ '[1;3D') {
1515 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1517 } else if (this.applicationCursor
) {
1518 result
.key
= C0
.ESC
+ 'OD';
1520 result
.key
= C0
.ESC
+ '[D';
1526 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1527 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1528 // http://unix.stackexchange.com/a/108106
1529 // macOS uses different escape sequences than linux
1530 if (result
.key
== C0
.ESC
+ '[1;3C') {
1531 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1533 } else if (this.applicationCursor
) {
1534 result
.key
= C0
.ESC
+ 'OC';
1536 result
.key
= C0
.ESC
+ '[C';
1542 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1543 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1544 // http://unix.stackexchange.com/a/108106
1545 if (result
.key
== C0
.ESC
+ '[1;3A') {
1546 result
.key
= C0
.ESC
+ '[1;5A';
1548 } else if (this.applicationCursor
) {
1549 result
.key
= C0
.ESC
+ 'OA';
1551 result
.key
= C0
.ESC
+ '[A';
1557 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1558 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1559 // http://unix.stackexchange.com/a/108106
1560 if (result
.key
== C0
.ESC
+ '[1;3B') {
1561 result
.key
= C0
.ESC
+ '[1;5B';
1563 } else if (this.applicationCursor
) {
1564 result
.key
= C0
.ESC
+ 'OB';
1566 result
.key
= C0
.ESC
+ '[B';
1571 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1572 // <Ctrl> or <Shift> + <Insert> are used to
1573 // copy-paste on some systems.
1574 result
.key
= C0
.ESC
+ '[2~';
1580 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1582 result
.key
= C0
.ESC
+ '[3~';
1588 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1589 else if (this.applicationCursor
)
1590 result
.key
= C0
.ESC
+ 'OH';
1592 result
.key
= C0
.ESC
+ '[H';
1597 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1598 else if (this.applicationCursor
)
1599 result
.key
= C0
.ESC
+ 'OF';
1601 result
.key
= C0
.ESC
+ '[F';
1606 result
.scrollDisp
= -(this.rows
- 1);
1608 result
.key
= C0
.ESC
+ '[5~';
1614 result
.scrollDisp
= this.rows
- 1;
1616 result
.key
= C0
.ESC
+ '[6~';
1622 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1624 result
.key
= C0
.ESC
+ 'OP';
1629 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1631 result
.key
= C0
.ESC
+ 'OQ';
1636 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1638 result
.key
= C0
.ESC
+ 'OR';
1643 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1645 result
.key
= C0
.ESC
+ 'OS';
1650 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1652 result
.key
= C0
.ESC
+ '[15~';
1657 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1659 result
.key
= C0
.ESC
+ '[17~';
1664 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1666 result
.key
= C0
.ESC
+ '[18~';
1671 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1673 result
.key
= C0
.ESC
+ '[19~';
1678 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1680 result
.key
= C0
.ESC
+ '[20~';
1685 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1687 result
.key
= C0
.ESC
+ '[21~';
1692 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1694 result
.key
= C0
.ESC
+ '[23~';
1699 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1701 result
.key
= C0
.ESC
+ '[24~';
1706 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1707 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1708 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1709 } else if (ev
.keyCode
=== 32) {
1711 result
.key
= String
.fromCharCode(0);
1712 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1713 // escape, file sep, group sep, record sep, unit sep
1714 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1715 } else if (ev
.keyCode
=== 56) {
1717 result
.key
= String
.fromCharCode(127);
1718 } else if (ev
.keyCode
=== 219) {
1719 // ^[ - Control Sequence Introducer (CSI)
1720 result
.key
= String
.fromCharCode(27);
1721 } else if (ev
.keyCode
=== 220) {
1722 // ^\ - String Terminator (ST)
1723 result
.key
= String
.fromCharCode(28);
1724 } else if (ev
.keyCode
=== 221) {
1725 // ^] - Operating System Command (OSC)
1726 result
.key
= String
.fromCharCode(29);
1728 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1729 // On Mac this is a third level shift. Use <Esc> instead.
1730 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1731 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1732 } else if (ev
.keyCode
=== 192) {
1733 result
.key
= C0
.ESC
+ '`';
1734 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1735 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1745 * Set the G level of the terminal
1748 Terminal
.prototype.setgLevel = function(g
) {
1750 this.charset
= this.charsets
[g
];
1754 * Set the charset for the given G level of the terminal
1758 Terminal
.prototype.setgCharset = function(g
, charset
) {
1759 this.charsets
[g
] = charset
;
1760 if (this.glevel
=== g
) {
1761 this.charset
= charset
;
1766 * Handle a keypress event.
1768 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1769 * @param {KeyboardEvent} ev The keypress event to be handled.
1771 Terminal
.prototype.keyPress = function(ev
) {
1778 } else if (ev
.which
== null) {
1780 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1787 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1792 key
= String
.fromCharCode(key
);
1794 this.emit('keypress', key
, ev
);
1795 this.emit('key', key
, ev
);
1803 * Send data for handling to the terminal
1804 * @param {string} data
1806 Terminal
.prototype.send = function(data
) {
1810 setTimeout(function() {
1811 self
.handler(self
.queue
);
1821 * Note: We could do sweet things with webaudio here
1823 Terminal
.prototype.bell = function() {
1824 if (!this.visualBell
) return;
1826 this.element
.style
.borderColor
= 'white';
1827 setTimeout(function() {
1828 self
.element
.style
.borderColor
= '';
1830 if (this.popOnBell
) this.focus();
1834 * Log the current state to the console.
1836 Terminal
.prototype.log = function() {
1837 if (!this.debug
) return;
1838 if (!this.context
.console
|| !this.context
.console
.log
) return;
1839 var args
= Array
.prototype.slice
.call(arguments
);
1840 this.context
.console
.log
.apply(this.context
.console
, args
);
1844 * Log the current state as error to the console.
1846 Terminal
.prototype.error = function() {
1847 if (!this.debug
) return;
1848 if (!this.context
.console
|| !this.context
.console
.error
) return;
1849 var args
= Array
.prototype.slice
.call(arguments
);
1850 this.context
.console
.error
.apply(this.context
.console
, args
);
1854 * Resizes the terminal.
1856 * @param {number} x The number of columns to resize to.
1857 * @param {number} y The number of rows to resize to.
1859 Terminal
.prototype.resize = function(x
, y
) {
1860 if (isNaN(x
) || isNaN(y
)) {
1871 if (x
=== this.cols
&& y
=== this.rows
) {
1881 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1882 i
= this.lines
.length
;
1884 while (this.lines
.get(i
).length
< x
) {
1885 this.lines
.get(i
).push(ch
);
1891 this.setupStops(this.cols
);
1899 // y is rows, not this.y
1900 if (this.lines
.length
< y
+ this.ybase
) {
1901 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
1902 // There is room above the buffer and there are no empty elements below the line,
1906 if (this.ydisp
> 0) {
1907 // Viewport is at the top of the buffer, must increase downwards
1911 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1912 // are blank lines after the cursor
1913 this.lines
.push(this.blankLine());
1916 if (this.children
.length
< y
) {
1922 if (this.lines
.length
> y
+ this.ybase
) {
1923 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
1924 // The line is a blank line below the cursor, remove it
1927 // The line is the cursor, scroll down
1932 if (this.children
.length
> y
) {
1933 el
= this.children
.shift();
1935 el
.parentNode
.removeChild(el
);
1941 // Make sure that the cursor stays on screen
1954 this.scrollBottom
= y
- 1;
1956 this.charMeasure
.measure();
1958 this.refresh(0, this.rows
- 1);
1962 this.geometry
= [this.cols
, this.rows
];
1963 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
1967 * Updates the range of rows to refresh
1968 * @param {number} y The number of rows to refresh next.
1970 Terminal
.prototype.updateRange = function(y
) {
1971 if (y
< this.refreshStart
) this.refreshStart
= y
;
1972 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
1973 // if (y > this.refreshEnd) {
1974 // this.refreshEnd = y;
1975 // if (y > this.rows - 1) {
1976 // this.refreshEnd = this.rows - 1;
1982 * Set the range of refreshing to the maximum value
1984 Terminal
.prototype.maxRange = function() {
1985 this.refreshStart
= 0;
1986 this.refreshEnd
= this.rows
- 1;
1992 * Setup the tab stops.
1995 Terminal
.prototype.setupStops = function(i
) {
1997 if (!this.tabs
[i
]) {
1998 i
= this.prevStop(i
);
2005 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
2006 this.tabs
[i
] = true;
2012 * Move the cursor to the previous tab stop from the given position (default is current).
2013 * @param {number} x The position to move the cursor to the previous tab stop.
2015 Terminal
.prototype.prevStop = function(x
) {
2016 if (x
== null) x
= this.x
;
2017 while (!this.tabs
[--x
] && x
> 0);
2018 return x
>= this.cols
2025 * Move the cursor one tab stop forward from the given position (default is current).
2026 * @param {number} x The position to move the cursor one tab stop forward.
2028 Terminal
.prototype.nextStop = function(x
) {
2029 if (x
== null) x
= this.x
;
2030 while (!this.tabs
[++x
] && x
< this.cols
);
2031 return x
>= this.cols
2038 * Erase in the identified line everything from "x" to the end of the line (right).
2039 * @param {number} x The column from which to start erasing to the end of the line.
2040 * @param {number} y The line in which to operate.
2042 Terminal
.prototype.eraseRight = function(x
, y
) {
2043 var line
= this.lines
.get(this.ybase
+ y
);
2047 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2048 for (; x
< this.cols
; x
++) {
2051 this.updateRange(y
);
2057 * Erase in the identified line everything from "x" to the start of the line (left).
2058 * @param {number} x The column from which to start erasing to the start of the line.
2059 * @param {number} y The line in which to operate.
2061 Terminal
.prototype.eraseLeft = function(x
, y
) {
2062 var line
= this.lines
.get(this.ybase
+ y
);
2066 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2071 this.updateRange(y
);
2075 * Clears the entire buffer, making the prompt line the new first line.
2077 Terminal
.prototype.clear = function() {
2078 if (this.ybase
=== 0 && this.y
=== 0) {
2079 // Don't clear if it's already clear
2082 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2083 this.lines
.length
= 1;
2087 for (var i
= 1; i
< this.rows
; i
++) {
2088 this.lines
.push(this.blankLine());
2090 this.refresh(0, this.rows
- 1);
2091 this.emit('scroll', this.ydisp
);
2095 * Erase all content in the given line
2096 * @param {number} y The line to erase all of its contents.
2098 Terminal
.prototype.eraseLine = function(y
) {
2099 this.eraseRight(0, y
);
2104 * Return the data array of a blank line
2105 * @param {number} cur First bunch of data for each "blank" character.
2107 Terminal
.prototype.blankLine = function(cur
) {
2112 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2116 for (; i
< this.cols
; i
++) {
2125 * If cur return the back color xterm feature attribute. Else return defAttr.
2126 * @param {object} cur
2128 Terminal
.prototype.ch = function(cur
) {
2130 ? [this.eraseAttr(), ' ', 1]
2131 : [this.defAttr
, ' ', 1];
2136 * Evaluate if the current erminal is the given argument.
2137 * @param {object} term The terminal to evaluate
2139 Terminal
.prototype.is = function(term
) {
2140 var name
= this.termName
;
2141 return (name
+ '').indexOf(term
) === 0;
2146 * Emit the 'data' event and populate the given data.
2147 * @param {string} data The data to populate in the event.
2149 Terminal
.prototype.handler = function(data
) {
2150 // Prevents all events to pty process if stdin is disabled
2151 if (this.options
.disableStdin
) {
2155 // Input is being sent to the terminal, the terminal should focus the prompt.
2156 if (this.ybase
!== this.ydisp
) {
2157 this.scrollToBottom();
2159 this.emit('data', data
);
2164 * Emit the 'title' event and populate the given title.
2165 * @param {string} title The title to populate in the event.
2167 Terminal
.prototype.handleTitle = function(title
) {
2169 * This event is emitted when the title of the terminal is changed
2170 * from inside the terminal. The parameter is the new title.
2174 this.emit('title', title
);
2183 * ESC D Index (IND is 0x84).
2185 Terminal
.prototype.index = function() {
2187 if (this.y
> this.scrollBottom
) {
2191 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2192 if (this.x
>= this.cols
) {
2199 * ESC M Reverse Index (RI is 0x8d).
2201 * Move the cursor up one row, inserting a new blank line if necessary.
2203 Terminal
.prototype.reverseIndex = function() {
2205 if (this.y
=== this.scrollTop
) {
2206 // possibly move the code below to term.reverseScroll();
2207 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2208 // blankLine(true) is xterm/linux behavior
2209 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2210 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2211 this.updateRange(this.scrollTop
);
2212 this.updateRange(this.scrollBottom
);
2220 * ESC c Full Reset (RIS).
2222 Terminal
.prototype.reset = function() {
2223 this.options
.rows
= this.rows
;
2224 this.options
.cols
= this.cols
;
2225 var customKeydownHandler
= this.customKeydownHandler
;
2226 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2227 Terminal
.call(this, this.options
);
2228 this.customKeydownHandler
= customKeydownHandler
;
2229 this.cursorBlinkInterval
= cursorBlinkInterval
;
2230 this.refresh(0, this.rows
- 1);
2231 this.viewport
.syncScrollArea();
2236 * ESC H Tab Set (HTS is 0x88).
2238 Terminal
.prototype.tabSet = function() {
2239 this.tabs
[this.x
] = true;
2246 function on(el
, type
, handler
, capture
) {
2247 if (!Array
.isArray(el
)) {
2250 el
.forEach(function (element
) {
2251 element
.addEventListener(type
, handler
, capture
|| false);
2255 function off(el
, type
, handler
, capture
) {
2256 el
.removeEventListener(type
, handler
, capture
|| false);
2259 function cancel(ev
, force
) {
2260 if (!this.cancelEvents
&& !force
) {
2263 ev
.preventDefault();
2264 ev
.stopPropagation();
2268 function inherits(child
, parent
) {
2270 this.constructor = child
;
2272 f
.prototype = parent
.prototype;
2273 child
.prototype = new f
;
2276 function indexOf(obj
, el
) {
2279 if (obj
[i
] === el
) return i
;
2284 function isThirdLevelShift(term
, ev
) {
2286 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2287 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2289 if (ev
.type
== 'keypress') {
2290 return thirdLevelKey
;
2293 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2294 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2297 // Expose to InputHandler (temporary)
2298 Terminal
.prototype.matchColor
= matchColor
;
2300 function matchColor(r1
, g1
, b1
) {
2301 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2303 if (matchColor
._cache
[hash
] != null) {
2304 return matchColor
._cache
[hash
];
2307 var ldiff
= Infinity
2316 for (; i
< Terminal
.vcolors
.length
; i
++) {
2317 c
= Terminal
.vcolors
[i
];
2322 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2335 return matchColor
._cache
[hash
] = li
;
2338 matchColor
._cache
= {};
2340 // http://stackoverflow.com/questions/1633828
2341 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2342 return Math
.pow(30 * (r1
- r2
), 2)
2343 + Math
.pow(59 * (g1
- g2
), 2)
2344 + Math
.pow(11 * (b1
- b2
), 2);
2347 function each(obj
, iter
, con
) {
2348 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2349 for (var i
= 0; i
< obj
.length
; i
++) {
2350 iter
.call(con
, obj
[i
], i
, obj
);
2354 function wasMondifierKeyOnlyEvent(ev
) {
2355 return ev
.keyCode
=== 16 || // Shift
2356 ev
.keyCode
=== 17 || // Ctrl
2357 ev
.keyCode
=== 18; // Alt
2360 function keys(obj
) {
2361 if (Object
.keys
) return Object
.keys(obj
);
2364 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2375 Terminal
.EventEmitter
= EventEmitter
;
2376 Terminal
.inherits
= inherits
;
2379 * Adds an event listener to the terminal.
2381 * @param {string} event The name of the event. TODO: Document all event types
2382 * @param {function} callback The function to call when the event is triggered.
2386 Terminal
.cancel
= cancel
;
2388 module
.exports
= Terminal
;