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