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