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