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