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