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