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