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