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