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