]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/xterm.js
a97070961df2e722c77a229a5ce5e20fb5d3a6e8
[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) {
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 ? this.selectionManager.hasSelection : false;
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 ? this.selectionManager.selectionText : '';
1449 };
1450
1451 /**
1452 * Clears the current terminal selection.
1453 */
1454 Terminal.prototype.clearSelection = function() {
1455 if (this.selectionManager) {
1456 this.selectionManager.clearSelection();
1457 }
1458 };
1459
1460 /**
1461 * Selects all text within the terminal.
1462 */
1463 Terminal.prototype.selectAll = function() {
1464 if (this.selectionManager) {
1465 this.selectionManager.selectAll();
1466 }
1467 };
1468
1469 /**
1470 * Handle a keydown event
1471 * Key Resources:
1472 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1473 * @param {KeyboardEvent} ev The keydown event to be handled.
1474 */
1475 Terminal.prototype.keyDown = function(ev) {
1476 if (this.customKeyEventHandler && this.customKeyEventHandler(ev) === false) {
1477 return false;
1478 }
1479
1480 this.restartCursorBlinking();
1481
1482 if (!this.compositionHelper.keydown.bind(this.compositionHelper)(ev)) {
1483 if (this.ybase !== this.ydisp) {
1484 this.scrollToBottom();
1485 }
1486 return false;
1487 }
1488
1489 var self = this;
1490 var result = this.evaluateKeyEscapeSequence(ev);
1491
1492 if (result.key === C0.DC3) { // XOFF
1493 this.writeStopped = true;
1494 } else if (result.key === C0.DC1) { // XON
1495 this.writeStopped = false;
1496 }
1497
1498 if (result.scrollDisp) {
1499 this.scrollDisp(result.scrollDisp);
1500 return this.cancel(ev, true);
1501 }
1502
1503 if (isThirdLevelShift(this, ev)) {
1504 return true;
1505 }
1506
1507 if (result.cancel) {
1508 // The event is canceled at the end already, is this necessary?
1509 this.cancel(ev, true);
1510 }
1511
1512 if (!result.key) {
1513 return true;
1514 }
1515
1516 this.emit('keydown', ev);
1517 this.emit('key', result.key, ev);
1518 this.showCursor();
1519 this.handler(result.key);
1520
1521 return this.cancel(ev, true);
1522 };
1523
1524 /**
1525 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1526 * returned value is the new key code to pass to the PTY.
1527 *
1528 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1529 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1530 */
1531 Terminal.prototype.evaluateKeyEscapeSequence = function(ev) {
1532 var result = {
1533 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1534 // canceled at the end of keyDown
1535 cancel: false,
1536 // The new key even to emit
1537 key: undefined,
1538 // The number of characters to scroll, if this is defined it will cancel the event
1539 scrollDisp: undefined
1540 };
1541 var modifiers = ev.shiftKey << 0 | ev.altKey << 1 | ev.ctrlKey << 2 | ev.metaKey << 3;
1542 switch (ev.keyCode) {
1543 case 8:
1544 // backspace
1545 if (ev.shiftKey) {
1546 result.key = C0.BS; // ^H
1547 break;
1548 }
1549 result.key = C0.DEL; // ^?
1550 break;
1551 case 9:
1552 // tab
1553 if (ev.shiftKey) {
1554 result.key = C0.ESC + '[Z';
1555 break;
1556 }
1557 result.key = C0.HT;
1558 result.cancel = true;
1559 break;
1560 case 13:
1561 // return/enter
1562 result.key = C0.CR;
1563 result.cancel = true;
1564 break;
1565 case 27:
1566 // escape
1567 result.key = C0.ESC;
1568 result.cancel = true;
1569 break;
1570 case 37:
1571 // left-arrow
1572 if (modifiers) {
1573 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';
1574 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1575 // http://unix.stackexchange.com/a/108106
1576 // macOS uses different escape sequences than linux
1577 if (result.key == C0.ESC + '[1;3D') {
1578 result.key = (this.browser.isMac) ? C0.ESC + 'b' : C0.ESC + '[1;5D';
1579 }
1580 } else if (this.applicationCursor) {
1581 result.key = C0.ESC + 'OD';
1582 } else {
1583 result.key = C0.ESC + '[D';
1584 }
1585 break;
1586 case 39:
1587 // right-arrow
1588 if (modifiers) {
1589 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';
1590 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1591 // http://unix.stackexchange.com/a/108106
1592 // macOS uses different escape sequences than linux
1593 if (result.key == C0.ESC + '[1;3C') {
1594 result.key = (this.browser.isMac) ? C0.ESC + 'f' : C0.ESC + '[1;5C';
1595 }
1596 } else if (this.applicationCursor) {
1597 result.key = C0.ESC + 'OC';
1598 } else {
1599 result.key = C0.ESC + '[C';
1600 }
1601 break;
1602 case 38:
1603 // up-arrow
1604 if (modifiers) {
1605 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';
1606 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1607 // http://unix.stackexchange.com/a/108106
1608 if (result.key == C0.ESC + '[1;3A') {
1609 result.key = C0.ESC + '[1;5A';
1610 }
1611 } else if (this.applicationCursor) {
1612 result.key = C0.ESC + 'OA';
1613 } else {
1614 result.key = C0.ESC + '[A';
1615 }
1616 break;
1617 case 40:
1618 // down-arrow
1619 if (modifiers) {
1620 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';
1621 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1622 // http://unix.stackexchange.com/a/108106
1623 if (result.key == C0.ESC + '[1;3B') {
1624 result.key = C0.ESC + '[1;5B';
1625 }
1626 } else if (this.applicationCursor) {
1627 result.key = C0.ESC + 'OB';
1628 } else {
1629 result.key = C0.ESC + '[B';
1630 }
1631 break;
1632 case 45:
1633 // insert
1634 if (!ev.shiftKey && !ev.ctrlKey) {
1635 // <Ctrl> or <Shift> + <Insert> are used to
1636 // copy-paste on some systems.
1637 result.key = C0.ESC + '[2~';
1638 }
1639 break;
1640 case 46:
1641 // delete
1642 if (modifiers) {
1643 result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';
1644 } else {
1645 result.key = C0.ESC + '[3~';
1646 }
1647 break;
1648 case 36:
1649 // home
1650 if (modifiers)
1651 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';
1652 else if (this.applicationCursor)
1653 result.key = C0.ESC + 'OH';
1654 else
1655 result.key = C0.ESC + '[H';
1656 break;
1657 case 35:
1658 // end
1659 if (modifiers)
1660 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';
1661 else if (this.applicationCursor)
1662 result.key = C0.ESC + 'OF';
1663 else
1664 result.key = C0.ESC + '[F';
1665 break;
1666 case 33:
1667 // page up
1668 if (ev.shiftKey) {
1669 result.scrollDisp = -(this.rows - 1);
1670 } else {
1671 result.key = C0.ESC + '[5~';
1672 }
1673 break;
1674 case 34:
1675 // page down
1676 if (ev.shiftKey) {
1677 result.scrollDisp = this.rows - 1;
1678 } else {
1679 result.key = C0.ESC + '[6~';
1680 }
1681 break;
1682 case 112:
1683 // F1-F12
1684 if (modifiers) {
1685 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';
1686 } else {
1687 result.key = C0.ESC + 'OP';
1688 }
1689 break;
1690 case 113:
1691 if (modifiers) {
1692 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';
1693 } else {
1694 result.key = C0.ESC + 'OQ';
1695 }
1696 break;
1697 case 114:
1698 if (modifiers) {
1699 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';
1700 } else {
1701 result.key = C0.ESC + 'OR';
1702 }
1703 break;
1704 case 115:
1705 if (modifiers) {
1706 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';
1707 } else {
1708 result.key = C0.ESC + 'OS';
1709 }
1710 break;
1711 case 116:
1712 if (modifiers) {
1713 result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';
1714 } else {
1715 result.key = C0.ESC + '[15~';
1716 }
1717 break;
1718 case 117:
1719 if (modifiers) {
1720 result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';
1721 } else {
1722 result.key = C0.ESC + '[17~';
1723 }
1724 break;
1725 case 118:
1726 if (modifiers) {
1727 result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';
1728 } else {
1729 result.key = C0.ESC + '[18~';
1730 }
1731 break;
1732 case 119:
1733 if (modifiers) {
1734 result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';
1735 } else {
1736 result.key = C0.ESC + '[19~';
1737 }
1738 break;
1739 case 120:
1740 if (modifiers) {
1741 result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';
1742 } else {
1743 result.key = C0.ESC + '[20~';
1744 }
1745 break;
1746 case 121:
1747 if (modifiers) {
1748 result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';
1749 } else {
1750 result.key = C0.ESC + '[21~';
1751 }
1752 break;
1753 case 122:
1754 if (modifiers) {
1755 result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';
1756 } else {
1757 result.key = C0.ESC + '[23~';
1758 }
1759 break;
1760 case 123:
1761 if (modifiers) {
1762 result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';
1763 } else {
1764 result.key = C0.ESC + '[24~';
1765 }
1766 break;
1767 default:
1768 // a-z and space
1769 if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
1770 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
1771 result.key = String.fromCharCode(ev.keyCode - 64);
1772 } else if (ev.keyCode === 32) {
1773 // NUL
1774 result.key = String.fromCharCode(0);
1775 } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
1776 // escape, file sep, group sep, record sep, unit sep
1777 result.key = String.fromCharCode(ev.keyCode - 51 + 27);
1778 } else if (ev.keyCode === 56) {
1779 // delete
1780 result.key = String.fromCharCode(127);
1781 } else if (ev.keyCode === 219) {
1782 // ^[ - Control Sequence Introducer (CSI)
1783 result.key = String.fromCharCode(27);
1784 } else if (ev.keyCode === 220) {
1785 // ^\ - String Terminator (ST)
1786 result.key = String.fromCharCode(28);
1787 } else if (ev.keyCode === 221) {
1788 // ^] - Operating System Command (OSC)
1789 result.key = String.fromCharCode(29);
1790 }
1791 } else if (!this.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
1792 // On Mac this is a third level shift. Use <Esc> instead.
1793 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
1794 result.key = C0.ESC + String.fromCharCode(ev.keyCode + 32);
1795 } else if (ev.keyCode === 192) {
1796 result.key = C0.ESC + '`';
1797 } else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
1798 result.key = C0.ESC + (ev.keyCode - 48);
1799 }
1800 } else if (this.browser.isMac && !ev.altKey && !ev.ctrlKey && ev.metaKey) {
1801 if (ev.keyCode === 65) { // cmd + a
1802 this.selectAll();
1803 }
1804 }
1805 break;
1806 }
1807
1808 return result;
1809 };
1810
1811 /**
1812 * Set the G level of the terminal
1813 * @param g
1814 */
1815 Terminal.prototype.setgLevel = function(g) {
1816 this.glevel = g;
1817 this.charset = this.charsets[g];
1818 };
1819
1820 /**
1821 * Set the charset for the given G level of the terminal
1822 * @param g
1823 * @param charset
1824 */
1825 Terminal.prototype.setgCharset = function(g, charset) {
1826 this.charsets[g] = charset;
1827 if (this.glevel === g) {
1828 this.charset = charset;
1829 }
1830 };
1831
1832 /**
1833 * Handle a keypress event.
1834 * Key Resources:
1835 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1836 * @param {KeyboardEvent} ev The keypress event to be handled.
1837 */
1838 Terminal.prototype.keyPress = function(ev) {
1839 var key;
1840
1841 if (this.customKeyEventHandler && this.customKeyEventHandler(ev) === false) {
1842 return false;
1843 }
1844
1845 this.cancel(ev);
1846
1847 if (ev.charCode) {
1848 key = ev.charCode;
1849 } else if (ev.which == null) {
1850 key = ev.keyCode;
1851 } else if (ev.which !== 0 && ev.charCode !== 0) {
1852 key = ev.which;
1853 } else {
1854 return false;
1855 }
1856
1857 if (!key || (
1858 (ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
1859 )) {
1860 return false;
1861 }
1862
1863 key = String.fromCharCode(key);
1864
1865 this.emit('keypress', key, ev);
1866 this.emit('key', key, ev);
1867 this.showCursor();
1868 this.handler(key);
1869
1870 return true;
1871 };
1872
1873 /**
1874 * Send data for handling to the terminal
1875 * @param {string} data
1876 */
1877 Terminal.prototype.send = function(data) {
1878 var self = this;
1879
1880 if (!this.queue) {
1881 setTimeout(function() {
1882 self.handler(self.queue);
1883 self.queue = '';
1884 }, 1);
1885 }
1886
1887 this.queue += data;
1888 };
1889
1890 /**
1891 * Ring the bell.
1892 * Note: We could do sweet things with webaudio here
1893 */
1894 Terminal.prototype.bell = function() {
1895 if (!this.visualBell) return;
1896 var self = this;
1897 this.element.style.borderColor = 'white';
1898 setTimeout(function() {
1899 self.element.style.borderColor = '';
1900 }, 10);
1901 if (this.popOnBell) this.focus();
1902 };
1903
1904 /**
1905 * Log the current state to the console.
1906 */
1907 Terminal.prototype.log = function() {
1908 if (!this.debug) return;
1909 if (!this.context.console || !this.context.console.log) return;
1910 var args = Array.prototype.slice.call(arguments);
1911 this.context.console.log.apply(this.context.console, args);
1912 };
1913
1914 /**
1915 * Log the current state as error to the console.
1916 */
1917 Terminal.prototype.error = function() {
1918 if (!this.debug) return;
1919 if (!this.context.console || !this.context.console.error) return;
1920 var args = Array.prototype.slice.call(arguments);
1921 this.context.console.error.apply(this.context.console, args);
1922 };
1923
1924 /**
1925 * Resizes the terminal.
1926 *
1927 * @param {number} x The number of columns to resize to.
1928 * @param {number} y The number of rows to resize to.
1929 */
1930 Terminal.prototype.resize = function(x, y) {
1931 if (isNaN(x) || isNaN(y)) {
1932 return;
1933 }
1934
1935 if (y > this.getOption('scrollback')) {
1936 this.setOption('scrollback', y)
1937 }
1938
1939 var line
1940 , el
1941 , i
1942 , j
1943 , ch
1944 , addToY;
1945
1946 if (x === this.cols && y === this.rows) {
1947 // Check if we still need to measure the char size (fixes #785).
1948 if (!this.charMeasure.width || !this.charMeasure.height) {
1949 this.charMeasure.measure();
1950 }
1951 return;
1952 }
1953
1954 if (x < 1) x = 1;
1955 if (y < 1) y = 1;
1956
1957 // resize cols
1958 j = this.cols;
1959 if (j < x) {
1960 ch = [this.defAttr, ' ', 1]; // does xterm use the default attr?
1961 i = this.lines.length;
1962 while (i--) {
1963 while (this.lines.get(i).length < x) {
1964 this.lines.get(i).push(ch);
1965 }
1966 }
1967 }
1968
1969 this.cols = x;
1970 this.setupStops(this.cols);
1971
1972 // resize rows
1973 j = this.rows;
1974 addToY = 0;
1975 if (j < y) {
1976 el = this.element;
1977 while (j++ < y) {
1978 // y is rows, not this.y
1979 if (this.lines.length < y + this.ybase) {
1980 if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
1981 // There is room above the buffer and there are no empty elements below the line,
1982 // scroll up
1983 this.ybase--;
1984 addToY++;
1985 if (this.ydisp > 0) {
1986 // Viewport is at the top of the buffer, must increase downwards
1987 this.ydisp--;
1988 }
1989 } else {
1990 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1991 // are blank lines after the cursor
1992 this.lines.push(this.blankLine());
1993 }
1994 }
1995 if (this.children.length < y) {
1996 this.insertRow();
1997 }
1998 }
1999 } else { // (j > y)
2000 while (j-- > y) {
2001 if (this.lines.length > y + this.ybase) {
2002 if (this.lines.length > this.ybase + this.y + 1) {
2003 // The line is a blank line below the cursor, remove it
2004 this.lines.pop();
2005 } else {
2006 // The line is the cursor, scroll down
2007 this.ybase++;
2008 this.ydisp++;
2009 }
2010 }
2011 if (this.children.length > y) {
2012 el = this.children.shift();
2013 if (!el) continue;
2014 el.parentNode.removeChild(el);
2015 }
2016 }
2017 }
2018 this.rows = y;
2019
2020 // Make sure that the cursor stays on screen
2021 if (this.y >= y) {
2022 this.y = y - 1;
2023 }
2024 if (addToY) {
2025 this.y += addToY;
2026 }
2027
2028 if (this.x >= x) {
2029 this.x = x - 1;
2030 }
2031
2032 this.scrollTop = 0;
2033 this.scrollBottom = y - 1;
2034
2035 this.charMeasure.measure();
2036
2037 this.refresh(0, this.rows - 1);
2038
2039 this.normal = null;
2040
2041 this.geometry = [this.cols, this.rows];
2042 this.emit('resize', {terminal: this, cols: x, rows: y});
2043 };
2044
2045 /**
2046 * Updates the range of rows to refresh
2047 * @param {number} y The number of rows to refresh next.
2048 */
2049 Terminal.prototype.updateRange = function(y) {
2050 if (y < this.refreshStart) this.refreshStart = y;
2051 if (y > this.refreshEnd) this.refreshEnd = y;
2052 // if (y > this.refreshEnd) {
2053 // this.refreshEnd = y;
2054 // if (y > this.rows - 1) {
2055 // this.refreshEnd = this.rows - 1;
2056 // }
2057 // }
2058 };
2059
2060 /**
2061 * Set the range of refreshing to the maximum value
2062 */
2063 Terminal.prototype.maxRange = function() {
2064 this.refreshStart = 0;
2065 this.refreshEnd = this.rows - 1;
2066 };
2067
2068
2069
2070 /**
2071 * Setup the tab stops.
2072 * @param {number} i
2073 */
2074 Terminal.prototype.setupStops = function(i) {
2075 if (i != null) {
2076 if (!this.tabs[i]) {
2077 i = this.prevStop(i);
2078 }
2079 } else {
2080 this.tabs = {};
2081 i = 0;
2082 }
2083
2084 for (; i < this.cols; i += this.getOption('tabStopWidth')) {
2085 this.tabs[i] = true;
2086 }
2087 };
2088
2089
2090 /**
2091 * Move the cursor to the previous tab stop from the given position (default is current).
2092 * @param {number} x The position to move the cursor to the previous tab stop.
2093 */
2094 Terminal.prototype.prevStop = function(x) {
2095 if (x == null) x = this.x;
2096 while (!this.tabs[--x] && x > 0);
2097 return x >= this.cols
2098 ? this.cols - 1
2099 : x < 0 ? 0 : x;
2100 };
2101
2102
2103 /**
2104 * Move the cursor one tab stop forward from the given position (default is current).
2105 * @param {number} x The position to move the cursor one tab stop forward.
2106 */
2107 Terminal.prototype.nextStop = function(x) {
2108 if (x == null) x = this.x;
2109 while (!this.tabs[++x] && x < this.cols);
2110 return x >= this.cols
2111 ? this.cols - 1
2112 : x < 0 ? 0 : x;
2113 };
2114
2115
2116 /**
2117 * Erase in the identified line everything from "x" to the end of the line (right).
2118 * @param {number} x The column from which to start erasing to the end of the line.
2119 * @param {number} y The line in which to operate.
2120 */
2121 Terminal.prototype.eraseRight = function(x, y) {
2122 var line = this.lines.get(this.ybase + y);
2123 if (!line) {
2124 return;
2125 }
2126 var ch = [this.eraseAttr(), ' ', 1]; // xterm
2127 for (; x < this.cols; x++) {
2128 line[x] = ch;
2129 }
2130 this.updateRange(y);
2131 };
2132
2133
2134
2135 /**
2136 * Erase in the identified line everything from "x" to the start of the line (left).
2137 * @param {number} x The column from which to start erasing to the start of the line.
2138 * @param {number} y The line in which to operate.
2139 */
2140 Terminal.prototype.eraseLeft = function(x, y) {
2141 var line = this.lines.get(this.ybase + y);
2142 if (!line) {
2143 return;
2144 }
2145 var ch = [this.eraseAttr(), ' ', 1]; // xterm
2146 x++;
2147 while (x--) {
2148 line[x] = ch;
2149 }
2150 this.updateRange(y);
2151 };
2152
2153 /**
2154 * Clears the entire buffer, making the prompt line the new first line.
2155 */
2156 Terminal.prototype.clear = function() {
2157 if (this.ybase === 0 && this.y === 0) {
2158 // Don't clear if it's already clear
2159 return;
2160 }
2161 this.lines.set(0, this.lines.get(this.ybase + this.y));
2162 this.lines.length = 1;
2163 this.ydisp = 0;
2164 this.ybase = 0;
2165 this.y = 0;
2166 for (var i = 1; i < this.rows; i++) {
2167 this.lines.push(this.blankLine());
2168 }
2169 this.refresh(0, this.rows - 1);
2170 this.emit('scroll', this.ydisp);
2171 };
2172
2173 /**
2174 * Erase all content in the given line
2175 * @param {number} y The line to erase all of its contents.
2176 */
2177 Terminal.prototype.eraseLine = function(y) {
2178 this.eraseRight(0, y);
2179 };
2180
2181
2182 /**
2183 * Return the data array of a blank line
2184 * @param {number} cur First bunch of data for each "blank" character.
2185 * @param {boolean} isWrapped Whether the new line is wrapped from the previous line.
2186 */
2187 Terminal.prototype.blankLine = function(cur, isWrapped) {
2188 var attr = cur
2189 ? this.eraseAttr()
2190 : this.defAttr;
2191
2192 var ch = [attr, ' ', 1] // width defaults to 1 halfwidth character
2193 , line = []
2194 , i = 0;
2195
2196 // TODO: It is not ideal that this is a property on an array, a buffer line
2197 // class should be added that will hold this data and other useful functions.
2198 if (isWrapped) {
2199 line.isWrapped = isWrapped;
2200 }
2201
2202 for (; i < this.cols; i++) {
2203 line[i] = ch;
2204 }
2205
2206 return line;
2207 };
2208
2209
2210 /**
2211 * If cur return the back color xterm feature attribute. Else return defAttr.
2212 * @param {object} cur
2213 */
2214 Terminal.prototype.ch = function(cur) {
2215 return cur
2216 ? [this.eraseAttr(), ' ', 1]
2217 : [this.defAttr, ' ', 1];
2218 };
2219
2220
2221 /**
2222 * Evaluate if the current erminal is the given argument.
2223 * @param {object} term The terminal to evaluate
2224 */
2225 Terminal.prototype.is = function(term) {
2226 var name = this.termName;
2227 return (name + '').indexOf(term) === 0;
2228 };
2229
2230
2231 /**
2232 * Emit the 'data' event and populate the given data.
2233 * @param {string} data The data to populate in the event.
2234 */
2235 Terminal.prototype.handler = function(data) {
2236 // Prevents all events to pty process if stdin is disabled
2237 if (this.options.disableStdin) {
2238 return;
2239 }
2240
2241 // Clear the selection if the selection manager is available and has an active selection
2242 if (this.selectionManager && this.selectionManager.hasSelection) {
2243 this.selectionManager.clearSelection();
2244 }
2245
2246 // Input is being sent to the terminal, the terminal should focus the prompt.
2247 if (this.ybase !== this.ydisp) {
2248 this.scrollToBottom();
2249 }
2250 this.emit('data', data);
2251 };
2252
2253
2254 /**
2255 * Emit the 'title' event and populate the given title.
2256 * @param {string} title The title to populate in the event.
2257 */
2258 Terminal.prototype.handleTitle = function(title) {
2259 /**
2260 * This event is emitted when the title of the terminal is changed
2261 * from inside the terminal. The parameter is the new title.
2262 *
2263 * @event title
2264 */
2265 this.emit('title', title);
2266 };
2267
2268
2269 /**
2270 * ESC
2271 */
2272
2273 /**
2274 * ESC D Index (IND is 0x84).
2275 */
2276 Terminal.prototype.index = function() {
2277 this.y++;
2278 if (this.y > this.scrollBottom) {
2279 this.y--;
2280 this.scroll();
2281 }
2282 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2283 if (this.x >= this.cols) {
2284 this.x--;
2285 }
2286 };
2287
2288
2289 /**
2290 * ESC M Reverse Index (RI is 0x8d).
2291 *
2292 * Move the cursor up one row, inserting a new blank line if necessary.
2293 */
2294 Terminal.prototype.reverseIndex = function() {
2295 var j;
2296 if (this.y === this.scrollTop) {
2297 // possibly move the code below to term.reverseScroll();
2298 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2299 // blankLine(true) is xterm/linux behavior
2300 this.lines.shiftElements(this.y + this.ybase, this.rows - 1, 1);
2301 this.lines.set(this.y + this.ybase, this.blankLine(true));
2302 this.updateRange(this.scrollTop);
2303 this.updateRange(this.scrollBottom);
2304 } else {
2305 this.y--;
2306 }
2307 };
2308
2309
2310 /**
2311 * ESC c Full Reset (RIS).
2312 */
2313 Terminal.prototype.reset = function() {
2314 this.options.rows = this.rows;
2315 this.options.cols = this.cols;
2316 var customKeyEventHandler = this.customKeyEventHandler;
2317 var cursorBlinkInterval = this.cursorBlinkInterval;
2318 Terminal.call(this, this.options);
2319 this.customKeyEventHandler = customKeyEventHandler;
2320 this.cursorBlinkInterval = cursorBlinkInterval;
2321 this.refresh(0, this.rows - 1);
2322 this.viewport.syncScrollArea();
2323 };
2324
2325
2326 /**
2327 * ESC H Tab Set (HTS is 0x88).
2328 */
2329 Terminal.prototype.tabSet = function() {
2330 this.tabs[this.x] = true;
2331 };
2332
2333 /**
2334 * Helpers
2335 */
2336
2337 function on(el, type, handler, capture) {
2338 if (!Array.isArray(el)) {
2339 el = [el];
2340 }
2341 el.forEach(function (element) {
2342 element.addEventListener(type, handler, capture || false);
2343 });
2344 }
2345
2346 function off(el, type, handler, capture) {
2347 el.removeEventListener(type, handler, capture || false);
2348 }
2349
2350 function cancel(ev, force) {
2351 if (!this.cancelEvents && !force) {
2352 return;
2353 }
2354 ev.preventDefault();
2355 ev.stopPropagation();
2356 return false;
2357 }
2358
2359 function inherits(child, parent) {
2360 function f() {
2361 this.constructor = child;
2362 }
2363 f.prototype = parent.prototype;
2364 child.prototype = new f;
2365 }
2366
2367 function indexOf(obj, el) {
2368 var i = obj.length;
2369 while (i--) {
2370 if (obj[i] === el) return i;
2371 }
2372 return -1;
2373 }
2374
2375 function isThirdLevelShift(term, ev) {
2376 var thirdLevelKey =
2377 (term.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
2378 (term.browser.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
2379
2380 if (ev.type == 'keypress') {
2381 return thirdLevelKey;
2382 }
2383
2384 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2385 return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
2386 }
2387
2388 // Expose to InputHandler (temporary)
2389 Terminal.prototype.matchColor = matchColor;
2390
2391 function matchColor(r1, g1, b1) {
2392 var hash = (r1 << 16) | (g1 << 8) | b1;
2393
2394 if (matchColor._cache[hash] != null) {
2395 return matchColor._cache[hash];
2396 }
2397
2398 var ldiff = Infinity
2399 , li = -1
2400 , i = 0
2401 , c
2402 , r2
2403 , g2
2404 , b2
2405 , diff;
2406
2407 for (; i < Terminal.vcolors.length; i++) {
2408 c = Terminal.vcolors[i];
2409 r2 = c[0];
2410 g2 = c[1];
2411 b2 = c[2];
2412
2413 diff = matchColor.distance(r1, g1, b1, r2, g2, b2);
2414
2415 if (diff === 0) {
2416 li = i;
2417 break;
2418 }
2419
2420 if (diff < ldiff) {
2421 ldiff = diff;
2422 li = i;
2423 }
2424 }
2425
2426 return matchColor._cache[hash] = li;
2427 }
2428
2429 matchColor._cache = {};
2430
2431 // http://stackoverflow.com/questions/1633828
2432 matchColor.distance = function(r1, g1, b1, r2, g2, b2) {
2433 return Math.pow(30 * (r1 - r2), 2)
2434 + Math.pow(59 * (g1 - g2), 2)
2435 + Math.pow(11 * (b1 - b2), 2);
2436 };
2437
2438 function each(obj, iter, con) {
2439 if (obj.forEach) return obj.forEach(iter, con);
2440 for (var i = 0; i < obj.length; i++) {
2441 iter.call(con, obj[i], i, obj);
2442 }
2443 }
2444
2445 function wasMondifierKeyOnlyEvent(ev) {
2446 return ev.keyCode === 16 || // Shift
2447 ev.keyCode === 17 || // Ctrl
2448 ev.keyCode === 18; // Alt
2449 }
2450
2451 function keys(obj) {
2452 if (Object.keys) return Object.keys(obj);
2453 var key, keys = [];
2454 for (key in obj) {
2455 if (Object.prototype.hasOwnProperty.call(obj, key)) {
2456 keys.push(key);
2457 }
2458 }
2459 return keys;
2460 }
2461
2462 /**
2463 * Expose
2464 */
2465
2466 Terminal.translateBufferLineToString = translateBufferLineToString;
2467 Terminal.EventEmitter = EventEmitter;
2468 Terminal.inherits = inherits;
2469
2470 /**
2471 * Adds an event listener to the terminal.
2472 *
2473 * @param {string} event The name of the event. TODO: Document all event types
2474 * @param {function} callback The function to call when the event is triggered.
2475 */
2476 Terminal.on = on;
2477 Terminal.off = off;
2478 Terminal.cancel = cancel;
2479
2480 module.exports = Terminal;