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