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