]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/xterm.js
Focus on `mousedown`, instead of `click`
[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 // Style 'block' applies with no class
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.setCursorBlinking(this.options.cursorBlink);
643
644 this.element.setAttribute('tabindex', 0);
645
646 this.viewportElement = document.createElement('div');
647 this.viewportElement.classList.add('xterm-viewport');
648 this.element.appendChild(this.viewportElement);
649 this.viewportScrollArea = document.createElement('div');
650 this.viewportScrollArea.classList.add('xterm-scroll-area');
651 this.viewportElement.appendChild(this.viewportScrollArea);
652
653 // Create the selection container.
654 this.selectionContainer = document.createElement('div');
655 this.selectionContainer.classList.add('xterm-selection');
656 this.element.appendChild(this.selectionContainer);
657
658 // Create the container that will hold the lines of the terminal and then
659 // produce the lines the lines.
660 this.rowContainer = document.createElement('div');
661 this.rowContainer.classList.add('xterm-rows');
662 this.element.appendChild(this.rowContainer);
663 this.children = [];
664 this.linkifier.attachToDom(document, this.children);
665
666 // Create the container that will hold helpers like the textarea for
667 // capturing DOM Events. Then produce the helpers.
668 this.helperContainer = document.createElement('div');
669 this.helperContainer.classList.add('xterm-helpers');
670 // TODO: This should probably be inserted once it's filled to prevent an additional layout
671 this.element.appendChild(this.helperContainer);
672 this.textarea = document.createElement('textarea');
673 this.textarea.classList.add('xterm-helper-textarea');
674 this.textarea.setAttribute('autocorrect', 'off');
675 this.textarea.setAttribute('autocapitalize', 'off');
676 this.textarea.setAttribute('spellcheck', 'false');
677 this.textarea.tabIndex = 0;
678 this.textarea.addEventListener('focus', function() {
679 self.emit('focus', {terminal: self});
680 });
681 this.textarea.addEventListener('blur', function() {
682 self.emit('blur', {terminal: self});
683 });
684 this.helperContainer.appendChild(this.textarea);
685
686 this.compositionView = document.createElement('div');
687 this.compositionView.classList.add('composition-view');
688 this.compositionHelper = new CompositionHelper(this.textarea, this.compositionView, this);
689 this.helperContainer.appendChild(this.compositionView);
690
691 this.charSizeStyleElement = document.createElement('style');
692 this.helperContainer.appendChild(this.charSizeStyleElement);
693
694 for (; i < this.rows; i++) {
695 this.insertRow();
696 }
697 this.parent.appendChild(this.element);
698
699 this.charMeasure = new CharMeasure(document, this.helperContainer);
700 this.charMeasure.on('charsizechanged', function () {
701 self.updateCharSizeStyles();
702 });
703 this.charMeasure.measure();
704
705 this.viewport = new Viewport(this, this.viewportElement, this.viewportScrollArea, this.charMeasure);
706 this.renderer = new Renderer(this);
707 this.selectionManager = new SelectionManager(
708 this, this.buffer.lines, this.rowContainer, this.charMeasure
709 );
710 this.selectionManager.on('refresh', data => {
711 this.renderer.refreshSelection(data.start, data.end);
712 });
713 this.selectionManager.on('newselection', text => {
714 // If there's a new selection, put it into the textarea, focus and select it
715 // in order to register it as a selection on the OS. This event is fired
716 // only on Linux to enable middle click to paste selection.
717 this.textarea.value = text;
718 this.textarea.focus();
719 this.textarea.select();
720 });
721 this.on('scroll', () => this.selectionManager.refresh());
722 this.viewportElement.addEventListener('scroll', () => this.selectionManager.refresh());
723
724 // Setup loop that draws to screen
725 this.refresh(0, this.rows - 1);
726
727 // Initialize global actions that
728 // need to be taken on the document.
729 this.initGlobal();
730
731 /**
732 * Automatic focus functionality.
733 * TODO: Default to `false` starting with xterm.js 3.0.
734 */
735 if (typeof focus == 'undefined') {
736 let message = 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
737
738 message += 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
739 message += 'it will default to `false`.';
740
741 console.warn(message);
742 focus = true;
743 }
744
745 if (focus) {
746 this.focus();
747 }
748
749 // Listen for mouse events and translate
750 // them into terminal mouse protocols.
751 this.bindMouse();
752
753 /**
754 * This event is emitted when terminal has completed opening.
755 *
756 * @event open
757 */
758 this.emit('open');
759 };
760
761
762 /**
763 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
764 * @param {string} addon The name of the addon to load
765 * @static
766 */
767 Terminal.loadAddon = function(addon, callback) {
768 if (typeof exports === 'object' && typeof module === 'object') {
769 // CommonJS
770 return require('./addons/' + addon + '/' + addon);
771 } else if (typeof define == 'function') {
772 // RequireJS
773 return require(['./addons/' + addon + '/' + addon], callback);
774 } else {
775 console.error('Cannot load a module without a CommonJS or RequireJS environment.');
776 return false;
777 }
778 };
779
780 /**
781 * Updates the helper CSS class with any changes necessary after the terminal's
782 * character width has been changed.
783 */
784 Terminal.prototype.updateCharSizeStyles = function() {
785 this.charSizeStyleElement.textContent =
786 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
787 `.xterm-normal-char{width:${this.charMeasure.width}px;}` +
788 `.xterm-rows > div{height:${this.charMeasure.height}px;}`;
789 }
790
791 /**
792 * XTerm mouse events
793 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
794 * To better understand these
795 * the xterm code is very helpful:
796 * Relevant files:
797 * button.c, charproc.c, misc.c
798 * Relevant functions in xterm/button.c:
799 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
800 */
801 Terminal.prototype.bindMouse = function() {
802 var el = this.element, self = this, pressed = 32;
803
804 // mouseup, mousedown, wheel
805 // left click: ^[[M 3<^[[M#3<
806 // wheel up: ^[[M`3>
807 function sendButton(ev) {
808 var button
809 , pos;
810
811 // get the xterm-style button
812 button = getButton(ev);
813
814 // get mouse coordinates
815 pos = getRawByteCoords(ev, self.rowContainer, self.charMeasure, self.cols, self.rows);
816 if (!pos) return;
817
818 sendEvent(button, pos);
819
820 switch (ev.overrideType || ev.type) {
821 case 'mousedown':
822 pressed = button;
823 break;
824 case 'mouseup':
825 // keep it at the left
826 // button, just in case.
827 pressed = 32;
828 break;
829 case 'wheel':
830 // nothing. don't
831 // interfere with
832 // `pressed`.
833 break;
834 }
835 }
836
837 // motion example of a left click:
838 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
839 function sendMove(ev) {
840 var button = pressed
841 , pos;
842
843 pos = getRawByteCoords(ev, self.rowContainer, self.charMeasure, self.cols, self.rows);
844 if (!pos) return;
845
846 // buttons marked as motions
847 // are incremented by 32
848 button += 32;
849
850 sendEvent(button, pos);
851 }
852
853 // encode button and
854 // position to characters
855 function encode(data, ch) {
856 if (!self.utfMouse) {
857 if (ch === 255) return data.push(0);
858 if (ch > 127) ch = 127;
859 data.push(ch);
860 } else {
861 if (ch === 2047) return data.push(0);
862 if (ch < 127) {
863 data.push(ch);
864 } else {
865 if (ch > 2047) ch = 2047;
866 data.push(0xC0 | (ch >> 6));
867 data.push(0x80 | (ch & 0x3F));
868 }
869 }
870 }
871
872 // send a mouse event:
873 // regular/utf8: ^[[M Cb Cx Cy
874 // urxvt: ^[[ Cb ; Cx ; Cy M
875 // sgr: ^[[ Cb ; Cx ; Cy M/m
876 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
877 // locator: CSI P e ; P b ; P r ; P c ; P p & w
878 function sendEvent(button, pos) {
879 // self.emit('mouse', {
880 // x: pos.x - 32,
881 // y: pos.x - 32,
882 // button: button
883 // });
884
885 if (self.vt300Mouse) {
886 // NOTE: Unstable.
887 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
888 button &= 3;
889 pos.x -= 32;
890 pos.y -= 32;
891 var data = C0.ESC + '[24';
892 if (button === 0) data += '1';
893 else if (button === 1) data += '3';
894 else if (button === 2) data += '5';
895 else if (button === 3) return;
896 else data += '0';
897 data += '~[' + pos.x + ',' + pos.y + ']\r';
898 self.send(data);
899 return;
900 }
901
902 if (self.decLocator) {
903 // NOTE: Unstable.
904 button &= 3;
905 pos.x -= 32;
906 pos.y -= 32;
907 if (button === 0) button = 2;
908 else if (button === 1) button = 4;
909 else if (button === 2) button = 6;
910 else if (button === 3) button = 3;
911 self.send(C0.ESC + '['
912 + button
913 + ';'
914 + (button === 3 ? 4 : 0)
915 + ';'
916 + pos.y
917 + ';'
918 + pos.x
919 + ';'
920 + (pos.page || 0)
921 + '&w');
922 return;
923 }
924
925 if (self.urxvtMouse) {
926 pos.x -= 32;
927 pos.y -= 32;
928 pos.x++;
929 pos.y++;
930 self.send(C0.ESC + '[' + button + ';' + pos.x + ';' + pos.y + 'M');
931 return;
932 }
933
934 if (self.sgrMouse) {
935 pos.x -= 32;
936 pos.y -= 32;
937 self.send(C0.ESC + '[<'
938 + (((button & 3) === 3 ? button & ~3 : button) - 32)
939 + ';'
940 + pos.x
941 + ';'
942 + pos.y
943 + ((button & 3) === 3 ? 'm' : 'M'));
944 return;
945 }
946
947 var data = [];
948
949 encode(data, button);
950 encode(data, pos.x);
951 encode(data, pos.y);
952
953 self.send(C0.ESC + '[M' + String.fromCharCode.apply(String, data));
954 }
955
956 function getButton(ev) {
957 var button
958 , shift
959 , meta
960 , ctrl
961 , mod;
962
963 // two low bits:
964 // 0 = left
965 // 1 = middle
966 // 2 = right
967 // 3 = release
968 // wheel up/down:
969 // 1, and 2 - with 64 added
970 switch (ev.overrideType || ev.type) {
971 case 'mousedown':
972 button = ev.button != null
973 ? +ev.button
974 : ev.which != null
975 ? ev.which - 1
976 : null;
977
978 if (self.browser.isMSIE) {
979 button = button === 1 ? 0 : button === 4 ? 1 : button;
980 }
981 break;
982 case 'mouseup':
983 button = 3;
984 break;
985 case 'DOMMouseScroll':
986 button = ev.detail < 0
987 ? 64
988 : 65;
989 break;
990 case 'wheel':
991 button = ev.wheelDeltaY > 0
992 ? 64
993 : 65;
994 break;
995 }
996
997 // next three bits are the modifiers:
998 // 4 = shift, 8 = meta, 16 = control
999 shift = ev.shiftKey ? 4 : 0;
1000 meta = ev.metaKey ? 8 : 0;
1001 ctrl = ev.ctrlKey ? 16 : 0;
1002 mod = shift | meta | ctrl;
1003
1004 // no mods
1005 if (self.vt200Mouse) {
1006 // ctrl only
1007 mod &= ctrl;
1008 } else if (!self.normalMouse) {
1009 mod = 0;
1010 }
1011
1012 // increment to SP
1013 button = (32 + (mod << 2)) + button;
1014
1015 return button;
1016 }
1017
1018 on(el, 'mousedown', function(ev) {
1019 // ensure focus
1020 self.focus();
1021
1022 if (!self.mouseEvents) return;
1023
1024 // send the button
1025 sendButton(ev);
1026
1027 // fix for odd bug
1028 //if (self.vt200Mouse && !self.normalMouse) {
1029 if (self.vt200Mouse) {
1030 ev.overrideType = 'mouseup';
1031 sendButton(ev);
1032 return self.cancel(ev);
1033 }
1034
1035 // bind events
1036 if (self.normalMouse) on(self.document, 'mousemove', sendMove);
1037
1038 // x10 compatibility mode can't send button releases
1039 if (!self.x10Mouse) {
1040 on(self.document, 'mouseup', function up(ev) {
1041 sendButton(ev);
1042 if (self.normalMouse) off(self.document, 'mousemove', sendMove);
1043 off(self.document, 'mouseup', up);
1044 return self.cancel(ev);
1045 });
1046 }
1047
1048 return self.cancel(ev);
1049 });
1050
1051 //if (self.normalMouse) {
1052 // on(self.document, 'mousemove', sendMove);
1053 //}
1054
1055 on(el, 'wheel', function(ev) {
1056 if (!self.mouseEvents) return;
1057 if (self.x10Mouse
1058 || self.vt300Mouse
1059 || self.decLocator) return;
1060 sendButton(ev);
1061 return self.cancel(ev);
1062 });
1063
1064 // allow wheel scrolling in
1065 // the shell for example
1066 on(el, 'wheel', function(ev) {
1067 if (self.mouseEvents) return;
1068 self.viewport.onWheel(ev);
1069 return self.cancel(ev);
1070 });
1071
1072 on(el, 'touchstart', function(ev) {
1073 if (self.mouseEvents) return;
1074 self.viewport.onTouchStart(ev);
1075 return self.cancel(ev);
1076 });
1077
1078 on(el, 'touchmove', function(ev) {
1079 if (self.mouseEvents) return;
1080 self.viewport.onTouchMove(ev);
1081 return self.cancel(ev);
1082 });
1083 };
1084
1085 /**
1086 * Destroys the terminal.
1087 */
1088 Terminal.prototype.destroy = function() {
1089 this.readable = false;
1090 this.writable = false;
1091 this._events = {};
1092 this.handler = function() {};
1093 this.write = function() {};
1094 if (this.element && this.element.parentNode) {
1095 this.element.parentNode.removeChild(this.element);
1096 }
1097 //this.emit('close');
1098 };
1099
1100 /**
1101 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1102 * opportunity.
1103 * @param {number} start The row to start from (between 0 and this.rows - 1).
1104 * @param {number} end The row to end at (between start and this.rows - 1).
1105 */
1106 Terminal.prototype.refresh = function(start, end) {
1107 if (this.renderer) {
1108 this.renderer.queueRefresh(start, end);
1109 }
1110 };
1111
1112 /**
1113 * Queues linkification for the specified rows.
1114 * @param {number} start The row to start from (between 0 and this.rows - 1).
1115 * @param {number} end The row to end at (between start and this.rows - 1).
1116 */
1117 Terminal.prototype.queueLinkification = function(start, end) {
1118 if (this.linkifier) {
1119 for (let i = start; i <= end; i++) {
1120 this.linkifier.linkifyRow(i);
1121 }
1122 }
1123 };
1124
1125 /**
1126 * Display the cursor element
1127 */
1128 Terminal.prototype.showCursor = function() {
1129 if (!this.cursorState) {
1130 this.cursorState = 1;
1131 this.refresh(this.buffer.y, this.buffer.y);
1132 }
1133 };
1134
1135 /**
1136 * Scroll the terminal down 1 row, creating a blank line.
1137 * @param {boolean} isWrapped Whether the new line is wrapped from the previous
1138 * line.
1139 */
1140 Terminal.prototype.scroll = function(isWrapped) {
1141 var row;
1142
1143 // Make room for the new row in lines
1144 if (this.buffer.lines.length === this.buffer.lines.maxLength) {
1145 this.buffer.lines.trimStart(1);
1146 this.buffer.ybase--;
1147 if (this.buffer.ydisp !== 0) {
1148 this.buffer.ydisp--;
1149 }
1150 }
1151
1152 this.buffer.ybase++;
1153
1154 // TODO: Why is this done twice?
1155 if (!this.userScrolling) {
1156 this.buffer.ydisp = this.buffer.ybase;
1157 }
1158
1159 // last line
1160 row = this.buffer.ybase + this.rows - 1;
1161
1162 // subtract the bottom scroll region
1163 row -= this.rows - 1 - this.buffer.scrollBottom;
1164
1165 if (row === this.buffer.lines.length) {
1166 // Optimization: pushing is faster than splicing when they amount to the same behavior
1167 this.buffer.lines.push(this.blankLine(undefined, isWrapped));
1168 } else {
1169 // add our new line
1170 this.buffer.lines.splice(row, 0, this.blankLine(undefined, isWrapped));
1171 }
1172
1173 if (this.buffer.scrollTop !== 0) {
1174 if (this.buffer.ybase !== 0) {
1175 this.buffer.ybase--;
1176 if (!this.userScrolling) {
1177 this.buffer.ydisp = this.buffer.ybase;
1178 }
1179 }
1180 this.buffer.lines.splice(this.buffer.ybase + this.buffer.scrollTop, 1);
1181 }
1182
1183 // this.maxRange();
1184 this.updateRange(this.buffer.scrollTop);
1185 this.updateRange(this.buffer.scrollBottom);
1186
1187 /**
1188 * This event is emitted whenever the terminal is scrolled.
1189 * The one parameter passed is the new y display position.
1190 *
1191 * @event scroll
1192 */
1193 this.emit('scroll', this.buffer.ydisp);
1194 };
1195
1196 /**
1197 * Scroll the display of the terminal
1198 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1199 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1200 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1201 * viewport originally.
1202 */
1203 Terminal.prototype.scrollDisp = function(disp, suppressScrollEvent) {
1204 if (disp < 0) {
1205 if (this.buffer.ydisp === 0) {
1206 return;
1207 }
1208 this.userScrolling = true;
1209 } else if (disp + this.buffer.ydisp >= this.buffer.ybase) {
1210 this.userScrolling = false;
1211 }
1212
1213 const oldYdisp = this.buffer.ydisp;
1214 this.buffer.ydisp = Math.max(Math.min(this.buffer.ydisp + disp, this.buffer.ybase), 0);
1215
1216 // No change occurred, don't trigger scroll/refresh
1217 if (oldYdisp === this.buffer.ydisp) {
1218 return;
1219 }
1220
1221 if (!suppressScrollEvent) {
1222 this.emit('scroll', this.buffer.ydisp);
1223 }
1224
1225 this.refresh(0, this.rows - 1);
1226 };
1227
1228 /**
1229 * Scroll the display of the terminal by a number of pages.
1230 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1231 */
1232 Terminal.prototype.scrollPages = function(pageCount) {
1233 this.scrollDisp(pageCount * (this.rows - 1));
1234 };
1235
1236 /**
1237 * Scrolls the display of the terminal to the top.
1238 */
1239 Terminal.prototype.scrollToTop = function() {
1240 this.scrollDisp(-this.buffer.ydisp);
1241 };
1242
1243 /**
1244 * Scrolls the display of the terminal to the bottom.
1245 */
1246 Terminal.prototype.scrollToBottom = function() {
1247 this.scrollDisp(this.buffer.ybase - this.buffer.ydisp);
1248 };
1249
1250 /**
1251 * Writes text to the terminal.
1252 * @param {string} data The text to write to the terminal.
1253 */
1254 Terminal.prototype.write = function(data) {
1255 this.writeBuffer.push(data);
1256
1257 // Send XOFF to pause the pty process if the write buffer becomes too large so
1258 // xterm.js can catch up before more data is sent. This is necessary in order
1259 // to keep signals such as ^C responsive.
1260 if (this.options.useFlowControl && !this.xoffSentToCatchUp && this.writeBuffer.length >= WRITE_BUFFER_PAUSE_THRESHOLD) {
1261 // XOFF - stop pty pipe
1262 // XON will be triggered by emulator before processing data chunk
1263 this.send(C0.DC3);
1264 this.xoffSentToCatchUp = true;
1265 }
1266
1267 if (!this.writeInProgress && this.writeBuffer.length > 0) {
1268 // Kick off a write which will write all data in sequence recursively
1269 this.writeInProgress = true;
1270 // Kick off an async innerWrite so more writes can come in while processing data
1271 var self = this;
1272 setTimeout(function () {
1273 self.innerWrite();
1274 });
1275 }
1276 };
1277
1278 Terminal.prototype.innerWrite = function() {
1279 var writeBatch = this.writeBuffer.splice(0, WRITE_BATCH_SIZE);
1280 while (writeBatch.length > 0) {
1281 var data = writeBatch.shift();
1282 var l = data.length, i = 0, j, cs, ch, code, low, ch_width, row;
1283
1284 // If XOFF was sent in order to catch up with the pty process, resume it if
1285 // the writeBuffer is empty to allow more data to come in.
1286 if (this.xoffSentToCatchUp && writeBatch.length === 0 && this.writeBuffer.length === 0) {
1287 this.send(C0.DC1);
1288 this.xoffSentToCatchUp = false;
1289 }
1290
1291 this.refreshStart = this.buffer.y;
1292 this.refreshEnd = this.buffer.y;
1293
1294 // HACK: Set the parser state based on it's state at the time of return.
1295 // This works around the bug #662 which saw the parser state reset in the
1296 // middle of parsing escape sequence in two chunks. For some reason the
1297 // state of the parser resets to 0 after exiting parser.parse. This change
1298 // just sets the state back based on the correct return statement.
1299 var state = this.parser.parse(data);
1300 this.parser.setState(state);
1301
1302 this.updateRange(this.buffer.y);
1303 this.refresh(this.refreshStart, this.refreshEnd);
1304 }
1305 if (this.writeBuffer.length > 0) {
1306 // Allow renderer to catch up before processing the next batch
1307 var self = this;
1308 setTimeout(function () {
1309 self.innerWrite();
1310 }, 0);
1311 } else {
1312 this.writeInProgress = false;
1313 }
1314 };
1315
1316 /**
1317 * Writes text to the terminal, followed by a break line character (\n).
1318 * @param {string} data The text to write to the terminal.
1319 */
1320 Terminal.prototype.writeln = function(data) {
1321 this.write(data + '\r\n');
1322 };
1323
1324 /**
1325 * DEPRECATED: only for backward compatibility. Please use attachCustomKeyEventHandler() instead.
1326 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1327 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1328 * the default action. The function returns whether the event should be processed by xterm.js.
1329 */
1330 Terminal.prototype.attachCustomKeydownHandler = function(customKeydownHandler) {
1331 let message = 'attachCustomKeydownHandler() is DEPRECATED and will be removed soon. Please use attachCustomKeyEventHandler() instead.';
1332 console.warn(message);
1333 this.attachCustomKeyEventHandler(customKeydownHandler);
1334 };
1335
1336 /**
1337 * Attaches a custom key event handler which is run before keys are processed, giving consumers of
1338 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1339 * should not.
1340 * @param {function} customKeyEventHandler The custom KeyboardEvent handler to attach. This is a
1341 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1342 * the default action. The function returns whether the event should be processed by xterm.js.
1343 */
1344 Terminal.prototype.attachCustomKeyEventHandler = function(customKeyEventHandler) {
1345 this.customKeyEventHandler = customKeyEventHandler;
1346 };
1347
1348 /**
1349 * Attaches a http(s) link handler, forcing web links to behave differently to
1350 * regular <a> tags. This will trigger a refresh as links potentially need to be
1351 * reconstructed. Calling this with null will remove the handler.
1352 * @param {LinkMatcherHandler} handler The handler callback function.
1353 */
1354 Terminal.prototype.setHypertextLinkHandler = function(handler) {
1355 if (!this.linkifier) {
1356 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1357 }
1358 this.linkifier.setHypertextLinkHandler(handler);
1359 // Refresh to force links to refresh
1360 this.refresh(0, this.rows - 1);
1361 };
1362
1363 /**
1364 * Attaches a validation callback for hypertext links. This is useful to use
1365 * validation logic or to do something with the link's element and url.
1366 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1367 * be cleared with null.
1368 */
1369 Terminal.prototype.setHypertextValidationCallback = function(callback) {
1370 if (!this.linkifier) {
1371 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1372 }
1373 this.linkifier.setHypertextValidationCallback(callback);
1374 // Refresh to force links to refresh
1375 this.refresh(0, this.rows - 1);
1376 };
1377
1378 /**
1379 * Registers a link matcher, allowing custom link patterns to be matched and
1380 * handled.
1381 * @param {RegExp} regex The regular expression to search for, specifically
1382 * this searches the textContent of the rows. You will want to use \s to match
1383 * a space ' ' character for example.
1384 * @param {LinkMatcherHandler} handler The callback when the link is called.
1385 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1386 * @return {number} The ID of the new matcher, this can be used to deregister.
1387 */
1388 Terminal.prototype.registerLinkMatcher = function(regex, handler, options) {
1389 if (this.linkifier) {
1390 var matcherId = this.linkifier.registerLinkMatcher(regex, handler, options);
1391 this.refresh(0, this.rows - 1);
1392 return matcherId;
1393 }
1394 };
1395
1396 /**
1397 * Deregisters a link matcher if it has been registered.
1398 * @param {number} matcherId The link matcher's ID (returned after register)
1399 */
1400 Terminal.prototype.deregisterLinkMatcher = function(matcherId) {
1401 if (this.linkifier) {
1402 if (this.linkifier.deregisterLinkMatcher(matcherId)) {
1403 this.refresh(0, this.rows - 1);
1404 }
1405 }
1406 };
1407
1408 /**
1409 * Gets whether the terminal has an active selection.
1410 */
1411 Terminal.prototype.hasSelection = function() {
1412 return this.selectionManager ? this.selectionManager.hasSelection : false;
1413 };
1414
1415 /**
1416 * Gets the terminal's current selection, this is useful for implementing copy
1417 * behavior outside of xterm.js.
1418 */
1419 Terminal.prototype.getSelection = function() {
1420 return this.selectionManager ? this.selectionManager.selectionText : '';
1421 };
1422
1423 /**
1424 * Clears the current terminal selection.
1425 */
1426 Terminal.prototype.clearSelection = function() {
1427 if (this.selectionManager) {
1428 this.selectionManager.clearSelection();
1429 }
1430 };
1431
1432 /**
1433 * Selects all text within the terminal.
1434 */
1435 Terminal.prototype.selectAll = function() {
1436 if (this.selectionManager) {
1437 this.selectionManager.selectAll();
1438 }
1439 };
1440
1441 /**
1442 * Handle a keydown event
1443 * Key Resources:
1444 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1445 * @param {KeyboardEvent} ev The keydown event to be handled.
1446 */
1447 Terminal.prototype.keyDown = function(ev) {
1448 if (this.customKeyEventHandler && this.customKeyEventHandler(ev) === false) {
1449 return false;
1450 }
1451
1452 this.restartCursorBlinking();
1453
1454 if (!this.compositionHelper.keydown.bind(this.compositionHelper)(ev)) {
1455 if (this.buffer.ybase !== this.buffer.ydisp) {
1456 this.scrollToBottom();
1457 }
1458 return false;
1459 }
1460
1461 var self = this;
1462 var result = this.evaluateKeyEscapeSequence(ev);
1463
1464 if (result.key === C0.DC3) { // XOFF
1465 this.writeStopped = true;
1466 } else if (result.key === C0.DC1) { // XON
1467 this.writeStopped = false;
1468 }
1469
1470 if (result.scrollDisp) {
1471 this.scrollDisp(result.scrollDisp);
1472 return this.cancel(ev, true);
1473 }
1474
1475 if (isThirdLevelShift(this, ev)) {
1476 return true;
1477 }
1478
1479 if (result.cancel) {
1480 // The event is canceled at the end already, is this necessary?
1481 this.cancel(ev, true);
1482 }
1483
1484 if (!result.key) {
1485 return true;
1486 }
1487
1488 this.emit('keydown', ev);
1489 this.emit('key', result.key, ev);
1490 this.showCursor();
1491 this.handler(result.key);
1492
1493 return this.cancel(ev, true);
1494 };
1495
1496 /**
1497 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1498 * returned value is the new key code to pass to the PTY.
1499 *
1500 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1501 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1502 */
1503 Terminal.prototype.evaluateKeyEscapeSequence = function(ev) {
1504 var result = {
1505 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1506 // canceled at the end of keyDown
1507 cancel: false,
1508 // The new key even to emit
1509 key: undefined,
1510 // The number of characters to scroll, if this is defined it will cancel the event
1511 scrollDisp: undefined
1512 };
1513 var modifiers = ev.shiftKey << 0 | ev.altKey << 1 | ev.ctrlKey << 2 | ev.metaKey << 3;
1514 switch (ev.keyCode) {
1515 case 8:
1516 // backspace
1517 if (ev.shiftKey) {
1518 result.key = C0.BS; // ^H
1519 break;
1520 }
1521 result.key = C0.DEL; // ^?
1522 break;
1523 case 9:
1524 // tab
1525 if (ev.shiftKey) {
1526 result.key = C0.ESC + '[Z';
1527 break;
1528 }
1529 result.key = C0.HT;
1530 result.cancel = true;
1531 break;
1532 case 13:
1533 // return/enter
1534 result.key = C0.CR;
1535 result.cancel = true;
1536 break;
1537 case 27:
1538 // escape
1539 result.key = C0.ESC;
1540 result.cancel = true;
1541 break;
1542 case 37:
1543 // left-arrow
1544 if (modifiers) {
1545 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';
1546 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1547 // http://unix.stackexchange.com/a/108106
1548 // macOS uses different escape sequences than linux
1549 if (result.key == C0.ESC + '[1;3D') {
1550 result.key = (this.browser.isMac) ? C0.ESC + 'b' : C0.ESC + '[1;5D';
1551 }
1552 } else if (this.applicationCursor) {
1553 result.key = C0.ESC + 'OD';
1554 } else {
1555 result.key = C0.ESC + '[D';
1556 }
1557 break;
1558 case 39:
1559 // right-arrow
1560 if (modifiers) {
1561 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';
1562 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1563 // http://unix.stackexchange.com/a/108106
1564 // macOS uses different escape sequences than linux
1565 if (result.key == C0.ESC + '[1;3C') {
1566 result.key = (this.browser.isMac) ? C0.ESC + 'f' : C0.ESC + '[1;5C';
1567 }
1568 } else if (this.applicationCursor) {
1569 result.key = C0.ESC + 'OC';
1570 } else {
1571 result.key = C0.ESC + '[C';
1572 }
1573 break;
1574 case 38:
1575 // up-arrow
1576 if (modifiers) {
1577 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';
1578 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1579 // http://unix.stackexchange.com/a/108106
1580 if (result.key == C0.ESC + '[1;3A') {
1581 result.key = C0.ESC + '[1;5A';
1582 }
1583 } else if (this.applicationCursor) {
1584 result.key = C0.ESC + 'OA';
1585 } else {
1586 result.key = C0.ESC + '[A';
1587 }
1588 break;
1589 case 40:
1590 // down-arrow
1591 if (modifiers) {
1592 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';
1593 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1594 // http://unix.stackexchange.com/a/108106
1595 if (result.key == C0.ESC + '[1;3B') {
1596 result.key = C0.ESC + '[1;5B';
1597 }
1598 } else if (this.applicationCursor) {
1599 result.key = C0.ESC + 'OB';
1600 } else {
1601 result.key = C0.ESC + '[B';
1602 }
1603 break;
1604 case 45:
1605 // insert
1606 if (!ev.shiftKey && !ev.ctrlKey) {
1607 // <Ctrl> or <Shift> + <Insert> are used to
1608 // copy-paste on some systems.
1609 result.key = C0.ESC + '[2~';
1610 }
1611 break;
1612 case 46:
1613 // delete
1614 if (modifiers) {
1615 result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';
1616 } else {
1617 result.key = C0.ESC + '[3~';
1618 }
1619 break;
1620 case 36:
1621 // home
1622 if (modifiers)
1623 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';
1624 else if (this.applicationCursor)
1625 result.key = C0.ESC + 'OH';
1626 else
1627 result.key = C0.ESC + '[H';
1628 break;
1629 case 35:
1630 // end
1631 if (modifiers)
1632 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';
1633 else if (this.applicationCursor)
1634 result.key = C0.ESC + 'OF';
1635 else
1636 result.key = C0.ESC + '[F';
1637 break;
1638 case 33:
1639 // page up
1640 if (ev.shiftKey) {
1641 result.scrollDisp = -(this.rows - 1);
1642 } else {
1643 result.key = C0.ESC + '[5~';
1644 }
1645 break;
1646 case 34:
1647 // page down
1648 if (ev.shiftKey) {
1649 result.scrollDisp = this.rows - 1;
1650 } else {
1651 result.key = C0.ESC + '[6~';
1652 }
1653 break;
1654 case 112:
1655 // F1-F12
1656 if (modifiers) {
1657 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';
1658 } else {
1659 result.key = C0.ESC + 'OP';
1660 }
1661 break;
1662 case 113:
1663 if (modifiers) {
1664 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';
1665 } else {
1666 result.key = C0.ESC + 'OQ';
1667 }
1668 break;
1669 case 114:
1670 if (modifiers) {
1671 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';
1672 } else {
1673 result.key = C0.ESC + 'OR';
1674 }
1675 break;
1676 case 115:
1677 if (modifiers) {
1678 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';
1679 } else {
1680 result.key = C0.ESC + 'OS';
1681 }
1682 break;
1683 case 116:
1684 if (modifiers) {
1685 result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';
1686 } else {
1687 result.key = C0.ESC + '[15~';
1688 }
1689 break;
1690 case 117:
1691 if (modifiers) {
1692 result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';
1693 } else {
1694 result.key = C0.ESC + '[17~';
1695 }
1696 break;
1697 case 118:
1698 if (modifiers) {
1699 result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';
1700 } else {
1701 result.key = C0.ESC + '[18~';
1702 }
1703 break;
1704 case 119:
1705 if (modifiers) {
1706 result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';
1707 } else {
1708 result.key = C0.ESC + '[19~';
1709 }
1710 break;
1711 case 120:
1712 if (modifiers) {
1713 result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';
1714 } else {
1715 result.key = C0.ESC + '[20~';
1716 }
1717 break;
1718 case 121:
1719 if (modifiers) {
1720 result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';
1721 } else {
1722 result.key = C0.ESC + '[21~';
1723 }
1724 break;
1725 case 122:
1726 if (modifiers) {
1727 result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';
1728 } else {
1729 result.key = C0.ESC + '[23~';
1730 }
1731 break;
1732 case 123:
1733 if (modifiers) {
1734 result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';
1735 } else {
1736 result.key = C0.ESC + '[24~';
1737 }
1738 break;
1739 default:
1740 // a-z and space
1741 if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
1742 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
1743 result.key = String.fromCharCode(ev.keyCode - 64);
1744 } else if (ev.keyCode === 32) {
1745 // NUL
1746 result.key = String.fromCharCode(0);
1747 } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
1748 // escape, file sep, group sep, record sep, unit sep
1749 result.key = String.fromCharCode(ev.keyCode - 51 + 27);
1750 } else if (ev.keyCode === 56) {
1751 // delete
1752 result.key = String.fromCharCode(127);
1753 } else if (ev.keyCode === 219) {
1754 // ^[ - Control Sequence Introducer (CSI)
1755 result.key = String.fromCharCode(27);
1756 } else if (ev.keyCode === 220) {
1757 // ^\ - String Terminator (ST)
1758 result.key = String.fromCharCode(28);
1759 } else if (ev.keyCode === 221) {
1760 // ^] - Operating System Command (OSC)
1761 result.key = String.fromCharCode(29);
1762 }
1763 } else if (!this.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
1764 // On Mac this is a third level shift. Use <Esc> instead.
1765 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
1766 result.key = C0.ESC + String.fromCharCode(ev.keyCode + 32);
1767 } else if (ev.keyCode === 192) {
1768 result.key = C0.ESC + '`';
1769 } else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
1770 result.key = C0.ESC + (ev.keyCode - 48);
1771 }
1772 } else if (this.browser.isMac && !ev.altKey && !ev.ctrlKey && ev.metaKey) {
1773 if (ev.keyCode === 65) { // cmd + a
1774 this.selectAll();
1775 }
1776 }
1777 break;
1778 }
1779
1780 return result;
1781 };
1782
1783 /**
1784 * Set the G level of the terminal
1785 * @param g
1786 */
1787 Terminal.prototype.setgLevel = function(g) {
1788 this.glevel = g;
1789 this.charset = this.charsets[g];
1790 };
1791
1792 /**
1793 * Set the charset for the given G level of the terminal
1794 * @param g
1795 * @param charset
1796 */
1797 Terminal.prototype.setgCharset = function(g, charset) {
1798 this.charsets[g] = charset;
1799 if (this.glevel === g) {
1800 this.charset = charset;
1801 }
1802 };
1803
1804 /**
1805 * Handle a keypress event.
1806 * Key Resources:
1807 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1808 * @param {KeyboardEvent} ev The keypress event to be handled.
1809 */
1810 Terminal.prototype.keyPress = function(ev) {
1811 var key;
1812
1813 if (this.customKeyEventHandler && this.customKeyEventHandler(ev) === false) {
1814 return false;
1815 }
1816
1817 this.cancel(ev);
1818
1819 if (ev.charCode) {
1820 key = ev.charCode;
1821 } else if (ev.which == null) {
1822 key = ev.keyCode;
1823 } else if (ev.which !== 0 && ev.charCode !== 0) {
1824 key = ev.which;
1825 } else {
1826 return false;
1827 }
1828
1829 if (!key || (
1830 (ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
1831 )) {
1832 return false;
1833 }
1834
1835 key = String.fromCharCode(key);
1836
1837 this.emit('keypress', key, ev);
1838 this.emit('key', key, ev);
1839 this.showCursor();
1840 this.handler(key);
1841
1842 return true;
1843 };
1844
1845 /**
1846 * Send data for handling to the terminal
1847 * @param {string} data
1848 */
1849 Terminal.prototype.send = function(data) {
1850 var self = this;
1851
1852 if (!this.queue) {
1853 setTimeout(function() {
1854 self.handler(self.queue);
1855 self.queue = '';
1856 }, 1);
1857 }
1858
1859 this.queue += data;
1860 };
1861
1862 /**
1863 * Ring the bell.
1864 * Note: We could do sweet things with webaudio here
1865 */
1866 Terminal.prototype.bell = function() {
1867 if (!this.visualBell) return;
1868 var self = this;
1869 this.element.style.borderColor = 'white';
1870 setTimeout(function() {
1871 self.element.style.borderColor = '';
1872 }, 10);
1873 if (this.popOnBell) this.focus();
1874 };
1875
1876 /**
1877 * Log the current state to the console.
1878 */
1879 Terminal.prototype.log = function() {
1880 if (!this.debug) return;
1881 if (!this.context.console || !this.context.console.log) return;
1882 var args = Array.prototype.slice.call(arguments);
1883 this.context.console.log.apply(this.context.console, args);
1884 };
1885
1886 /**
1887 * Log the current state as error to the console.
1888 */
1889 Terminal.prototype.error = function() {
1890 if (!this.debug) return;
1891 if (!this.context.console || !this.context.console.error) return;
1892 var args = Array.prototype.slice.call(arguments);
1893 this.context.console.error.apply(this.context.console, args);
1894 };
1895
1896 /**
1897 * Resizes the terminal.
1898 *
1899 * @param {number} x The number of columns to resize to.
1900 * @param {number} y The number of rows to resize to.
1901 */
1902 Terminal.prototype.resize = function(x, y) {
1903 if (isNaN(x) || isNaN(y)) {
1904 return;
1905 }
1906
1907 if (y > this.getOption('scrollback')) {
1908 this.setOption('scrollback', y)
1909 }
1910
1911 var line
1912 , el
1913 , i
1914 , j
1915 , ch
1916 , addToY;
1917
1918 if (x === this.cols && y === this.rows) {
1919 // Check if we still need to measure the char size (fixes #785).
1920 if (!this.charMeasure.width || !this.charMeasure.height) {
1921 this.charMeasure.measure();
1922 }
1923 return;
1924 }
1925
1926 if (x < 1) x = 1;
1927 if (y < 1) y = 1;
1928
1929 // resize cols
1930 j = this.cols;
1931 if (j < x) {
1932 ch = [this.defAttr, ' ', 1]; // does xterm use the default attr?
1933 i = this.buffer.lines.length;
1934 while (i--) {
1935 if (this.buffer.lines.get(i) === undefined) {
1936 this.buffer.lines.set(i, this.blankLine());
1937 }
1938 while (this.buffer.lines.get(i).length < x) {
1939 this.buffer.lines.get(i).push(ch);
1940 }
1941 }
1942 }
1943
1944 this.cols = x;
1945 this.setupStops(this.cols);
1946
1947 // resize rows
1948 j = this.rows;
1949 addToY = 0;
1950 if (j < y) {
1951 el = this.element;
1952 while (j++ < y) {
1953 // y is rows, not this.buffer.y
1954 if (this.buffer.lines.length < y + this.buffer.ybase) {
1955 if (this.buffer.ybase > 0 && this.buffer.lines.length <= this.buffer.ybase + this.buffer.y + addToY + 1) {
1956 // There is room above the buffer and there are no empty elements below the line,
1957 // scroll up
1958 this.buffer.ybase--;
1959 addToY++;
1960 if (this.buffer.ydisp > 0) {
1961 // Viewport is at the top of the buffer, must increase downwards
1962 this.buffer.ydisp--;
1963 }
1964 } else {
1965 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1966 // are blank lines after the cursor
1967 this.buffer.lines.push(this.blankLine());
1968 }
1969 }
1970 if (this.children.length < y) {
1971 this.insertRow();
1972 }
1973 }
1974 } else { // (j > y)
1975 while (j-- > y) {
1976 if (this.buffer.lines.length > y + this.buffer.ybase) {
1977 if (this.buffer.lines.length > this.buffer.ybase + this.buffer.y + 1) {
1978 // The line is a blank line below the cursor, remove it
1979 this.buffer.lines.pop();
1980 } else {
1981 // The line is the cursor, scroll down
1982 this.buffer.ybase++;
1983 this.buffer.ydisp++;
1984 }
1985 }
1986 if (this.children.length > y) {
1987 el = this.children.shift();
1988 if (!el) continue;
1989 el.parentNode.removeChild(el);
1990 }
1991 }
1992 }
1993 this.rows = y;
1994
1995 // Make sure that the cursor stays on screen
1996 if (this.buffer.y >= y) {
1997 this.buffer.y = y - 1;
1998 }
1999 if (addToY) {
2000 this.buffer.y += addToY;
2001 }
2002
2003 if (this.buffer.x >= x) {
2004 this.buffer.x = x - 1;
2005 }
2006
2007 this.buffer.scrollTop = 0;
2008 this.buffer.scrollBottom = y - 1;
2009
2010 this.charMeasure.measure();
2011
2012 this.refresh(0, this.rows - 1);
2013
2014 this.geometry = [this.cols, this.rows];
2015 this.emit('resize', {terminal: this, cols: x, rows: y});
2016 };
2017
2018 /**
2019 * Updates the range of rows to refresh
2020 * @param {number} y The number of rows to refresh next.
2021 */
2022 Terminal.prototype.updateRange = function(y) {
2023 if (y < this.refreshStart) this.refreshStart = y;
2024 if (y > this.refreshEnd) this.refreshEnd = y;
2025 // if (y > this.refreshEnd) {
2026 // this.refreshEnd = y;
2027 // if (y > this.rows - 1) {
2028 // this.refreshEnd = this.rows - 1;
2029 // }
2030 // }
2031 };
2032
2033 /**
2034 * Set the range of refreshing to the maximum value
2035 */
2036 Terminal.prototype.maxRange = function() {
2037 this.refreshStart = 0;
2038 this.refreshEnd = this.rows - 1;
2039 };
2040
2041
2042
2043 /**
2044 * Setup the tab stops.
2045 * @param {number} i
2046 */
2047 Terminal.prototype.setupStops = function(i) {
2048 if (i != null) {
2049 if (!this.buffer.tabs[i]) {
2050 i = this.prevStop(i);
2051 }
2052 } else {
2053 this.buffer.tabs = {};
2054 i = 0;
2055 }
2056
2057 for (; i < this.cols; i += this.getOption('tabStopWidth')) {
2058 this.buffer.tabs[i] = true;
2059 }
2060 };
2061
2062
2063 /**
2064 * Move the cursor to the previous tab stop from the given position (default is current).
2065 * @param {number} x The position to move the cursor to the previous tab stop.
2066 */
2067 Terminal.prototype.prevStop = function(x) {
2068 if (x == null) x = this.buffer.x;
2069 while (!this.buffer.tabs[--x] && x > 0);
2070 return x >= this.cols
2071 ? this.cols - 1
2072 : x < 0 ? 0 : x;
2073 };
2074
2075
2076 /**
2077 * Move the cursor one tab stop forward from the given position (default is current).
2078 * @param {number} x The position to move the cursor one tab stop forward.
2079 */
2080 Terminal.prototype.nextStop = function(x) {
2081 if (x == null) x = this.buffer.x;
2082 while (!this.buffer.tabs[++x] && x < this.cols);
2083 return x >= this.cols
2084 ? this.cols - 1
2085 : x < 0 ? 0 : x;
2086 };
2087
2088
2089 /**
2090 * Erase in the identified line everything from "x" to the end of the line (right).
2091 * @param {number} x The column from which to start erasing to the end of the line.
2092 * @param {number} y The line in which to operate.
2093 */
2094 Terminal.prototype.eraseRight = function(x, y) {
2095 var line = this.buffer.lines.get(this.buffer.ybase + y);
2096 if (!line) {
2097 return;
2098 }
2099 var ch = [this.eraseAttr(), ' ', 1]; // xterm
2100 for (; x < this.cols; x++) {
2101 line[x] = ch;
2102 }
2103 this.updateRange(y);
2104 };
2105
2106
2107
2108 /**
2109 * Erase in the identified line everything from "x" to the start of the line (left).
2110 * @param {number} x The column from which to start erasing to the start of the line.
2111 * @param {number} y The line in which to operate.
2112 */
2113 Terminal.prototype.eraseLeft = function(x, y) {
2114 var line = this.buffer.lines.get(this.buffer.ybase + y);
2115 if (!line) {
2116 return;
2117 }
2118 var ch = [this.eraseAttr(), ' ', 1]; // xterm
2119 x++;
2120 while (x--) {
2121 line[x] = ch;
2122 }
2123 this.updateRange(y);
2124 };
2125
2126 /**
2127 * Clears the entire buffer, making the prompt line the new first line.
2128 */
2129 Terminal.prototype.clear = function() {
2130 if (this.buffer.ybase === 0 && this.buffer.y === 0) {
2131 // Don't clear if it's already clear
2132 return;
2133 }
2134 this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y));
2135 this.buffer.lines.length = 1;
2136 this.buffer.ydisp = 0;
2137 this.buffer.ybase = 0;
2138 this.buffer.y = 0;
2139 for (var i = 1; i < this.rows; i++) {
2140 this.buffer.lines.push(this.blankLine());
2141 }
2142 this.refresh(0, this.rows - 1);
2143 this.emit('scroll', this.buffer.ydisp);
2144 };
2145
2146 /**
2147 * Erase all content in the given line
2148 * @param {number} y The line to erase all of its contents.
2149 */
2150 Terminal.prototype.eraseLine = function(y) {
2151 this.eraseRight(0, y);
2152 };
2153
2154
2155 /**
2156 * Return the data array of a blank line
2157 * @param {number} cur First bunch of data for each "blank" character.
2158 * @param {boolean} isWrapped Whether the new line is wrapped from the previous line.
2159 */
2160 Terminal.prototype.blankLine = function(cur, isWrapped) {
2161 var attr = cur
2162 ? this.eraseAttr()
2163 : this.defAttr;
2164
2165 var ch = [attr, ' ', 1] // width defaults to 1 halfwidth character
2166 , line = []
2167 , i = 0;
2168
2169 // TODO: It is not ideal that this is a property on an array, a buffer line
2170 // class should be added that will hold this data and other useful functions.
2171 if (isWrapped) {
2172 line.isWrapped = isWrapped;
2173 }
2174
2175 for (; i < this.cols; i++) {
2176 line[i] = ch;
2177 }
2178
2179 return line;
2180 };
2181
2182
2183 /**
2184 * If cur return the back color xterm feature attribute. Else return defAttr.
2185 * @param {object} cur
2186 */
2187 Terminal.prototype.ch = function(cur) {
2188 return cur
2189 ? [this.eraseAttr(), ' ', 1]
2190 : [this.defAttr, ' ', 1];
2191 };
2192
2193
2194 /**
2195 * Evaluate if the current terminal is the given argument.
2196 * @param {object} term The terminal to evaluate
2197 */
2198 Terminal.prototype.is = function(term) {
2199 var name = this.termName;
2200 return (name + '').indexOf(term) === 0;
2201 };
2202
2203
2204 /**
2205 * Emit the 'data' event and populate the given data.
2206 * @param {string} data The data to populate in the event.
2207 */
2208 Terminal.prototype.handler = function(data) {
2209 // Prevents all events to pty process if stdin is disabled
2210 if (this.options.disableStdin) {
2211 return;
2212 }
2213
2214 // Clear the selection if the selection manager is available and has an active selection
2215 if (this.selectionManager && this.selectionManager.hasSelection) {
2216 this.selectionManager.clearSelection();
2217 }
2218
2219 // Input is being sent to the terminal, the terminal should focus the prompt.
2220 if (this.buffer.ybase !== this.buffer.ydisp) {
2221 this.scrollToBottom();
2222 }
2223 this.emit('data', data);
2224 };
2225
2226
2227 /**
2228 * Emit the 'title' event and populate the given title.
2229 * @param {string} title The title to populate in the event.
2230 */
2231 Terminal.prototype.handleTitle = function(title) {
2232 /**
2233 * This event is emitted when the title of the terminal is changed
2234 * from inside the terminal. The parameter is the new title.
2235 *
2236 * @event title
2237 */
2238 this.emit('title', title);
2239 };
2240
2241
2242 /**
2243 * ESC
2244 */
2245
2246 /**
2247 * ESC D Index (IND is 0x84).
2248 */
2249 Terminal.prototype.index = function() {
2250 this.buffer.y++;
2251 if (this.buffer.y > this.buffer.scrollBottom) {
2252 this.buffer.y--;
2253 this.scroll();
2254 }
2255 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2256 if (this.buffer.x >= this.cols) {
2257 this.buffer.x--;
2258 }
2259 };
2260
2261
2262 /**
2263 * ESC M Reverse Index (RI is 0x8d).
2264 *
2265 * Move the cursor up one row, inserting a new blank line if necessary.
2266 */
2267 Terminal.prototype.reverseIndex = function() {
2268 var j;
2269 if (this.buffer.y === this.buffer.scrollTop) {
2270 // possibly move the code below to term.reverseScroll();
2271 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2272 // blankLine(true) is xterm/linux behavior
2273 this.buffer.lines.shiftElements(this.buffer.y + this.buffer.ybase, this.rows - 1, 1);
2274 this.buffer.lines.set(this.buffer.y + this.buffer.ybase, this.blankLine(true));
2275 this.updateRange(this.buffer.scrollTop);
2276 this.updateRange(this.buffer.scrollBottom);
2277 } else {
2278 this.buffer.y--;
2279 }
2280 };
2281
2282
2283 /**
2284 * ESC c Full Reset (RIS).
2285 */
2286 Terminal.prototype.reset = function() {
2287 this.options.rows = this.rows;
2288 this.options.cols = this.cols;
2289 var customKeyEventHandler = this.customKeyEventHandler;
2290 var cursorBlinkInterval = this.cursorBlinkInterval;
2291 var inputHandler = this.inputHandler;
2292 var buffers = this.buffers;
2293 Terminal.call(this, this.options);
2294 this.customKeyEventHandler = customKeyEventHandler;
2295 this.cursorBlinkInterval = cursorBlinkInterval;
2296 this.inputHandler = inputHandler;
2297 this.buffers = buffers;
2298 this.refresh(0, this.rows - 1);
2299 this.viewport.syncScrollArea();
2300 };
2301
2302
2303 /**
2304 * ESC H Tab Set (HTS is 0x88).
2305 */
2306 Terminal.prototype.tabSet = function() {
2307 this.buffer.tabs[this.buffer.x] = true;
2308 };
2309
2310 /**
2311 * Helpers
2312 */
2313
2314 function on(el, type, handler, capture) {
2315 if (!Array.isArray(el)) {
2316 el = [el];
2317 }
2318 el.forEach(function (element) {
2319 element.addEventListener(type, handler, capture || false);
2320 });
2321 }
2322
2323 function off(el, type, handler, capture) {
2324 el.removeEventListener(type, handler, capture || false);
2325 }
2326
2327 function cancel(ev, force) {
2328 if (!this.cancelEvents && !force) {
2329 return;
2330 }
2331 ev.preventDefault();
2332 ev.stopPropagation();
2333 return false;
2334 }
2335
2336 function inherits(child, parent) {
2337 function f() {
2338 this.constructor = child;
2339 }
2340 f.prototype = parent.prototype;
2341 child.prototype = new f;
2342 }
2343
2344 function indexOf(obj, el) {
2345 var i = obj.length;
2346 while (i--) {
2347 if (obj[i] === el) return i;
2348 }
2349 return -1;
2350 }
2351
2352 function isThirdLevelShift(term, ev) {
2353 var thirdLevelKey =
2354 (term.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
2355 (term.browser.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
2356
2357 if (ev.type == 'keypress') {
2358 return thirdLevelKey;
2359 }
2360
2361 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2362 return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
2363 }
2364
2365 // Expose to InputHandler (temporary)
2366 Terminal.prototype.matchColor = matchColor;
2367
2368 function matchColor(r1, g1, b1) {
2369 var hash = (r1 << 16) | (g1 << 8) | b1;
2370
2371 if (matchColor._cache[hash] != null) {
2372 return matchColor._cache[hash];
2373 }
2374
2375 var ldiff = Infinity
2376 , li = -1
2377 , i = 0
2378 , c
2379 , r2
2380 , g2
2381 , b2
2382 , diff;
2383
2384 for (; i < Terminal.vcolors.length; i++) {
2385 c = Terminal.vcolors[i];
2386 r2 = c[0];
2387 g2 = c[1];
2388 b2 = c[2];
2389
2390 diff = matchColor.distance(r1, g1, b1, r2, g2, b2);
2391
2392 if (diff === 0) {
2393 li = i;
2394 break;
2395 }
2396
2397 if (diff < ldiff) {
2398 ldiff = diff;
2399 li = i;
2400 }
2401 }
2402
2403 return matchColor._cache[hash] = li;
2404 }
2405
2406 matchColor._cache = {};
2407
2408 // http://stackoverflow.com/questions/1633828
2409 matchColor.distance = function(r1, g1, b1, r2, g2, b2) {
2410 return Math.pow(30 * (r1 - r2), 2)
2411 + Math.pow(59 * (g1 - g2), 2)
2412 + Math.pow(11 * (b1 - b2), 2);
2413 };
2414
2415 function each(obj, iter, con) {
2416 if (obj.forEach) return obj.forEach(iter, con);
2417 for (var i = 0; i < obj.length; i++) {
2418 iter.call(con, obj[i], i, obj);
2419 }
2420 }
2421
2422 function wasMondifierKeyOnlyEvent(ev) {
2423 return ev.keyCode === 16 || // Shift
2424 ev.keyCode === 17 || // Ctrl
2425 ev.keyCode === 18; // Alt
2426 }
2427
2428 function keys(obj) {
2429 if (Object.keys) return Object.keys(obj);
2430 var key, keys = [];
2431 for (key in obj) {
2432 if (Object.prototype.hasOwnProperty.call(obj, key)) {
2433 keys.push(key);
2434 }
2435 }
2436 return keys;
2437 }
2438
2439 /**
2440 * Expose
2441 */
2442
2443 Terminal.translateBufferLineToString = translateBufferLineToString;
2444 Terminal.EventEmitter = EventEmitter;
2445 Terminal.inherits = inherits;
2446
2447 /**
2448 * Adds an event listener to the terminal.
2449 *
2450 * @param {string} event The name of the event. TODO: Document all event types
2451 * @param {function} callback The function to call when the event is triggered.
2452 */
2453 Terminal.on = on;
2454 Terminal.off = off;
2455 Terminal.cancel = cancel;
2456
2457 module.exports = Terminal;