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