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