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