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