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