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
, moveTextAreaUnderMouseCursor
, 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';
28 import { getRawByteCoords
} from './utils/Mouse';
31 * Terminal Emulation References:
33 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
34 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
35 * http://invisible-island.net/vttest/
36 * http://www.inwap.com/pdp10/ansicode.txt
37 * http://linux.die.net/man/4/console_codes
38 * http://linux.die.net/man/7/urxvt
41 // Let it work inside Node.js for automated testing purposes.
42 var document
= (typeof window
!= 'undefined') ? window
.document
: null;
45 * The amount of write requests to queue before sending an XOFF signal to the
46 * pty process. This number must be small in order for ^C and similar sequences
49 var WRITE_BUFFER_PAUSE_THRESHOLD
= 5;
52 * The number of writes to perform in a single batch before allowing the
53 * renderer to catch up with a 0ms setTimeout.
55 var WRITE_BATCH_SIZE
= 300;
58 * The time between cursor blinks. This is driven by JS rather than a CSS
59 * animation due to a bug in Chromium that causes it to use excessive CPU time.
60 * See https://github.com/Microsoft/vscode/issues/22900
62 var CURSOR_BLINK_INTERVAL
= 600;
69 * Creates a new `Terminal` object.
71 * @param {object} options An object containing a set of options, the available options are:
72 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
73 * - `cols` (number): The number of columns of the terminal (horizontal size)
74 * - `rows` (number): The number of rows of the terminal (vertical size)
78 * @alias module:xterm/src/xterm
80 function Terminal(options
) {
83 if (!(this instanceof Terminal
)) {
84 return new Terminal(arguments
[0], arguments
[1], arguments
[2]);
87 self
.browser
= Browser
;
88 self
.cancel
= Terminal
.cancel
;
90 EventEmitter
.call(this);
92 if (typeof options
=== 'number') {
100 options
= options
|| {};
103 Object
.keys(Terminal
.defaults
).forEach(function(key
) {
104 if (options
[key
] == null) {
105 options
[key
] = Terminal
.options
[key
];
107 if (Terminal
[key
] !== Terminal
.defaults
[key
]) {
108 options
[key
] = Terminal
[key
];
111 self
[key
] = options
[key
];
114 if (options
.colors
.length
=== 8) {
115 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(8));
116 } else if (options
.colors
.length
=== 16) {
117 options
.colors
= options
.colors
.concat(Terminal
._colors
.slice(16));
118 } else if (options
.colors
.length
=== 10) {
119 options
.colors
= options
.colors
.slice(0, -2).concat(
120 Terminal
._colors
.slice(8, -2), options
.colors
.slice(-2));
121 } else if (options
.colors
.length
=== 18) {
122 options
.colors
= options
.colors
.concat(
123 Terminal
._colors
.slice(16, -2), options
.colors
.slice(-2));
125 this.colors
= options
.colors
;
127 this.options
= options
;
129 // this.context = options.context || window;
130 // this.document = options.document || document;
131 this.parent
= options
.body
|| options
.parent
|| (
132 document
? document
.getElementsByTagName('body')[0] : null
135 this.cols
= options
.cols
|| options
.geometry
[0];
136 this.rows
= options
.rows
|| options
.geometry
[1];
137 this.geometry
= [this.cols
, this.rows
];
139 if (options
.handler
) {
140 this.on('data', options
.handler
);
144 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
150 * The scroll position of the viewport
155 * The cursor's x position after ybase
160 * The cursor's y position after ybase
164 this.cursorState
= 0;
165 this.cursorHidden
= false;
169 this.scrollBottom
= this.rows
- 1;
170 this.customKeyEventHandler
= null;
171 this.cursorBlinkInterval
= null;
174 this.applicationKeypad
= false;
175 this.applicationCursor
= false;
176 this.originMode
= false;
177 this.insertMode
= false;
178 this.wraparoundMode
= true; // defaults: xterm - true, vt100 - false
183 this.gcharset
= null;
185 this.charsets
= [null];
209 this.readable
= true;
210 this.writable
= true;
212 this.defAttr
= (0 << 18) | (257 << 9) | (256 << 0);
213 this.curAttr
= this.defAttr
;
216 this.currentParam
= 0;
220 this.inputHandler
= new InputHandler(this);
221 this.parser
= new Parser(this.inputHandler
, this);
222 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
223 this.renderer
= this.renderer
|| null;
224 this.selectionManager
= this.selectionManager
|| null;
225 this.linkifier
= this.linkifier
|| new Linkifier();
228 this.writeBuffer
= [];
229 this.writeInProgress
= false;
232 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
233 * This is a distinct state from writeStopped so that if the user requested
234 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
237 this.xoffSentToCatchUp
= false;
239 /** Whether writing has been stopped as a result of XOFF */
240 this.writeStopped
= false;
242 // leftover surrogate high from previous write invocation
243 this.surrogate_high
= '';
246 * An array of all lines in the entire buffer, including the prompt. The lines are array of
247 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
249 this.lines
= new CircularList(this.scrollback
);
252 this.lines
.push(this.blankLine());
254 // Ensure the selection manager has the correct buffer
255 if (this.selectionManager
) {
256 this.selectionManager
.setBuffer(this.lines
);
262 // Store if user went browsing history in scrollback
263 this.userScrolling
= false;
266 inherits(Terminal
, EventEmitter
);
269 * back_color_erase feature for xterm.
271 Terminal
.prototype.eraseAttr = function() {
272 // if (this.is('screen')) return this.defAttr;
273 return (this.defAttr
& ~0x1ff) | (this.curAttr
& 0x1ff);
281 Terminal
.tangoColors
= [
302 // Colors 0-15 + 16-255
303 // Much thanks to TooTallNate for writing this.
304 Terminal
.colors
= (function() {
305 var colors
= Terminal
.tangoColors
.slice()
306 , r
= [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
311 for (; i
< 216; i
++) {
312 out(r
[(i
/ 36) % 6 | 0], r
[(i
/ 6) % 6 | 0], r
[i
% 6]);
317 for (; i
< 24; i
++) {
322 function out(r
, g
, b
) {
323 colors
.push('#' + hex(r
) + hex(g
) + hex(b
));
328 return c
.length
< 2 ? '0' + c
: c
;
334 Terminal
._colors
= Terminal
.colors
.slice();
336 Terminal
.vcolors
= (function() {
338 , colors
= Terminal
.colors
342 for (; i
< 256; i
++) {
343 color
= parseInt(colors
[i
].substring(1), 16);
345 (color
>> 16) & 0xff,
358 Terminal
.defaults
= {
359 colors
: Terminal
.colors
,
365 cursorStyle
: 'block',
373 useFlowControl
: false,
375 // programFeatures: false,
379 Terminal
.options
= {};
381 Terminal
.focus
= null;
383 each(keys(Terminal
.defaults
), function(key
) {
384 Terminal
[key
] = Terminal
.defaults
[key
];
385 Terminal
.options
[key
] = Terminal
.defaults
[key
];
389 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
391 Terminal
.prototype.focus = function() {
392 return this.textarea
.focus();
396 * Retrieves an option's value from the terminal.
397 * @param {string} key The option key.
399 Terminal
.prototype.getOption = function(key
, value
) {
400 if (!(key
in Terminal
.defaults
)) {
401 throw new Error('No option with key "' + key
+ '"');
404 if (typeof this.options
[key
] !== 'undefined') {
405 return this.options
[key
];
412 * Sets an option on the terminal.
413 * @param {string} key The option key.
414 * @param {string} value The option value.
416 Terminal
.prototype.setOption = function(key
, value
) {
417 if (!(key
in Terminal
.defaults
)) {
418 throw new Error('No option with key "' + key
+ '"');
422 if (this.options
[key
] !== value
) {
423 if (this.lines
.length
> value
) {
424 const amountToTrim
= this.lines
.length
- value
;
425 const needsRefresh
= (this.ydisp
- amountToTrim
< 0);
426 this.lines
.trimStart(amountToTrim
);
427 this.ybase
= Math
.max(this.ybase
- amountToTrim
, 0);
428 this.ydisp
= Math
.max(this.ydisp
- amountToTrim
, 0);
430 this.refresh(0, this.rows
- 1);
433 this.lines
.maxLength
= value
;
434 this.viewport
.syncScrollArea();
439 this.options
[key
] = value
;
441 case 'cursorBlink': this.setCursorBlinking(value
); break;
443 // Style 'block' applies with no class
444 this.element
.classList
.toggle(`xterm-cursor-style-underline`, value
=== 'underline');
445 this.element
.classList
.toggle(`xterm-cursor-style-bar`, value
=== 'bar');
447 case 'tabStopWidth': this.setupStops(); break;
451 Terminal
.prototype.restartCursorBlinking = function () {
452 this.setCursorBlinking(this.options
.cursorBlink
);
455 Terminal
.prototype.setCursorBlinking = function (enabled
) {
456 this.element
.classList
.toggle('xterm-cursor-blink', enabled
);
457 this.clearCursorBlinkingInterval();
460 this.cursorBlinkInterval
= setInterval(function () {
461 self
.element
.classList
.toggle('xterm-cursor-blink-on');
462 }, CURSOR_BLINK_INTERVAL
);
466 Terminal
.prototype.clearCursorBlinkingInterval = function () {
467 this.element
.classList
.remove('xterm-cursor-blink-on');
468 if (this.cursorBlinkInterval
) {
469 clearInterval(this.cursorBlinkInterval
);
470 this.cursorBlinkInterval
= null;
475 * Binds the desired focus behavior on a given terminal object.
479 Terminal
.bindFocus = function (term
) {
480 on(term
.textarea
, 'focus', function (ev
) {
481 if (term
.sendFocus
) {
482 term
.send(C0
.ESC
+ '[I');
484 term
.element
.classList
.add('focus');
486 term
.restartCursorBlinking
.apply(term
);
487 Terminal
.focus
= term
;
488 term
.emit('focus', {terminal
: term
});
493 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
495 Terminal
.prototype.blur = function() {
496 return this.textarea
.blur();
500 * Binds the desired blur behavior on a given terminal object.
504 Terminal
.bindBlur = function (term
) {
505 on(term
.textarea
, 'blur', function (ev
) {
506 term
.refresh(term
.y
, term
.y
);
507 if (term
.sendFocus
) {
508 term
.send(C0
.ESC
+ '[O');
510 term
.element
.classList
.remove('focus');
511 term
.clearCursorBlinkingInterval
.apply(term
);
512 Terminal
.focus
= null;
513 term
.emit('blur', {terminal
: term
});
518 * Initialize default behavior
520 Terminal
.prototype.initGlobal = function() {
523 Terminal
.bindKeys(this);
524 Terminal
.bindFocus(this);
525 Terminal
.bindBlur(this);
527 // Bind clipboard functionality
528 on(this.element
, 'copy', event
=> {
529 // If mouse events are active it means the selection manager is disabled and
530 // copy should be handled by the host program.
531 if (this.mouseEvents
) {
534 copyHandler(event
, term
, this.selectionManager
);
536 const pasteHandlerWrapper
= event
=> pasteHandler(event
, term
);
537 on(this.textarea
, 'paste', pasteHandlerWrapper
);
538 on(this.element
, 'paste', pasteHandlerWrapper
);
540 // Handle right click context menus
541 if (term
.browser
.isFirefox
) {
542 // Firefox doesn't appear to fire the contextmenu event on right click
543 on(this.element
, 'mousedown', event
=> {
544 if (event
.button
== 2) {
545 rightClickHandler(event
, this.textarea
, this.selectionManager
);
549 on(this.element
, 'contextmenu', event
=> {
550 rightClickHandler(event
, this.textarea
, this.selectionManager
);
554 // Move the textarea under the cursor when middle clicking on Linux to ensure
555 // middle click to paste selection works. This only appears to work in Chrome
556 // at the time is writing.
557 if (term
.browser
.isLinux
) {
558 // Use auxclick event over mousedown the latter doesn't seem to work. Note
559 // that the regular click event doesn't fire for the middle mouse button.
560 on(this.element
, 'auxclick', event
=> {
561 if (event
.button
=== 1) {
562 moveTextAreaUnderMouseCursor(event
, this.textarea
, this.selectionManager
);
569 * Apply key handling to the terminal
571 Terminal
.bindKeys = function(term
) {
572 on(term
.element
, 'keydown', function(ev
) {
573 if (document
.activeElement
!= this) {
579 on(term
.element
, 'keypress', function(ev
) {
580 if (document
.activeElement
!= this) {
586 on(term
.element
, 'keyup', function(ev
) {
587 if (!wasMondifierKeyOnlyEvent(ev
)) {
592 on(term
.textarea
, 'keydown', function(ev
) {
596 on(term
.textarea
, 'keypress', function(ev
) {
598 // Truncate the textarea's value, since it is not needed
602 on(term
.textarea
, 'compositionstart', term
.compositionHelper
.compositionstart
.bind(term
.compositionHelper
));
603 on(term
.textarea
, 'compositionupdate', term
.compositionHelper
.compositionupdate
.bind(term
.compositionHelper
));
604 on(term
.textarea
, 'compositionend', term
.compositionHelper
.compositionend
.bind(term
.compositionHelper
));
605 term
.on('refresh', term
.compositionHelper
.updateCompositionElements
.bind(term
.compositionHelper
));
606 term
.on('refresh', function (data
) {
607 term
.queueLinkification(data
.start
, data
.end
)
613 * Insert the given row to the terminal or produce a new one
614 * if no row argument is passed. Return the inserted row.
615 * @param {HTMLElement} row (optional) The row to append to the terminal.
617 Terminal
.prototype.insertRow = function (row
) {
618 if (typeof row
!= 'object') {
619 row
= document
.createElement('div');
622 this.rowContainer
.appendChild(row
);
623 this.children
.push(row
);
629 * Opens the terminal within an element.
631 * @param {HTMLElement} parent The element to create the terminal within.
632 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
634 Terminal
.prototype.open = function(parent
, focus
) {
635 var self
=this, i
=0, div
;
637 this.parent
= parent
|| this.parent
;
640 throw new Error('Terminal requires a parent element.');
643 // Grab global elements
644 this.context
= this.parent
.ownerDocument
.defaultView
;
645 this.document
= this.parent
.ownerDocument
;
646 this.body
= this.document
.getElementsByTagName('body')[0];
648 //Create main element container
649 this.element
= this.document
.createElement('div');
650 this.element
.classList
.add('terminal');
651 this.element
.classList
.add('xterm');
652 this.element
.classList
.add('xterm-theme-' + this.theme
);
653 this.setCursorBlinking(this.options
.cursorBlink
);
655 this.element
.setAttribute('tabindex', 0);
657 this.viewportElement
= document
.createElement('div');
658 this.viewportElement
.classList
.add('xterm-viewport');
659 this.element
.appendChild(this.viewportElement
);
660 this.viewportScrollArea
= document
.createElement('div');
661 this.viewportScrollArea
.classList
.add('xterm-scroll-area');
662 this.viewportElement
.appendChild(this.viewportScrollArea
);
664 // Create the selection container.
665 this.selectionContainer
= document
.createElement('div');
666 this.selectionContainer
.classList
.add('xterm-selection');
667 this.element
.appendChild(this.selectionContainer
);
669 // Create the container that will hold the lines of the terminal and then
670 // produce the lines the lines.
671 this.rowContainer
= document
.createElement('div');
672 this.rowContainer
.classList
.add('xterm-rows');
673 this.element
.appendChild(this.rowContainer
);
675 this.linkifier
.attachToDom(document
, this.children
);
677 // Create the container that will hold helpers like the textarea for
678 // capturing DOM Events. Then produce the helpers.
679 this.helperContainer
= document
.createElement('div');
680 this.helperContainer
.classList
.add('xterm-helpers');
681 // TODO: This should probably be inserted once it's filled to prevent an additional layout
682 this.element
.appendChild(this.helperContainer
);
683 this.textarea
= document
.createElement('textarea');
684 this.textarea
.classList
.add('xterm-helper-textarea');
685 this.textarea
.setAttribute('autocorrect', 'off');
686 this.textarea
.setAttribute('autocapitalize', 'off');
687 this.textarea
.setAttribute('spellcheck', 'false');
688 this.textarea
.tabIndex
= 0;
689 this.textarea
.addEventListener('focus', function() {
690 self
.emit('focus', {terminal
: self
});
692 this.textarea
.addEventListener('blur', function() {
693 self
.emit('blur', {terminal
: self
});
695 this.helperContainer
.appendChild(this.textarea
);
697 this.compositionView
= document
.createElement('div');
698 this.compositionView
.classList
.add('composition-view');
699 this.compositionHelper
= new CompositionHelper(this.textarea
, this.compositionView
, this);
700 this.helperContainer
.appendChild(this.compositionView
);
702 this.charSizeStyleElement
= document
.createElement('style');
703 this.helperContainer
.appendChild(this.charSizeStyleElement
);
705 for (; i
< this.rows
; i
++) {
708 this.parent
.appendChild(this.element
);
710 this.charMeasure
= new CharMeasure(document
, this.helperContainer
);
711 this.charMeasure
.on('charsizechanged', function () {
712 self
.updateCharSizeStyles();
714 this.charMeasure
.measure();
716 this.viewport
= new Viewport(this, this.viewportElement
, this.viewportScrollArea
, this.charMeasure
);
717 this.renderer
= new Renderer(this);
718 this.selectionManager
= new SelectionManager(this, this.lines
, this.rowContainer
, this.charMeasure
);
719 this.selectionManager
.on('refresh', data
=> {
720 this.renderer
.refreshSelection(data
.start
, data
.end
);
722 this.selectionManager
.on('newselection', text
=> {
723 // If there's a new selection, put it into the textarea, focus and select it
724 // in order to register it as a selection on the OS. This event is fired
725 // only on Linux to enable middle click to paste selection.
726 this.textarea
.value
= text
;
727 this.textarea
.focus();
728 this.textarea
.select();
730 this.on('scroll', () => this.selectionManager
.refresh());
731 this.viewportElement
.addEventListener('scroll', () => this.selectionManager
.refresh());
733 // Setup loop that draws to screen
734 this.refresh(0, this.rows
- 1);
736 // Initialize global actions that
737 // need to be taken on the document.
741 * Automatic focus functionality.
742 * TODO: Default to `false` starting with xterm.js 3.0.
744 if (typeof focus
== 'undefined') {
745 let message
= 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
747 message
+= 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
748 message
+= 'it will default to `false`.';
750 console
.warn(message
);
758 on(this.element
, 'click', function() {
759 var selection
= document
.getSelection(),
760 collapsed
= selection
.isCollapsed
,
761 isRange
= typeof collapsed
== 'boolean' ? !collapsed
: selection
.type
== 'Range';
767 // Listen for mouse events and translate
768 // them into terminal mouse protocols.
772 * This event is emitted when terminal has completed opening.
781 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
782 * @param {string} addon The name of the addon to load
785 Terminal
.loadAddon = function(addon
, callback
) {
786 if (typeof exports
=== 'object' && typeof module
=== 'object') {
788 return require('./addons/' + addon
+ '/' + addon
);
789 } else if (typeof define
== 'function') {
791 return require(['./addons/' + addon
+ '/' + addon
], callback
);
793 console
.error('Cannot load a module without a CommonJS or RequireJS environment.');
799 * Updates the helper CSS class with any changes necessary after the terminal's
800 * character width has been changed.
802 Terminal
.prototype.updateCharSizeStyles = function() {
803 this.charSizeStyleElement
.textContent
=
804 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
805 `.xterm-normal-char{width:${this.charMeasure.width}px;}` +
806 `.xterm-rows > div{height:${this.charMeasure.height}px;}`;
811 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
812 * To better understand these
813 * the xterm code is very helpful:
815 * button.c, charproc.c, misc.c
816 * Relevant functions in xterm/button.c:
817 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
819 Terminal
.prototype.bindMouse = function() {
820 var el
= this.element
, self
= this, pressed
= 32;
822 // mouseup, mousedown, wheel
823 // left click: ^[[M 3<^[[M#3<
825 function sendButton(ev
) {
829 // get the xterm-style button
830 button
= getButton(ev
);
832 // get mouse coordinates
833 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
836 sendEvent(button
, pos
);
838 switch (ev
.overrideType
|| ev
.type
) {
843 // keep it at the left
844 // button, just in case.
855 // motion example of a left click:
856 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
857 function sendMove(ev
) {
861 pos
= getRawByteCoords(ev
, self
.rowContainer
, self
.charMeasure
, self
.cols
, self
.rows
);
864 // buttons marked as motions
865 // are incremented by 32
868 sendEvent(button
, pos
);
872 // position to characters
873 function encode(data
, ch
) {
874 if (!self
.utfMouse
) {
875 if (ch
=== 255) return data
.push(0);
876 if (ch
> 127) ch
= 127;
879 if (ch
=== 2047) return data
.push(0);
883 if (ch
> 2047) ch
= 2047;
884 data
.push(0xC0 | (ch
>> 6));
885 data
.push(0x80 | (ch
& 0x3F));
890 // send a mouse event:
891 // regular/utf8: ^[[M Cb Cx Cy
892 // urxvt: ^[[ Cb ; Cx ; Cy M
893 // sgr: ^[[ Cb ; Cx ; Cy M/m
894 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
895 // locator: CSI P e ; P b ; P r ; P c ; P p & w
896 function sendEvent(button
, pos
) {
897 // self.emit('mouse', {
903 if (self
.vt300Mouse
) {
905 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
909 var data
= C0
.ESC
+ '[24';
910 if (button
=== 0) data
+= '1';
911 else if (button
=== 1) data
+= '3';
912 else if (button
=== 2) data
+= '5';
913 else if (button
=== 3) return;
915 data
+= '~[' + pos
.x
+ ',' + pos
.y
+ ']\r';
920 if (self
.decLocator
) {
925 if (button
=== 0) button
= 2;
926 else if (button
=== 1) button
= 4;
927 else if (button
=== 2) button
= 6;
928 else if (button
=== 3) button
= 3;
929 self
.send(C0
.ESC
+ '['
932 + (button
=== 3 ? 4 : 0)
943 if (self
.urxvtMouse
) {
948 self
.send(C0
.ESC
+ '[' + button
+ ';' + pos
.x
+ ';' + pos
.y
+ 'M');
955 self
.send(C0
.ESC
+ '[<'
956 + (((button
& 3) === 3 ? button
& ~3 : button
) - 32)
961 + ((button
& 3) === 3 ? 'm' : 'M'));
967 encode(data
, button
);
971 self
.send(C0
.ESC
+ '[M' + String
.fromCharCode
.apply(String
, data
));
974 function getButton(ev
) {
987 // 1, and 2 - with 64 added
988 switch (ev
.overrideType
|| ev
.type
) {
990 button
= ev
.button
!= null
996 if (self
.browser
.isMSIE
) {
997 button
= button
=== 1 ? 0 : button
=== 4 ? 1 : button
;
1003 case 'DOMMouseScroll':
1004 button
= ev
.detail
< 0
1009 button
= ev
.wheelDeltaY
> 0
1015 // next three bits are the modifiers:
1016 // 4 = shift, 8 = meta, 16 = control
1017 shift
= ev
.shiftKey
? 4 : 0;
1018 meta
= ev
.metaKey
? 8 : 0;
1019 ctrl
= ev
.ctrlKey
? 16 : 0;
1020 mod
= shift
| meta
| ctrl
;
1023 if (self
.vt200Mouse
) {
1026 } else if (!self
.normalMouse
) {
1031 button
= (32 + (mod
<< 2)) + button
;
1036 on(el
, 'mousedown', function(ev
) {
1037 if (!self
.mouseEvents
) return;
1046 //if (self.vt200Mouse && !self.normalMouse) {
1047 if (self
.vt200Mouse
) {
1048 ev
.overrideType
= 'mouseup';
1050 return self
.cancel(ev
);
1054 if (self
.normalMouse
) on(self
.document
, 'mousemove', sendMove
);
1056 // x10 compatibility mode can't send button releases
1057 if (!self
.x10Mouse
) {
1058 on(self
.document
, 'mouseup', function up(ev
) {
1060 if (self
.normalMouse
) off(self
.document
, 'mousemove', sendMove
);
1061 off(self
.document
, 'mouseup', up
);
1062 return self
.cancel(ev
);
1066 return self
.cancel(ev
);
1069 //if (self.normalMouse) {
1070 // on(self.document, 'mousemove', sendMove);
1073 on(el
, 'wheel', function(ev
) {
1074 if (!self
.mouseEvents
) return;
1077 || self
.decLocator
) return;
1079 return self
.cancel(ev
);
1082 // allow wheel scrolling in
1083 // the shell for example
1084 on(el
, 'wheel', function(ev
) {
1085 if (self
.mouseEvents
) return;
1086 self
.viewport
.onWheel(ev
);
1087 return self
.cancel(ev
);
1092 * Destroys the terminal.
1094 Terminal
.prototype.destroy = function() {
1095 this.readable
= false;
1096 this.writable
= false;
1098 this.handler = function() {};
1099 this.write = function() {};
1100 if (this.element
&& this.element
.parentNode
) {
1101 this.element
.parentNode
.removeChild(this.element
);
1103 //this.emit('close');
1107 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1109 * @param {number} start The row to start from (between 0 and this.rows - 1).
1110 * @param {number} end The row to end at (between start and this.rows - 1).
1112 Terminal
.prototype.refresh = function(start
, end
) {
1113 if (this.renderer
) {
1114 this.renderer
.queueRefresh(start
, end
);
1119 * Queues linkification for the specified rows.
1120 * @param {number} start The row to start from (between 0 and this.rows - 1).
1121 * @param {number} end The row to end at (between start and this.rows - 1).
1123 Terminal
.prototype.queueLinkification = function(start
, end
) {
1124 if (this.linkifier
) {
1125 for (let i
= start
; i
<= end
; i
++) {
1126 this.linkifier
.linkifyRow(i
);
1132 * Display the cursor element
1134 Terminal
.prototype.showCursor = function() {
1135 if (!this.cursorState
) {
1136 this.cursorState
= 1;
1137 this.refresh(this.y
, this.y
);
1142 * Scroll the terminal down 1 row, creating a blank line.
1143 * @param {boolean} isWrapped Whether the new line is wrapped from the previous
1146 Terminal
.prototype.scroll = function(isWrapped
) {
1149 // Make room for the new row in lines
1150 if (this.lines
.length
=== this.lines
.maxLength
) {
1151 this.lines
.trimStart(1);
1153 if (this.ydisp
!== 0) {
1160 // TODO: Why is this done twice?
1161 if (!this.userScrolling
) {
1162 this.ydisp
= this.ybase
;
1166 row
= this.ybase
+ this.rows
- 1;
1168 // subtract the bottom scroll region
1169 row
-= this.rows
- 1 - this.scrollBottom
;
1171 if (row
=== this.lines
.length
) {
1172 // Optimization: pushing is faster than splicing when they amount to the same behavior
1173 this.lines
.push(this.blankLine(undefined, isWrapped
));
1176 this.lines
.splice(row
, 0, this.blankLine(undefined, isWrapped
));
1179 if (this.scrollTop
!== 0) {
1180 if (this.ybase
!== 0) {
1182 if (!this.userScrolling
) {
1183 this.ydisp
= this.ybase
;
1186 this.lines
.splice(this.ybase
+ this.scrollTop
, 1);
1190 this.updateRange(this.scrollTop
);
1191 this.updateRange(this.scrollBottom
);
1194 * This event is emitted whenever the terminal is scrolled.
1195 * The one parameter passed is the new y display position.
1199 this.emit('scroll', this.ydisp
);
1203 * Scroll the display of the terminal
1204 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1205 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1206 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1207 * viewport originally.
1209 Terminal
.prototype.scrollDisp = function(disp
, suppressScrollEvent
) {
1211 if (this.ydisp
=== 0) {
1214 this.userScrolling
= true;
1215 } else if (disp
+ this.ydisp
>= this.ybase
) {
1216 this.userScrolling
= false;
1221 if (this.ydisp
> this.ybase
) {
1222 this.ydisp
= this.ybase
;
1223 } else if (this.ydisp
< 0) {
1227 if (!suppressScrollEvent
) {
1228 this.emit('scroll', this.ydisp
);
1231 this.refresh(0, this.rows
- 1);
1235 * Scroll the display of the terminal by a number of pages.
1236 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1238 Terminal
.prototype.scrollPages = function(pageCount
) {
1239 this.scrollDisp(pageCount
* (this.rows
- 1));
1243 * Scrolls the display of the terminal to the top.
1245 Terminal
.prototype.scrollToTop = function() {
1246 this.scrollDisp(-this.ydisp
);
1250 * Scrolls the display of the terminal to the bottom.
1252 Terminal
.prototype.scrollToBottom = function() {
1253 this.scrollDisp(this.ybase
- this.ydisp
);
1257 * Writes text to the terminal.
1258 * @param {string} data The text to write to the terminal.
1260 Terminal
.prototype.write = function(data
) {
1261 this.writeBuffer
.push(data
);
1263 // Send XOFF to pause the pty process if the write buffer becomes too large so
1264 // xterm.js can catch up before more data is sent. This is necessary in order
1265 // to keep signals such as ^C responsive.
1266 if (this.options
.useFlowControl
&& !this.xoffSentToCatchUp
&& this.writeBuffer
.length
>= WRITE_BUFFER_PAUSE_THRESHOLD
) {
1267 // XOFF - stop pty pipe
1268 // XON will be triggered by emulator before processing data chunk
1270 this.xoffSentToCatchUp
= true;
1273 if (!this.writeInProgress
&& this.writeBuffer
.length
> 0) {
1274 // Kick off a write which will write all data in sequence recursively
1275 this.writeInProgress
= true;
1276 // Kick off an async innerWrite so more writes can come in while processing data
1278 setTimeout(function () {
1284 Terminal
.prototype.innerWrite = function() {
1285 var writeBatch
= this.writeBuffer
.splice(0, WRITE_BATCH_SIZE
);
1286 while (writeBatch
.length
> 0) {
1287 var data
= writeBatch
.shift();
1288 var l
= data
.length
, i
= 0, j
, cs
, ch
, code
, low
, ch_width
, row
;
1290 // If XOFF was sent in order to catch up with the pty process, resume it if
1291 // the writeBuffer is empty to allow more data to come in.
1292 if (this.xoffSentToCatchUp
&& writeBatch
.length
=== 0 && this.writeBuffer
.length
=== 0) {
1294 this.xoffSentToCatchUp
= false;
1297 this.refreshStart
= this.y
;
1298 this.refreshEnd
= this.y
;
1300 // HACK: Set the parser state based on it's state at the time of return.
1301 // This works around the bug #662 which saw the parser state reset in the
1302 // middle of parsing escape sequence in two chunks. For some reason the
1303 // state of the parser resets to 0 after exiting parser.parse. This change
1304 // just sets the state back based on the correct return statement.
1305 var state
= this.parser
.parse(data
);
1306 this.parser
.setState(state
);
1308 this.updateRange(this.y
);
1309 this.refresh(this.refreshStart
, this.refreshEnd
);
1311 if (this.writeBuffer
.length
> 0) {
1312 // Allow renderer to catch up before processing the next batch
1314 setTimeout(function () {
1318 this.writeInProgress
= false;
1323 * Writes text to the terminal, followed by a break line character (\n).
1324 * @param {string} data The text to write to the terminal.
1326 Terminal
.prototype.writeln = function(data
) {
1327 this.write(data
+ '\r\n');
1331 * DEPRECATED: only for backward compatibility. Please use attachCustomKeyEventHandler() instead.
1332 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1333 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1334 * the default action. The function returns whether the event should be processed by xterm.js.
1336 Terminal
.prototype.attachCustomKeydownHandler = function(customKeydownHandler
) {
1337 let message
= 'attachCustomKeydownHandler() is DEPRECATED and will be removed soon. Please use attachCustomKeyEventHandler() instead.';
1338 console
.warn(message
);
1339 this.attachCustomKeyEventHandler(customKeydownHandler
);
1343 * Attaches a custom key event handler which is run before keys are processed, giving consumers of
1344 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1346 * @param {function} customKeyEventHandler The custom KeyboardEvent handler to attach. This is a
1347 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1348 * the default action. The function returns whether the event should be processed by xterm.js.
1350 Terminal
.prototype.attachCustomKeyEventHandler = function(customKeyEventHandler
) {
1351 this.customKeyEventHandler
= customKeyEventHandler
;
1355 * Attaches a http(s) link handler, forcing web links to behave differently to
1356 * regular <a> tags. This will trigger a refresh as links potentially need to be
1357 * reconstructed. Calling this with null will remove the handler.
1358 * @param {LinkMatcherHandler} handler The handler callback function.
1360 Terminal
.prototype.setHypertextLinkHandler = function(handler
) {
1361 if (!this.linkifier
) {
1362 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1364 this.linkifier
.setHypertextLinkHandler(handler
);
1365 // Refresh to force links to refresh
1366 this.refresh(0, this.rows
- 1);
1370 * Attaches a validation callback for hypertext links. This is useful to use
1371 * validation logic or to do something with the link's element and url.
1372 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1373 * be cleared with null.
1375 Terminal
.prototype.setHypertextValidationCallback = function(callback
) {
1376 if (!this.linkifier
) {
1377 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1379 this.linkifier
.setHypertextValidationCallback(callback
);
1380 // Refresh to force links to refresh
1381 this.refresh(0, this.rows
- 1);
1385 * Registers a link matcher, allowing custom link patterns to be matched and
1387 * @param {RegExp} regex The regular expression to search for, specifically
1388 * this searches the textContent of the rows. You will want to use \s to match
1389 * a space ' ' character for example.
1390 * @param {LinkMatcherHandler} handler The callback when the link is called.
1391 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1392 * @return {number} The ID of the new matcher, this can be used to deregister.
1394 Terminal
.prototype.registerLinkMatcher = function(regex
, handler
, options
) {
1395 if (this.linkifier
) {
1396 var matcherId
= this.linkifier
.registerLinkMatcher(regex
, handler
, options
);
1397 this.refresh(0, this.rows
- 1);
1403 * Deregisters a link matcher if it has been registered.
1404 * @param {number} matcherId The link matcher's ID (returned after register)
1406 Terminal
.prototype.deregisterLinkMatcher = function(matcherId
) {
1407 if (this.linkifier
) {
1408 if (this.linkifier
.deregisterLinkMatcher(matcherId
)) {
1409 this.refresh(0, this.rows
- 1);
1415 * Gets whether the terminal has an active selection.
1417 Terminal
.prototype.hasSelection = function() {
1418 return this.selectionManager
.hasSelection
;
1422 * Gets the terminal's current selection, this is useful for implementing copy
1423 * behavior outside of xterm.js.
1425 Terminal
.prototype.getSelection = function() {
1426 return this.selectionManager
.selectionText
;
1430 * Clears the current terminal selection.
1432 Terminal
.prototype.clearSelection = function() {
1433 this.selectionManager
.clearSelection();
1437 * Selects all text within the terminal.
1439 Terminal
.prototype.selectAll = function() {
1440 this.selectionManager
.selectAll();
1444 * Handle a keydown event
1446 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1447 * @param {KeyboardEvent} ev The keydown event to be handled.
1449 Terminal
.prototype.keyDown = function(ev
) {
1450 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1454 this.restartCursorBlinking();
1456 if (!this.compositionHelper
.keydown
.bind(this.compositionHelper
)(ev
)) {
1457 if (this.ybase
!== this.ydisp
) {
1458 this.scrollToBottom();
1464 var result
= this.evaluateKeyEscapeSequence(ev
);
1466 if (result
.key
=== C0
.DC3
) { // XOFF
1467 this.writeStopped
= true;
1468 } else if (result
.key
=== C0
.DC1
) { // XON
1469 this.writeStopped
= false;
1472 if (result
.scrollDisp
) {
1473 this.scrollDisp(result
.scrollDisp
);
1474 return this.cancel(ev
, true);
1477 if (isThirdLevelShift(this, ev
)) {
1481 if (result
.cancel
) {
1482 // The event is canceled at the end already, is this necessary?
1483 this.cancel(ev
, true);
1490 this.emit('keydown', ev
);
1491 this.emit('key', result
.key
, ev
);
1493 this.handler(result
.key
);
1495 return this.cancel(ev
, true);
1499 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1500 * returned value is the new key code to pass to the PTY.
1502 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1503 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1505 Terminal
.prototype.evaluateKeyEscapeSequence = function(ev
) {
1507 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1508 // canceled at the end of keyDown
1510 // The new key even to emit
1512 // The number of characters to scroll, if this is defined it will cancel the event
1513 scrollDisp
: undefined
1515 var modifiers
= ev
.shiftKey
<< 0 | ev
.altKey
<< 1 | ev
.ctrlKey
<< 2 | ev
.metaKey
<< 3;
1516 switch (ev
.keyCode
) {
1520 result
.key
= C0
.BS
; // ^H
1523 result
.key
= C0
.DEL
; // ^?
1528 result
.key
= C0
.ESC
+ '[Z';
1532 result
.cancel
= true;
1537 result
.cancel
= true;
1541 result
.key
= C0
.ESC
;
1542 result
.cancel
= true;
1547 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'D';
1548 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1549 // http://unix.stackexchange.com/a/108106
1550 // macOS uses different escape sequences than linux
1551 if (result
.key
== C0
.ESC
+ '[1;3D') {
1552 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'b' : C0
.ESC
+ '[1;5D';
1554 } else if (this.applicationCursor
) {
1555 result
.key
= C0
.ESC
+ 'OD';
1557 result
.key
= C0
.ESC
+ '[D';
1563 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'C';
1564 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1565 // http://unix.stackexchange.com/a/108106
1566 // macOS uses different escape sequences than linux
1567 if (result
.key
== C0
.ESC
+ '[1;3C') {
1568 result
.key
= (this.browser
.isMac
) ? C0
.ESC
+ 'f' : C0
.ESC
+ '[1;5C';
1570 } else if (this.applicationCursor
) {
1571 result
.key
= C0
.ESC
+ 'OC';
1573 result
.key
= C0
.ESC
+ '[C';
1579 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'A';
1580 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1581 // http://unix.stackexchange.com/a/108106
1582 if (result
.key
== C0
.ESC
+ '[1;3A') {
1583 result
.key
= C0
.ESC
+ '[1;5A';
1585 } else if (this.applicationCursor
) {
1586 result
.key
= C0
.ESC
+ 'OA';
1588 result
.key
= C0
.ESC
+ '[A';
1594 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'B';
1595 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1596 // http://unix.stackexchange.com/a/108106
1597 if (result
.key
== C0
.ESC
+ '[1;3B') {
1598 result
.key
= C0
.ESC
+ '[1;5B';
1600 } else if (this.applicationCursor
) {
1601 result
.key
= C0
.ESC
+ 'OB';
1603 result
.key
= C0
.ESC
+ '[B';
1608 if (!ev
.shiftKey
&& !ev
.ctrlKey
) {
1609 // <Ctrl> or <Shift> + <Insert> are used to
1610 // copy-paste on some systems.
1611 result
.key
= C0
.ESC
+ '[2~';
1617 result
.key
= C0
.ESC
+ '[3;' + (modifiers
+ 1) + '~';
1619 result
.key
= C0
.ESC
+ '[3~';
1625 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'H';
1626 else if (this.applicationCursor
)
1627 result
.key
= C0
.ESC
+ 'OH';
1629 result
.key
= C0
.ESC
+ '[H';
1634 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'F';
1635 else if (this.applicationCursor
)
1636 result
.key
= C0
.ESC
+ 'OF';
1638 result
.key
= C0
.ESC
+ '[F';
1643 result
.scrollDisp
= -(this.rows
- 1);
1645 result
.key
= C0
.ESC
+ '[5~';
1651 result
.scrollDisp
= this.rows
- 1;
1653 result
.key
= C0
.ESC
+ '[6~';
1659 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'P';
1661 result
.key
= C0
.ESC
+ 'OP';
1666 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'Q';
1668 result
.key
= C0
.ESC
+ 'OQ';
1673 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'R';
1675 result
.key
= C0
.ESC
+ 'OR';
1680 result
.key
= C0
.ESC
+ '[1;' + (modifiers
+ 1) + 'S';
1682 result
.key
= C0
.ESC
+ 'OS';
1687 result
.key
= C0
.ESC
+ '[15;' + (modifiers
+ 1) + '~';
1689 result
.key
= C0
.ESC
+ '[15~';
1694 result
.key
= C0
.ESC
+ '[17;' + (modifiers
+ 1) + '~';
1696 result
.key
= C0
.ESC
+ '[17~';
1701 result
.key
= C0
.ESC
+ '[18;' + (modifiers
+ 1) + '~';
1703 result
.key
= C0
.ESC
+ '[18~';
1708 result
.key
= C0
.ESC
+ '[19;' + (modifiers
+ 1) + '~';
1710 result
.key
= C0
.ESC
+ '[19~';
1715 result
.key
= C0
.ESC
+ '[20;' + (modifiers
+ 1) + '~';
1717 result
.key
= C0
.ESC
+ '[20~';
1722 result
.key
= C0
.ESC
+ '[21;' + (modifiers
+ 1) + '~';
1724 result
.key
= C0
.ESC
+ '[21~';
1729 result
.key
= C0
.ESC
+ '[23;' + (modifiers
+ 1) + '~';
1731 result
.key
= C0
.ESC
+ '[23~';
1736 result
.key
= C0
.ESC
+ '[24;' + (modifiers
+ 1) + '~';
1738 result
.key
= C0
.ESC
+ '[24~';
1743 if (ev
.ctrlKey
&& !ev
.shiftKey
&& !ev
.altKey
&& !ev
.metaKey
) {
1744 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1745 result
.key
= String
.fromCharCode(ev
.keyCode
- 64);
1746 } else if (ev
.keyCode
=== 32) {
1748 result
.key
= String
.fromCharCode(0);
1749 } else if (ev
.keyCode
>= 51 && ev
.keyCode
<= 55) {
1750 // escape, file sep, group sep, record sep, unit sep
1751 result
.key
= String
.fromCharCode(ev
.keyCode
- 51 + 27);
1752 } else if (ev
.keyCode
=== 56) {
1754 result
.key
= String
.fromCharCode(127);
1755 } else if (ev
.keyCode
=== 219) {
1756 // ^[ - Control Sequence Introducer (CSI)
1757 result
.key
= String
.fromCharCode(27);
1758 } else if (ev
.keyCode
=== 220) {
1759 // ^\ - String Terminator (ST)
1760 result
.key
= String
.fromCharCode(28);
1761 } else if (ev
.keyCode
=== 221) {
1762 // ^] - Operating System Command (OSC)
1763 result
.key
= String
.fromCharCode(29);
1765 } else if (!this.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) {
1766 // On Mac this is a third level shift. Use <Esc> instead.
1767 if (ev
.keyCode
>= 65 && ev
.keyCode
<= 90) {
1768 result
.key
= C0
.ESC
+ String
.fromCharCode(ev
.keyCode
+ 32);
1769 } else if (ev
.keyCode
=== 192) {
1770 result
.key
= C0
.ESC
+ '`';
1771 } else if (ev
.keyCode
>= 48 && ev
.keyCode
<= 57) {
1772 result
.key
= C0
.ESC
+ (ev
.keyCode
- 48);
1774 } else if (this.browser
.isMac
&& !ev
.altKey
&& !ev
.ctrlKey
&& ev
.metaKey
) {
1775 if (ev
.keyCode
=== 65) { // cmd + a
1786 * Set the G level of the terminal
1789 Terminal
.prototype.setgLevel = function(g
) {
1791 this.charset
= this.charsets
[g
];
1795 * Set the charset for the given G level of the terminal
1799 Terminal
.prototype.setgCharset = function(g
, charset
) {
1800 this.charsets
[g
] = charset
;
1801 if (this.glevel
=== g
) {
1802 this.charset
= charset
;
1807 * Handle a keypress event.
1809 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1810 * @param {KeyboardEvent} ev The keypress event to be handled.
1812 Terminal
.prototype.keyPress = function(ev
) {
1815 if (this.customKeyEventHandler
&& this.customKeyEventHandler(ev
) === false) {
1823 } else if (ev
.which
== null) {
1825 } else if (ev
.which
!== 0 && ev
.charCode
!== 0) {
1832 (ev
.altKey
|| ev
.ctrlKey
|| ev
.metaKey
) && !isThirdLevelShift(this, ev
)
1837 key
= String
.fromCharCode(key
);
1839 this.emit('keypress', key
, ev
);
1840 this.emit('key', key
, ev
);
1848 * Send data for handling to the terminal
1849 * @param {string} data
1851 Terminal
.prototype.send = function(data
) {
1855 setTimeout(function() {
1856 self
.handler(self
.queue
);
1866 * Note: We could do sweet things with webaudio here
1868 Terminal
.prototype.bell = function() {
1869 if (!this.visualBell
) return;
1871 this.element
.style
.borderColor
= 'white';
1872 setTimeout(function() {
1873 self
.element
.style
.borderColor
= '';
1875 if (this.popOnBell
) this.focus();
1879 * Log the current state to the console.
1881 Terminal
.prototype.log = function() {
1882 if (!this.debug
) return;
1883 if (!this.context
.console
|| !this.context
.console
.log
) return;
1884 var args
= Array
.prototype.slice
.call(arguments
);
1885 this.context
.console
.log
.apply(this.context
.console
, args
);
1889 * Log the current state as error to the console.
1891 Terminal
.prototype.error = function() {
1892 if (!this.debug
) return;
1893 if (!this.context
.console
|| !this.context
.console
.error
) return;
1894 var args
= Array
.prototype.slice
.call(arguments
);
1895 this.context
.console
.error
.apply(this.context
.console
, args
);
1899 * Resizes the terminal.
1901 * @param {number} x The number of columns to resize to.
1902 * @param {number} y The number of rows to resize to.
1904 Terminal
.prototype.resize = function(x
, y
) {
1905 if (isNaN(x
) || isNaN(y
)) {
1916 if (x
=== this.cols
&& y
=== this.rows
) {
1926 ch
= [this.defAttr
, ' ', 1]; // does xterm use the default attr?
1927 i
= this.lines
.length
;
1929 while (this.lines
.get(i
).length
< x
) {
1930 this.lines
.get(i
).push(ch
);
1936 this.setupStops(this.cols
);
1944 // y is rows, not this.y
1945 if (this.lines
.length
< y
+ this.ybase
) {
1946 if (this.ybase
> 0 && this.lines
.length
<= this.ybase
+ this.y
+ addToY
+ 1) {
1947 // There is room above the buffer and there are no empty elements below the line,
1951 if (this.ydisp
> 0) {
1952 // Viewport is at the top of the buffer, must increase downwards
1956 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1957 // are blank lines after the cursor
1958 this.lines
.push(this.blankLine());
1961 if (this.children
.length
< y
) {
1967 if (this.lines
.length
> y
+ this.ybase
) {
1968 if (this.lines
.length
> this.ybase
+ this.y
+ 1) {
1969 // The line is a blank line below the cursor, remove it
1972 // The line is the cursor, scroll down
1977 if (this.children
.length
> y
) {
1978 el
= this.children
.shift();
1980 el
.parentNode
.removeChild(el
);
1986 // Make sure that the cursor stays on screen
1999 this.scrollBottom
= y
- 1;
2001 this.charMeasure
.measure();
2003 this.refresh(0, this.rows
- 1);
2007 this.geometry
= [this.cols
, this.rows
];
2008 this.emit('resize', {terminal
: this, cols
: x
, rows
: y
});
2012 * Updates the range of rows to refresh
2013 * @param {number} y The number of rows to refresh next.
2015 Terminal
.prototype.updateRange = function(y
) {
2016 if (y
< this.refreshStart
) this.refreshStart
= y
;
2017 if (y
> this.refreshEnd
) this.refreshEnd
= y
;
2018 // if (y > this.refreshEnd) {
2019 // this.refreshEnd = y;
2020 // if (y > this.rows - 1) {
2021 // this.refreshEnd = this.rows - 1;
2027 * Set the range of refreshing to the maximum value
2029 Terminal
.prototype.maxRange = function() {
2030 this.refreshStart
= 0;
2031 this.refreshEnd
= this.rows
- 1;
2037 * Setup the tab stops.
2040 Terminal
.prototype.setupStops = function(i
) {
2042 if (!this.tabs
[i
]) {
2043 i
= this.prevStop(i
);
2050 for (; i
< this.cols
; i
+= this.getOption('tabStopWidth')) {
2051 this.tabs
[i
] = true;
2057 * Move the cursor to the previous tab stop from the given position (default is current).
2058 * @param {number} x The position to move the cursor to the previous tab stop.
2060 Terminal
.prototype.prevStop = function(x
) {
2061 if (x
== null) x
= this.x
;
2062 while (!this.tabs
[--x
] && x
> 0);
2063 return x
>= this.cols
2070 * Move the cursor one tab stop forward from the given position (default is current).
2071 * @param {number} x The position to move the cursor one tab stop forward.
2073 Terminal
.prototype.nextStop = function(x
) {
2074 if (x
== null) x
= this.x
;
2075 while (!this.tabs
[++x
] && x
< this.cols
);
2076 return x
>= this.cols
2083 * Erase in the identified line everything from "x" to the end of the line (right).
2084 * @param {number} x The column from which to start erasing to the end of the line.
2085 * @param {number} y The line in which to operate.
2087 Terminal
.prototype.eraseRight = function(x
, y
) {
2088 var line
= this.lines
.get(this.ybase
+ y
);
2092 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2093 for (; x
< this.cols
; x
++) {
2096 this.updateRange(y
);
2102 * Erase in the identified line everything from "x" to the start of the line (left).
2103 * @param {number} x The column from which to start erasing to the start of the line.
2104 * @param {number} y The line in which to operate.
2106 Terminal
.prototype.eraseLeft = function(x
, y
) {
2107 var line
= this.lines
.get(this.ybase
+ y
);
2111 var ch
= [this.eraseAttr(), ' ', 1]; // xterm
2116 this.updateRange(y
);
2120 * Clears the entire buffer, making the prompt line the new first line.
2122 Terminal
.prototype.clear = function() {
2123 if (this.ybase
=== 0 && this.y
=== 0) {
2124 // Don't clear if it's already clear
2127 this.lines
.set(0, this.lines
.get(this.ybase
+ this.y
));
2128 this.lines
.length
= 1;
2132 for (var i
= 1; i
< this.rows
; i
++) {
2133 this.lines
.push(this.blankLine());
2135 this.refresh(0, this.rows
- 1);
2136 this.emit('scroll', this.ydisp
);
2140 * Erase all content in the given line
2141 * @param {number} y The line to erase all of its contents.
2143 Terminal
.prototype.eraseLine = function(y
) {
2144 this.eraseRight(0, y
);
2149 * Return the data array of a blank line
2150 * @param {number} cur First bunch of data for each "blank" character.
2151 * @param {boolean} isWrapped Whether the new line is wrapped from the previous line.
2153 Terminal
.prototype.blankLine = function(cur
, isWrapped
) {
2158 var ch
= [attr
, ' ', 1] // width defaults to 1 halfwidth character
2162 // TODO: It is not ideal that this is a property on an array, a buffer line
2163 // class should be added that will hold this data and other useful functions.
2165 line
.isWrapped
= isWrapped
;
2168 for (; i
< this.cols
; i
++) {
2177 * If cur return the back color xterm feature attribute. Else return defAttr.
2178 * @param {object} cur
2180 Terminal
.prototype.ch = function(cur
) {
2182 ? [this.eraseAttr(), ' ', 1]
2183 : [this.defAttr
, ' ', 1];
2188 * Evaluate if the current erminal is the given argument.
2189 * @param {object} term The terminal to evaluate
2191 Terminal
.prototype.is = function(term
) {
2192 var name
= this.termName
;
2193 return (name
+ '').indexOf(term
) === 0;
2198 * Emit the 'data' event and populate the given data.
2199 * @param {string} data The data to populate in the event.
2201 Terminal
.prototype.handler = function(data
) {
2202 // Prevents all events to pty process if stdin is disabled
2203 if (this.options
.disableStdin
) {
2207 // Input is being sent to the terminal, the terminal should focus the prompt.
2208 if (this.ybase
!== this.ydisp
) {
2209 this.scrollToBottom();
2211 this.emit('data', data
);
2216 * Emit the 'title' event and populate the given title.
2217 * @param {string} title The title to populate in the event.
2219 Terminal
.prototype.handleTitle = function(title
) {
2221 * This event is emitted when the title of the terminal is changed
2222 * from inside the terminal. The parameter is the new title.
2226 this.emit('title', title
);
2235 * ESC D Index (IND is 0x84).
2237 Terminal
.prototype.index = function() {
2239 if (this.y
> this.scrollBottom
) {
2243 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2244 if (this.x
>= this.cols
) {
2251 * ESC M Reverse Index (RI is 0x8d).
2253 * Move the cursor up one row, inserting a new blank line if necessary.
2255 Terminal
.prototype.reverseIndex = function() {
2257 if (this.y
=== this.scrollTop
) {
2258 // possibly move the code below to term.reverseScroll();
2259 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2260 // blankLine(true) is xterm/linux behavior
2261 this.lines
.shiftElements(this.y
+ this.ybase
, this.rows
- 1, 1);
2262 this.lines
.set(this.y
+ this.ybase
, this.blankLine(true));
2263 this.updateRange(this.scrollTop
);
2264 this.updateRange(this.scrollBottom
);
2272 * ESC c Full Reset (RIS).
2274 Terminal
.prototype.reset = function() {
2275 this.options
.rows
= this.rows
;
2276 this.options
.cols
= this.cols
;
2277 var customKeyEventHandler
= this.customKeyEventHandler
;
2278 var cursorBlinkInterval
= this.cursorBlinkInterval
;
2279 Terminal
.call(this, this.options
);
2280 this.customKeyEventHandler
= customKeyEventHandler
;
2281 this.cursorBlinkInterval
= cursorBlinkInterval
;
2282 this.refresh(0, this.rows
- 1);
2283 this.viewport
.syncScrollArea();
2288 * ESC H Tab Set (HTS is 0x88).
2290 Terminal
.prototype.tabSet = function() {
2291 this.tabs
[this.x
] = true;
2298 function on(el
, type
, handler
, capture
) {
2299 if (!Array
.isArray(el
)) {
2302 el
.forEach(function (element
) {
2303 element
.addEventListener(type
, handler
, capture
|| false);
2307 function off(el
, type
, handler
, capture
) {
2308 el
.removeEventListener(type
, handler
, capture
|| false);
2311 function cancel(ev
, force
) {
2312 if (!this.cancelEvents
&& !force
) {
2315 ev
.preventDefault();
2316 ev
.stopPropagation();
2320 function inherits(child
, parent
) {
2322 this.constructor = child
;
2324 f
.prototype = parent
.prototype;
2325 child
.prototype = new f
;
2328 function indexOf(obj
, el
) {
2331 if (obj
[i
] === el
) return i
;
2336 function isThirdLevelShift(term
, ev
) {
2338 (term
.browser
.isMac
&& ev
.altKey
&& !ev
.ctrlKey
&& !ev
.metaKey
) ||
2339 (term
.browser
.isMSWindows
&& ev
.altKey
&& ev
.ctrlKey
&& !ev
.metaKey
);
2341 if (ev
.type
== 'keypress') {
2342 return thirdLevelKey
;
2345 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2346 return thirdLevelKey
&& (!ev
.keyCode
|| ev
.keyCode
> 47);
2349 // Expose to InputHandler (temporary)
2350 Terminal
.prototype.matchColor
= matchColor
;
2352 function matchColor(r1
, g1
, b1
) {
2353 var hash
= (r1
<< 16) | (g1
<< 8) | b1
;
2355 if (matchColor
._cache
[hash
] != null) {
2356 return matchColor
._cache
[hash
];
2359 var ldiff
= Infinity
2368 for (; i
< Terminal
.vcolors
.length
; i
++) {
2369 c
= Terminal
.vcolors
[i
];
2374 diff
= matchColor
.distance(r1
, g1
, b1
, r2
, g2
, b2
);
2387 return matchColor
._cache
[hash
] = li
;
2390 matchColor
._cache
= {};
2392 // http://stackoverflow.com/questions/1633828
2393 matchColor
.distance = function(r1
, g1
, b1
, r2
, g2
, b2
) {
2394 return Math
.pow(30 * (r1
- r2
), 2)
2395 + Math
.pow(59 * (g1
- g2
), 2)
2396 + Math
.pow(11 * (b1
- b2
), 2);
2399 function each(obj
, iter
, con
) {
2400 if (obj
.forEach
) return obj
.forEach(iter
, con
);
2401 for (var i
= 0; i
< obj
.length
; i
++) {
2402 iter
.call(con
, obj
[i
], i
, obj
);
2406 function wasMondifierKeyOnlyEvent(ev
) {
2407 return ev
.keyCode
=== 16 || // Shift
2408 ev
.keyCode
=== 17 || // Ctrl
2409 ev
.keyCode
=== 18; // Alt
2412 function keys(obj
) {
2413 if (Object
.keys
) return Object
.keys(obj
);
2416 if (Object
.prototype.hasOwnProperty
.call(obj
, key
)) {
2427 Terminal
.EventEmitter
= EventEmitter
;
2428 Terminal
.inherits
= inherits
;
2431 * Adds an event listener to the terminal.
2433 * @param {string} event The name of the event. TODO: Document all event types
2434 * @param {function} callback The function to call when the event is triggered.
2438 Terminal
.cancel
= cancel
;
2440 module
.exports
= Terminal
;