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