]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/xterm.js
Merge remote-tracking branch 'origin/master' into 553_find_api
[mirror_xterm.js.git] / src / xterm.js
1 /**
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
9 * other features.
10 * @license MIT
11 */
12
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 { SearchHelper } from './SearchHelper';
25 import { CharMeasure } from './utils/CharMeasure';
26 import * as Browser from './utils/Browser';
27 import * as Mouse from './utils/Mouse';
28 import { CHARSETS } from './Charsets';
29 import { getRawByteCoords } from './utils/Mouse';
30
31 /**
32 * Terminal Emulation References:
33 * http://vt100.net/
34 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
35 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
36 * http://invisible-island.net/vttest/
37 * http://www.inwap.com/pdp10/ansicode.txt
38 * http://linux.die.net/man/4/console_codes
39 * http://linux.die.net/man/7/urxvt
40 */
41
42 // Let it work inside Node.js for automated testing purposes.
43 var document = (typeof window != 'undefined') ? window.document : null;
44
45 /**
46 * The amount of write requests to queue before sending an XOFF signal to the
47 * pty process. This number must be small in order for ^C and similar sequences
48 * to be responsive.
49 */
50 var WRITE_BUFFER_PAUSE_THRESHOLD = 5;
51
52 /**
53 * The number of writes to perform in a single batch before allowing the
54 * renderer to catch up with a 0ms setTimeout.
55 */
56 var WRITE_BATCH_SIZE = 300;
57
58 /**
59 * The time between cursor blinks. This is driven by JS rather than a CSS
60 * animation due to a bug in Chromium that causes it to use excessive CPU time.
61 * See https://github.com/Microsoft/vscode/issues/22900
62 */
63 var CURSOR_BLINK_INTERVAL = 600;
64
65 /**
66 * Terminal
67 */
68
69 /**
70 * Creates a new `Terminal` object.
71 *
72 * @param {object} options An object containing a set of options, the available options are:
73 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
74 * - `cols` (number): The number of columns of the terminal (horizontal size)
75 * - `rows` (number): The number of rows of the terminal (vertical size)
76 *
77 * @public
78 * @class Xterm Xterm
79 * @alias module:xterm/src/xterm
80 */
81 function Terminal(options) {
82 var self = this;
83
84 if (!(this instanceof Terminal)) {
85 return new Terminal(arguments[0], arguments[1], arguments[2]);
86 }
87
88 self.browser = Browser;
89 self.cancel = Terminal.cancel;
90
91 EventEmitter.call(this);
92
93 if (typeof options === 'number') {
94 options = {
95 cols: arguments[0],
96 rows: arguments[1],
97 handler: arguments[2]
98 };
99 }
100
101 options = options || {};
102
103
104 Object.keys(Terminal.defaults).forEach(function(key) {
105 if (options[key] == null) {
106 options[key] = Terminal.options[key];
107
108 if (Terminal[key] !== Terminal.defaults[key]) {
109 options[key] = Terminal[key];
110 }
111 }
112 self[key] = options[key];
113 });
114
115 if (options.colors.length === 8) {
116 options.colors = options.colors.concat(Terminal._colors.slice(8));
117 } else if (options.colors.length === 16) {
118 options.colors = options.colors.concat(Terminal._colors.slice(16));
119 } else if (options.colors.length === 10) {
120 options.colors = options.colors.slice(0, -2).concat(
121 Terminal._colors.slice(8, -2), options.colors.slice(-2));
122 } else if (options.colors.length === 18) {
123 options.colors = options.colors.concat(
124 Terminal._colors.slice(16, -2), options.colors.slice(-2));
125 }
126 this.colors = options.colors;
127
128 this.options = options;
129
130 // this.context = options.context || window;
131 // this.document = options.document || document;
132 this.parent = options.body || options.parent || (
133 document ? document.getElementsByTagName('body')[0] : null
134 );
135
136 this.cols = options.cols || options.geometry[0];
137 this.rows = options.rows || options.geometry[1];
138 this.geometry = [this.cols, this.rows];
139
140 if (options.handler) {
141 this.on('data', options.handler);
142 }
143
144 /**
145 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
146 * buffer
147 */
148 this.ybase = 0;
149
150 /**
151 * The scroll position of the viewport
152 */
153 this.ydisp = 0;
154
155 /**
156 * The cursor's x position after ybase
157 */
158 this.x = 0;
159
160 /**
161 * The cursor's y position after ybase
162 */
163 this.y = 0;
164
165 this.cursorState = 0;
166 this.cursorHidden = false;
167 this.convertEol;
168 this.queue = '';
169 this.scrollTop = 0;
170 this.scrollBottom = this.rows - 1;
171 this.customKeydownHandler = null;
172 this.cursorBlinkInterval = null;
173
174 // modes
175 this.applicationKeypad = false;
176 this.applicationCursor = false;
177 this.originMode = false;
178 this.insertMode = false;
179 this.wraparoundMode = true; // defaults: xterm - true, vt100 - false
180 this.normal = null;
181
182 // charset
183 this.charset = null;
184 this.gcharset = null;
185 this.glevel = 0;
186 this.charsets = [null];
187
188 // mouse properties
189 this.decLocator;
190 this.x10Mouse;
191 this.vt200Mouse;
192 this.vt300Mouse;
193 this.normalMouse;
194 this.mouseEvents;
195 this.sendFocus;
196 this.utfMouse;
197 this.sgrMouse;
198 this.urxvtMouse;
199
200 // misc
201 this.element;
202 this.children;
203 this.refreshStart;
204 this.refreshEnd;
205 this.savedX;
206 this.savedY;
207 this.savedCols;
208
209 // stream
210 this.readable = true;
211 this.writable = true;
212
213 this.defAttr = (0 << 18) | (257 << 9) | (256 << 0);
214 this.curAttr = this.defAttr;
215
216 this.params = [];
217 this.currentParam = 0;
218 this.prefix = '';
219 this.postfix = '';
220
221 this.inputHandler = new InputHandler(this);
222 this.parser = new Parser(this.inputHandler, this);
223 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
224 this.renderer = this.renderer || null;
225 this.selectionManager = this.selectionManager || null;
226 this.linkifier = this.linkifier || new Linkifier();
227 this.searchHelper = this.searchHelper || null;
228
229 // user input states
230 this.writeBuffer = [];
231 this.writeInProgress = false;
232
233 /**
234 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
235 * This is a distinct state from writeStopped so that if the user requested
236 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
237 * below threshold.
238 */
239 this.xoffSentToCatchUp = false;
240
241 /** Whether writing has been stopped as a result of XOFF */
242 this.writeStopped = false;
243
244 // leftover surrogate high from previous write invocation
245 this.surrogate_high = '';
246
247 /**
248 * An array of all lines in the entire buffer, including the prompt. The lines are array of
249 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
250 */
251 this.lines = new CircularList(this.scrollback);
252 var i = this.rows;
253 while (i--) {
254 this.lines.push(this.blankLine());
255 }
256 // Ensure the selection manager has the correct buffer
257 if (this.selectionManager) {
258 this.selectionManager.setBuffer(this.lines);
259 }
260
261 this.tabs;
262 this.setupStops();
263
264 // Store if user went browsing history in scrollback
265 this.userScrolling = false;
266 }
267
268 inherits(Terminal, EventEmitter);
269
270 /**
271 * back_color_erase feature for xterm.
272 */
273 Terminal.prototype.eraseAttr = function() {
274 // if (this.is('screen')) return this.defAttr;
275 return (this.defAttr & ~0x1ff) | (this.curAttr & 0x1ff);
276 };
277
278 /**
279 * Colors
280 */
281
282 // Colors 0-15
283 Terminal.tangoColors = [
284 // dark:
285 '#2e3436',
286 '#cc0000',
287 '#4e9a06',
288 '#c4a000',
289 '#3465a4',
290 '#75507b',
291 '#06989a',
292 '#d3d7cf',
293 // bright:
294 '#555753',
295 '#ef2929',
296 '#8ae234',
297 '#fce94f',
298 '#729fcf',
299 '#ad7fa8',
300 '#34e2e2',
301 '#eeeeec'
302 ];
303
304 // Colors 0-15 + 16-255
305 // Much thanks to TooTallNate for writing this.
306 Terminal.colors = (function() {
307 var colors = Terminal.tangoColors.slice()
308 , r = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
309 , i;
310
311 // 16-231
312 i = 0;
313 for (; i < 216; i++) {
314 out(r[(i / 36) % 6 | 0], r[(i / 6) % 6 | 0], r[i % 6]);
315 }
316
317 // 232-255 (grey)
318 i = 0;
319 for (; i < 24; i++) {
320 r = 8 + i * 10;
321 out(r, r, r);
322 }
323
324 function out(r, g, b) {
325 colors.push('#' + hex(r) + hex(g) + hex(b));
326 }
327
328 function hex(c) {
329 c = c.toString(16);
330 return c.length < 2 ? '0' + c : c;
331 }
332
333 return colors;
334 })();
335
336 Terminal._colors = Terminal.colors.slice();
337
338 Terminal.vcolors = (function() {
339 var out = []
340 , colors = Terminal.colors
341 , i = 0
342 , color;
343
344 for (; i < 256; i++) {
345 color = parseInt(colors[i].substring(1), 16);
346 out.push([
347 (color >> 16) & 0xff,
348 (color >> 8) & 0xff,
349 color & 0xff
350 ]);
351 }
352
353 return out;
354 })();
355
356 /**
357 * Options
358 */
359
360 Terminal.defaults = {
361 colors: Terminal.colors,
362 theme: 'default',
363 convertEol: false,
364 termName: 'xterm',
365 geometry: [80, 24],
366 cursorBlink: false,
367 cursorStyle: 'block',
368 visualBell: false,
369 popOnBell: false,
370 scrollback: 1000,
371 screenKeys: false,
372 debug: false,
373 cancelEvents: false,
374 disableStdin: false,
375 useFlowControl: false,
376 tabStopWidth: 8
377 // programFeatures: false,
378 // focusKeys: false,
379 };
380
381 Terminal.options = {};
382
383 Terminal.focus = null;
384
385 each(keys(Terminal.defaults), function(key) {
386 Terminal[key] = Terminal.defaults[key];
387 Terminal.options[key] = Terminal.defaults[key];
388 });
389
390 /**
391 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
392 */
393 Terminal.prototype.focus = function() {
394 return this.textarea.focus();
395 };
396
397 /**
398 * Retrieves an option's value from the terminal.
399 * @param {string} key The option key.
400 */
401 Terminal.prototype.getOption = function(key, value) {
402 if (!(key in Terminal.defaults)) {
403 throw new Error('No option with key "' + key + '"');
404 }
405
406 if (typeof this.options[key] !== 'undefined') {
407 return this.options[key];
408 }
409
410 return this[key];
411 };
412
413 /**
414 * Sets an option on the terminal.
415 * @param {string} key The option key.
416 * @param {string} value The option value.
417 */
418 Terminal.prototype.setOption = function(key, value) {
419 if (!(key in Terminal.defaults)) {
420 throw new Error('No option with key "' + key + '"');
421 }
422 switch (key) {
423 case 'scrollback':
424 if (this.options[key] !== value) {
425 if (this.lines.length > value) {
426 const amountToTrim = this.lines.length - value;
427 const needsRefresh = (this.ydisp - amountToTrim < 0);
428 this.lines.trimStart(amountToTrim);
429 this.ybase = Math.max(this.ybase - amountToTrim, 0);
430 this.ydisp = Math.max(this.ydisp - amountToTrim, 0);
431 if (needsRefresh) {
432 this.refresh(0, this.rows - 1);
433 }
434 }
435 this.lines.maxLength = value;
436 this.viewport.syncScrollArea();
437 }
438 break;
439 }
440 this[key] = value;
441 this.options[key] = value;
442 switch (key) {
443 case 'cursorBlink': this.setCursorBlinking(value); break;
444 case 'cursorStyle':
445 // Style 'block' applies with no class
446 this.element.classList.toggle(`xterm-cursor-style-underline`, value === 'underline');
447 this.element.classList.toggle(`xterm-cursor-style-bar`, value === 'bar');
448 break;
449 case 'tabStopWidth': this.setupStops(); break;
450 }
451 };
452
453 Terminal.prototype.restartCursorBlinking = function () {
454 this.setCursorBlinking(this.options.cursorBlink);
455 };
456
457 Terminal.prototype.setCursorBlinking = function (enabled) {
458 this.element.classList.toggle('xterm-cursor-blink', enabled);
459 this.clearCursorBlinkingInterval();
460 if (enabled) {
461 var self = this;
462 this.cursorBlinkInterval = setInterval(function () {
463 self.element.classList.toggle('xterm-cursor-blink-on');
464 }, CURSOR_BLINK_INTERVAL);
465 }
466 };
467
468 Terminal.prototype.clearCursorBlinkingInterval = function () {
469 this.element.classList.remove('xterm-cursor-blink-on');
470 if (this.cursorBlinkInterval) {
471 clearInterval(this.cursorBlinkInterval);
472 this.cursorBlinkInterval = null;
473 }
474 };
475
476 /**
477 * Binds the desired focus behavior on a given terminal object.
478 *
479 * @static
480 */
481 Terminal.bindFocus = function (term) {
482 on(term.textarea, 'focus', function (ev) {
483 if (term.sendFocus) {
484 term.send(C0.ESC + '[I');
485 }
486 term.element.classList.add('focus');
487 term.showCursor();
488 term.restartCursorBlinking.apply(term);
489 Terminal.focus = term;
490 term.emit('focus', {terminal: term});
491 });
492 };
493
494 /**
495 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
496 */
497 Terminal.prototype.blur = function() {
498 return this.textarea.blur();
499 };
500
501 /**
502 * Binds the desired blur behavior on a given terminal object.
503 *
504 * @static
505 */
506 Terminal.bindBlur = function (term) {
507 on(term.textarea, 'blur', function (ev) {
508 term.refresh(term.y, term.y);
509 if (term.sendFocus) {
510 term.send(C0.ESC + '[O');
511 }
512 term.element.classList.remove('focus');
513 term.clearCursorBlinkingInterval.apply(term);
514 Terminal.focus = null;
515 term.emit('blur', {terminal: term});
516 });
517 };
518
519 /**
520 * Initialize default behavior
521 */
522 Terminal.prototype.initGlobal = function() {
523 var term = this;
524
525 Terminal.bindKeys(this);
526 Terminal.bindFocus(this);
527 Terminal.bindBlur(this);
528
529 // Bind clipboard functionality
530 on(this.element, 'copy', event => {
531 // If mouse events are active it means the selection manager is disabled and
532 // copy should be handled by the host program.
533 if (this.mouseEvents) {
534 return;
535 }
536 copyHandler(event, term, this.selectionManager);
537 });
538 const pasteHandlerWrapper = event => pasteHandler(event, term);
539 on(this.textarea, 'paste', pasteHandlerWrapper);
540 on(this.element, 'paste', pasteHandlerWrapper);
541
542 if (term.browser.isFirefox) {
543 on(this.element, 'mousedown', event => {
544 if (ev.button == 2) {
545 rightClickHandler(event, this.textarea, this.selectionManager);
546 }
547 });
548 } else {
549 on(this.element, 'contextmenu', event => {
550 rightClickHandler(event, this.textarea, this.selectionManager);
551 });
552 }
553 };
554
555 /**
556 * Apply key handling to the terminal
557 */
558 Terminal.bindKeys = function(term) {
559 on(term.element, 'keydown', function(ev) {
560 if (document.activeElement != this) {
561 return;
562 }
563 term.keyDown(ev);
564 }, true);
565
566 on(term.element, 'keypress', function(ev) {
567 if (document.activeElement != this) {
568 return;
569 }
570 term.keyPress(ev);
571 }, true);
572
573 on(term.element, 'keyup', function(ev) {
574 if (!wasMondifierKeyOnlyEvent(ev)) {
575 term.focus(term);
576 }
577 }, true);
578
579 on(term.textarea, 'keydown', function(ev) {
580 term.keyDown(ev);
581 }, true);
582
583 on(term.textarea, 'keypress', function(ev) {
584 term.keyPress(ev);
585 // Truncate the textarea's value, since it is not needed
586 this.value = '';
587 }, true);
588
589 on(term.textarea, 'compositionstart', term.compositionHelper.compositionstart.bind(term.compositionHelper));
590 on(term.textarea, 'compositionupdate', term.compositionHelper.compositionupdate.bind(term.compositionHelper));
591 on(term.textarea, 'compositionend', term.compositionHelper.compositionend.bind(term.compositionHelper));
592 term.on('refresh', term.compositionHelper.updateCompositionElements.bind(term.compositionHelper));
593 term.on('refresh', function (data) {
594 term.queueLinkification(data.start, data.end)
595 });
596 };
597
598
599 /**
600 * Insert the given row to the terminal or produce a new one
601 * if no row argument is passed. Return the inserted row.
602 * @param {HTMLElement} row (optional) The row to append to the terminal.
603 */
604 Terminal.prototype.insertRow = function (row) {
605 if (typeof row != 'object') {
606 row = document.createElement('div');
607 }
608
609 this.rowContainer.appendChild(row);
610 this.children.push(row);
611
612 return row;
613 };
614
615 /**
616 * Opens the terminal within an element.
617 *
618 * @param {HTMLElement} parent The element to create the terminal within.
619 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
620 */
621 Terminal.prototype.open = function(parent, focus) {
622 var self=this, i=0, div;
623
624 this.parent = parent || this.parent;
625
626 if (!this.parent) {
627 throw new Error('Terminal requires a parent element.');
628 }
629
630 // Grab global elements
631 this.context = this.parent.ownerDocument.defaultView;
632 this.document = this.parent.ownerDocument;
633 this.body = this.document.getElementsByTagName('body')[0];
634
635 //Create main element container
636 this.element = this.document.createElement('div');
637 this.element.classList.add('terminal');
638 this.element.classList.add('xterm');
639 this.element.classList.add('xterm-theme-' + this.theme);
640 this.setCursorBlinking(this.options.cursorBlink);
641
642 this.element.style.height;
643 this.element.setAttribute('tabindex', 0);
644
645 this.viewportElement = document.createElement('div');
646 this.viewportElement.classList.add('xterm-viewport');
647 this.element.appendChild(this.viewportElement);
648 this.viewportScrollArea = document.createElement('div');
649 this.viewportScrollArea.classList.add('xterm-scroll-area');
650 this.viewportElement.appendChild(this.viewportScrollArea);
651
652 // Create the selection container. This needs to be added before the
653 // rowContainer as the selection must be below the text.
654 this.selectionContainer = document.createElement('div');
655 this.selectionContainer.classList.add('xterm-selection');
656 this.element.appendChild(this.selectionContainer);
657
658 // Create the container that will hold the lines of the terminal and then
659 // produce the lines the lines.
660 this.rowContainer = document.createElement('div');
661 this.rowContainer.classList.add('xterm-rows');
662 this.element.appendChild(this.rowContainer);
663 this.children = [];
664 this.linkifier.attachToDom(document, this.children);
665
666 // Create the container that will hold helpers like the textarea for
667 // capturing DOM Events. Then produce the helpers.
668 this.helperContainer = document.createElement('div');
669 this.helperContainer.classList.add('xterm-helpers');
670 // TODO: This should probably be inserted once it's filled to prevent an additional layout
671 this.element.appendChild(this.helperContainer);
672 this.textarea = document.createElement('textarea');
673 this.textarea.classList.add('xterm-helper-textarea');
674 this.textarea.setAttribute('autocorrect', 'off');
675 this.textarea.setAttribute('autocapitalize', 'off');
676 this.textarea.setAttribute('spellcheck', 'false');
677 this.textarea.tabIndex = 0;
678 this.textarea.addEventListener('focus', function() {
679 self.emit('focus', {terminal: self});
680 });
681 this.textarea.addEventListener('blur', function() {
682 self.emit('blur', {terminal: self});
683 });
684 this.helperContainer.appendChild(this.textarea);
685
686 this.compositionView = document.createElement('div');
687 this.compositionView.classList.add('composition-view');
688 this.compositionHelper = new CompositionHelper(this.textarea, this.compositionView, this);
689 this.helperContainer.appendChild(this.compositionView);
690
691 this.charSizeStyleElement = document.createElement('style');
692 this.helperContainer.appendChild(this.charSizeStyleElement);
693
694 for (; i < this.rows; i++) {
695 this.insertRow();
696 }
697 this.parent.appendChild(this.element);
698
699 this.charMeasure = new CharMeasure(document, this.helperContainer);
700 this.charMeasure.on('charsizechanged', function () {
701 self.updateCharSizeStyles();
702 });
703 this.charMeasure.measure();
704
705 this.viewport = new Viewport(this, this.viewportElement, this.viewportScrollArea, this.charMeasure);
706 this.renderer = new Renderer(this);
707 this.selectionManager = new SelectionManager(this, this.lines, this.rowContainer, this.charMeasure);
708 this.selectionManager.on('refresh', data => this.renderer.refreshSelection(data.start, data.end));
709 this.on('scroll', () => this.selectionManager.refresh());
710 this.viewportElement.addEventListener('scroll', () => this.selectionManager.refresh());
711 this.searchHelper = new SearchHelper(this);;
712
713 // Setup loop that draws to screen
714 this.refresh(0, this.rows - 1);
715
716 // Initialize global actions that
717 // need to be taken on the document.
718 this.initGlobal();
719
720 /**
721 * Automatic focus functionality.
722 * TODO: Default to `false` starting with xterm.js 3.0.
723 */
724 if (typeof focus == 'undefined') {
725 let message = 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
726
727 message += 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
728 message += 'it will default to `false`.';
729
730 console.warn(message);
731 focus = true;
732 }
733
734 if (focus) {
735 this.focus();
736 }
737
738 on(this.element, 'click', function() {
739 var selection = document.getSelection(),
740 collapsed = selection.isCollapsed,
741 isRange = typeof collapsed == 'boolean' ? !collapsed : selection.type == 'Range';
742 if (!isRange) {
743 self.focus();
744 }
745 });
746
747 // Listen for mouse events and translate
748 // them into terminal mouse protocols.
749 this.bindMouse();
750
751 /**
752 * This event is emitted when terminal has completed opening.
753 *
754 * @event open
755 */
756 this.emit('open');
757 };
758
759
760 /**
761 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
762 * @param {string} addon The name of the addon to load
763 * @static
764 */
765 Terminal.loadAddon = function(addon, callback) {
766 if (typeof exports === 'object' && typeof module === 'object') {
767 // CommonJS
768 return require('./addons/' + addon + '/' + addon);
769 } else if (typeof define == 'function') {
770 // RequireJS
771 return require(['./addons/' + addon + '/' + addon], callback);
772 } else {
773 console.error('Cannot load a module without a CommonJS or RequireJS environment.');
774 return false;
775 }
776 };
777
778 /**
779 * Updates the helper CSS class with any changes necessary after the terminal's
780 * character width has been changed.
781 */
782 Terminal.prototype.updateCharSizeStyles = function() {
783 this.charSizeStyleElement.textContent =
784 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
785 `.xterm-normal-char{width:${this.charMeasure.width}px;}` +
786 `.xterm-rows > div{height:${this.charMeasure.height}px;}`;
787 }
788
789 /**
790 * XTerm mouse events
791 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
792 * To better understand these
793 * the xterm code is very helpful:
794 * Relevant files:
795 * button.c, charproc.c, misc.c
796 * Relevant functions in xterm/button.c:
797 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
798 */
799 Terminal.prototype.bindMouse = function() {
800 var el = this.element, self = this, pressed = 32;
801
802 // mouseup, mousedown, wheel
803 // left click: ^[[M 3<^[[M#3<
804 // wheel up: ^[[M`3>
805 function sendButton(ev) {
806 var button
807 , pos;
808
809 // get the xterm-style button
810 button = getButton(ev);
811
812 // get mouse coordinates
813 pos = getRawByteCoords(ev, self.rowContainer, self.charMeasure, self.cols, self.rows);
814 if (!pos) return;
815
816 sendEvent(button, pos);
817
818 switch (ev.overrideType || ev.type) {
819 case 'mousedown':
820 pressed = button;
821 break;
822 case 'mouseup':
823 // keep it at the left
824 // button, just in case.
825 pressed = 32;
826 break;
827 case 'wheel':
828 // nothing. don't
829 // interfere with
830 // `pressed`.
831 break;
832 }
833 }
834
835 // motion example of a left click:
836 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
837 function sendMove(ev) {
838 var button = pressed
839 , pos;
840
841 pos = getRawByteCoords(ev, self.rowContainer, self.charMeasure, self.cols, self.rows);
842 if (!pos) return;
843
844 // buttons marked as motions
845 // are incremented by 32
846 button += 32;
847
848 sendEvent(button, pos);
849 }
850
851 // encode button and
852 // position to characters
853 function encode(data, ch) {
854 if (!self.utfMouse) {
855 if (ch === 255) return data.push(0);
856 if (ch > 127) ch = 127;
857 data.push(ch);
858 } else {
859 if (ch === 2047) return data.push(0);
860 if (ch < 127) {
861 data.push(ch);
862 } else {
863 if (ch > 2047) ch = 2047;
864 data.push(0xC0 | (ch >> 6));
865 data.push(0x80 | (ch & 0x3F));
866 }
867 }
868 }
869
870 // send a mouse event:
871 // regular/utf8: ^[[M Cb Cx Cy
872 // urxvt: ^[[ Cb ; Cx ; Cy M
873 // sgr: ^[[ Cb ; Cx ; Cy M/m
874 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
875 // locator: CSI P e ; P b ; P r ; P c ; P p & w
876 function sendEvent(button, pos) {
877 // self.emit('mouse', {
878 // x: pos.x - 32,
879 // y: pos.x - 32,
880 // button: button
881 // });
882
883 if (self.vt300Mouse) {
884 // NOTE: Unstable.
885 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
886 button &= 3;
887 pos.x -= 32;
888 pos.y -= 32;
889 var data = C0.ESC + '[24';
890 if (button === 0) data += '1';
891 else if (button === 1) data += '3';
892 else if (button === 2) data += '5';
893 else if (button === 3) return;
894 else data += '0';
895 data += '~[' + pos.x + ',' + pos.y + ']\r';
896 self.send(data);
897 return;
898 }
899
900 if (self.decLocator) {
901 // NOTE: Unstable.
902 button &= 3;
903 pos.x -= 32;
904 pos.y -= 32;
905 if (button === 0) button = 2;
906 else if (button === 1) button = 4;
907 else if (button === 2) button = 6;
908 else if (button === 3) button = 3;
909 self.send(C0.ESC + '['
910 + button
911 + ';'
912 + (button === 3 ? 4 : 0)
913 + ';'
914 + pos.y
915 + ';'
916 + pos.x
917 + ';'
918 + (pos.page || 0)
919 + '&w');
920 return;
921 }
922
923 if (self.urxvtMouse) {
924 pos.x -= 32;
925 pos.y -= 32;
926 pos.x++;
927 pos.y++;
928 self.send(C0.ESC + '[' + button + ';' + pos.x + ';' + pos.y + 'M');
929 return;
930 }
931
932 if (self.sgrMouse) {
933 pos.x -= 32;
934 pos.y -= 32;
935 self.send(C0.ESC + '[<'
936 + (((button & 3) === 3 ? button & ~3 : button) - 32)
937 + ';'
938 + pos.x
939 + ';'
940 + pos.y
941 + ((button & 3) === 3 ? 'm' : 'M'));
942 return;
943 }
944
945 var data = [];
946
947 encode(data, button);
948 encode(data, pos.x);
949 encode(data, pos.y);
950
951 self.send(C0.ESC + '[M' + String.fromCharCode.apply(String, data));
952 }
953
954 function getButton(ev) {
955 var button
956 , shift
957 , meta
958 , ctrl
959 , mod;
960
961 // two low bits:
962 // 0 = left
963 // 1 = middle
964 // 2 = right
965 // 3 = release
966 // wheel up/down:
967 // 1, and 2 - with 64 added
968 switch (ev.overrideType || ev.type) {
969 case 'mousedown':
970 button = ev.button != null
971 ? +ev.button
972 : ev.which != null
973 ? ev.which - 1
974 : null;
975
976 if (self.browser.isMSIE) {
977 button = button === 1 ? 0 : button === 4 ? 1 : button;
978 }
979 break;
980 case 'mouseup':
981 button = 3;
982 break;
983 case 'DOMMouseScroll':
984 button = ev.detail < 0
985 ? 64
986 : 65;
987 break;
988 case 'wheel':
989 button = ev.wheelDeltaY > 0
990 ? 64
991 : 65;
992 break;
993 }
994
995 // next three bits are the modifiers:
996 // 4 = shift, 8 = meta, 16 = control
997 shift = ev.shiftKey ? 4 : 0;
998 meta = ev.metaKey ? 8 : 0;
999 ctrl = ev.ctrlKey ? 16 : 0;
1000 mod = shift | meta | ctrl;
1001
1002 // no mods
1003 if (self.vt200Mouse) {
1004 // ctrl only
1005 mod &= ctrl;
1006 } else if (!self.normalMouse) {
1007 mod = 0;
1008 }
1009
1010 // increment to SP
1011 button = (32 + (mod << 2)) + button;
1012
1013 return button;
1014 }
1015
1016 on(el, 'mousedown', function(ev) {
1017 if (!self.mouseEvents) return;
1018
1019 // send the button
1020 sendButton(ev);
1021
1022 // ensure focus
1023 self.focus();
1024
1025 // fix for odd bug
1026 //if (self.vt200Mouse && !self.normalMouse) {
1027 if (self.vt200Mouse) {
1028 ev.overrideType = 'mouseup';
1029 sendButton(ev);
1030 return self.cancel(ev);
1031 }
1032
1033 // bind events
1034 if (self.normalMouse) on(self.document, 'mousemove', sendMove);
1035
1036 // x10 compatibility mode can't send button releases
1037 if (!self.x10Mouse) {
1038 on(self.document, 'mouseup', function up(ev) {
1039 sendButton(ev);
1040 if (self.normalMouse) off(self.document, 'mousemove', sendMove);
1041 off(self.document, 'mouseup', up);
1042 return self.cancel(ev);
1043 });
1044 }
1045
1046 return self.cancel(ev);
1047 });
1048
1049 //if (self.normalMouse) {
1050 // on(self.document, 'mousemove', sendMove);
1051 //}
1052
1053 on(el, 'wheel', function(ev) {
1054 if (!self.mouseEvents) return;
1055 if (self.x10Mouse
1056 || self.vt300Mouse
1057 || self.decLocator) return;
1058 sendButton(ev);
1059 return self.cancel(ev);
1060 });
1061
1062 // allow wheel scrolling in
1063 // the shell for example
1064 on(el, 'wheel', function(ev) {
1065 if (self.mouseEvents) return;
1066 self.viewport.onWheel(ev);
1067 return self.cancel(ev);
1068 });
1069 };
1070
1071 /**
1072 * Destroys the terminal.
1073 */
1074 Terminal.prototype.destroy = function() {
1075 this.readable = false;
1076 this.writable = false;
1077 this._events = {};
1078 this.handler = function() {};
1079 this.write = function() {};
1080 if (this.element && this.element.parentNode) {
1081 this.element.parentNode.removeChild(this.element);
1082 }
1083 //this.emit('close');
1084 };
1085
1086 /**
1087 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1088 * opportunity.
1089 * @param {number} start The row to start from (between 0 and this.rows - 1).
1090 * @param {number} end The row to end at (between start and this.rows - 1).
1091 */
1092 Terminal.prototype.refresh = function(start, end) {
1093 if (this.renderer) {
1094 this.renderer.queueRefresh(start, end);
1095 }
1096 };
1097
1098 /**
1099 * Queues linkification for the specified rows.
1100 * @param {number} start The row to start from (between 0 and this.rows - 1).
1101 * @param {number} end The row to end at (between start and this.rows - 1).
1102 */
1103 Terminal.prototype.queueLinkification = function(start, end) {
1104 if (this.linkifier) {
1105 for (let i = start; i <= end; i++) {
1106 this.linkifier.linkifyRow(i);
1107 }
1108 }
1109 }
1110
1111 /**
1112 * Display the cursor element
1113 */
1114 Terminal.prototype.showCursor = function() {
1115 if (!this.cursorState) {
1116 this.cursorState = 1;
1117 this.refresh(this.y, this.y);
1118 }
1119 };
1120
1121 /**
1122 * Scroll the terminal down 1 row, creating a blank line.
1123 * @param {boolean} isWrapped Whether the new line is wrapped from the previous
1124 * line.
1125 */
1126 Terminal.prototype.scroll = function(isWrapped) {
1127 var row;
1128
1129 // Make room for the new row in lines
1130 if (this.lines.length === this.lines.maxLength) {
1131 this.lines.trimStart(1);
1132 this.ybase--;
1133 if (this.ydisp !== 0) {
1134 this.ydisp--;
1135 }
1136 }
1137
1138 this.ybase++;
1139
1140 // TODO: Why is this done twice?
1141 if (!this.userScrolling) {
1142 this.ydisp = this.ybase;
1143 }
1144
1145 // last line
1146 row = this.ybase + this.rows - 1;
1147
1148 // subtract the bottom scroll region
1149 row -= this.rows - 1 - this.scrollBottom;
1150
1151 if (row === this.lines.length) {
1152 // Optimization: pushing is faster than splicing when they amount to the same behavior
1153 this.lines.push(this.blankLine(undefined, isWrapped));
1154 } else {
1155 // add our new line
1156 this.lines.splice(row, 0, this.blankLine(undefined, isWrapped));
1157 }
1158
1159 if (this.scrollTop !== 0) {
1160 if (this.ybase !== 0) {
1161 this.ybase--;
1162 if (!this.userScrolling) {
1163 this.ydisp = this.ybase;
1164 }
1165 }
1166 this.lines.splice(this.ybase + this.scrollTop, 1);
1167 }
1168
1169 // this.maxRange();
1170 this.updateRange(this.scrollTop);
1171 this.updateRange(this.scrollBottom);
1172
1173 /**
1174 * This event is emitted whenever the terminal is scrolled.
1175 * The one parameter passed is the new y display position.
1176 *
1177 * @event scroll
1178 */
1179 this.emit('scroll', this.ydisp);
1180 };
1181
1182 /**
1183 * Scroll the display of the terminal
1184 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1185 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1186 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1187 * viewport originally.
1188 */
1189 Terminal.prototype.scrollDisp = function(disp, suppressScrollEvent) {
1190 if (disp < 0) {
1191 if (this.ydisp === 0) {
1192 return;
1193 }
1194 this.userScrolling = true;
1195 } else if (disp + this.ydisp >= this.ybase) {
1196 this.userScrolling = false;
1197 }
1198
1199 this.ydisp += disp;
1200
1201 if (this.ydisp > this.ybase) {
1202 this.ydisp = this.ybase;
1203 } else if (this.ydisp < 0) {
1204 this.ydisp = 0;
1205 }
1206
1207 if (!suppressScrollEvent) {
1208 this.emit('scroll', this.ydisp);
1209 }
1210
1211 this.refresh(0, this.rows - 1);
1212 };
1213
1214 /**
1215 * Scroll the display of the terminal by a number of pages.
1216 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1217 */
1218 Terminal.prototype.scrollPages = function(pageCount) {
1219 this.scrollDisp(pageCount * (this.rows - 1));
1220 }
1221
1222 /**
1223 * Scrolls the display of the terminal to the top.
1224 */
1225 Terminal.prototype.scrollToTop = function() {
1226 this.scrollDisp(-this.ydisp);
1227 }
1228
1229 /**
1230 * Scrolls the display of the terminal to the bottom.
1231 */
1232 Terminal.prototype.scrollToBottom = function() {
1233 this.scrollDisp(this.ybase - this.ydisp);
1234 }
1235
1236 /**
1237 * Writes text to the terminal.
1238 * @param {string} text The text to write to the terminal.
1239 */
1240 Terminal.prototype.write = function(data) {
1241 this.writeBuffer.push(data);
1242
1243 // Send XOFF to pause the pty process if the write buffer becomes too large so
1244 // xterm.js can catch up before more data is sent. This is necessary in order
1245 // to keep signals such as ^C responsive.
1246 if (this.options.useFlowControl && !this.xoffSentToCatchUp && this.writeBuffer.length >= WRITE_BUFFER_PAUSE_THRESHOLD) {
1247 // XOFF - stop pty pipe
1248 // XON will be triggered by emulator before processing data chunk
1249 this.send(C0.DC3);
1250 this.xoffSentToCatchUp = true;
1251 }
1252
1253 if (!this.writeInProgress && this.writeBuffer.length > 0) {
1254 // Kick off a write which will write all data in sequence recursively
1255 this.writeInProgress = true;
1256 // Kick off an async innerWrite so more writes can come in while processing data
1257 var self = this;
1258 setTimeout(function () {
1259 self.innerWrite();
1260 });
1261 }
1262 }
1263
1264 Terminal.prototype.innerWrite = function() {
1265 var writeBatch = this.writeBuffer.splice(0, WRITE_BATCH_SIZE);
1266 while (writeBatch.length > 0) {
1267 var data = writeBatch.shift();
1268 var l = data.length, i = 0, j, cs, ch, code, low, ch_width, row;
1269
1270 // If XOFF was sent in order to catch up with the pty process, resume it if
1271 // the writeBuffer is empty to allow more data to come in.
1272 if (this.xoffSentToCatchUp && writeBatch.length === 0 && this.writeBuffer.length === 0) {
1273 this.send(C0.DC1);
1274 this.xoffSentToCatchUp = false;
1275 }
1276
1277 this.refreshStart = this.y;
1278 this.refreshEnd = this.y;
1279
1280 // HACK: Set the parser state based on it's state at the time of return.
1281 // This works around the bug #662 which saw the parser state reset in the
1282 // middle of parsing escape sequence in two chunks. For some reason the
1283 // state of the parser resets to 0 after exiting parser.parse. This change
1284 // just sets the state back based on the correct return statement.
1285 var state = this.parser.parse(data);
1286 this.parser.setState(state);
1287
1288 this.updateRange(this.y);
1289 this.refresh(this.refreshStart, this.refreshEnd);
1290 }
1291 if (this.writeBuffer.length > 0) {
1292 // Allow renderer to catch up before processing the next batch
1293 var self = this;
1294 setTimeout(function () {
1295 self.innerWrite();
1296 }, 0);
1297 } else {
1298 this.writeInProgress = false;
1299 }
1300 };
1301
1302 /**
1303 * Writes text to the terminal, followed by a break line character (\n).
1304 * @param {string} text The text to write to the terminal.
1305 */
1306 Terminal.prototype.writeln = function(data) {
1307 this.write(data + '\r\n');
1308 };
1309
1310 /**
1311 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1312 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1313 * should not.
1314 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1315 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1316 * the default action. The function returns whether the event should be processed by xterm.js.
1317 */
1318 Terminal.prototype.attachCustomKeydownHandler = function(customKeydownHandler) {
1319 this.customKeydownHandler = customKeydownHandler;
1320 }
1321
1322 /**
1323 * Attaches a http(s) link handler, forcing web links to behave differently to
1324 * regular <a> tags. This will trigger a refresh as links potentially need to be
1325 * reconstructed. Calling this with null will remove the handler.
1326 * @param {LinkHandler} handler The handler callback function.
1327 */
1328 Terminal.prototype.setHypertextLinkHandler = function(handler) {
1329 if (!this.linkifier) {
1330 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1331 }
1332 this.linkifier.setHypertextLinkHandler(handler);
1333 // Refresh to force links to refresh
1334 this.refresh(0, this.rows - 1);
1335 }
1336
1337 /**
1338 * Attaches a validation callback for hypertext links. This is useful to use
1339 * validation logic or to do something with the link's element and url.
1340 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1341 * be cleared with null.
1342 */
1343 Terminal.prototype.setHypertextValidationCallback = function(handler) {
1344 if (!this.linkifier) {
1345 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1346 }
1347 this.linkifier.setHypertextValidationCallback(handler);
1348 // Refresh to force links to refresh
1349 this.refresh(0, this.rows - 1);
1350 }
1351
1352 /**
1353 * Registers a link matcher, allowing custom link patterns to be matched and
1354 * handled.
1355 * @param {RegExp} regex The regular expression to search for, specifically
1356 * this searches the textContent of the rows. You will want to use \s to match
1357 * a space ' ' character for example.
1358 * @param {LinkHandler} handler The callback when the link is called.
1359 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1360 * @return {number} The ID of the new matcher, this can be used to deregister.
1361 */
1362 Terminal.prototype.registerLinkMatcher = function(regex, handler, options) {
1363 if (this.linkifier) {
1364 var matcherId = this.linkifier.registerLinkMatcher(regex, handler, options);
1365 this.refresh(0, this.rows - 1);
1366 return matcherId;
1367 }
1368 }
1369
1370 /**
1371 * Deregisters a link matcher if it has been registered.
1372 * @param {number} matcherId The link matcher's ID (returned after register)
1373 */
1374 Terminal.prototype.deregisterLinkMatcher = function(matcherId) {
1375 if (this.linkifier) {
1376 if (this.linkifier.deregisterLinkMatcher(matcherId)) {
1377 this.refresh(0, this.rows - 1);
1378 }
1379 }
1380 }
1381
1382 /**
1383 * Gets whether the terminal has an active selection.
1384 */
1385 Terminal.prototype.hasSelection = function() {
1386 return this.selectionManager.hasSelection;
1387 }
1388
1389 /**
1390 * Gets the terminal's current selection, this is useful for implementing copy
1391 * behavior outside of xterm.js.
1392 */
1393 Terminal.prototype.getSelection = function() {
1394 return this.selectionManager.selectionText;
1395 }
1396
1397 /**
1398 * Clears the current terminal selection.
1399 */
1400 Terminal.prototype.clearSelection = function() {
1401 this.selectionManager.clearSelection();
1402 }
1403
1404 /**
1405 * Selects all text within the terminal.
1406 */
1407 Terminal.prototype.selectAll = function() {
1408 this.selectionManager.selectAll();
1409 }
1410
1411 /**
1412 * Find the next instance of the term, then scroll to and select it. If it
1413 * doesn't exist, do nothing.
1414 * @param term The term to search for.
1415 * @return Whether a result was found.
1416 */
1417 Terminal.prototype.findNext = function(term) {
1418 return this.searchHelper.findNext(term);
1419 }
1420
1421 /**
1422 * Find the previous instance of the term, then scroll to and select it. If it
1423 * doesn't exist, do nothing.
1424 * @param term The term to search for.
1425 * @return Whether a result was found.
1426 */
1427 Terminal.prototype.findPrevious = function(term) {
1428 return this.searchHelper.findPrevious(term);
1429 }
1430
1431 /**
1432 * Handle a keydown event
1433 * Key Resources:
1434 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1435 * @param {KeyboardEvent} ev The keydown event to be handled.
1436 */
1437 Terminal.prototype.keyDown = function(ev) {
1438 if (this.customKeydownHandler && this.customKeydownHandler(ev) === false) {
1439 return false;
1440 }
1441
1442 this.restartCursorBlinking();
1443
1444 if (!this.compositionHelper.keydown.bind(this.compositionHelper)(ev)) {
1445 if (this.ybase !== this.ydisp) {
1446 this.scrollToBottom();
1447 }
1448 return false;
1449 }
1450
1451 var self = this;
1452 var result = this.evaluateKeyEscapeSequence(ev);
1453
1454 if (result.key === C0.DC3) { // XOFF
1455 this.writeStopped = true;
1456 } else if (result.key === C0.DC1) { // XON
1457 this.writeStopped = false;
1458 }
1459
1460 if (result.scrollDisp) {
1461 this.scrollDisp(result.scrollDisp);
1462 return this.cancel(ev, true);
1463 }
1464
1465 if (isThirdLevelShift(this, ev)) {
1466 return true;
1467 }
1468
1469 if (result.cancel) {
1470 // The event is canceled at the end already, is this necessary?
1471 this.cancel(ev, true);
1472 }
1473
1474 if (!result.key) {
1475 return true;
1476 }
1477
1478 this.emit('keydown', ev);
1479 this.emit('key', result.key, ev);
1480 this.showCursor();
1481 this.handler(result.key);
1482
1483 return this.cancel(ev, true);
1484 };
1485
1486 /**
1487 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1488 * returned value is the new key code to pass to the PTY.
1489 *
1490 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1491 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1492 */
1493 Terminal.prototype.evaluateKeyEscapeSequence = function(ev) {
1494 var result = {
1495 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1496 // canceled at the end of keyDown
1497 cancel: false,
1498 // The new key even to emit
1499 key: undefined,
1500 // The number of characters to scroll, if this is defined it will cancel the event
1501 scrollDisp: undefined
1502 };
1503 var modifiers = ev.shiftKey << 0 | ev.altKey << 1 | ev.ctrlKey << 2 | ev.metaKey << 3;
1504 switch (ev.keyCode) {
1505 case 8:
1506 // backspace
1507 if (ev.shiftKey) {
1508 result.key = C0.BS; // ^H
1509 break;
1510 }
1511 result.key = C0.DEL; // ^?
1512 break;
1513 case 9:
1514 // tab
1515 if (ev.shiftKey) {
1516 result.key = C0.ESC + '[Z';
1517 break;
1518 }
1519 result.key = C0.HT;
1520 result.cancel = true;
1521 break;
1522 case 13:
1523 // return/enter
1524 result.key = C0.CR;
1525 result.cancel = true;
1526 break;
1527 case 27:
1528 // escape
1529 result.key = C0.ESC;
1530 result.cancel = true;
1531 break;
1532 case 37:
1533 // left-arrow
1534 if (modifiers) {
1535 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';
1536 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1537 // http://unix.stackexchange.com/a/108106
1538 // macOS uses different escape sequences than linux
1539 if (result.key == C0.ESC + '[1;3D') {
1540 result.key = (this.browser.isMac) ? C0.ESC + 'b' : C0.ESC + '[1;5D';
1541 }
1542 } else if (this.applicationCursor) {
1543 result.key = C0.ESC + 'OD';
1544 } else {
1545 result.key = C0.ESC + '[D';
1546 }
1547 break;
1548 case 39:
1549 // right-arrow
1550 if (modifiers) {
1551 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';
1552 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1553 // http://unix.stackexchange.com/a/108106
1554 // macOS uses different escape sequences than linux
1555 if (result.key == C0.ESC + '[1;3C') {
1556 result.key = (this.browser.isMac) ? C0.ESC + 'f' : C0.ESC + '[1;5C';
1557 }
1558 } else if (this.applicationCursor) {
1559 result.key = C0.ESC + 'OC';
1560 } else {
1561 result.key = C0.ESC + '[C';
1562 }
1563 break;
1564 case 38:
1565 // up-arrow
1566 if (modifiers) {
1567 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';
1568 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1569 // http://unix.stackexchange.com/a/108106
1570 if (result.key == C0.ESC + '[1;3A') {
1571 result.key = C0.ESC + '[1;5A';
1572 }
1573 } else if (this.applicationCursor) {
1574 result.key = C0.ESC + 'OA';
1575 } else {
1576 result.key = C0.ESC + '[A';
1577 }
1578 break;
1579 case 40:
1580 // down-arrow
1581 if (modifiers) {
1582 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';
1583 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1584 // http://unix.stackexchange.com/a/108106
1585 if (result.key == C0.ESC + '[1;3B') {
1586 result.key = C0.ESC + '[1;5B';
1587 }
1588 } else if (this.applicationCursor) {
1589 result.key = C0.ESC + 'OB';
1590 } else {
1591 result.key = C0.ESC + '[B';
1592 }
1593 break;
1594 case 45:
1595 // insert
1596 if (!ev.shiftKey && !ev.ctrlKey) {
1597 // <Ctrl> or <Shift> + <Insert> are used to
1598 // copy-paste on some systems.
1599 result.key = C0.ESC + '[2~';
1600 }
1601 break;
1602 case 46:
1603 // delete
1604 if (modifiers) {
1605 result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';
1606 } else {
1607 result.key = C0.ESC + '[3~';
1608 }
1609 break;
1610 case 36:
1611 // home
1612 if (modifiers)
1613 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';
1614 else if (this.applicationCursor)
1615 result.key = C0.ESC + 'OH';
1616 else
1617 result.key = C0.ESC + '[H';
1618 break;
1619 case 35:
1620 // end
1621 if (modifiers)
1622 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';
1623 else if (this.applicationCursor)
1624 result.key = C0.ESC + 'OF';
1625 else
1626 result.key = C0.ESC + '[F';
1627 break;
1628 case 33:
1629 // page up
1630 if (ev.shiftKey) {
1631 result.scrollDisp = -(this.rows - 1);
1632 } else {
1633 result.key = C0.ESC + '[5~';
1634 }
1635 break;
1636 case 34:
1637 // page down
1638 if (ev.shiftKey) {
1639 result.scrollDisp = this.rows - 1;
1640 } else {
1641 result.key = C0.ESC + '[6~';
1642 }
1643 break;
1644 case 112:
1645 // F1-F12
1646 if (modifiers) {
1647 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';
1648 } else {
1649 result.key = C0.ESC + 'OP';
1650 }
1651 break;
1652 case 113:
1653 if (modifiers) {
1654 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';
1655 } else {
1656 result.key = C0.ESC + 'OQ';
1657 }
1658 break;
1659 case 114:
1660 if (modifiers) {
1661 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';
1662 } else {
1663 result.key = C0.ESC + 'OR';
1664 }
1665 break;
1666 case 115:
1667 if (modifiers) {
1668 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';
1669 } else {
1670 result.key = C0.ESC + 'OS';
1671 }
1672 break;
1673 case 116:
1674 if (modifiers) {
1675 result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';
1676 } else {
1677 result.key = C0.ESC + '[15~';
1678 }
1679 break;
1680 case 117:
1681 if (modifiers) {
1682 result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';
1683 } else {
1684 result.key = C0.ESC + '[17~';
1685 }
1686 break;
1687 case 118:
1688 if (modifiers) {
1689 result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';
1690 } else {
1691 result.key = C0.ESC + '[18~';
1692 }
1693 break;
1694 case 119:
1695 if (modifiers) {
1696 result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';
1697 } else {
1698 result.key = C0.ESC + '[19~';
1699 }
1700 break;
1701 case 120:
1702 if (modifiers) {
1703 result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';
1704 } else {
1705 result.key = C0.ESC + '[20~';
1706 }
1707 break;
1708 case 121:
1709 if (modifiers) {
1710 result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';
1711 } else {
1712 result.key = C0.ESC + '[21~';
1713 }
1714 break;
1715 case 122:
1716 if (modifiers) {
1717 result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';
1718 } else {
1719 result.key = C0.ESC + '[23~';
1720 }
1721 break;
1722 case 123:
1723 if (modifiers) {
1724 result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';
1725 } else {
1726 result.key = C0.ESC + '[24~';
1727 }
1728 break;
1729 default:
1730 // a-z and space
1731 if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
1732 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
1733 result.key = String.fromCharCode(ev.keyCode - 64);
1734 } else if (ev.keyCode === 32) {
1735 // NUL
1736 result.key = String.fromCharCode(0);
1737 } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
1738 // escape, file sep, group sep, record sep, unit sep
1739 result.key = String.fromCharCode(ev.keyCode - 51 + 27);
1740 } else if (ev.keyCode === 56) {
1741 // delete
1742 result.key = String.fromCharCode(127);
1743 } else if (ev.keyCode === 219) {
1744 // ^[ - Control Sequence Introducer (CSI)
1745 result.key = String.fromCharCode(27);
1746 } else if (ev.keyCode === 220) {
1747 // ^\ - String Terminator (ST)
1748 result.key = String.fromCharCode(28);
1749 } else if (ev.keyCode === 221) {
1750 // ^] - Operating System Command (OSC)
1751 result.key = String.fromCharCode(29);
1752 }
1753 } else if (!this.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
1754 // On Mac this is a third level shift. Use <Esc> instead.
1755 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
1756 result.key = C0.ESC + String.fromCharCode(ev.keyCode + 32);
1757 } else if (ev.keyCode === 192) {
1758 result.key = C0.ESC + '`';
1759 } else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
1760 result.key = C0.ESC + (ev.keyCode - 48);
1761 }
1762 } else if (this.browser.isMac && !ev.altKey && !ev.ctrlKey && ev.metaKey) {
1763 if (ev.keyCode === 65) { // cmd + a
1764 this.selectAll();
1765 }
1766 }
1767 break;
1768 }
1769
1770 return result;
1771 };
1772
1773 /**
1774 * Set the G level of the terminal
1775 * @param g
1776 */
1777 Terminal.prototype.setgLevel = function(g) {
1778 this.glevel = g;
1779 this.charset = this.charsets[g];
1780 };
1781
1782 /**
1783 * Set the charset for the given G level of the terminal
1784 * @param g
1785 * @param charset
1786 */
1787 Terminal.prototype.setgCharset = function(g, charset) {
1788 this.charsets[g] = charset;
1789 if (this.glevel === g) {
1790 this.charset = charset;
1791 }
1792 };
1793
1794 /**
1795 * Handle a keypress event.
1796 * Key Resources:
1797 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1798 * @param {KeyboardEvent} ev The keypress event to be handled.
1799 */
1800 Terminal.prototype.keyPress = function(ev) {
1801 var key;
1802
1803 this.cancel(ev);
1804
1805 if (ev.charCode) {
1806 key = ev.charCode;
1807 } else if (ev.which == null) {
1808 key = ev.keyCode;
1809 } else if (ev.which !== 0 && ev.charCode !== 0) {
1810 key = ev.which;
1811 } else {
1812 return false;
1813 }
1814
1815 if (!key || (
1816 (ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
1817 )) {
1818 return false;
1819 }
1820
1821 key = String.fromCharCode(key);
1822
1823 this.emit('keypress', key, ev);
1824 this.emit('key', key, ev);
1825 this.showCursor();
1826 this.handler(key);
1827
1828 return false;
1829 };
1830
1831 /**
1832 * Send data for handling to the terminal
1833 * @param {string} data
1834 */
1835 Terminal.prototype.send = function(data) {
1836 var self = this;
1837
1838 if (!this.queue) {
1839 setTimeout(function() {
1840 self.handler(self.queue);
1841 self.queue = '';
1842 }, 1);
1843 }
1844
1845 this.queue += data;
1846 };
1847
1848 /**
1849 * Ring the bell.
1850 * Note: We could do sweet things with webaudio here
1851 */
1852 Terminal.prototype.bell = function() {
1853 if (!this.visualBell) return;
1854 var self = this;
1855 this.element.style.borderColor = 'white';
1856 setTimeout(function() {
1857 self.element.style.borderColor = '';
1858 }, 10);
1859 if (this.popOnBell) this.focus();
1860 };
1861
1862 /**
1863 * Log the current state to the console.
1864 */
1865 Terminal.prototype.log = function() {
1866 if (!this.debug) return;
1867 if (!this.context.console || !this.context.console.log) return;
1868 var args = Array.prototype.slice.call(arguments);
1869 this.context.console.log.apply(this.context.console, args);
1870 };
1871
1872 /**
1873 * Log the current state as error to the console.
1874 */
1875 Terminal.prototype.error = function() {
1876 if (!this.debug) return;
1877 if (!this.context.console || !this.context.console.error) return;
1878 var args = Array.prototype.slice.call(arguments);
1879 this.context.console.error.apply(this.context.console, args);
1880 };
1881
1882 /**
1883 * Resizes the terminal.
1884 *
1885 * @param {number} x The number of columns to resize to.
1886 * @param {number} y The number of rows to resize to.
1887 */
1888 Terminal.prototype.resize = function(x, y) {
1889 if (isNaN(x) || isNaN(y)) {
1890 return;
1891 }
1892
1893 var line
1894 , el
1895 , i
1896 , j
1897 , ch
1898 , addToY;
1899
1900 if (x === this.cols && y === this.rows) {
1901 return;
1902 }
1903
1904 if (x < 1) x = 1;
1905 if (y < 1) y = 1;
1906
1907 // resize cols
1908 j = this.cols;
1909 if (j < x) {
1910 ch = [this.defAttr, ' ', 1]; // does xterm use the default attr?
1911 i = this.lines.length;
1912 while (i--) {
1913 while (this.lines.get(i).length < x) {
1914 this.lines.get(i).push(ch);
1915 }
1916 }
1917 }
1918
1919 this.cols = x;
1920 this.setupStops(this.cols);
1921
1922 // resize rows
1923 j = this.rows;
1924 addToY = 0;
1925 if (j < y) {
1926 el = this.element;
1927 while (j++ < y) {
1928 // y is rows, not this.y
1929 if (this.lines.length < y + this.ybase) {
1930 if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
1931 // There is room above the buffer and there are no empty elements below the line,
1932 // scroll up
1933 this.ybase--;
1934 addToY++
1935 if (this.ydisp > 0) {
1936 // Viewport is at the top of the buffer, must increase downwards
1937 this.ydisp--;
1938 }
1939 } else {
1940 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1941 // are blank lines after the cursor
1942 this.lines.push(this.blankLine());
1943 }
1944 }
1945 if (this.children.length < y) {
1946 this.insertRow();
1947 }
1948 }
1949 } else { // (j > y)
1950 while (j-- > y) {
1951 if (this.lines.length > y + this.ybase) {
1952 if (this.lines.length > this.ybase + this.y + 1) {
1953 // The line is a blank line below the cursor, remove it
1954 this.lines.pop();
1955 } else {
1956 // The line is the cursor, scroll down
1957 this.ybase++;
1958 this.ydisp++;
1959 }
1960 }
1961 if (this.children.length > y) {
1962 el = this.children.shift();
1963 if (!el) continue;
1964 el.parentNode.removeChild(el);
1965 }
1966 }
1967 }
1968 this.rows = y;
1969
1970 // Make sure that the cursor stays on screen
1971 if (this.y >= y) {
1972 this.y = y - 1;
1973 }
1974 if (addToY) {
1975 this.y += addToY;
1976 }
1977
1978 if (this.x >= x) {
1979 this.x = x - 1;
1980 }
1981
1982 this.scrollTop = 0;
1983 this.scrollBottom = y - 1;
1984
1985 this.charMeasure.measure();
1986
1987 this.refresh(0, this.rows - 1);
1988
1989 this.normal = null;
1990
1991 this.geometry = [this.cols, this.rows];
1992 this.emit('resize', {terminal: this, cols: x, rows: y});
1993 };
1994
1995 /**
1996 * Updates the range of rows to refresh
1997 * @param {number} y The number of rows to refresh next.
1998 */
1999 Terminal.prototype.updateRange = function(y) {
2000 if (y < this.refreshStart) this.refreshStart = y;
2001 if (y > this.refreshEnd) this.refreshEnd = y;
2002 // if (y > this.refreshEnd) {
2003 // this.refreshEnd = y;
2004 // if (y > this.rows - 1) {
2005 // this.refreshEnd = this.rows - 1;
2006 // }
2007 // }
2008 };
2009
2010 /**
2011 * Set the range of refreshing to the maximum value
2012 */
2013 Terminal.prototype.maxRange = function() {
2014 this.refreshStart = 0;
2015 this.refreshEnd = this.rows - 1;
2016 };
2017
2018
2019
2020 /**
2021 * Setup the tab stops.
2022 * @param {number} i
2023 */
2024 Terminal.prototype.setupStops = function(i) {
2025 if (i != null) {
2026 if (!this.tabs[i]) {
2027 i = this.prevStop(i);
2028 }
2029 } else {
2030 this.tabs = {};
2031 i = 0;
2032 }
2033
2034 for (; i < this.cols; i += this.getOption('tabStopWidth')) {
2035 this.tabs[i] = true;
2036 }
2037 };
2038
2039
2040 /**
2041 * Move the cursor to the previous tab stop from the given position (default is current).
2042 * @param {number} x The position to move the cursor to the previous tab stop.
2043 */
2044 Terminal.prototype.prevStop = function(x) {
2045 if (x == null) x = this.x;
2046 while (!this.tabs[--x] && x > 0);
2047 return x >= this.cols
2048 ? this.cols - 1
2049 : x < 0 ? 0 : x;
2050 };
2051
2052
2053 /**
2054 * Move the cursor one tab stop forward from the given position (default is current).
2055 * @param {number} x The position to move the cursor one tab stop forward.
2056 */
2057 Terminal.prototype.nextStop = function(x) {
2058 if (x == null) x = this.x;
2059 while (!this.tabs[++x] && x < this.cols);
2060 return x >= this.cols
2061 ? this.cols - 1
2062 : x < 0 ? 0 : x;
2063 };
2064
2065
2066 /**
2067 * Erase in the identified line everything from "x" to the end of the line (right).
2068 * @param {number} x The column from which to start erasing to the end of the line.
2069 * @param {number} y The line in which to operate.
2070 */
2071 Terminal.prototype.eraseRight = function(x, y) {
2072 var line = this.lines.get(this.ybase + y);
2073 if (!line) {
2074 return;
2075 }
2076 var ch = [this.eraseAttr(), ' ', 1]; // xterm
2077 for (; x < this.cols; x++) {
2078 line[x] = ch;
2079 }
2080 this.updateRange(y);
2081 };
2082
2083
2084
2085 /**
2086 * Erase in the identified line everything from "x" to the start of the line (left).
2087 * @param {number} x The column from which to start erasing to the start of the line.
2088 * @param {number} y The line in which to operate.
2089 */
2090 Terminal.prototype.eraseLeft = function(x, y) {
2091 var line = this.lines.get(this.ybase + y);
2092 if (!line) {
2093 return;
2094 }
2095 var ch = [this.eraseAttr(), ' ', 1]; // xterm
2096 x++;
2097 while (x--) {
2098 line[x] = ch;
2099 }
2100 this.updateRange(y);
2101 };
2102
2103 /**
2104 * Clears the entire buffer, making the prompt line the new first line.
2105 */
2106 Terminal.prototype.clear = function() {
2107 if (this.ybase === 0 && this.y === 0) {
2108 // Don't clear if it's already clear
2109 return;
2110 }
2111 this.lines.set(0, this.lines.get(this.ybase + this.y));
2112 this.lines.length = 1;
2113 this.ydisp = 0;
2114 this.ybase = 0;
2115 this.y = 0;
2116 for (var i = 1; i < this.rows; i++) {
2117 this.lines.push(this.blankLine());
2118 }
2119 this.refresh(0, this.rows - 1);
2120 this.emit('scroll', this.ydisp);
2121 };
2122
2123 /**
2124 * Erase all content in the given line
2125 * @param {number} y The line to erase all of its contents.
2126 */
2127 Terminal.prototype.eraseLine = function(y) {
2128 this.eraseRight(0, y);
2129 };
2130
2131
2132 /**
2133 * Return the data array of a blank line
2134 * @param {number} cur First bunch of data for each "blank" character.
2135 * @param {boolean} isWrapped Whether the new line is wrapped from the previous line.
2136 */
2137 Terminal.prototype.blankLine = function(cur, isWrapped) {
2138 var attr = cur
2139 ? this.eraseAttr()
2140 : this.defAttr;
2141
2142 var ch = [attr, ' ', 1] // width defaults to 1 halfwidth character
2143 , line = []
2144 , i = 0;
2145
2146 // TODO: It is not ideal that this is a property on an array, a buffer line
2147 // class should be added that will hold this data and other useful functions.
2148 if (isWrapped) {
2149 line.isWrapped = isWrapped;
2150 }
2151
2152 for (; i < this.cols; i++) {
2153 line[i] = ch;
2154 }
2155
2156 return line;
2157 };
2158
2159
2160 /**
2161 * If cur return the back color xterm feature attribute. Else return defAttr.
2162 * @param {object} cur
2163 */
2164 Terminal.prototype.ch = function(cur) {
2165 return cur
2166 ? [this.eraseAttr(), ' ', 1]
2167 : [this.defAttr, ' ', 1];
2168 };
2169
2170
2171 /**
2172 * Evaluate if the current erminal is the given argument.
2173 * @param {object} term The terminal to evaluate
2174 */
2175 Terminal.prototype.is = function(term) {
2176 var name = this.termName;
2177 return (name + '').indexOf(term) === 0;
2178 };
2179
2180
2181 /**
2182 * Emit the 'data' event and populate the given data.
2183 * @param {string} data The data to populate in the event.
2184 */
2185 Terminal.prototype.handler = function(data) {
2186 // Prevents all events to pty process if stdin is disabled
2187 if (this.options.disableStdin) {
2188 return;
2189 }
2190
2191 // Input is being sent to the terminal, the terminal should focus the prompt.
2192 if (this.ybase !== this.ydisp) {
2193 this.scrollToBottom();
2194 }
2195 this.emit('data', data);
2196 };
2197
2198
2199 /**
2200 * Emit the 'title' event and populate the given title.
2201 * @param {string} title The title to populate in the event.
2202 */
2203 Terminal.prototype.handleTitle = function(title) {
2204 /**
2205 * This event is emitted when the title of the terminal is changed
2206 * from inside the terminal. The parameter is the new title.
2207 *
2208 * @event title
2209 */
2210 this.emit('title', title);
2211 };
2212
2213
2214 /**
2215 * ESC
2216 */
2217
2218 /**
2219 * ESC D Index (IND is 0x84).
2220 */
2221 Terminal.prototype.index = function() {
2222 this.y++;
2223 if (this.y > this.scrollBottom) {
2224 this.y--;
2225 this.scroll();
2226 }
2227 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2228 if (this.x >= this.cols) {
2229 this.x--;
2230 }
2231 };
2232
2233
2234 /**
2235 * ESC M Reverse Index (RI is 0x8d).
2236 *
2237 * Move the cursor up one row, inserting a new blank line if necessary.
2238 */
2239 Terminal.prototype.reverseIndex = function() {
2240 var j;
2241 if (this.y === this.scrollTop) {
2242 // possibly move the code below to term.reverseScroll();
2243 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2244 // blankLine(true) is xterm/linux behavior
2245 this.lines.shiftElements(this.y + this.ybase, this.rows - 1, 1);
2246 this.lines.set(this.y + this.ybase, this.blankLine(true));
2247 this.updateRange(this.scrollTop);
2248 this.updateRange(this.scrollBottom);
2249 } else {
2250 this.y--;
2251 }
2252 };
2253
2254
2255 /**
2256 * ESC c Full Reset (RIS).
2257 */
2258 Terminal.prototype.reset = function() {
2259 this.options.rows = this.rows;
2260 this.options.cols = this.cols;
2261 var customKeydownHandler = this.customKeydownHandler;
2262 var cursorBlinkInterval = this.cursorBlinkInterval;
2263 Terminal.call(this, this.options);
2264 this.customKeydownHandler = customKeydownHandler;
2265 this.cursorBlinkInterval = cursorBlinkInterval;
2266 this.refresh(0, this.rows - 1);
2267 this.viewport.syncScrollArea();
2268 };
2269
2270
2271 /**
2272 * ESC H Tab Set (HTS is 0x88).
2273 */
2274 Terminal.prototype.tabSet = function() {
2275 this.tabs[this.x] = true;
2276 };
2277
2278 /**
2279 * Helpers
2280 */
2281
2282 function on(el, type, handler, capture) {
2283 if (!Array.isArray(el)) {
2284 el = [el];
2285 }
2286 el.forEach(function (element) {
2287 element.addEventListener(type, handler, capture || false);
2288 });
2289 }
2290
2291 function off(el, type, handler, capture) {
2292 el.removeEventListener(type, handler, capture || false);
2293 }
2294
2295 function cancel(ev, force) {
2296 if (!this.cancelEvents && !force) {
2297 return;
2298 }
2299 ev.preventDefault();
2300 ev.stopPropagation();
2301 return false;
2302 }
2303
2304 function inherits(child, parent) {
2305 function f() {
2306 this.constructor = child;
2307 }
2308 f.prototype = parent.prototype;
2309 child.prototype = new f;
2310 }
2311
2312 function indexOf(obj, el) {
2313 var i = obj.length;
2314 while (i--) {
2315 if (obj[i] === el) return i;
2316 }
2317 return -1;
2318 }
2319
2320 function isThirdLevelShift(term, ev) {
2321 var thirdLevelKey =
2322 (term.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
2323 (term.browser.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
2324
2325 if (ev.type == 'keypress') {
2326 return thirdLevelKey;
2327 }
2328
2329 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2330 return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
2331 }
2332
2333 // Expose to InputHandler (temporary)
2334 Terminal.prototype.matchColor = matchColor;
2335
2336 function matchColor(r1, g1, b1) {
2337 var hash = (r1 << 16) | (g1 << 8) | b1;
2338
2339 if (matchColor._cache[hash] != null) {
2340 return matchColor._cache[hash];
2341 }
2342
2343 var ldiff = Infinity
2344 , li = -1
2345 , i = 0
2346 , c
2347 , r2
2348 , g2
2349 , b2
2350 , diff;
2351
2352 for (; i < Terminal.vcolors.length; i++) {
2353 c = Terminal.vcolors[i];
2354 r2 = c[0];
2355 g2 = c[1];
2356 b2 = c[2];
2357
2358 diff = matchColor.distance(r1, g1, b1, r2, g2, b2);
2359
2360 if (diff === 0) {
2361 li = i;
2362 break;
2363 }
2364
2365 if (diff < ldiff) {
2366 ldiff = diff;
2367 li = i;
2368 }
2369 }
2370
2371 return matchColor._cache[hash] = li;
2372 }
2373
2374 matchColor._cache = {};
2375
2376 // http://stackoverflow.com/questions/1633828
2377 matchColor.distance = function(r1, g1, b1, r2, g2, b2) {
2378 return Math.pow(30 * (r1 - r2), 2)
2379 + Math.pow(59 * (g1 - g2), 2)
2380 + Math.pow(11 * (b1 - b2), 2);
2381 };
2382
2383 function each(obj, iter, con) {
2384 if (obj.forEach) return obj.forEach(iter, con);
2385 for (var i = 0; i < obj.length; i++) {
2386 iter.call(con, obj[i], i, obj);
2387 }
2388 }
2389
2390 function wasMondifierKeyOnlyEvent(ev) {
2391 return ev.keyCode === 16 || // Shift
2392 ev.keyCode === 17 || // Ctrl
2393 ev.keyCode === 18; // Alt
2394 }
2395
2396 function keys(obj) {
2397 if (Object.keys) return Object.keys(obj);
2398 var key, keys = [];
2399 for (key in obj) {
2400 if (Object.prototype.hasOwnProperty.call(obj, key)) {
2401 keys.push(key);
2402 }
2403 }
2404 return keys;
2405 }
2406
2407 /**
2408 * Expose
2409 */
2410
2411 Terminal.EventEmitter = EventEmitter;
2412 Terminal.inherits = inherits;
2413
2414 /**
2415 * Adds an event listener to the terminal.
2416 *
2417 * @param {string} event The name of the event. TODO: Document all event types
2418 * @param {function} callback The function to call when the event is triggered.
2419 */
2420 Terminal.on = on;
2421 Terminal.off = off;
2422 Terminal.cancel = cancel;
2423
2424 module.exports = Terminal;