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