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