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