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