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