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