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