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