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