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