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