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