]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/xterm.js
Add disableStdin option
[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.js';
14 import { EventEmitter } from './EventEmitter.js';
15 import { Viewport } from './Viewport.js';
16 import { rightClickHandler, pasteHandler, copyHandler } from './handlers/Clipboard.js';
17 import { CircularList } from './utils/CircularList.js';
18 import * as Browser from './utils/Browser';
19 import * as Keyboard from './utils/Keyboard';
20
21 /**
22 * Terminal Emulation References:
23 * http://vt100.net/
24 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
25 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
26 * http://invisible-island.net/vttest/
27 * http://www.inwap.com/pdp10/ansicode.txt
28 * http://linux.die.net/man/4/console_codes
29 * http://linux.die.net/man/7/urxvt
30 */
31
32 // Let it work inside Node.js for automated testing purposes.
33 var document = (typeof window != 'undefined') ? window.document : null;
34
35 /**
36 * States
37 */
38 var normal = 0, escaped = 1, csi = 2, osc = 3, charset = 4, dcs = 5, ignore = 6;
39
40 /**
41 * Terminal
42 */
43
44 /**
45 * Creates a new `Terminal` object.
46 *
47 * @param {object} options An object containing a set of options, the available options are:
48 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
49 * - `cols` (number): The number of columns of the terminal (horizontal size)
50 * - `rows` (number): The number of rows of the terminal (vertical size)
51 *
52 * @public
53 * @class Xterm Xterm
54 * @alias module:xterm/src/xterm
55 */
56 function Terminal(options) {
57 var self = this;
58
59 if (!(this instanceof Terminal)) {
60 return new Terminal(arguments[0], arguments[1], arguments[2]);
61 }
62
63 self.browser = Browser;
64 self.cancel = Terminal.cancel;
65
66 EventEmitter.call(this);
67
68 if (typeof options === 'number') {
69 options = {
70 cols: arguments[0],
71 rows: arguments[1],
72 handler: arguments[2]
73 };
74 }
75
76 options = options || {};
77
78
79 Object.keys(Terminal.defaults).forEach(function(key) {
80 if (options[key] == null) {
81 options[key] = Terminal.options[key];
82
83 if (Terminal[key] !== Terminal.defaults[key]) {
84 options[key] = Terminal[key];
85 }
86 }
87 self[key] = options[key];
88 });
89
90 if (options.colors.length === 8) {
91 options.colors = options.colors.concat(Terminal._colors.slice(8));
92 } else if (options.colors.length === 16) {
93 options.colors = options.colors.concat(Terminal._colors.slice(16));
94 } else if (options.colors.length === 10) {
95 options.colors = options.colors.slice(0, -2).concat(
96 Terminal._colors.slice(8, -2), options.colors.slice(-2));
97 } else if (options.colors.length === 18) {
98 options.colors = options.colors.concat(
99 Terminal._colors.slice(16, -2), options.colors.slice(-2));
100 }
101 this.colors = options.colors;
102
103 this.options = options;
104
105 // this.context = options.context || window;
106 // this.document = options.document || document;
107 this.parent = options.body || options.parent || (
108 document ? document.getElementsByTagName('body')[0] : null
109 );
110
111 this.cols = options.cols || options.geometry[0];
112 this.rows = options.rows || options.geometry[1];
113 this.geometry = [this.cols, this.rows];
114
115 if (options.handler) {
116 this.on('data', options.handler);
117 }
118
119 /**
120 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
121 * buffer
122 */
123 this.ybase = 0;
124
125 /**
126 * The scroll position of the viewport
127 */
128 this.ydisp = 0;
129
130 /**
131 * The cursor's x position after ybase
132 */
133 this.x = 0;
134
135 /**
136 * The cursor's y position after ybase
137 */
138 this.y = 0;
139
140 /**
141 * Used to debounce the refresh function
142 */
143 this.isRefreshing = false;
144
145 /**
146 * Whether there is a full terminal refresh queued
147 */
148
149 this.cursorState = 0;
150 this.cursorHidden = false;
151 this.convertEol;
152 this.state = 0;
153 this.queue = '';
154 this.scrollTop = 0;
155 this.scrollBottom = this.rows - 1;
156 this.customKeydownHandler = null;
157
158 // modes
159 this.applicationKeypad = false;
160 this.applicationCursor = false;
161 this.originMode = false;
162 this.insertMode = false;
163 this.wraparoundMode = true; // defaults: xterm - true, vt100 - false
164 this.normal = null;
165
166 // charset
167 this.charset = null;
168 this.gcharset = null;
169 this.glevel = 0;
170 this.charsets = [null];
171
172 // mouse properties
173 this.decLocator;
174 this.x10Mouse;
175 this.vt200Mouse;
176 this.vt300Mouse;
177 this.normalMouse;
178 this.mouseEvents;
179 this.sendFocus;
180 this.utfMouse;
181 this.sgrMouse;
182 this.urxvtMouse;
183
184 // misc
185 this.element;
186 this.children;
187 this.refreshStart;
188 this.refreshEnd;
189 this.savedX;
190 this.savedY;
191 this.savedCols;
192
193 // stream
194 this.readable = true;
195 this.writable = true;
196
197 this.defAttr = (0 << 18) | (257 << 9) | (256 << 0);
198 this.curAttr = this.defAttr;
199
200 this.params = [];
201 this.currentParam = 0;
202 this.prefix = '';
203 this.postfix = '';
204
205 // leftover surrogate high from previous write invocation
206 this.surrogate_high = '';
207
208 /**
209 * An array of all lines in the entire buffer, including the prompt. The lines are array of
210 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
211 */
212 this.lines = new CircularList(this.scrollback);
213 var i = this.rows;
214 while (i--) {
215 this.lines.push(this.blankLine());
216 }
217
218 this.tabs;
219 this.setupStops();
220
221 // Store if user went browsing history in scrollback
222 this.userScrolling = false;
223 }
224
225 inherits(Terminal, EventEmitter);
226
227 /**
228 * back_color_erase feature for xterm.
229 */
230 Terminal.prototype.eraseAttr = function() {
231 // if (this.is('screen')) return this.defAttr;
232 return (this.defAttr & ~0x1ff) | (this.curAttr & 0x1ff);
233 };
234
235 /**
236 * Colors
237 */
238
239 // Colors 0-15
240 Terminal.tangoColors = [
241 // dark:
242 '#2e3436',
243 '#cc0000',
244 '#4e9a06',
245 '#c4a000',
246 '#3465a4',
247 '#75507b',
248 '#06989a',
249 '#d3d7cf',
250 // bright:
251 '#555753',
252 '#ef2929',
253 '#8ae234',
254 '#fce94f',
255 '#729fcf',
256 '#ad7fa8',
257 '#34e2e2',
258 '#eeeeec'
259 ];
260
261 // Colors 0-15 + 16-255
262 // Much thanks to TooTallNate for writing this.
263 Terminal.colors = (function() {
264 var colors = Terminal.tangoColors.slice()
265 , r = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
266 , i;
267
268 // 16-231
269 i = 0;
270 for (; i < 216; i++) {
271 out(r[(i / 36) % 6 | 0], r[(i / 6) % 6 | 0], r[i % 6]);
272 }
273
274 // 232-255 (grey)
275 i = 0;
276 for (; i < 24; i++) {
277 r = 8 + i * 10;
278 out(r, r, r);
279 }
280
281 function out(r, g, b) {
282 colors.push('#' + hex(r) + hex(g) + hex(b));
283 }
284
285 function hex(c) {
286 c = c.toString(16);
287 return c.length < 2 ? '0' + c : c;
288 }
289
290 return colors;
291 })();
292
293 Terminal._colors = Terminal.colors.slice();
294
295 Terminal.vcolors = (function() {
296 var out = []
297 , colors = Terminal.colors
298 , i = 0
299 , color;
300
301 for (; i < 256; i++) {
302 color = parseInt(colors[i].substring(1), 16);
303 out.push([
304 (color >> 16) & 0xff,
305 (color >> 8) & 0xff,
306 color & 0xff
307 ]);
308 }
309
310 return out;
311 })();
312
313 /**
314 * Options
315 */
316
317 Terminal.defaults = {
318 colors: Terminal.colors,
319 theme: 'default',
320 convertEol: false,
321 termName: 'xterm',
322 geometry: [80, 24],
323 cursorBlink: false,
324 visualBell: false,
325 popOnBell: false,
326 scrollback: 1000,
327 screenKeys: false,
328 debug: false,
329 cancelEvents: false,
330 disableStdin: false
331 // programFeatures: false,
332 // focusKeys: false,
333 };
334
335 Terminal.options = {};
336
337 Terminal.focus = null;
338
339 each(keys(Terminal.defaults), function(key) {
340 Terminal[key] = Terminal.defaults[key];
341 Terminal.options[key] = Terminal.defaults[key];
342 });
343
344 /**
345 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
346 */
347 Terminal.prototype.focus = function() {
348 return this.textarea.focus();
349 };
350
351 /**
352 * Retrieves an option's value from the terminal.
353 * @param {string} key The option key.
354 */
355 Terminal.prototype.getOption = function(key, value) {
356 if (!(key in Terminal.defaults)) {
357 throw new Error('No option with key "' + key + '"');
358 }
359
360 if (typeof this.options[key] !== 'undefined') {
361 return this.options[key];
362 }
363
364 return this[key];
365 };
366
367 /**
368 * Sets an option on the terminal.
369 * @param {string} key The option key.
370 * @param {string} value The option value.
371 */
372 Terminal.prototype.setOption = function(key, value) {
373 if (!(key in Terminal.defaults)) {
374 throw new Error('No option with key "' + key + '"');
375 }
376 this[key] = value;
377 this.options[key] = value;
378 };
379
380 /**
381 * Binds the desired focus behavior on a given terminal object.
382 *
383 * @static
384 */
385 Terminal.bindFocus = function (term) {
386 on(term.textarea, 'focus', function (ev) {
387 if (term.sendFocus) {
388 term.send('\x1b[I');
389 }
390 term.element.classList.add('focus');
391 term.showCursor();
392 Terminal.focus = term;
393 term.emit('focus', {terminal: term});
394 });
395 };
396
397 /**
398 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
399 */
400 Terminal.prototype.blur = function() {
401 return this.textarea.blur();
402 };
403
404 /**
405 * Binds the desired blur behavior on a given terminal object.
406 *
407 * @static
408 */
409 Terminal.bindBlur = function (term) {
410 on(term.textarea, 'blur', function (ev) {
411 term.refresh(term.y, term.y);
412 if (term.sendFocus) {
413 term.send('\x1b[O');
414 }
415 term.element.classList.remove('focus');
416 Terminal.focus = null;
417 term.emit('blur', {terminal: term});
418 });
419 };
420
421 /**
422 * Initialize default behavior
423 */
424 Terminal.prototype.initGlobal = function() {
425 var term = this;
426
427 Terminal.bindKeys(this);
428 Terminal.bindFocus(this);
429 Terminal.bindBlur(this);
430
431 // Bind clipboard functionality
432 on(this.element, 'copy', function (ev) {
433 copyHandler.call(this, ev, term);
434 });
435 on(this.textarea, 'paste', function (ev) {
436 pasteHandler.call(this, ev, term);
437 });
438 on(this.element, 'paste', function (ev) {
439 pasteHandler.call(this, ev, term);
440 });
441
442 function rightClickHandlerWrapper (ev) {
443 rightClickHandler.call(this, ev, term);
444 }
445
446 if (term.browser.isFirefox) {
447 on(this.element, 'mousedown', function (ev) {
448 if (ev.button == 2) {
449 rightClickHandlerWrapper(ev);
450 }
451 });
452 } else {
453 on(this.element, 'contextmenu', rightClickHandlerWrapper);
454 }
455 };
456
457 /**
458 * Apply key handling to the terminal
459 */
460 Terminal.bindKeys = function(term) {
461 on(term.element, 'keydown', function(ev) {
462 if (document.activeElement != this) {
463 return;
464 }
465 term.keyDown(ev);
466 }, true);
467
468 on(term.element, 'keypress', function(ev) {
469 if (document.activeElement != this) {
470 return;
471 }
472 term.keyPress(ev);
473 }, true);
474
475 on(term.element, 'keyup', term.focus.bind(term));
476
477 on(term.textarea, 'keydown', function(ev) {
478 term.keyDown(ev);
479 }, true);
480
481 on(term.textarea, 'keypress', function(ev) {
482 term.keyPress(ev);
483 // Truncate the textarea's value, since it is not needed
484 this.value = '';
485 }, true);
486
487 on(term.textarea, 'compositionstart', term.compositionHelper.compositionstart.bind(term.compositionHelper));
488 on(term.textarea, 'compositionupdate', term.compositionHelper.compositionupdate.bind(term.compositionHelper));
489 on(term.textarea, 'compositionend', term.compositionHelper.compositionend.bind(term.compositionHelper));
490 term.on('refresh', term.compositionHelper.updateCompositionElements.bind(term.compositionHelper));
491 };
492
493
494 /**
495 * Insert the given row to the terminal or produce a new one
496 * if no row argument is passed. Return the inserted row.
497 * @param {HTMLElement} row (optional) The row to append to the terminal.
498 */
499 Terminal.prototype.insertRow = function (row) {
500 if (typeof row != 'object') {
501 row = document.createElement('div');
502 }
503
504 this.rowContainer.appendChild(row);
505 this.children.push(row);
506
507 return row;
508 };
509
510 /**
511 * Opens the terminal within an element.
512 *
513 * @param {HTMLElement} parent The element to create the terminal within.
514 */
515 Terminal.prototype.open = function(parent) {
516 var self=this, i=0, div;
517
518 this.parent = parent || this.parent;
519
520 if (!this.parent) {
521 throw new Error('Terminal requires a parent element.');
522 }
523
524 // Grab global elements
525 this.context = this.parent.ownerDocument.defaultView;
526 this.document = this.parent.ownerDocument;
527 this.body = this.document.getElementsByTagName('body')[0];
528
529 //Create main element container
530 this.element = this.document.createElement('div');
531 this.element.classList.add('terminal');
532 this.element.classList.add('xterm');
533 this.element.classList.add('xterm-theme-' + this.theme);
534
535 this.element.style.height
536 this.element.setAttribute('tabindex', 0);
537
538 this.viewportElement = document.createElement('div');
539 this.viewportElement.classList.add('xterm-viewport');
540 this.element.appendChild(this.viewportElement);
541 this.viewportScrollArea = document.createElement('div');
542 this.viewportScrollArea.classList.add('xterm-scroll-area');
543 this.viewportElement.appendChild(this.viewportScrollArea);
544
545 // Create the container that will hold the lines of the terminal and then
546 // produce the lines the lines.
547 this.rowContainer = document.createElement('div');
548 this.rowContainer.classList.add('xterm-rows');
549 this.element.appendChild(this.rowContainer);
550 this.children = [];
551
552 // Create the container that will hold helpers like the textarea for
553 // capturing DOM Events. Then produce the helpers.
554 this.helperContainer = document.createElement('div');
555 this.helperContainer.classList.add('xterm-helpers');
556 // TODO: This should probably be inserted once it's filled to prevent an additional layout
557 this.element.appendChild(this.helperContainer);
558 this.textarea = document.createElement('textarea');
559 this.textarea.classList.add('xterm-helper-textarea');
560 this.textarea.setAttribute('autocorrect', 'off');
561 this.textarea.setAttribute('autocapitalize', 'off');
562 this.textarea.setAttribute('spellcheck', 'false');
563 this.textarea.tabIndex = 0;
564 this.textarea.addEventListener('focus', function() {
565 self.emit('focus', {terminal: self});
566 });
567 this.textarea.addEventListener('blur', function() {
568 self.emit('blur', {terminal: self});
569 });
570 this.helperContainer.appendChild(this.textarea);
571
572 this.compositionView = document.createElement('div');
573 this.compositionView.classList.add('composition-view');
574 this.compositionHelper = new CompositionHelper(this.textarea, this.compositionView, this);
575 this.helperContainer.appendChild(this.compositionView);
576
577 this.charMeasureElement = document.createElement('div');
578 this.charMeasureElement.classList.add('xterm-char-measure-element');
579 this.charMeasureElement.innerHTML = 'W';
580 this.helperContainer.appendChild(this.charMeasureElement);
581
582 for (; i < this.rows; i++) {
583 this.insertRow();
584 }
585 this.parent.appendChild(this.element);
586
587 this.viewport = new Viewport(this, this.viewportElement, this.viewportScrollArea, this.charMeasureElement);
588
589 // Draw the screen.
590 this.refresh(0, this.rows - 1);
591
592 // Initialize global actions that
593 // need to be taken on the document.
594 this.initGlobal();
595
596 // Ensure there is a Terminal.focus.
597 this.focus();
598
599 on(this.element, 'click', function() {
600 var selection = document.getSelection(),
601 collapsed = selection.isCollapsed,
602 isRange = typeof collapsed == 'boolean' ? !collapsed : selection.type == 'Range';
603 if (!isRange) {
604 self.focus();
605 }
606 });
607
608 // Listen for mouse events and translate
609 // them into terminal mouse protocols.
610 this.bindMouse();
611
612 // Figure out whether boldness affects
613 // the character width of monospace fonts.
614 if (Terminal.brokenBold == null) {
615 Terminal.brokenBold = isBoldBroken(this.document);
616 }
617
618 /**
619 * This event is emitted when terminal has completed opening.
620 *
621 * @event open
622 */
623 this.emit('open');
624 };
625
626
627 /**
628 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
629 * @param {string} addon The name of the addon to load
630 * @static
631 */
632 Terminal.loadAddon = function(addon, callback) {
633 if (typeof exports === 'object' && typeof module === 'object') {
634 // CommonJS
635 return require('./addons/' + addon + '/' + addon);
636 } else if (typeof define == 'function') {
637 // RequireJS
638 return require(['./addons/' + addon + '/' + addon], callback);
639 } else {
640 console.error('Cannot load a module without a CommonJS or RequireJS environment.');
641 return false;
642 }
643 };
644
645
646 /**
647 * XTerm mouse events
648 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
649 * To better understand these
650 * the xterm code is very helpful:
651 * Relevant files:
652 * button.c, charproc.c, misc.c
653 * Relevant functions in xterm/button.c:
654 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
655 */
656 Terminal.prototype.bindMouse = function() {
657 var el = this.element, self = this, pressed = 32;
658
659 // mouseup, mousedown, wheel
660 // left click: ^[[M 3<^[[M#3<
661 // wheel up: ^[[M`3>
662 function sendButton(ev) {
663 var button
664 , pos;
665
666 // get the xterm-style button
667 button = getButton(ev);
668
669 // get mouse coordinates
670 pos = getCoords(ev);
671 if (!pos) return;
672
673 sendEvent(button, pos);
674
675 switch (ev.overrideType || ev.type) {
676 case 'mousedown':
677 pressed = button;
678 break;
679 case 'mouseup':
680 // keep it at the left
681 // button, just in case.
682 pressed = 32;
683 break;
684 case 'wheel':
685 // nothing. don't
686 // interfere with
687 // `pressed`.
688 break;
689 }
690 }
691
692 // motion example of a left click:
693 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
694 function sendMove(ev) {
695 var button = pressed
696 , pos;
697
698 pos = getCoords(ev);
699 if (!pos) return;
700
701 // buttons marked as motions
702 // are incremented by 32
703 button += 32;
704
705 sendEvent(button, pos);
706 }
707
708 // encode button and
709 // position to characters
710 function encode(data, ch) {
711 if (!self.utfMouse) {
712 if (ch === 255) return data.push(0);
713 if (ch > 127) ch = 127;
714 data.push(ch);
715 } else {
716 if (ch === 2047) return data.push(0);
717 if (ch < 127) {
718 data.push(ch);
719 } else {
720 if (ch > 2047) ch = 2047;
721 data.push(0xC0 | (ch >> 6));
722 data.push(0x80 | (ch & 0x3F));
723 }
724 }
725 }
726
727 // send a mouse event:
728 // regular/utf8: ^[[M Cb Cx Cy
729 // urxvt: ^[[ Cb ; Cx ; Cy M
730 // sgr: ^[[ Cb ; Cx ; Cy M/m
731 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
732 // locator: CSI P e ; P b ; P r ; P c ; P p & w
733 function sendEvent(button, pos) {
734 // self.emit('mouse', {
735 // x: pos.x - 32,
736 // y: pos.x - 32,
737 // button: button
738 // });
739
740 if (self.vt300Mouse) {
741 // NOTE: Unstable.
742 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
743 button &= 3;
744 pos.x -= 32;
745 pos.y -= 32;
746 var data = '\x1b[24';
747 if (button === 0) data += '1';
748 else if (button === 1) data += '3';
749 else if (button === 2) data += '5';
750 else if (button === 3) return;
751 else data += '0';
752 data += '~[' + pos.x + ',' + pos.y + ']\r';
753 self.send(data);
754 return;
755 }
756
757 if (self.decLocator) {
758 // NOTE: Unstable.
759 button &= 3;
760 pos.x -= 32;
761 pos.y -= 32;
762 if (button === 0) button = 2;
763 else if (button === 1) button = 4;
764 else if (button === 2) button = 6;
765 else if (button === 3) button = 3;
766 self.send('\x1b['
767 + button
768 + ';'
769 + (button === 3 ? 4 : 0)
770 + ';'
771 + pos.y
772 + ';'
773 + pos.x
774 + ';'
775 + (pos.page || 0)
776 + '&w');
777 return;
778 }
779
780 if (self.urxvtMouse) {
781 pos.x -= 32;
782 pos.y -= 32;
783 pos.x++;
784 pos.y++;
785 self.send('\x1b[' + button + ';' + pos.x + ';' + pos.y + 'M');
786 return;
787 }
788
789 if (self.sgrMouse) {
790 pos.x -= 32;
791 pos.y -= 32;
792 self.send('\x1b[<'
793 + (((button & 3) === 3 ? button & ~3 : button) - 32)
794 + ';'
795 + pos.x
796 + ';'
797 + pos.y
798 + ((button & 3) === 3 ? 'm' : 'M'));
799 return;
800 }
801
802 var data = [];
803
804 encode(data, button);
805 encode(data, pos.x);
806 encode(data, pos.y);
807
808 self.send('\x1b[M' + String.fromCharCode.apply(String, data));
809 }
810
811 function getButton(ev) {
812 var button
813 , shift
814 , meta
815 , ctrl
816 , mod;
817
818 // two low bits:
819 // 0 = left
820 // 1 = middle
821 // 2 = right
822 // 3 = release
823 // wheel up/down:
824 // 1, and 2 - with 64 added
825 switch (ev.overrideType || ev.type) {
826 case 'mousedown':
827 button = ev.button != null
828 ? +ev.button
829 : ev.which != null
830 ? ev.which - 1
831 : null;
832
833 if (self.browser.isMSIE) {
834 button = button === 1 ? 0 : button === 4 ? 1 : button;
835 }
836 break;
837 case 'mouseup':
838 button = 3;
839 break;
840 case 'DOMMouseScroll':
841 button = ev.detail < 0
842 ? 64
843 : 65;
844 break;
845 case 'wheel':
846 button = ev.wheelDeltaY > 0
847 ? 64
848 : 65;
849 break;
850 }
851
852 // next three bits are the modifiers:
853 // 4 = shift, 8 = meta, 16 = control
854 shift = ev.shiftKey ? 4 : 0;
855 meta = ev.metaKey ? 8 : 0;
856 ctrl = ev.ctrlKey ? 16 : 0;
857 mod = shift | meta | ctrl;
858
859 // no mods
860 if (self.vt200Mouse) {
861 // ctrl only
862 mod &= ctrl;
863 } else if (!self.normalMouse) {
864 mod = 0;
865 }
866
867 // increment to SP
868 button = (32 + (mod << 2)) + button;
869
870 return button;
871 }
872
873 // mouse coordinates measured in cols/rows
874 function getCoords(ev) {
875 var x, y, w, h, el;
876
877 // ignore browsers without pageX for now
878 if (ev.pageX == null) return;
879
880 x = ev.pageX;
881 y = ev.pageY;
882 el = self.element;
883
884 // should probably check offsetParent
885 // but this is more portable
886 while (el && el !== self.document.documentElement) {
887 x -= el.offsetLeft;
888 y -= el.offsetTop;
889 el = 'offsetParent' in el
890 ? el.offsetParent
891 : el.parentNode;
892 }
893
894 // convert to cols/rows
895 w = self.element.clientWidth;
896 h = self.element.clientHeight;
897 x = Math.ceil((x / w) * self.cols);
898 y = Math.ceil((y / h) * self.rows);
899
900 // be sure to avoid sending
901 // bad positions to the program
902 if (x < 0) x = 0;
903 if (x > self.cols) x = self.cols;
904 if (y < 0) y = 0;
905 if (y > self.rows) y = self.rows;
906
907 // xterm sends raw bytes and
908 // starts at 32 (SP) for each.
909 x += 32;
910 y += 32;
911
912 return {
913 x: x,
914 y: y,
915 type: 'wheel'
916 };
917 }
918
919 on(el, 'mousedown', function(ev) {
920 if (!self.mouseEvents) return;
921
922 // send the button
923 sendButton(ev);
924
925 // ensure focus
926 self.focus();
927
928 // fix for odd bug
929 //if (self.vt200Mouse && !self.normalMouse) {
930 if (self.vt200Mouse) {
931 ev.overrideType = 'mouseup';
932 sendButton(ev);
933 return self.cancel(ev);
934 }
935
936 // bind events
937 if (self.normalMouse) on(self.document, 'mousemove', sendMove);
938
939 // x10 compatibility mode can't send button releases
940 if (!self.x10Mouse) {
941 on(self.document, 'mouseup', function up(ev) {
942 sendButton(ev);
943 if (self.normalMouse) off(self.document, 'mousemove', sendMove);
944 off(self.document, 'mouseup', up);
945 return self.cancel(ev);
946 });
947 }
948
949 return self.cancel(ev);
950 });
951
952 //if (self.normalMouse) {
953 // on(self.document, 'mousemove', sendMove);
954 //}
955
956 on(el, 'wheel', function(ev) {
957 if (!self.mouseEvents) return;
958 if (self.x10Mouse
959 || self.vt300Mouse
960 || self.decLocator) return;
961 sendButton(ev);
962 return self.cancel(ev);
963 });
964
965 // allow wheel scrolling in
966 // the shell for example
967 on(el, 'wheel', function(ev) {
968 if (self.mouseEvents) return;
969 self.viewport.onWheel(ev);
970 return self.cancel(ev);
971 });
972 };
973
974 /**
975 * Destroys the terminal.
976 */
977 Terminal.prototype.destroy = function() {
978 this.readable = false;
979 this.writable = false;
980 this._events = {};
981 this.handler = function() {};
982 this.write = function() {};
983 if (this.element.parentNode) {
984 this.element.parentNode.removeChild(this.element);
985 }
986 //this.emit('close');
987 };
988
989
990 /**
991 * Flags used to render terminal text properly
992 */
993 Terminal.flags = {
994 BOLD: 1,
995 UNDERLINE: 2,
996 BLINK: 4,
997 INVERSE: 8,
998 INVISIBLE: 16
999 }
1000
1001 /**
1002 * Refreshes (re-renders) terminal content within two rows (inclusive)
1003 *
1004 * Rendering Engine:
1005 *
1006 * In the screen buffer, each character is stored as a an array with a character
1007 * and a 32-bit integer:
1008 * - First value: a utf-16 character.
1009 * - Second value:
1010 * - Next 9 bits: background color (0-511).
1011 * - Next 9 bits: foreground color (0-511).
1012 * - Next 14 bits: a mask for misc. flags:
1013 * - 1=bold
1014 * - 2=underline
1015 * - 4=blink
1016 * - 8=inverse
1017 * - 16=invisible
1018 *
1019 * @param {number} start The row to start from (between 0 and terminal's height terminal - 1)
1020 * @param {number} end The row to end at (between fromRow and terminal's height terminal - 1)
1021 * @param {boolean} queue Whether the refresh should ran right now or be queued
1022 */
1023 Terminal.prototype.refresh = function(start, end, queue) {
1024 var self = this;
1025
1026 // queue defaults to true
1027 queue = (typeof queue == 'undefined') ? true : queue;
1028
1029 /**
1030 * The refresh queue allows refresh to execute only approximately 30 times a second. For
1031 * commands that pass a significant amount of output to the write function, this prevents the
1032 * terminal from maxing out the CPU and making the UI unresponsive. While commands can still
1033 * run beyond what they do on the terminal, it is far better with a debounce in place as
1034 * every single terminal manipulation does not need to be constructed in the DOM.
1035 *
1036 * A side-effect of this is that it makes ^C to interrupt a process seem more responsive.
1037 */
1038 if (queue) {
1039 // If refresh should be queued, order the refresh and return.
1040 if (this._refreshIsQueued) {
1041 // If a refresh has already been queued, just order a full refresh next
1042 this._fullRefreshNext = true;
1043 } else {
1044 setTimeout(function () {
1045 self.refresh(start, end, false);
1046 }, 34)
1047 this._refreshIsQueued = true;
1048 }
1049 return;
1050 }
1051
1052 // If refresh should be run right now (not be queued), release the lock
1053 this._refreshIsQueued = false;
1054
1055 // If multiple refreshes were requested, make a full refresh.
1056 if (this._fullRefreshNext) {
1057 start = 0;
1058 end = this.rows - 1;
1059 this._fullRefreshNext = false // reset lock
1060 }
1061
1062 var x, y, i, line, out, ch, ch_width, width, data, attr, bg, fg, flags, row, parent, focused = document.activeElement;
1063
1064 // If this is a big refresh, remove the terminal rows from the DOM for faster calculations
1065 if (end - start >= this.rows / 2) {
1066 parent = this.element.parentNode;
1067 if (parent) {
1068 this.element.removeChild(this.rowContainer);
1069 }
1070 }
1071
1072 width = this.cols;
1073 y = start;
1074
1075 if (end >= this.rows.length) {
1076 this.log('`end` is too large. Most likely a bad CSR.');
1077 end = this.rows.length - 1;
1078 }
1079
1080 for (; y <= end; y++) {
1081 row = y + this.ydisp;
1082
1083 line = this.lines.get(row);
1084 out = '';
1085
1086 if (this.y === y - (this.ybase - this.ydisp)
1087 && this.cursorState
1088 && !this.cursorHidden) {
1089 x = this.x;
1090 } else {
1091 x = -1;
1092 }
1093
1094 attr = this.defAttr;
1095 i = 0;
1096
1097 for (; i < width; i++) {
1098 data = line[i][0];
1099 ch = line[i][1];
1100 ch_width = line[i][2];
1101 if (!ch_width)
1102 continue;
1103
1104 if (i === x) data = -1;
1105
1106 if (data !== attr) {
1107 if (attr !== this.defAttr) {
1108 out += '</span>';
1109 }
1110 if (data !== this.defAttr) {
1111 if (data === -1) {
1112 out += '<span class="reverse-video terminal-cursor';
1113 if (this.cursorBlink) {
1114 out += ' blinking';
1115 }
1116 out += '">';
1117 } else {
1118 var classNames = [];
1119
1120 bg = data & 0x1ff;
1121 fg = (data >> 9) & 0x1ff;
1122 flags = data >> 18;
1123
1124 if (flags & Terminal.flags.BOLD) {
1125 if (!Terminal.brokenBold) {
1126 classNames.push('xterm-bold');
1127 }
1128 // See: XTerm*boldColors
1129 if (fg < 8) fg += 8;
1130 }
1131
1132 if (flags & Terminal.flags.UNDERLINE) {
1133 classNames.push('xterm-underline');
1134 }
1135
1136 if (flags & Terminal.flags.BLINK) {
1137 classNames.push('xterm-blink');
1138 }
1139
1140 // If inverse flag is on, then swap the foreground and background variables.
1141 if (flags & Terminal.flags.INVERSE) {
1142 /* One-line variable swap in JavaScript: http://stackoverflow.com/a/16201730 */
1143 bg = [fg, fg = bg][0];
1144 // Should inverse just be before the
1145 // above boldColors effect instead?
1146 if ((flags & 1) && fg < 8) fg += 8;
1147 }
1148
1149 if (flags & Terminal.flags.INVISIBLE) {
1150 classNames.push('xterm-hidden');
1151 }
1152
1153 /**
1154 * Weird situation: Invert flag used black foreground and white background results
1155 * in invalid background color, positioned at the 256 index of the 256 terminal
1156 * color map. Pin the colors manually in such a case.
1157 *
1158 * Source: https://github.com/sourcelair/xterm.js/issues/57
1159 */
1160 if (flags & Terminal.flags.INVERSE) {
1161 if (bg == 257) {
1162 bg = 15;
1163 }
1164 if (fg == 256) {
1165 fg = 0;
1166 }
1167 }
1168
1169 if (bg < 256) {
1170 classNames.push('xterm-bg-color-' + bg);
1171 }
1172
1173 if (fg < 256) {
1174 classNames.push('xterm-color-' + fg);
1175 }
1176
1177 out += '<span';
1178 if (classNames.length) {
1179 out += ' class="' + classNames.join(' ') + '"';
1180 }
1181 out += '>';
1182 }
1183 }
1184 }
1185
1186 switch (ch) {
1187 case '&':
1188 out += '&amp;';
1189 break;
1190 case '<':
1191 out += '&lt;';
1192 break;
1193 case '>':
1194 out += '&gt;';
1195 break;
1196 default:
1197 if (ch <= ' ') {
1198 out += '&nbsp;';
1199 } else {
1200 out += ch;
1201 }
1202 break;
1203 }
1204
1205 attr = data;
1206 }
1207
1208 if (attr !== this.defAttr) {
1209 out += '</span>';
1210 }
1211
1212 this.children[y].innerHTML = out;
1213 }
1214
1215 if (parent) {
1216 this.element.appendChild(this.rowContainer);
1217 }
1218
1219 this.emit('refresh', {element: this.element, start: start, end: end});
1220 };
1221
1222 /**
1223 * Display the cursor element
1224 */
1225 Terminal.prototype.showCursor = function() {
1226 if (!this.cursorState) {
1227 this.cursorState = 1;
1228 this.refresh(this.y, this.y);
1229 }
1230 };
1231
1232 /**
1233 * Scroll the terminal down 1 row, creating a blank line.
1234 */
1235 Terminal.prototype.scroll = function() {
1236 var row;
1237
1238 this.ybase++;
1239
1240 // TODO: Why is this done twice?
1241 if (!this.userScrolling) {
1242 this.ydisp = this.ybase;
1243 }
1244
1245 // last line
1246 row = this.ybase + this.rows - 1;
1247
1248 // subtract the bottom scroll region
1249 row -= this.rows - 1 - this.scrollBottom;
1250
1251 if (row === this.lines.length) {
1252 // Compensate ybase and ydisp if lines has hit the maximum buffer size
1253 if (this.lines.length === this.lines.maxLength) {
1254 this.ybase--;
1255 if (this.ydisp !== 0) {
1256 this.ydisp--;
1257 }
1258 }
1259 // Optimization: pushing is faster than splicing when they amount to the same behavior
1260 this.lines.push(this.blankLine());
1261 } else {
1262 // add our new line
1263 this.lines.splice(row, 0, this.blankLine());
1264 }
1265
1266 if (this.scrollTop !== 0) {
1267 if (this.ybase !== 0) {
1268 this.ybase--;
1269 if (!this.userScrolling) {
1270 this.ydisp = this.ybase;
1271 }
1272 }
1273 this.lines.splice(this.ybase + this.scrollTop, 1);
1274 }
1275
1276 // this.maxRange();
1277 this.updateRange(this.scrollTop);
1278 this.updateRange(this.scrollBottom);
1279
1280 /**
1281 * This event is emitted whenever the terminal is scrolled.
1282 * The one parameter passed is the new y display position.
1283 *
1284 * @event scroll
1285 */
1286 this.emit('scroll', this.ydisp);
1287 };
1288
1289 /**
1290 * Scroll the display of the terminal
1291 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1292 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1293 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1294 * viewport originally.
1295 */
1296 Terminal.prototype.scrollDisp = function(disp, suppressScrollEvent) {
1297 if (disp < 0) {
1298 this.userScrolling = true;
1299 } else if (disp + this.ydisp >= this.ybase) {
1300 this.userScrolling = false;
1301 }
1302
1303 this.ydisp += disp;
1304
1305 if (this.ydisp > this.ybase) {
1306 this.ydisp = this.ybase;
1307 } else if (this.ydisp < 0) {
1308 this.ydisp = 0;
1309 }
1310
1311 if (!suppressScrollEvent) {
1312 this.emit('scroll', this.ydisp);
1313 }
1314
1315 this.refresh(0, this.rows - 1);
1316 };
1317
1318 /**
1319 * Scroll the display of the terminal by a number of pages.
1320 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1321 */
1322 Terminal.prototype.scrollPages = function(pageCount) {
1323 this.scrollDisp(pageCount * (this.rows - 1));
1324 }
1325
1326 /**
1327 * Scrolls the display of the terminal to the top.
1328 */
1329 Terminal.prototype.scrollToTop = function() {
1330 this.scrollDisp(-this.ydisp);
1331 }
1332
1333 /**
1334 * Scrolls the display of the terminal to the bottom.
1335 */
1336 Terminal.prototype.scrollToBottom = function() {
1337 this.scrollDisp(this.ybase - this.ydisp);
1338 }
1339
1340 /**
1341 * Writes text to the terminal.
1342 * @param {string} text The text to write to the terminal.
1343 */
1344 Terminal.prototype.write = function(data) {
1345 var l = data.length, i = 0, j, cs, ch, code, low, ch_width, row;
1346
1347 this.refreshStart = this.y;
1348 this.refreshEnd = this.y;
1349
1350 // apply leftover surrogate high from last write
1351 if (this.surrogate_high) {
1352 data = this.surrogate_high + data;
1353 this.surrogate_high = '';
1354 }
1355
1356 for (; i < l; i++) {
1357 ch = data[i];
1358
1359 // FIXME: higher chars than 0xa0 are not allowed in escape sequences
1360 // --> maybe move to default
1361 code = data.charCodeAt(i);
1362 if (0xD800 <= code && code <= 0xDBFF) {
1363 // we got a surrogate high
1364 // get surrogate low (next 2 bytes)
1365 low = data.charCodeAt(i+1);
1366 if (isNaN(low)) {
1367 // end of data stream, save surrogate high
1368 this.surrogate_high = ch;
1369 continue;
1370 }
1371 code = ((code - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
1372 ch += data.charAt(i+1);
1373 }
1374 // surrogate low - already handled above
1375 if (0xDC00 <= code && code <= 0xDFFF)
1376 continue;
1377 switch (this.state) {
1378 case normal:
1379 switch (ch) {
1380 case '\x07':
1381 this.bell();
1382 break;
1383
1384 // '\n', '\v', '\f'
1385 case '\n':
1386 case '\x0b':
1387 case '\x0c':
1388 if (this.convertEol) {
1389 this.x = 0;
1390 }
1391 this.y++;
1392 if (this.y > this.scrollBottom) {
1393 this.y--;
1394 this.scroll();
1395 }
1396 break;
1397
1398 // '\r'
1399 case '\r':
1400 this.x = 0;
1401 break;
1402
1403 // '\b'
1404 case '\x08':
1405 if (this.x > 0) {
1406 this.x--;
1407 }
1408 break;
1409
1410 // '\t'
1411 case '\t':
1412 this.x = this.nextStop();
1413 break;
1414
1415 // shift out
1416 case '\x0e':
1417 this.setgLevel(1);
1418 break;
1419
1420 // shift in
1421 case '\x0f':
1422 this.setgLevel(0);
1423 break;
1424
1425 // '\e'
1426 case '\x1b':
1427 this.state = escaped;
1428 break;
1429
1430 default:
1431 // ' '
1432 // calculate print space
1433 // expensive call, therefore we save width in line buffer
1434 ch_width = wcwidth(code);
1435
1436 if (ch >= ' ') {
1437 if (this.charset && this.charset[ch]) {
1438 ch = this.charset[ch];
1439 }
1440
1441 row = this.y + this.ybase;
1442
1443 // insert combining char in last cell
1444 // FIXME: needs handling after cursor jumps
1445 if (!ch_width && this.x) {
1446 // dont overflow left
1447 if (this.lines.get(row)[this.x-1]) {
1448 if (!this.lines.get(row)[this.x-1][2]) {
1449
1450 // found empty cell after fullwidth, need to go 2 cells back
1451 if (this.lines.get(row)[this.x-2])
1452 this.lines.get(row)[this.x-2][1] += ch;
1453
1454 } else {
1455 this.lines.get(row)[this.x-1][1] += ch;
1456 }
1457 this.updateRange(this.y);
1458 }
1459 break;
1460 }
1461
1462 // goto next line if ch would overflow
1463 // TODO: needs a global min terminal width of 2
1464 if (this.x+ch_width-1 >= this.cols) {
1465 // autowrap - DECAWM
1466 if (this.wraparoundMode) {
1467 this.x = 0;
1468 this.y++;
1469 if (this.y > this.scrollBottom) {
1470 this.y--;
1471 this.scroll();
1472 }
1473 } else {
1474 this.x = this.cols-1;
1475 if(ch_width===2) // FIXME: check for xterm behavior
1476 continue;
1477 }
1478 }
1479 row = this.y + this.ybase;
1480
1481 // insert mode: move characters to right
1482 if (this.insertMode) {
1483 // do this twice for a fullwidth char
1484 for (var moves=0; moves<ch_width; ++moves) {
1485 // remove last cell, if it's width is 0
1486 // we have to adjust the second last cell as well
1487 var removed = this.lines.get(this.y + this.ybase).pop();
1488 if (removed[2]===0
1489 && this.lines.get(row)[this.cols-2]
1490 && this.lines.get(row)[this.cols-2][2]===2)
1491 this.lines.get(row)[this.cols-2] = [this.curAttr, ' ', 1];
1492
1493 // insert empty cell at cursor
1494 this.lines.get(row).splice(this.x, 0, [this.curAttr, ' ', 1]);
1495 }
1496 }
1497
1498 this.lines.get(row)[this.x] = [this.curAttr, ch, ch_width];
1499 this.x++;
1500 this.updateRange(this.y);
1501
1502 // fullwidth char - set next cell width to zero and advance cursor
1503 if (ch_width===2) {
1504 this.lines.get(row)[this.x] = [this.curAttr, '', 0];
1505 this.x++;
1506 }
1507 }
1508 break;
1509 }
1510 break;
1511 case escaped:
1512 switch (ch) {
1513 // ESC [ Control Sequence Introducer ( CSI is 0x9b).
1514 case '[':
1515 this.params = [];
1516 this.currentParam = 0;
1517 this.state = csi;
1518 break;
1519
1520 // ESC ] Operating System Command ( OSC is 0x9d).
1521 case ']':
1522 this.params = [];
1523 this.currentParam = 0;
1524 this.state = osc;
1525 break;
1526
1527 // ESC P Device Control String ( DCS is 0x90).
1528 case 'P':
1529 this.params = [];
1530 this.currentParam = 0;
1531 this.state = dcs;
1532 break;
1533
1534 // ESC _ Application Program Command ( APC is 0x9f).
1535 case '_':
1536 this.state = ignore;
1537 break;
1538
1539 // ESC ^ Privacy Message ( PM is 0x9e).
1540 case '^':
1541 this.state = ignore;
1542 break;
1543
1544 // ESC c Full Reset (RIS).
1545 case 'c':
1546 this.reset();
1547 break;
1548
1549 // ESC E Next Line ( NEL is 0x85).
1550 // ESC D Index ( IND is 0x84).
1551 case 'E':
1552 this.x = 0;
1553 ;
1554 case 'D':
1555 this.index();
1556 break;
1557
1558 // ESC M Reverse Index ( RI is 0x8d).
1559 case 'M':
1560 this.reverseIndex();
1561 break;
1562
1563 // ESC % Select default/utf-8 character set.
1564 // @ = default, G = utf-8
1565 case '%':
1566 //this.charset = null;
1567 this.setgLevel(0);
1568 this.setgCharset(0, Terminal.charsets.US);
1569 this.state = normal;
1570 i++;
1571 break;
1572
1573 // ESC (,),*,+,-,. Designate G0-G2 Character Set.
1574 case '(': // <-- this seems to get all the attention
1575 case ')':
1576 case '*':
1577 case '+':
1578 case '-':
1579 case '.':
1580 switch (ch) {
1581 case '(':
1582 this.gcharset = 0;
1583 break;
1584 case ')':
1585 this.gcharset = 1;
1586 break;
1587 case '*':
1588 this.gcharset = 2;
1589 break;
1590 case '+':
1591 this.gcharset = 3;
1592 break;
1593 case '-':
1594 this.gcharset = 1;
1595 break;
1596 case '.':
1597 this.gcharset = 2;
1598 break;
1599 }
1600 this.state = charset;
1601 break;
1602
1603 // Designate G3 Character Set (VT300).
1604 // A = ISO Latin-1 Supplemental.
1605 // Not implemented.
1606 case '/':
1607 this.gcharset = 3;
1608 this.state = charset;
1609 i--;
1610 break;
1611
1612 // ESC N
1613 // Single Shift Select of G2 Character Set
1614 // ( SS2 is 0x8e). This affects next character only.
1615 case 'N':
1616 break;
1617 // ESC O
1618 // Single Shift Select of G3 Character Set
1619 // ( SS3 is 0x8f). This affects next character only.
1620 case 'O':
1621 break;
1622 // ESC n
1623 // Invoke the G2 Character Set as GL (LS2).
1624 case 'n':
1625 this.setgLevel(2);
1626 break;
1627 // ESC o
1628 // Invoke the G3 Character Set as GL (LS3).
1629 case 'o':
1630 this.setgLevel(3);
1631 break;
1632 // ESC |
1633 // Invoke the G3 Character Set as GR (LS3R).
1634 case '|':
1635 this.setgLevel(3);
1636 break;
1637 // ESC }
1638 // Invoke the G2 Character Set as GR (LS2R).
1639 case '}':
1640 this.setgLevel(2);
1641 break;
1642 // ESC ~
1643 // Invoke the G1 Character Set as GR (LS1R).
1644 case '~':
1645 this.setgLevel(1);
1646 break;
1647
1648 // ESC 7 Save Cursor (DECSC).
1649 case '7':
1650 this.saveCursor();
1651 this.state = normal;
1652 break;
1653
1654 // ESC 8 Restore Cursor (DECRC).
1655 case '8':
1656 this.restoreCursor();
1657 this.state = normal;
1658 break;
1659
1660 // ESC # 3 DEC line height/width
1661 case '#':
1662 this.state = normal;
1663 i++;
1664 break;
1665
1666 // ESC H Tab Set (HTS is 0x88).
1667 case 'H':
1668 this.tabSet();
1669 break;
1670
1671 // ESC = Application Keypad (DECKPAM).
1672 case '=':
1673 this.log('Serial port requested application keypad.');
1674 this.applicationKeypad = true;
1675 this.viewport.syncScrollArea();
1676 this.state = normal;
1677 break;
1678
1679 // ESC > Normal Keypad (DECKPNM).
1680 case '>':
1681 this.log('Switching back to normal keypad.');
1682 this.applicationKeypad = false;
1683 this.viewport.syncScrollArea();
1684 this.state = normal;
1685 break;
1686
1687 default:
1688 this.state = normal;
1689 this.error('Unknown ESC control: %s.', ch);
1690 break;
1691 }
1692 break;
1693
1694 case charset:
1695 switch (ch) {
1696 case '0': // DEC Special Character and Line Drawing Set.
1697 cs = Terminal.charsets.SCLD;
1698 break;
1699 case 'A': // UK
1700 cs = Terminal.charsets.UK;
1701 break;
1702 case 'B': // United States (USASCII).
1703 cs = Terminal.charsets.US;
1704 break;
1705 case '4': // Dutch
1706 cs = Terminal.charsets.Dutch;
1707 break;
1708 case 'C': // Finnish
1709 case '5':
1710 cs = Terminal.charsets.Finnish;
1711 break;
1712 case 'R': // French
1713 cs = Terminal.charsets.French;
1714 break;
1715 case 'Q': // FrenchCanadian
1716 cs = Terminal.charsets.FrenchCanadian;
1717 break;
1718 case 'K': // German
1719 cs = Terminal.charsets.German;
1720 break;
1721 case 'Y': // Italian
1722 cs = Terminal.charsets.Italian;
1723 break;
1724 case 'E': // NorwegianDanish
1725 case '6':
1726 cs = Terminal.charsets.NorwegianDanish;
1727 break;
1728 case 'Z': // Spanish
1729 cs = Terminal.charsets.Spanish;
1730 break;
1731 case 'H': // Swedish
1732 case '7':
1733 cs = Terminal.charsets.Swedish;
1734 break;
1735 case '=': // Swiss
1736 cs = Terminal.charsets.Swiss;
1737 break;
1738 case '/': // ISOLatin (actually /A)
1739 cs = Terminal.charsets.ISOLatin;
1740 i++;
1741 break;
1742 default: // Default
1743 cs = Terminal.charsets.US;
1744 break;
1745 }
1746 this.setgCharset(this.gcharset, cs);
1747 this.gcharset = null;
1748 this.state = normal;
1749 break;
1750
1751 case osc:
1752 // OSC Ps ; Pt ST
1753 // OSC Ps ; Pt BEL
1754 // Set Text Parameters.
1755 if (ch === '\x1b' || ch === '\x07') {
1756 if (ch === '\x1b') i++;
1757
1758 this.params.push(this.currentParam);
1759
1760 switch (this.params[0]) {
1761 case 0:
1762 case 1:
1763 case 2:
1764 if (this.params[1]) {
1765 this.title = this.params[1];
1766 this.handleTitle(this.title);
1767 }
1768 break;
1769 case 3:
1770 // set X property
1771 break;
1772 case 4:
1773 case 5:
1774 // change dynamic colors
1775 break;
1776 case 10:
1777 case 11:
1778 case 12:
1779 case 13:
1780 case 14:
1781 case 15:
1782 case 16:
1783 case 17:
1784 case 18:
1785 case 19:
1786 // change dynamic ui colors
1787 break;
1788 case 46:
1789 // change log file
1790 break;
1791 case 50:
1792 // dynamic font
1793 break;
1794 case 51:
1795 // emacs shell
1796 break;
1797 case 52:
1798 // manipulate selection data
1799 break;
1800 case 104:
1801 case 105:
1802 case 110:
1803 case 111:
1804 case 112:
1805 case 113:
1806 case 114:
1807 case 115:
1808 case 116:
1809 case 117:
1810 case 118:
1811 // reset colors
1812 break;
1813 }
1814
1815 this.params = [];
1816 this.currentParam = 0;
1817 this.state = normal;
1818 } else {
1819 if (!this.params.length) {
1820 if (ch >= '0' && ch <= '9') {
1821 this.currentParam =
1822 this.currentParam * 10 + ch.charCodeAt(0) - 48;
1823 } else if (ch === ';') {
1824 this.params.push(this.currentParam);
1825 this.currentParam = '';
1826 }
1827 } else {
1828 this.currentParam += ch;
1829 }
1830 }
1831 break;
1832
1833 case csi:
1834 // '?', '>', '!'
1835 if (ch === '?' || ch === '>' || ch === '!') {
1836 this.prefix = ch;
1837 break;
1838 }
1839
1840 // 0 - 9
1841 if (ch >= '0' && ch <= '9') {
1842 this.currentParam = this.currentParam * 10 + ch.charCodeAt(0) - 48;
1843 break;
1844 }
1845
1846 // '$', '"', ' ', '\''
1847 if (ch === '$' || ch === '"' || ch === ' ' || ch === '\'') {
1848 this.postfix = ch;
1849 break;
1850 }
1851
1852 this.params.push(this.currentParam);
1853 this.currentParam = 0;
1854
1855 // ';'
1856 if (ch === ';') break;
1857
1858 this.state = normal;
1859
1860 switch (ch) {
1861 // CSI Ps A
1862 // Cursor Up Ps Times (default = 1) (CUU).
1863 case 'A':
1864 this.cursorUp(this.params);
1865 break;
1866
1867 // CSI Ps B
1868 // Cursor Down Ps Times (default = 1) (CUD).
1869 case 'B':
1870 this.cursorDown(this.params);
1871 break;
1872
1873 // CSI Ps C
1874 // Cursor Forward Ps Times (default = 1) (CUF).
1875 case 'C':
1876 this.cursorForward(this.params);
1877 break;
1878
1879 // CSI Ps D
1880 // Cursor Backward Ps Times (default = 1) (CUB).
1881 case 'D':
1882 this.cursorBackward(this.params);
1883 break;
1884
1885 // CSI Ps ; Ps H
1886 // Cursor Position [row;column] (default = [1,1]) (CUP).
1887 case 'H':
1888 this.cursorPos(this.params);
1889 break;
1890
1891 // CSI Ps J Erase in Display (ED).
1892 case 'J':
1893 this.eraseInDisplay(this.params);
1894 break;
1895
1896 // CSI Ps K Erase in Line (EL).
1897 case 'K':
1898 this.eraseInLine(this.params);
1899 break;
1900
1901 // CSI Pm m Character Attributes (SGR).
1902 case 'm':
1903 if (!this.prefix) {
1904 this.charAttributes(this.params);
1905 }
1906 break;
1907
1908 // CSI Ps n Device Status Report (DSR).
1909 case 'n':
1910 if (!this.prefix) {
1911 this.deviceStatus(this.params);
1912 }
1913 break;
1914
1915 /**
1916 * Additions
1917 */
1918
1919 // CSI Ps @
1920 // Insert Ps (Blank) Character(s) (default = 1) (ICH).
1921 case '@':
1922 this.insertChars(this.params);
1923 break;
1924
1925 // CSI Ps E
1926 // Cursor Next Line Ps Times (default = 1) (CNL).
1927 case 'E':
1928 this.cursorNextLine(this.params);
1929 break;
1930
1931 // CSI Ps F
1932 // Cursor Preceding Line Ps Times (default = 1) (CNL).
1933 case 'F':
1934 this.cursorPrecedingLine(this.params);
1935 break;
1936
1937 // CSI Ps G
1938 // Cursor Character Absolute [column] (default = [row,1]) (CHA).
1939 case 'G':
1940 this.cursorCharAbsolute(this.params);
1941 break;
1942
1943 // CSI Ps L
1944 // Insert Ps Line(s) (default = 1) (IL).
1945 case 'L':
1946 this.insertLines(this.params);
1947 break;
1948
1949 // CSI Ps M
1950 // Delete Ps Line(s) (default = 1) (DL).
1951 case 'M':
1952 this.deleteLines(this.params);
1953 break;
1954
1955 // CSI Ps P
1956 // Delete Ps Character(s) (default = 1) (DCH).
1957 case 'P':
1958 this.deleteChars(this.params);
1959 break;
1960
1961 // CSI Ps X
1962 // Erase Ps Character(s) (default = 1) (ECH).
1963 case 'X':
1964 this.eraseChars(this.params);
1965 break;
1966
1967 // CSI Pm ` Character Position Absolute
1968 // [column] (default = [row,1]) (HPA).
1969 case '`':
1970 this.charPosAbsolute(this.params);
1971 break;
1972
1973 // 141 61 a * HPR -
1974 // Horizontal Position Relative
1975 case 'a':
1976 this.HPositionRelative(this.params);
1977 break;
1978
1979 // CSI P s c
1980 // Send Device Attributes (Primary DA).
1981 // CSI > P s c
1982 // Send Device Attributes (Secondary DA)
1983 case 'c':
1984 this.sendDeviceAttributes(this.params);
1985 break;
1986
1987 // CSI Pm d
1988 // Line Position Absolute [row] (default = [1,column]) (VPA).
1989 case 'd':
1990 this.linePosAbsolute(this.params);
1991 break;
1992
1993 // 145 65 e * VPR - Vertical Position Relative
1994 case 'e':
1995 this.VPositionRelative(this.params);
1996 break;
1997
1998 // CSI Ps ; Ps f
1999 // Horizontal and Vertical Position [row;column] (default =
2000 // [1,1]) (HVP).
2001 case 'f':
2002 this.HVPosition(this.params);
2003 break;
2004
2005 // CSI Pm h Set Mode (SM).
2006 // CSI ? Pm h - mouse escape codes, cursor escape codes
2007 case 'h':
2008 this.setMode(this.params);
2009 break;
2010
2011 // CSI Pm l Reset Mode (RM).
2012 // CSI ? Pm l
2013 case 'l':
2014 this.resetMode(this.params);
2015 break;
2016
2017 // CSI Ps ; Ps r
2018 // Set Scrolling Region [top;bottom] (default = full size of win-
2019 // dow) (DECSTBM).
2020 // CSI ? Pm r
2021 case 'r':
2022 this.setScrollRegion(this.params);
2023 break;
2024
2025 // CSI s
2026 // Save cursor (ANSI.SYS).
2027 case 's':
2028 this.saveCursor(this.params);
2029 break;
2030
2031 // CSI u
2032 // Restore cursor (ANSI.SYS).
2033 case 'u':
2034 this.restoreCursor(this.params);
2035 break;
2036
2037 /**
2038 * Lesser Used
2039 */
2040
2041 // CSI Ps I
2042 // Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
2043 case 'I':
2044 this.cursorForwardTab(this.params);
2045 break;
2046
2047 // CSI Ps S Scroll up Ps lines (default = 1) (SU).
2048 case 'S':
2049 this.scrollUp(this.params);
2050 break;
2051
2052 // CSI Ps T Scroll down Ps lines (default = 1) (SD).
2053 // CSI Ps ; Ps ; Ps ; Ps ; Ps T
2054 // CSI > Ps; Ps T
2055 case 'T':
2056 // if (this.prefix === '>') {
2057 // this.resetTitleModes(this.params);
2058 // break;
2059 // }
2060 // if (this.params.length > 2) {
2061 // this.initMouseTracking(this.params);
2062 // break;
2063 // }
2064 if (this.params.length < 2 && !this.prefix) {
2065 this.scrollDown(this.params);
2066 }
2067 break;
2068
2069 // CSI Ps Z
2070 // Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
2071 case 'Z':
2072 this.cursorBackwardTab(this.params);
2073 break;
2074
2075 // CSI Ps b Repeat the preceding graphic character Ps times (REP).
2076 case 'b':
2077 this.repeatPrecedingCharacter(this.params);
2078 break;
2079
2080 // CSI Ps g Tab Clear (TBC).
2081 case 'g':
2082 this.tabClear(this.params);
2083 break;
2084
2085 // CSI Pm i Media Copy (MC).
2086 // CSI ? Pm i
2087 // case 'i':
2088 // this.mediaCopy(this.params);
2089 // break;
2090
2091 // CSI Pm m Character Attributes (SGR).
2092 // CSI > Ps; Ps m
2093 // case 'm': // duplicate
2094 // if (this.prefix === '>') {
2095 // this.setResources(this.params);
2096 // } else {
2097 // this.charAttributes(this.params);
2098 // }
2099 // break;
2100
2101 // CSI Ps n Device Status Report (DSR).
2102 // CSI > Ps n
2103 // case 'n': // duplicate
2104 // if (this.prefix === '>') {
2105 // this.disableModifiers(this.params);
2106 // } else {
2107 // this.deviceStatus(this.params);
2108 // }
2109 // break;
2110
2111 // CSI > Ps p Set pointer mode.
2112 // CSI ! p Soft terminal reset (DECSTR).
2113 // CSI Ps$ p
2114 // Request ANSI mode (DECRQM).
2115 // CSI ? Ps$ p
2116 // Request DEC private mode (DECRQM).
2117 // CSI Ps ; Ps " p
2118 case 'p':
2119 switch (this.prefix) {
2120 // case '>':
2121 // this.setPointerMode(this.params);
2122 // break;
2123 case '!':
2124 this.softReset(this.params);
2125 break;
2126 // case '?':
2127 // if (this.postfix === '$') {
2128 // this.requestPrivateMode(this.params);
2129 // }
2130 // break;
2131 // default:
2132 // if (this.postfix === '"') {
2133 // this.setConformanceLevel(this.params);
2134 // } else if (this.postfix === '$') {
2135 // this.requestAnsiMode(this.params);
2136 // }
2137 // break;
2138 }
2139 break;
2140
2141 // CSI Ps q Load LEDs (DECLL).
2142 // CSI Ps SP q
2143 // CSI Ps " q
2144 // case 'q':
2145 // if (this.postfix === ' ') {
2146 // this.setCursorStyle(this.params);
2147 // break;
2148 // }
2149 // if (this.postfix === '"') {
2150 // this.setCharProtectionAttr(this.params);
2151 // break;
2152 // }
2153 // this.loadLEDs(this.params);
2154 // break;
2155
2156 // CSI Ps ; Ps r
2157 // Set Scrolling Region [top;bottom] (default = full size of win-
2158 // dow) (DECSTBM).
2159 // CSI ? Pm r
2160 // CSI Pt; Pl; Pb; Pr; Ps$ r
2161 // case 'r': // duplicate
2162 // if (this.prefix === '?') {
2163 // this.restorePrivateValues(this.params);
2164 // } else if (this.postfix === '$') {
2165 // this.setAttrInRectangle(this.params);
2166 // } else {
2167 // this.setScrollRegion(this.params);
2168 // }
2169 // break;
2170
2171 // CSI s Save cursor (ANSI.SYS).
2172 // CSI ? Pm s
2173 // case 's': // duplicate
2174 // if (this.prefix === '?') {
2175 // this.savePrivateValues(this.params);
2176 // } else {
2177 // this.saveCursor(this.params);
2178 // }
2179 // break;
2180
2181 // CSI Ps ; Ps ; Ps t
2182 // CSI Pt; Pl; Pb; Pr; Ps$ t
2183 // CSI > Ps; Ps t
2184 // CSI Ps SP t
2185 // case 't':
2186 // if (this.postfix === '$') {
2187 // this.reverseAttrInRectangle(this.params);
2188 // } else if (this.postfix === ' ') {
2189 // this.setWarningBellVolume(this.params);
2190 // } else {
2191 // if (this.prefix === '>') {
2192 // this.setTitleModeFeature(this.params);
2193 // } else {
2194 // this.manipulateWindow(this.params);
2195 // }
2196 // }
2197 // break;
2198
2199 // CSI u Restore cursor (ANSI.SYS).
2200 // CSI Ps SP u
2201 // case 'u': // duplicate
2202 // if (this.postfix === ' ') {
2203 // this.setMarginBellVolume(this.params);
2204 // } else {
2205 // this.restoreCursor(this.params);
2206 // }
2207 // break;
2208
2209 // CSI Pt; Pl; Pb; Pr; Pp; Pt; Pl; Pp$ v
2210 // case 'v':
2211 // if (this.postfix === '$') {
2212 // this.copyRectagle(this.params);
2213 // }
2214 // break;
2215
2216 // CSI Pt ; Pl ; Pb ; Pr ' w
2217 // case 'w':
2218 // if (this.postfix === '\'') {
2219 // this.enableFilterRectangle(this.params);
2220 // }
2221 // break;
2222
2223 // CSI Ps x Request Terminal Parameters (DECREQTPARM).
2224 // CSI Ps x Select Attribute Change Extent (DECSACE).
2225 // CSI Pc; Pt; Pl; Pb; Pr$ x
2226 // case 'x':
2227 // if (this.postfix === '$') {
2228 // this.fillRectangle(this.params);
2229 // } else {
2230 // this.requestParameters(this.params);
2231 // //this.__(this.params);
2232 // }
2233 // break;
2234
2235 // CSI Ps ; Pu ' z
2236 // CSI Pt; Pl; Pb; Pr$ z
2237 // case 'z':
2238 // if (this.postfix === '\'') {
2239 // this.enableLocatorReporting(this.params);
2240 // } else if (this.postfix === '$') {
2241 // this.eraseRectangle(this.params);
2242 // }
2243 // break;
2244
2245 // CSI Pm ' {
2246 // CSI Pt; Pl; Pb; Pr$ {
2247 // case '{':
2248 // if (this.postfix === '\'') {
2249 // this.setLocatorEvents(this.params);
2250 // } else if (this.postfix === '$') {
2251 // this.selectiveEraseRectangle(this.params);
2252 // }
2253 // break;
2254
2255 // CSI Ps ' |
2256 // case '|':
2257 // if (this.postfix === '\'') {
2258 // this.requestLocatorPosition(this.params);
2259 // }
2260 // break;
2261
2262 // CSI P m SP }
2263 // Insert P s Column(s) (default = 1) (DECIC), VT420 and up.
2264 // case '}':
2265 // if (this.postfix === ' ') {
2266 // this.insertColumns(this.params);
2267 // }
2268 // break;
2269
2270 // CSI P m SP ~
2271 // Delete P s Column(s) (default = 1) (DECDC), VT420 and up
2272 // case '~':
2273 // if (this.postfix === ' ') {
2274 // this.deleteColumns(this.params);
2275 // }
2276 // break;
2277
2278 default:
2279 this.error('Unknown CSI code: %s.', ch);
2280 break;
2281 }
2282
2283 this.prefix = '';
2284 this.postfix = '';
2285 break;
2286
2287 case dcs:
2288 if (ch === '\x1b' || ch === '\x07') {
2289 if (ch === '\x1b') i++;
2290
2291 switch (this.prefix) {
2292 // User-Defined Keys (DECUDK).
2293 case '':
2294 break;
2295
2296 // Request Status String (DECRQSS).
2297 // test: echo -e '\eP$q"p\e\\'
2298 case '$q':
2299 var pt = this.currentParam
2300 , valid = false;
2301
2302 switch (pt) {
2303 // DECSCA
2304 case '"q':
2305 pt = '0"q';
2306 break;
2307
2308 // DECSCL
2309 case '"p':
2310 pt = '61"p';
2311 break;
2312
2313 // DECSTBM
2314 case 'r':
2315 pt = ''
2316 + (this.scrollTop + 1)
2317 + ';'
2318 + (this.scrollBottom + 1)
2319 + 'r';
2320 break;
2321
2322 // SGR
2323 case 'm':
2324 pt = '0m';
2325 break;
2326
2327 default:
2328 this.error('Unknown DCS Pt: %s.', pt);
2329 pt = '';
2330 break;
2331 }
2332
2333 this.send('\x1bP' + +valid + '$r' + pt + '\x1b\\');
2334 break;
2335
2336 // Set Termcap/Terminfo Data (xterm, experimental).
2337 case '+p':
2338 break;
2339
2340 // Request Termcap/Terminfo String (xterm, experimental)
2341 // Regular xterm does not even respond to this sequence.
2342 // This can cause a small glitch in vim.
2343 // test: echo -ne '\eP+q6b64\e\\'
2344 case '+q':
2345 var pt = this.currentParam
2346 , valid = false;
2347
2348 this.send('\x1bP' + +valid + '+r' + pt + '\x1b\\');
2349 break;
2350
2351 default:
2352 this.error('Unknown DCS prefix: %s.', this.prefix);
2353 break;
2354 }
2355
2356 this.currentParam = 0;
2357 this.prefix = '';
2358 this.state = normal;
2359 } else if (!this.currentParam) {
2360 if (!this.prefix && ch !== '$' && ch !== '+') {
2361 this.currentParam = ch;
2362 } else if (this.prefix.length === 2) {
2363 this.currentParam = ch;
2364 } else {
2365 this.prefix += ch;
2366 }
2367 } else {
2368 this.currentParam += ch;
2369 }
2370 break;
2371
2372 case ignore:
2373 // For PM and APC.
2374 if (ch === '\x1b' || ch === '\x07') {
2375 if (ch === '\x1b') i++;
2376 this.state = normal;
2377 }
2378 break;
2379 }
2380 }
2381
2382 this.updateRange(this.y);
2383 this.refresh(this.refreshStart, this.refreshEnd);
2384 };
2385
2386 /**
2387 * Writes text to the terminal, followed by a break line character (\n).
2388 * @param {string} text The text to write to the terminal.
2389 */
2390 Terminal.prototype.writeln = function(data) {
2391 this.write(data + '\r\n');
2392 };
2393
2394 /**
2395 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
2396 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
2397 * should not.
2398 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
2399 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
2400 * the default action. The function returns whether the event should be processed by xterm.js.
2401 */
2402 Terminal.prototype.attachCustomKeydownHandler = function(customKeydownHandler) {
2403 this.customKeydownHandler = customKeydownHandler;
2404 }
2405
2406 /**
2407 * Handle a keydown event
2408 * Key Resources:
2409 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
2410 * @param {KeyboardEvent} ev The keydown event to be handled.
2411 */
2412 Terminal.prototype.keyDown = function(ev) {
2413 if (this.customKeydownHandler && this.customKeydownHandler(ev) === false) {
2414 return false;
2415 }
2416
2417 if (!this.compositionHelper.keydown.bind(this.compositionHelper)(ev)) {
2418 if (this.ybase !== this.ydisp) {
2419 this.scrollToBottom();
2420 }
2421 return false;
2422 }
2423
2424 var self = this;
2425 var result = this.evaluateKeyEscapeSequence(ev);
2426
2427 if (result.scrollDisp) {
2428 this.scrollDisp(result.scrollDisp);
2429 return this.cancel(ev, true);
2430 }
2431
2432 if (isThirdLevelShift(this, ev)) {
2433 return true;
2434 }
2435
2436 if (result.cancel) {
2437 // The event is canceled at the end already, is this necessary?
2438 this.cancel(ev, true);
2439 }
2440
2441 if (!result.key) {
2442 return true;
2443 }
2444
2445 this.emit('keydown', ev);
2446 this.emit('key', result.key, ev);
2447 this.showCursor();
2448 this.handler(result.key);
2449
2450 return this.cancel(ev, true);
2451 };
2452
2453 /**
2454 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
2455 * returned value is the new key code to pass to the PTY.
2456 *
2457 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
2458 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
2459 */
2460 Terminal.prototype.evaluateKeyEscapeSequence = function(ev) {
2461 var result = {
2462 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
2463 // canceled at the end of keyDown
2464 cancel: false,
2465 // The new key even to emit
2466 key: undefined,
2467 // The number of characters to scroll, if this is defined it will cancel the event
2468 scrollDisp: undefined
2469 };
2470 var modifiers = ev.shiftKey << 0 | ev.altKey << 1 | ev.ctrlKey << 2 | ev.metaKey << 3;
2471 switch (ev.keyCode) {
2472 case 8:
2473 // backspace
2474 if (ev.shiftKey) {
2475 result.key = '\x08'; // ^H
2476 break;
2477 }
2478 result.key = '\x7f'; // ^?
2479 break;
2480 case 9:
2481 // tab
2482 if (ev.shiftKey) {
2483 result.key = '\x1b[Z';
2484 break;
2485 }
2486 result.key = '\t';
2487 result.cancel = true;
2488 break;
2489 case 13:
2490 // return/enter
2491 result.key = '\r';
2492 result.cancel = true;
2493 break;
2494 case 27:
2495 // escape
2496 result.key = '\x1b';
2497 result.cancel = true;
2498 break;
2499 case 37:
2500 // left-arrow
2501 if (modifiers) {
2502 result.key = '\x1b[1;' + (modifiers + 1) + 'D';
2503 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
2504 // http://unix.stackexchange.com/a/108106
2505 // macOS uses different escape sequences than linux
2506 if (result.key == '\x1b[1;3D') {
2507 result.key = (this.browser.isMac) ? '\x1bb' : '\x1b[1;5D';
2508 }
2509 } else if (this.applicationCursor) {
2510 result.key = '\x1bOD';
2511 } else {
2512 result.key = '\x1b[D';
2513 }
2514 break;
2515 case 39:
2516 // right-arrow
2517 if (modifiers) {
2518 result.key = '\x1b[1;' + (modifiers + 1) + 'C';
2519 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
2520 // http://unix.stackexchange.com/a/108106
2521 // macOS uses different escape sequences than linux
2522 if (result.key == '\x1b[1;3C') {
2523 result.key = (this.browser.isMac) ? '\x1bf' : '\x1b[1;5C';
2524 }
2525 } else if (this.applicationCursor) {
2526 result.key = '\x1bOC';
2527 } else {
2528 result.key = '\x1b[C';
2529 }
2530 break;
2531 case 38:
2532 // up-arrow
2533 if (modifiers) {
2534 result.key = '\x1b[1;' + (modifiers + 1) + 'A';
2535 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
2536 // http://unix.stackexchange.com/a/108106
2537 if (result.key == '\x1b[1;3A') {
2538 result.key = '\x1b[1;5A';
2539 }
2540 } else if (this.applicationCursor) {
2541 result.key = '\x1bOA';
2542 } else {
2543 result.key = '\x1b[A';
2544 }
2545 break;
2546 case 40:
2547 // down-arrow
2548 if (modifiers) {
2549 result.key = '\x1b[1;' + (modifiers + 1) + 'B';
2550 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
2551 // http://unix.stackexchange.com/a/108106
2552 if (result.key == '\x1b[1;3B') {
2553 result.key = '\x1b[1;5B';
2554 }
2555 } else if (this.applicationCursor) {
2556 result.key = '\x1bOB';
2557 } else {
2558 result.key = '\x1b[B';
2559 }
2560 break;
2561 case 45:
2562 // insert
2563 if (!ev.shiftKey && !ev.ctrlKey) {
2564 // <Ctrl> or <Shift> + <Insert> are used to
2565 // copy-paste on some systems.
2566 result.key = '\x1b[2~';
2567 }
2568 break;
2569 case 46:
2570 // delete
2571 if (modifiers) {
2572 result.key = '\x1b[3;' + (modifiers + 1) + '~';
2573 } else {
2574 result.key = '\x1b[3~';
2575 }
2576 break;
2577 case 36:
2578 // home
2579 if (modifiers)
2580 result.key = '\x1b[1;' + (modifiers + 1) + 'H';
2581 else if (this.applicationCursor)
2582 result.key = '\x1bOH';
2583 else
2584 result.key = '\x1b[H';
2585 break;
2586 case 35:
2587 // end
2588 if (modifiers)
2589 result.key = '\x1b[1;' + (modifiers + 1) + 'F';
2590 else if (this.applicationCursor)
2591 result.key = '\x1bOF';
2592 else
2593 result.key = '\x1b[F';
2594 break;
2595 case 33:
2596 // page up
2597 if (ev.shiftKey) {
2598 result.scrollDisp = -(this.rows - 1);
2599 } else {
2600 result.key = '\x1b[5~';
2601 }
2602 break;
2603 case 34:
2604 // page down
2605 if (ev.shiftKey) {
2606 result.scrollDisp = this.rows - 1;
2607 } else {
2608 result.key = '\x1b[6~';
2609 }
2610 break;
2611 case 112:
2612 // F1-F12
2613 if (modifiers) {
2614 result.key = '\x1b[1;' + (modifiers + 1) + 'P';
2615 } else {
2616 result.key = '\x1bOP';
2617 }
2618 break;
2619 case 113:
2620 if (modifiers) {
2621 result.key = '\x1b[1;' + (modifiers + 1) + 'Q';
2622 } else {
2623 result.key = '\x1bOQ';
2624 }
2625 break;
2626 case 114:
2627 if (modifiers) {
2628 result.key = '\x1b[1;' + (modifiers + 1) + 'R';
2629 } else {
2630 result.key = '\x1bOR';
2631 }
2632 break;
2633 case 115:
2634 if (modifiers) {
2635 result.key = '\x1b[1;' + (modifiers + 1) + 'S';
2636 } else {
2637 result.key = '\x1bOS';
2638 }
2639 break;
2640 case 116:
2641 if (modifiers) {
2642 result.key = '\x1b[15;' + (modifiers + 1) + '~';
2643 } else {
2644 result.key = '\x1b[15~';
2645 }
2646 break;
2647 case 117:
2648 if (modifiers) {
2649 result.key = '\x1b[17;' + (modifiers + 1) + '~';
2650 } else {
2651 result.key = '\x1b[17~';
2652 }
2653 break;
2654 case 118:
2655 if (modifiers) {
2656 result.key = '\x1b[18;' + (modifiers + 1) + '~';
2657 } else {
2658 result.key = '\x1b[18~';
2659 }
2660 break;
2661 case 119:
2662 if (modifiers) {
2663 result.key = '\x1b[19;' + (modifiers + 1) + '~';
2664 } else {
2665 result.key = '\x1b[19~';
2666 }
2667 break;
2668 case 120:
2669 if (modifiers) {
2670 result.key = '\x1b[20;' + (modifiers + 1) + '~';
2671 } else {
2672 result.key = '\x1b[20~';
2673 }
2674 break;
2675 case 121:
2676 if (modifiers) {
2677 result.key = '\x1b[21;' + (modifiers + 1) + '~';
2678 } else {
2679 result.key = '\x1b[21~';
2680 }
2681 break;
2682 case 122:
2683 if (modifiers) {
2684 result.key = '\x1b[23;' + (modifiers + 1) + '~';
2685 } else {
2686 result.key = '\x1b[23~';
2687 }
2688 break;
2689 case 123:
2690 if (modifiers) {
2691 result.key = '\x1b[24;' + (modifiers + 1) + '~';
2692 } else {
2693 result.key = '\x1b[24~';
2694 }
2695 break;
2696 default:
2697 // a-z and space
2698 if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
2699 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
2700 result.key = String.fromCharCode(ev.keyCode - 64);
2701 } else if (ev.keyCode === 32) {
2702 // NUL
2703 result.key = String.fromCharCode(0);
2704 } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
2705 // escape, file sep, group sep, record sep, unit sep
2706 result.key = String.fromCharCode(ev.keyCode - 51 + 27);
2707 } else if (ev.keyCode === 56) {
2708 // delete
2709 result.key = String.fromCharCode(127);
2710 } else if (ev.keyCode === 219) {
2711 // ^[ - Control Sequence Introducer (CSI)
2712 result.key = String.fromCharCode(27);
2713 } else if (ev.keyCode === 220) {
2714 // ^\ - String Terminator (ST)
2715 result.key = String.fromCharCode(28);
2716 } else if (ev.keyCode === 221) {
2717 // ^] - Operating System Command (OSC)
2718 result.key = String.fromCharCode(29);
2719 }
2720 } else if (!this.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
2721 // On Mac this is a third level shift. Use <Esc> instead.
2722 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
2723 result.key = '\x1b' + String.fromCharCode(ev.keyCode + 32);
2724 } else if (ev.keyCode === 192) {
2725 result.key = '\x1b`';
2726 } else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
2727 result.key = '\x1b' + (ev.keyCode - 48);
2728 }
2729 }
2730 break;
2731 }
2732 return result;
2733 };
2734
2735 /**
2736 * Set the G level of the terminal
2737 * @param g
2738 */
2739 Terminal.prototype.setgLevel = function(g) {
2740 this.glevel = g;
2741 this.charset = this.charsets[g];
2742 };
2743
2744 /**
2745 * Set the charset for the given G level of the terminal
2746 * @param g
2747 * @param charset
2748 */
2749 Terminal.prototype.setgCharset = function(g, charset) {
2750 this.charsets[g] = charset;
2751 if (this.glevel === g) {
2752 this.charset = charset;
2753 }
2754 };
2755
2756 /**
2757 * Handle a keypress event.
2758 * Key Resources:
2759 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
2760 * @param {KeyboardEvent} ev The keypress event to be handled.
2761 */
2762 Terminal.prototype.keyPress = function(ev) {
2763 var key;
2764
2765 this.cancel(ev);
2766
2767 if (ev.charCode) {
2768 key = ev.charCode;
2769 } else if (ev.which == null) {
2770 key = ev.keyCode;
2771 } else if (ev.which !== 0 && ev.charCode !== 0) {
2772 key = ev.which;
2773 } else {
2774 return false;
2775 }
2776
2777 if (!key || (
2778 (ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
2779 )) {
2780 return false;
2781 }
2782
2783 key = String.fromCharCode(key);
2784
2785 this.emit('keypress', key, ev);
2786 this.emit('key', key, ev);
2787 this.showCursor();
2788 this.handler(key);
2789
2790 return false;
2791 };
2792
2793 /**
2794 * Send data for handling to the terminal
2795 * @param {string} data
2796 */
2797 Terminal.prototype.send = function(data) {
2798 var self = this;
2799
2800 if (!this.queue) {
2801 setTimeout(function() {
2802 self.handler(self.queue);
2803 self.queue = '';
2804 }, 1);
2805 }
2806
2807 this.queue += data;
2808 };
2809
2810 /**
2811 * Ring the bell.
2812 * Note: We could do sweet things with webaudio here
2813 */
2814 Terminal.prototype.bell = function() {
2815 if (!this.visualBell) return;
2816 var self = this;
2817 this.element.style.borderColor = 'white';
2818 setTimeout(function() {
2819 self.element.style.borderColor = '';
2820 }, 10);
2821 if (this.popOnBell) this.focus();
2822 };
2823
2824 /**
2825 * Log the current state to the console.
2826 */
2827 Terminal.prototype.log = function() {
2828 if (!this.debug) return;
2829 if (!this.context.console || !this.context.console.log) return;
2830 var args = Array.prototype.slice.call(arguments);
2831 this.context.console.log.apply(this.context.console, args);
2832 };
2833
2834 /**
2835 * Log the current state as error to the console.
2836 */
2837 Terminal.prototype.error = function() {
2838 if (!this.debug) return;
2839 if (!this.context.console || !this.context.console.error) return;
2840 var args = Array.prototype.slice.call(arguments);
2841 this.context.console.error.apply(this.context.console, args);
2842 };
2843
2844 /**
2845 * Resizes the terminal.
2846 *
2847 * @param {number} x The number of columns to resize to.
2848 * @param {number} y The number of rows to resize to.
2849 */
2850 Terminal.prototype.resize = function(x, y) {
2851 var line
2852 , el
2853 , i
2854 , j
2855 , ch
2856 , addToY;
2857
2858 if (x === this.cols && y === this.rows) {
2859 return;
2860 }
2861
2862 if (x < 1) x = 1;
2863 if (y < 1) y = 1;
2864
2865 // resize cols
2866 j = this.cols;
2867 if (j < x) {
2868 ch = [this.defAttr, ' ', 1]; // does xterm use the default attr?
2869 i = this.lines.length;
2870 while (i--) {
2871 while (this.lines.get(i).length < x) {
2872 this.lines.get(i).push(ch);
2873 }
2874 }
2875 } else { // (j > x)
2876 i = this.lines.length;
2877 while (i--) {
2878 while (this.lines.get(i).length > x) {
2879 this.lines.get(i).pop();
2880 }
2881 }
2882 }
2883 this.setupStops(j);
2884 this.cols = x;
2885
2886 // resize rows
2887 j = this.rows;
2888 addToY = 0;
2889 if (j < y) {
2890 el = this.element;
2891 while (j++ < y) {
2892 // y is rows, not this.y
2893 if (this.lines.length < y + this.ybase) {
2894 if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
2895 // There is room above the buffer and there are no empty elements below the line,
2896 // scroll up
2897 this.ybase--;
2898 addToY++
2899 if (this.ydisp > 0) {
2900 // Viewport is at the top of the buffer, must increase downwards
2901 this.ydisp--;
2902 }
2903 } else {
2904 // Add a blank line if there is no buffer left at the top to scroll to, or if there
2905 // are blank lines after the cursor
2906 this.lines.push(this.blankLine());
2907 }
2908 }
2909 if (this.children.length < y) {
2910 this.insertRow();
2911 }
2912 }
2913 } else { // (j > y)
2914 while (j-- > y) {
2915 if (this.lines.length > y + this.ybase) {
2916 if (this.lines.length > this.ybase + this.y + 1) {
2917 // The line is a blank line below the cursor, remove it
2918 this.lines.pop();
2919 } else {
2920 // The line is the cursor, scroll down
2921 this.ybase++;
2922 this.ydisp++;
2923 }
2924 }
2925 if (this.children.length > y) {
2926 el = this.children.shift();
2927 if (!el) continue;
2928 el.parentNode.removeChild(el);
2929 }
2930 }
2931 }
2932 this.rows = y;
2933
2934 // Make sure that the cursor stays on screen
2935 if (this.y >= y) {
2936 this.y = y - 1;
2937 }
2938 if (addToY) {
2939 this.y += addToY;
2940 }
2941
2942 if (this.x >= x) {
2943 this.x = x - 1;
2944 }
2945
2946 this.scrollTop = 0;
2947 this.scrollBottom = y - 1;
2948
2949 this.refresh(0, this.rows - 1);
2950
2951 this.normal = null;
2952
2953 this.geometry = [this.cols, this.rows];
2954 this.emit('resize', {terminal: this, cols: x, rows: y});
2955 };
2956
2957 /**
2958 * Updates the range of rows to refresh
2959 * @param {number} y The number of rows to refresh next.
2960 */
2961 Terminal.prototype.updateRange = function(y) {
2962 if (y < this.refreshStart) this.refreshStart = y;
2963 if (y > this.refreshEnd) this.refreshEnd = y;
2964 // if (y > this.refreshEnd) {
2965 // this.refreshEnd = y;
2966 // if (y > this.rows - 1) {
2967 // this.refreshEnd = this.rows - 1;
2968 // }
2969 // }
2970 };
2971
2972 /**
2973 * Set the range of refreshing to the maximum value
2974 */
2975 Terminal.prototype.maxRange = function() {
2976 this.refreshStart = 0;
2977 this.refreshEnd = this.rows - 1;
2978 };
2979
2980
2981
2982 /**
2983 * Setup the tab stops.
2984 * @param {number} i
2985 */
2986 Terminal.prototype.setupStops = function(i) {
2987 if (i != null) {
2988 if (!this.tabs[i]) {
2989 i = this.prevStop(i);
2990 }
2991 } else {
2992 this.tabs = {};
2993 i = 0;
2994 }
2995
2996 for (; i < this.cols; i += 8) {
2997 this.tabs[i] = true;
2998 }
2999 };
3000
3001
3002 /**
3003 * Move the cursor to the previous tab stop from the given position (default is current).
3004 * @param {number} x The position to move the cursor to the previous tab stop.
3005 */
3006 Terminal.prototype.prevStop = function(x) {
3007 if (x == null) x = this.x;
3008 while (!this.tabs[--x] && x > 0);
3009 return x >= this.cols
3010 ? this.cols - 1
3011 : x < 0 ? 0 : x;
3012 };
3013
3014
3015 /**
3016 * Move the cursor one tab stop forward from the given position (default is current).
3017 * @param {number} x The position to move the cursor one tab stop forward.
3018 */
3019 Terminal.prototype.nextStop = function(x) {
3020 if (x == null) x = this.x;
3021 while (!this.tabs[++x] && x < this.cols);
3022 return x >= this.cols
3023 ? this.cols - 1
3024 : x < 0 ? 0 : x;
3025 };
3026
3027
3028 /**
3029 * Erase in the identified line everything from "x" to the end of the line (right).
3030 * @param {number} x The column from which to start erasing to the end of the line.
3031 * @param {number} y The line in which to operate.
3032 */
3033 Terminal.prototype.eraseRight = function(x, y) {
3034 var line = this.lines.get(this.ybase + y)
3035 , ch = [this.eraseAttr(), ' ', 1]; // xterm
3036
3037
3038 for (; x < this.cols; x++) {
3039 line[x] = ch;
3040 }
3041
3042 this.updateRange(y);
3043 };
3044
3045
3046
3047 /**
3048 * Erase in the identified line everything from "x" to the start of the line (left).
3049 * @param {number} x The column from which to start erasing to the start of the line.
3050 * @param {number} y The line in which to operate.
3051 */
3052 Terminal.prototype.eraseLeft = function(x, y) {
3053 var line = this.lines.get(this.ybase + y)
3054 , ch = [this.eraseAttr(), ' ', 1]; // xterm
3055
3056 x++;
3057 while (x--) line[x] = ch;
3058
3059 this.updateRange(y);
3060 };
3061
3062 /**
3063 * Clears the entire buffer, making the prompt line the new first line.
3064 */
3065 Terminal.prototype.clear = function() {
3066 if (this.ybase === 0 && this.y === 0) {
3067 // Don't clear if it's already clear
3068 return;
3069 }
3070 this.lines.set(0, this.lines.get(this.ybase + this.y));
3071 this.lines.length = 1;
3072 this.ydisp = 0;
3073 this.ybase = 0;
3074 this.y = 0;
3075 for (var i = 1; i < this.rows; i++) {
3076 this.lines.push(this.blankLine());
3077 }
3078 this.refresh(0, this.rows - 1);
3079 this.emit('scroll', this.ydisp);
3080 };
3081
3082 /**
3083 * Erase all content in the given line
3084 * @param {number} y The line to erase all of its contents.
3085 */
3086 Terminal.prototype.eraseLine = function(y) {
3087 this.eraseRight(0, y);
3088 };
3089
3090
3091 /**
3092 * Return the data array of a blank line
3093 * @param {number} cur First bunch of data for each "blank" character.
3094 */
3095 Terminal.prototype.blankLine = function(cur) {
3096 var attr = cur
3097 ? this.eraseAttr()
3098 : this.defAttr;
3099
3100 var ch = [attr, ' ', 1] // width defaults to 1 halfwidth character
3101 , line = []
3102 , i = 0;
3103
3104 for (; i < this.cols; i++) {
3105 line[i] = ch;
3106 }
3107
3108 return line;
3109 };
3110
3111
3112 /**
3113 * If cur return the back color xterm feature attribute. Else return defAttr.
3114 * @param {object} cur
3115 */
3116 Terminal.prototype.ch = function(cur) {
3117 return cur
3118 ? [this.eraseAttr(), ' ', 1]
3119 : [this.defAttr, ' ', 1];
3120 };
3121
3122
3123 /**
3124 * Evaluate if the current erminal is the given argument.
3125 * @param {object} term The terminal to evaluate
3126 */
3127 Terminal.prototype.is = function(term) {
3128 var name = this.termName;
3129 return (name + '').indexOf(term) === 0;
3130 };
3131
3132
3133 /**
3134 * Emit the 'data' event and populate the given data.
3135 * @param {string} data The data to populate in the event.
3136 */
3137 Terminal.prototype.handler = function(data) {
3138 // Prevents all events to pty process if stdin is disabled
3139 if (this.options.disableStdin) {
3140 return;
3141 }
3142
3143 // Input is being sent to the terminal, the terminal should focus the prompt.
3144 if (this.ybase !== this.ydisp) {
3145 this.scrollToBottom();
3146 }
3147 this.emit('data', data);
3148 };
3149
3150
3151 /**
3152 * Emit the 'title' event and populate the given title.
3153 * @param {string} title The title to populate in the event.
3154 */
3155 Terminal.prototype.handleTitle = function(title) {
3156 /**
3157 * This event is emitted when the title of the terminal is changed
3158 * from inside the terminal. The parameter is the new title.
3159 *
3160 * @event title
3161 */
3162 this.emit('title', title);
3163 };
3164
3165
3166 /**
3167 * ESC
3168 */
3169
3170 /**
3171 * ESC D Index (IND is 0x84).
3172 */
3173 Terminal.prototype.index = function() {
3174 this.y++;
3175 if (this.y > this.scrollBottom) {
3176 this.y--;
3177 this.scroll();
3178 }
3179 this.state = normal;
3180 };
3181
3182
3183 /**
3184 * ESC M Reverse Index (RI is 0x8d).
3185 *
3186 * Move the cursor up one row, inserting a new blank line if necessary.
3187 */
3188 Terminal.prototype.reverseIndex = function() {
3189 var j;
3190 if (this.y === this.scrollTop) {
3191 // possibly move the code below to term.reverseScroll();
3192 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
3193 // blankLine(true) is xterm/linux behavior
3194 this.lines.shiftElements(this.y + this.ybase, this.rows - 1, 1);
3195 this.lines.set(this.y + this.ybase, this.blankLine(true));
3196 this.updateRange(this.scrollTop);
3197 this.updateRange(this.scrollBottom);
3198 } else {
3199 this.y--;
3200 }
3201 this.state = normal;
3202 };
3203
3204
3205 /**
3206 * ESC c Full Reset (RIS).
3207 */
3208 Terminal.prototype.reset = function() {
3209 this.options.rows = this.rows;
3210 this.options.cols = this.cols;
3211 var customKeydownHandler = this.customKeydownHandler;
3212 Terminal.call(this, this.options);
3213 this.customKeydownHandler = customKeydownHandler;
3214 this.refresh(0, this.rows - 1);
3215 this.viewport.syncScrollArea();
3216 };
3217
3218
3219 /**
3220 * ESC H Tab Set (HTS is 0x88).
3221 */
3222 Terminal.prototype.tabSet = function() {
3223 this.tabs[this.x] = true;
3224 this.state = normal;
3225 };
3226
3227
3228 /**
3229 * CSI
3230 */
3231
3232 /**
3233 * CSI Ps A
3234 * Cursor Up Ps Times (default = 1) (CUU).
3235 */
3236 Terminal.prototype.cursorUp = function(params) {
3237 var param = params[0];
3238 if (param < 1) param = 1;
3239 this.y -= param;
3240 if (this.y < 0) this.y = 0;
3241 };
3242
3243
3244 /**
3245 * CSI Ps B
3246 * Cursor Down Ps Times (default = 1) (CUD).
3247 */
3248 Terminal.prototype.cursorDown = function(params) {
3249 var param = params[0];
3250 if (param < 1) param = 1;
3251 this.y += param;
3252 if (this.y >= this.rows) {
3253 this.y = this.rows - 1;
3254 }
3255 };
3256
3257
3258 /**
3259 * CSI Ps C
3260 * Cursor Forward Ps Times (default = 1) (CUF).
3261 */
3262 Terminal.prototype.cursorForward = function(params) {
3263 var param = params[0];
3264 if (param < 1) param = 1;
3265 this.x += param;
3266 if (this.x >= this.cols) {
3267 this.x = this.cols - 1;
3268 }
3269 };
3270
3271
3272 /**
3273 * CSI Ps D
3274 * Cursor Backward Ps Times (default = 1) (CUB).
3275 */
3276 Terminal.prototype.cursorBackward = function(params) {
3277 var param = params[0];
3278 if (param < 1) param = 1;
3279 this.x -= param;
3280 if (this.x < 0) this.x = 0;
3281 };
3282
3283
3284 /**
3285 * CSI Ps ; Ps H
3286 * Cursor Position [row;column] (default = [1,1]) (CUP).
3287 */
3288 Terminal.prototype.cursorPos = function(params) {
3289 var row, col;
3290
3291 row = params[0] - 1;
3292
3293 if (params.length >= 2) {
3294 col = params[1] - 1;
3295 } else {
3296 col = 0;
3297 }
3298
3299 if (row < 0) {
3300 row = 0;
3301 } else if (row >= this.rows) {
3302 row = this.rows - 1;
3303 }
3304
3305 if (col < 0) {
3306 col = 0;
3307 } else if (col >= this.cols) {
3308 col = this.cols - 1;
3309 }
3310
3311 this.x = col;
3312 this.y = row;
3313 };
3314
3315
3316 /**
3317 * CSI Ps J Erase in Display (ED).
3318 * Ps = 0 -> Erase Below (default).
3319 * Ps = 1 -> Erase Above.
3320 * Ps = 2 -> Erase All.
3321 * Ps = 3 -> Erase Saved Lines (xterm).
3322 * CSI ? Ps J
3323 * Erase in Display (DECSED).
3324 * Ps = 0 -> Selective Erase Below (default).
3325 * Ps = 1 -> Selective Erase Above.
3326 * Ps = 2 -> Selective Erase All.
3327 */
3328 Terminal.prototype.eraseInDisplay = function(params) {
3329 var j;
3330 switch (params[0]) {
3331 case 0:
3332 this.eraseRight(this.x, this.y);
3333 j = this.y + 1;
3334 for (; j < this.rows; j++) {
3335 this.eraseLine(j);
3336 }
3337 break;
3338 case 1:
3339 this.eraseLeft(this.x, this.y);
3340 j = this.y;
3341 while (j--) {
3342 this.eraseLine(j);
3343 }
3344 break;
3345 case 2:
3346 j = this.rows;
3347 while (j--) this.eraseLine(j);
3348 break;
3349 case 3:
3350 ; // no saved lines
3351 break;
3352 }
3353 };
3354
3355
3356 /**
3357 * CSI Ps K Erase in Line (EL).
3358 * Ps = 0 -> Erase to Right (default).
3359 * Ps = 1 -> Erase to Left.
3360 * Ps = 2 -> Erase All.
3361 * CSI ? Ps K
3362 * Erase in Line (DECSEL).
3363 * Ps = 0 -> Selective Erase to Right (default).
3364 * Ps = 1 -> Selective Erase to Left.
3365 * Ps = 2 -> Selective Erase All.
3366 */
3367 Terminal.prototype.eraseInLine = function(params) {
3368 switch (params[0]) {
3369 case 0:
3370 this.eraseRight(this.x, this.y);
3371 break;
3372 case 1:
3373 this.eraseLeft(this.x, this.y);
3374 break;
3375 case 2:
3376 this.eraseLine(this.y);
3377 break;
3378 }
3379 };
3380
3381
3382 /**
3383 * CSI Pm m Character Attributes (SGR).
3384 * Ps = 0 -> Normal (default).
3385 * Ps = 1 -> Bold.
3386 * Ps = 4 -> Underlined.
3387 * Ps = 5 -> Blink (appears as Bold).
3388 * Ps = 7 -> Inverse.
3389 * Ps = 8 -> Invisible, i.e., hidden (VT300).
3390 * Ps = 2 2 -> Normal (neither bold nor faint).
3391 * Ps = 2 4 -> Not underlined.
3392 * Ps = 2 5 -> Steady (not blinking).
3393 * Ps = 2 7 -> Positive (not inverse).
3394 * Ps = 2 8 -> Visible, i.e., not hidden (VT300).
3395 * Ps = 3 0 -> Set foreground color to Black.
3396 * Ps = 3 1 -> Set foreground color to Red.
3397 * Ps = 3 2 -> Set foreground color to Green.
3398 * Ps = 3 3 -> Set foreground color to Yellow.
3399 * Ps = 3 4 -> Set foreground color to Blue.
3400 * Ps = 3 5 -> Set foreground color to Magenta.
3401 * Ps = 3 6 -> Set foreground color to Cyan.
3402 * Ps = 3 7 -> Set foreground color to White.
3403 * Ps = 3 9 -> Set foreground color to default (original).
3404 * Ps = 4 0 -> Set background color to Black.
3405 * Ps = 4 1 -> Set background color to Red.
3406 * Ps = 4 2 -> Set background color to Green.
3407 * Ps = 4 3 -> Set background color to Yellow.
3408 * Ps = 4 4 -> Set background color to Blue.
3409 * Ps = 4 5 -> Set background color to Magenta.
3410 * Ps = 4 6 -> Set background color to Cyan.
3411 * Ps = 4 7 -> Set background color to White.
3412 * Ps = 4 9 -> Set background color to default (original).
3413 *
3414 * If 16-color support is compiled, the following apply. Assume
3415 * that xterm's resources are set so that the ISO color codes are
3416 * the first 8 of a set of 16. Then the aixterm colors are the
3417 * bright versions of the ISO colors:
3418 * Ps = 9 0 -> Set foreground color to Black.
3419 * Ps = 9 1 -> Set foreground color to Red.
3420 * Ps = 9 2 -> Set foreground color to Green.
3421 * Ps = 9 3 -> Set foreground color to Yellow.
3422 * Ps = 9 4 -> Set foreground color to Blue.
3423 * Ps = 9 5 -> Set foreground color to Magenta.
3424 * Ps = 9 6 -> Set foreground color to Cyan.
3425 * Ps = 9 7 -> Set foreground color to White.
3426 * Ps = 1 0 0 -> Set background color to Black.
3427 * Ps = 1 0 1 -> Set background color to Red.
3428 * Ps = 1 0 2 -> Set background color to Green.
3429 * Ps = 1 0 3 -> Set background color to Yellow.
3430 * Ps = 1 0 4 -> Set background color to Blue.
3431 * Ps = 1 0 5 -> Set background color to Magenta.
3432 * Ps = 1 0 6 -> Set background color to Cyan.
3433 * Ps = 1 0 7 -> Set background color to White.
3434 *
3435 * If xterm is compiled with the 16-color support disabled, it
3436 * supports the following, from rxvt:
3437 * Ps = 1 0 0 -> Set foreground and background color to
3438 * default.
3439 *
3440 * If 88- or 256-color support is compiled, the following apply.
3441 * Ps = 3 8 ; 5 ; Ps -> Set foreground color to the second
3442 * Ps.
3443 * Ps = 4 8 ; 5 ; Ps -> Set background color to the second
3444 * Ps.
3445 */
3446 Terminal.prototype.charAttributes = function(params) {
3447 // Optimize a single SGR0.
3448 if (params.length === 1 && params[0] === 0) {
3449 this.curAttr = this.defAttr;
3450 return;
3451 }
3452
3453 var l = params.length
3454 , i = 0
3455 , flags = this.curAttr >> 18
3456 , fg = (this.curAttr >> 9) & 0x1ff
3457 , bg = this.curAttr & 0x1ff
3458 , p;
3459
3460 for (; i < l; i++) {
3461 p = params[i];
3462 if (p >= 30 && p <= 37) {
3463 // fg color 8
3464 fg = p - 30;
3465 } else if (p >= 40 && p <= 47) {
3466 // bg color 8
3467 bg = p - 40;
3468 } else if (p >= 90 && p <= 97) {
3469 // fg color 16
3470 p += 8;
3471 fg = p - 90;
3472 } else if (p >= 100 && p <= 107) {
3473 // bg color 16
3474 p += 8;
3475 bg = p - 100;
3476 } else if (p === 0) {
3477 // default
3478 flags = this.defAttr >> 18;
3479 fg = (this.defAttr >> 9) & 0x1ff;
3480 bg = this.defAttr & 0x1ff;
3481 // flags = 0;
3482 // fg = 0x1ff;
3483 // bg = 0x1ff;
3484 } else if (p === 1) {
3485 // bold text
3486 flags |= 1;
3487 } else if (p === 4) {
3488 // underlined text
3489 flags |= 2;
3490 } else if (p === 5) {
3491 // blink
3492 flags |= 4;
3493 } else if (p === 7) {
3494 // inverse and positive
3495 // test with: echo -e '\e[31m\e[42mhello\e[7mworld\e[27mhi\e[m'
3496 flags |= 8;
3497 } else if (p === 8) {
3498 // invisible
3499 flags |= 16;
3500 } else if (p === 22) {
3501 // not bold
3502 flags &= ~1;
3503 } else if (p === 24) {
3504 // not underlined
3505 flags &= ~2;
3506 } else if (p === 25) {
3507 // not blink
3508 flags &= ~4;
3509 } else if (p === 27) {
3510 // not inverse
3511 flags &= ~8;
3512 } else if (p === 28) {
3513 // not invisible
3514 flags &= ~16;
3515 } else if (p === 39) {
3516 // reset fg
3517 fg = (this.defAttr >> 9) & 0x1ff;
3518 } else if (p === 49) {
3519 // reset bg
3520 bg = this.defAttr & 0x1ff;
3521 } else if (p === 38) {
3522 // fg color 256
3523 if (params[i + 1] === 2) {
3524 i += 2;
3525 fg = matchColor(
3526 params[i] & 0xff,
3527 params[i + 1] & 0xff,
3528 params[i + 2] & 0xff);
3529 if (fg === -1) fg = 0x1ff;
3530 i += 2;
3531 } else if (params[i + 1] === 5) {
3532 i += 2;
3533 p = params[i] & 0xff;
3534 fg = p;
3535 }
3536 } else if (p === 48) {
3537 // bg color 256
3538 if (params[i + 1] === 2) {
3539 i += 2;
3540 bg = matchColor(
3541 params[i] & 0xff,
3542 params[i + 1] & 0xff,
3543 params[i + 2] & 0xff);
3544 if (bg === -1) bg = 0x1ff;
3545 i += 2;
3546 } else if (params[i + 1] === 5) {
3547 i += 2;
3548 p = params[i] & 0xff;
3549 bg = p;
3550 }
3551 } else if (p === 100) {
3552 // reset fg/bg
3553 fg = (this.defAttr >> 9) & 0x1ff;
3554 bg = this.defAttr & 0x1ff;
3555 } else {
3556 this.error('Unknown SGR attribute: %d.', p);
3557 }
3558 }
3559
3560 this.curAttr = (flags << 18) | (fg << 9) | bg;
3561 };
3562
3563
3564 /**
3565 * CSI Ps n Device Status Report (DSR).
3566 * Ps = 5 -> Status Report. Result (``OK'') is
3567 * CSI 0 n
3568 * Ps = 6 -> Report Cursor Position (CPR) [row;column].
3569 * Result is
3570 * CSI r ; c R
3571 * CSI ? Ps n
3572 * Device Status Report (DSR, DEC-specific).
3573 * Ps = 6 -> Report Cursor Position (CPR) [row;column] as CSI
3574 * ? r ; c R (assumes page is zero).
3575 * Ps = 1 5 -> Report Printer status as CSI ? 1 0 n (ready).
3576 * or CSI ? 1 1 n (not ready).
3577 * Ps = 2 5 -> Report UDK status as CSI ? 2 0 n (unlocked)
3578 * or CSI ? 2 1 n (locked).
3579 * Ps = 2 6 -> Report Keyboard status as
3580 * CSI ? 2 7 ; 1 ; 0 ; 0 n (North American).
3581 * The last two parameters apply to VT400 & up, and denote key-
3582 * board ready and LK01 respectively.
3583 * Ps = 5 3 -> Report Locator status as
3584 * CSI ? 5 3 n Locator available, if compiled-in, or
3585 * CSI ? 5 0 n No Locator, if not.
3586 */
3587 Terminal.prototype.deviceStatus = function(params) {
3588 if (!this.prefix) {
3589 switch (params[0]) {
3590 case 5:
3591 // status report
3592 this.send('\x1b[0n');
3593 break;
3594 case 6:
3595 // cursor position
3596 this.send('\x1b['
3597 + (this.y + 1)
3598 + ';'
3599 + (this.x + 1)
3600 + 'R');
3601 break;
3602 }
3603 } else if (this.prefix === '?') {
3604 // modern xterm doesnt seem to
3605 // respond to any of these except ?6, 6, and 5
3606 switch (params[0]) {
3607 case 6:
3608 // cursor position
3609 this.send('\x1b[?'
3610 + (this.y + 1)
3611 + ';'
3612 + (this.x + 1)
3613 + 'R');
3614 break;
3615 case 15:
3616 // no printer
3617 // this.send('\x1b[?11n');
3618 break;
3619 case 25:
3620 // dont support user defined keys
3621 // this.send('\x1b[?21n');
3622 break;
3623 case 26:
3624 // north american keyboard
3625 // this.send('\x1b[?27;1;0;0n');
3626 break;
3627 case 53:
3628 // no dec locator/mouse
3629 // this.send('\x1b[?50n');
3630 break;
3631 }
3632 }
3633 };
3634
3635
3636 /**
3637 * Additions
3638 */
3639
3640 /**
3641 * CSI Ps @
3642 * Insert Ps (Blank) Character(s) (default = 1) (ICH).
3643 */
3644 Terminal.prototype.insertChars = function(params) {
3645 var param, row, j, ch;
3646
3647 param = params[0];
3648 if (param < 1) param = 1;
3649
3650 row = this.y + this.ybase;
3651 j = this.x;
3652 ch = [this.eraseAttr(), ' ', 1]; // xterm
3653
3654 while (param-- && j < this.cols) {
3655 this.lines.get(row).splice(j++, 0, ch);
3656 this.lines.get(row).pop();
3657 }
3658 };
3659
3660 /**
3661 * CSI Ps E
3662 * Cursor Next Line Ps Times (default = 1) (CNL).
3663 * same as CSI Ps B ?
3664 */
3665 Terminal.prototype.cursorNextLine = function(params) {
3666 var param = params[0];
3667 if (param < 1) param = 1;
3668 this.y += param;
3669 if (this.y >= this.rows) {
3670 this.y = this.rows - 1;
3671 }
3672 this.x = 0;
3673 };
3674
3675
3676 /**
3677 * CSI Ps F
3678 * Cursor Preceding Line Ps Times (default = 1) (CNL).
3679 * reuse CSI Ps A ?
3680 */
3681 Terminal.prototype.cursorPrecedingLine = function(params) {
3682 var param = params[0];
3683 if (param < 1) param = 1;
3684 this.y -= param;
3685 if (this.y < 0) this.y = 0;
3686 this.x = 0;
3687 };
3688
3689
3690 /**
3691 * CSI Ps G
3692 * Cursor Character Absolute [column] (default = [row,1]) (CHA).
3693 */
3694 Terminal.prototype.cursorCharAbsolute = function(params) {
3695 var param = params[0];
3696 if (param < 1) param = 1;
3697 this.x = param - 1;
3698 };
3699
3700
3701 /**
3702 * CSI Ps L
3703 * Insert Ps Line(s) (default = 1) (IL).
3704 */
3705 Terminal.prototype.insertLines = function(params) {
3706 var param, row, j;
3707
3708 param = params[0];
3709 if (param < 1) param = 1;
3710 row = this.y + this.ybase;
3711
3712 j = this.rows - 1 - this.scrollBottom;
3713 j = this.rows - 1 + this.ybase - j + 1;
3714
3715 while (param--) {
3716 if (this.lines.length === this.lines.maxLength) {
3717 // Trim the start of lines to make room for the new line
3718 this.lines.trimStart(1);
3719 this.ybase--;
3720 this.ydisp--;
3721 row--;
3722 j--;
3723 }
3724 // test: echo -e '\e[44m\e[1L\e[0m'
3725 // blankLine(true) - xterm/linux behavior
3726 this.lines.splice(row, 0, this.blankLine(true));
3727 this.lines.splice(j, 1);
3728 }
3729
3730 // this.maxRange();
3731 this.updateRange(this.y);
3732 this.updateRange(this.scrollBottom);
3733 };
3734
3735
3736 /**
3737 * CSI Ps M
3738 * Delete Ps Line(s) (default = 1) (DL).
3739 */
3740 Terminal.prototype.deleteLines = function(params) {
3741 var param, row, j;
3742
3743 param = params[0];
3744 if (param < 1) param = 1;
3745 row = this.y + this.ybase;
3746
3747 j = this.rows - 1 - this.scrollBottom;
3748 j = this.rows - 1 + this.ybase - j;
3749
3750 while (param--) {
3751 if (this.lines.length === this.lines.maxLength) {
3752 // Trim the start of lines to make room for the new line
3753 this.lines.trimStart(1);
3754 this.ybase -= 1;
3755 this.ydisp -= 1;
3756 }
3757 // test: echo -e '\e[44m\e[1M\e[0m'
3758 // blankLine(true) - xterm/linux behavior
3759 this.lines.splice(j + 1, 0, this.blankLine(true));
3760 this.lines.splice(row, 1);
3761 }
3762
3763 // this.maxRange();
3764 this.updateRange(this.y);
3765 this.updateRange(this.scrollBottom);
3766 };
3767
3768
3769 /**
3770 * CSI Ps P
3771 * Delete Ps Character(s) (default = 1) (DCH).
3772 */
3773 Terminal.prototype.deleteChars = function(params) {
3774 var param, row, ch;
3775
3776 param = params[0];
3777 if (param < 1) param = 1;
3778
3779 row = this.y + this.ybase;
3780 ch = [this.eraseAttr(), ' ', 1]; // xterm
3781
3782 while (param--) {
3783 this.lines.get(row).splice(this.x, 1);
3784 this.lines.get(row).push(ch);
3785 }
3786 };
3787
3788 /**
3789 * CSI Ps X
3790 * Erase Ps Character(s) (default = 1) (ECH).
3791 */
3792 Terminal.prototype.eraseChars = function(params) {
3793 var param, row, j, ch;
3794
3795 param = params[0];
3796 if (param < 1) param = 1;
3797
3798 row = this.y + this.ybase;
3799 j = this.x;
3800 ch = [this.eraseAttr(), ' ', 1]; // xterm
3801
3802 while (param-- && j < this.cols) {
3803 this.lines.get(row)[j++] = ch;
3804 }
3805 };
3806
3807 /**
3808 * CSI Pm ` Character Position Absolute
3809 * [column] (default = [row,1]) (HPA).
3810 */
3811 Terminal.prototype.charPosAbsolute = function(params) {
3812 var param = params[0];
3813 if (param < 1) param = 1;
3814 this.x = param - 1;
3815 if (this.x >= this.cols) {
3816 this.x = this.cols - 1;
3817 }
3818 };
3819
3820
3821 /**
3822 * 141 61 a * HPR -
3823 * Horizontal Position Relative
3824 * reuse CSI Ps C ?
3825 */
3826 Terminal.prototype.HPositionRelative = function(params) {
3827 var param = params[0];
3828 if (param < 1) param = 1;
3829 this.x += param;
3830 if (this.x >= this.cols) {
3831 this.x = this.cols - 1;
3832 }
3833 };
3834
3835
3836 /**
3837 * CSI Ps c Send Device Attributes (Primary DA).
3838 * Ps = 0 or omitted -> request attributes from terminal. The
3839 * response depends on the decTerminalID resource setting.
3840 * -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'')
3841 * -> CSI ? 1 ; 0 c (``VT101 with No Options'')
3842 * -> CSI ? 6 c (``VT102'')
3843 * -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'')
3844 * The VT100-style response parameters do not mean anything by
3845 * themselves. VT220 parameters do, telling the host what fea-
3846 * tures the terminal supports:
3847 * Ps = 1 -> 132-columns.
3848 * Ps = 2 -> Printer.
3849 * Ps = 6 -> Selective erase.
3850 * Ps = 8 -> User-defined keys.
3851 * Ps = 9 -> National replacement character sets.
3852 * Ps = 1 5 -> Technical characters.
3853 * Ps = 2 2 -> ANSI color, e.g., VT525.
3854 * Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode).
3855 * CSI > Ps c
3856 * Send Device Attributes (Secondary DA).
3857 * Ps = 0 or omitted -> request the terminal's identification
3858 * code. The response depends on the decTerminalID resource set-
3859 * ting. It should apply only to VT220 and up, but xterm extends
3860 * this to VT100.
3861 * -> CSI > Pp ; Pv ; Pc c
3862 * where Pp denotes the terminal type
3863 * Pp = 0 -> ``VT100''.
3864 * Pp = 1 -> ``VT220''.
3865 * and Pv is the firmware version (for xterm, this was originally
3866 * the XFree86 patch number, starting with 95). In a DEC termi-
3867 * nal, Pc indicates the ROM cartridge registration number and is
3868 * always zero.
3869 * More information:
3870 * xterm/charproc.c - line 2012, for more information.
3871 * vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)
3872 */
3873 Terminal.prototype.sendDeviceAttributes = function(params) {
3874 if (params[0] > 0) return;
3875
3876 if (!this.prefix) {
3877 if (this.is('xterm')
3878 || this.is('rxvt-unicode')
3879 || this.is('screen')) {
3880 this.send('\x1b[?1;2c');
3881 } else if (this.is('linux')) {
3882 this.send('\x1b[?6c');
3883 }
3884 } else if (this.prefix === '>') {
3885 // xterm and urxvt
3886 // seem to spit this
3887 // out around ~370 times (?).
3888 if (this.is('xterm')) {
3889 this.send('\x1b[>0;276;0c');
3890 } else if (this.is('rxvt-unicode')) {
3891 this.send('\x1b[>85;95;0c');
3892 } else if (this.is('linux')) {
3893 // not supported by linux console.
3894 // linux console echoes parameters.
3895 this.send(params[0] + 'c');
3896 } else if (this.is('screen')) {
3897 this.send('\x1b[>83;40003;0c');
3898 }
3899 }
3900 };
3901
3902
3903 /**
3904 * CSI Pm d
3905 * Line Position Absolute [row] (default = [1,column]) (VPA).
3906 */
3907 Terminal.prototype.linePosAbsolute = function(params) {
3908 var param = params[0];
3909 if (param < 1) param = 1;
3910 this.y = param - 1;
3911 if (this.y >= this.rows) {
3912 this.y = this.rows - 1;
3913 }
3914 };
3915
3916
3917 /**
3918 * 145 65 e * VPR - Vertical Position Relative
3919 * reuse CSI Ps B ?
3920 */
3921 Terminal.prototype.VPositionRelative = function(params) {
3922 var param = params[0];
3923 if (param < 1) param = 1;
3924 this.y += param;
3925 if (this.y >= this.rows) {
3926 this.y = this.rows - 1;
3927 }
3928 };
3929
3930
3931 /**
3932 * CSI Ps ; Ps f
3933 * Horizontal and Vertical Position [row;column] (default =
3934 * [1,1]) (HVP).
3935 */
3936 Terminal.prototype.HVPosition = function(params) {
3937 if (params[0] < 1) params[0] = 1;
3938 if (params[1] < 1) params[1] = 1;
3939
3940 this.y = params[0] - 1;
3941 if (this.y >= this.rows) {
3942 this.y = this.rows - 1;
3943 }
3944
3945 this.x = params[1] - 1;
3946 if (this.x >= this.cols) {
3947 this.x = this.cols - 1;
3948 }
3949 };
3950
3951
3952 /**
3953 * CSI Pm h Set Mode (SM).
3954 * Ps = 2 -> Keyboard Action Mode (AM).
3955 * Ps = 4 -> Insert Mode (IRM).
3956 * Ps = 1 2 -> Send/receive (SRM).
3957 * Ps = 2 0 -> Automatic Newline (LNM).
3958 * CSI ? Pm h
3959 * DEC Private Mode Set (DECSET).
3960 * Ps = 1 -> Application Cursor Keys (DECCKM).
3961 * Ps = 2 -> Designate USASCII for character sets G0-G3
3962 * (DECANM), and set VT100 mode.
3963 * Ps = 3 -> 132 Column Mode (DECCOLM).
3964 * Ps = 4 -> Smooth (Slow) Scroll (DECSCLM).
3965 * Ps = 5 -> Reverse Video (DECSCNM).
3966 * Ps = 6 -> Origin Mode (DECOM).
3967 * Ps = 7 -> Wraparound Mode (DECAWM).
3968 * Ps = 8 -> Auto-repeat Keys (DECARM).
3969 * Ps = 9 -> Send Mouse X & Y on button press. See the sec-
3970 * tion Mouse Tracking.
3971 * Ps = 1 0 -> Show toolbar (rxvt).
3972 * Ps = 1 2 -> Start Blinking Cursor (att610).
3973 * Ps = 1 8 -> Print form feed (DECPFF).
3974 * Ps = 1 9 -> Set print extent to full screen (DECPEX).
3975 * Ps = 2 5 -> Show Cursor (DECTCEM).
3976 * Ps = 3 0 -> Show scrollbar (rxvt).
3977 * Ps = 3 5 -> Enable font-shifting functions (rxvt).
3978 * Ps = 3 8 -> Enter Tektronix Mode (DECTEK).
3979 * Ps = 4 0 -> Allow 80 -> 132 Mode.
3980 * Ps = 4 1 -> more(1) fix (see curses resource).
3981 * Ps = 4 2 -> Enable Nation Replacement Character sets (DECN-
3982 * RCM).
3983 * Ps = 4 4 -> Turn On Margin Bell.
3984 * Ps = 4 5 -> Reverse-wraparound Mode.
3985 * Ps = 4 6 -> Start Logging. This is normally disabled by a
3986 * compile-time option.
3987 * Ps = 4 7 -> Use Alternate Screen Buffer. (This may be dis-
3988 * abled by the titeInhibit resource).
3989 * Ps = 6 6 -> Application keypad (DECNKM).
3990 * Ps = 6 7 -> Backarrow key sends backspace (DECBKM).
3991 * Ps = 1 0 0 0 -> Send Mouse X & Y on button press and
3992 * release. See the section Mouse Tracking.
3993 * Ps = 1 0 0 1 -> Use Hilite Mouse Tracking.
3994 * Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking.
3995 * Ps = 1 0 0 3 -> Use All Motion Mouse Tracking.
3996 * Ps = 1 0 0 4 -> Send FocusIn/FocusOut events.
3997 * Ps = 1 0 0 5 -> Enable Extended Mouse Mode.
3998 * Ps = 1 0 1 0 -> Scroll to bottom on tty output (rxvt).
3999 * Ps = 1 0 1 1 -> Scroll to bottom on key press (rxvt).
4000 * Ps = 1 0 3 4 -> Interpret "meta" key, sets eighth bit.
4001 * (enables the eightBitInput resource).
4002 * Ps = 1 0 3 5 -> Enable special modifiers for Alt and Num-
4003 * Lock keys. (This enables the numLock resource).
4004 * Ps = 1 0 3 6 -> Send ESC when Meta modifies a key. (This
4005 * enables the metaSendsEscape resource).
4006 * Ps = 1 0 3 7 -> Send DEL from the editing-keypad Delete
4007 * key.
4008 * Ps = 1 0 3 9 -> Send ESC when Alt modifies a key. (This
4009 * enables the altSendsEscape resource).
4010 * Ps = 1 0 4 0 -> Keep selection even if not highlighted.
4011 * (This enables the keepSelection resource).
4012 * Ps = 1 0 4 1 -> Use the CLIPBOARD selection. (This enables
4013 * the selectToClipboard resource).
4014 * Ps = 1 0 4 2 -> Enable Urgency window manager hint when
4015 * Control-G is received. (This enables the bellIsUrgent
4016 * resource).
4017 * Ps = 1 0 4 3 -> Enable raising of the window when Control-G
4018 * is received. (enables the popOnBell resource).
4019 * Ps = 1 0 4 7 -> Use Alternate Screen Buffer. (This may be
4020 * disabled by the titeInhibit resource).
4021 * Ps = 1 0 4 8 -> Save cursor as in DECSC. (This may be dis-
4022 * abled by the titeInhibit resource).
4023 * Ps = 1 0 4 9 -> Save cursor as in DECSC and use Alternate
4024 * Screen Buffer, clearing it first. (This may be disabled by
4025 * the titeInhibit resource). This combines the effects of the 1
4026 * 0 4 7 and 1 0 4 8 modes. Use this with terminfo-based
4027 * applications rather than the 4 7 mode.
4028 * Ps = 1 0 5 0 -> Set terminfo/termcap function-key mode.
4029 * Ps = 1 0 5 1 -> Set Sun function-key mode.
4030 * Ps = 1 0 5 2 -> Set HP function-key mode.
4031 * Ps = 1 0 5 3 -> Set SCO function-key mode.
4032 * Ps = 1 0 6 0 -> Set legacy keyboard emulation (X11R6).
4033 * Ps = 1 0 6 1 -> Set VT220 keyboard emulation.
4034 * Ps = 2 0 0 4 -> Set bracketed paste mode.
4035 * Modes:
4036 * http: *vt100.net/docs/vt220-rm/chapter4.html
4037 */
4038 Terminal.prototype.setMode = function(params) {
4039 if (typeof params === 'object') {
4040 var l = params.length
4041 , i = 0;
4042
4043 for (; i < l; i++) {
4044 this.setMode(params[i]);
4045 }
4046
4047 return;
4048 }
4049
4050 if (!this.prefix) {
4051 switch (params) {
4052 case 4:
4053 this.insertMode = true;
4054 break;
4055 case 20:
4056 //this.convertEol = true;
4057 break;
4058 }
4059 } else if (this.prefix === '?') {
4060 switch (params) {
4061 case 1:
4062 this.applicationCursor = true;
4063 break;
4064 case 2:
4065 this.setgCharset(0, Terminal.charsets.US);
4066 this.setgCharset(1, Terminal.charsets.US);
4067 this.setgCharset(2, Terminal.charsets.US);
4068 this.setgCharset(3, Terminal.charsets.US);
4069 // set VT100 mode here
4070 break;
4071 case 3: // 132 col mode
4072 this.savedCols = this.cols;
4073 this.resize(132, this.rows);
4074 break;
4075 case 6:
4076 this.originMode = true;
4077 break;
4078 case 7:
4079 this.wraparoundMode = true;
4080 break;
4081 case 12:
4082 // this.cursorBlink = true;
4083 break;
4084 case 66:
4085 this.log('Serial port requested application keypad.');
4086 this.applicationKeypad = true;
4087 this.viewport.syncScrollArea();
4088 break;
4089 case 9: // X10 Mouse
4090 // no release, no motion, no wheel, no modifiers.
4091 case 1000: // vt200 mouse
4092 // no motion.
4093 // no modifiers, except control on the wheel.
4094 case 1002: // button event mouse
4095 case 1003: // any event mouse
4096 // any event - sends motion events,
4097 // even if there is no button held down.
4098 this.x10Mouse = params === 9;
4099 this.vt200Mouse = params === 1000;
4100 this.normalMouse = params > 1000;
4101 this.mouseEvents = true;
4102 this.element.style.cursor = 'default';
4103 this.log('Binding to mouse events.');
4104 break;
4105 case 1004: // send focusin/focusout events
4106 // focusin: ^[[I
4107 // focusout: ^[[O
4108 this.sendFocus = true;
4109 break;
4110 case 1005: // utf8 ext mode mouse
4111 this.utfMouse = true;
4112 // for wide terminals
4113 // simply encodes large values as utf8 characters
4114 break;
4115 case 1006: // sgr ext mode mouse
4116 this.sgrMouse = true;
4117 // for wide terminals
4118 // does not add 32 to fields
4119 // press: ^[[<b;x;yM
4120 // release: ^[[<b;x;ym
4121 break;
4122 case 1015: // urxvt ext mode mouse
4123 this.urxvtMouse = true;
4124 // for wide terminals
4125 // numbers for fields
4126 // press: ^[[b;x;yM
4127 // motion: ^[[b;x;yT
4128 break;
4129 case 25: // show cursor
4130 this.cursorHidden = false;
4131 break;
4132 case 1049: // alt screen buffer cursor
4133 //this.saveCursor();
4134 ; // FALL-THROUGH
4135 case 47: // alt screen buffer
4136 case 1047: // alt screen buffer
4137 if (!this.normal) {
4138 var normal = {
4139 lines: this.lines,
4140 ybase: this.ybase,
4141 ydisp: this.ydisp,
4142 x: this.x,
4143 y: this.y,
4144 scrollTop: this.scrollTop,
4145 scrollBottom: this.scrollBottom,
4146 tabs: this.tabs
4147 // XXX save charset(s) here?
4148 // charset: this.charset,
4149 // glevel: this.glevel,
4150 // charsets: this.charsets
4151 };
4152 this.reset();
4153 this.viewport.syncScrollArea();
4154 this.normal = normal;
4155 this.showCursor();
4156 }
4157 break;
4158 }
4159 }
4160 };
4161
4162 /**
4163 * CSI Pm l Reset Mode (RM).
4164 * Ps = 2 -> Keyboard Action Mode (AM).
4165 * Ps = 4 -> Replace Mode (IRM).
4166 * Ps = 1 2 -> Send/receive (SRM).
4167 * Ps = 2 0 -> Normal Linefeed (LNM).
4168 * CSI ? Pm l
4169 * DEC Private Mode Reset (DECRST).
4170 * Ps = 1 -> Normal Cursor Keys (DECCKM).
4171 * Ps = 2 -> Designate VT52 mode (DECANM).
4172 * Ps = 3 -> 80 Column Mode (DECCOLM).
4173 * Ps = 4 -> Jump (Fast) Scroll (DECSCLM).
4174 * Ps = 5 -> Normal Video (DECSCNM).
4175 * Ps = 6 -> Normal Cursor Mode (DECOM).
4176 * Ps = 7 -> No Wraparound Mode (DECAWM).
4177 * Ps = 8 -> No Auto-repeat Keys (DECARM).
4178 * Ps = 9 -> Don't send Mouse X & Y on button press.
4179 * Ps = 1 0 -> Hide toolbar (rxvt).
4180 * Ps = 1 2 -> Stop Blinking Cursor (att610).
4181 * Ps = 1 8 -> Don't print form feed (DECPFF).
4182 * Ps = 1 9 -> Limit print to scrolling region (DECPEX).
4183 * Ps = 2 5 -> Hide Cursor (DECTCEM).
4184 * Ps = 3 0 -> Don't show scrollbar (rxvt).
4185 * Ps = 3 5 -> Disable font-shifting functions (rxvt).
4186 * Ps = 4 0 -> Disallow 80 -> 132 Mode.
4187 * Ps = 4 1 -> No more(1) fix (see curses resource).
4188 * Ps = 4 2 -> Disable Nation Replacement Character sets (DEC-
4189 * NRCM).
4190 * Ps = 4 4 -> Turn Off Margin Bell.
4191 * Ps = 4 5 -> No Reverse-wraparound Mode.
4192 * Ps = 4 6 -> Stop Logging. (This is normally disabled by a
4193 * compile-time option).
4194 * Ps = 4 7 -> Use Normal Screen Buffer.
4195 * Ps = 6 6 -> Numeric keypad (DECNKM).
4196 * Ps = 6 7 -> Backarrow key sends delete (DECBKM).
4197 * Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and
4198 * release. See the section Mouse Tracking.
4199 * Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking.
4200 * Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking.
4201 * Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking.
4202 * Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events.
4203 * Ps = 1 0 0 5 -> Disable Extended Mouse Mode.
4204 * Ps = 1 0 1 0 -> Don't scroll to bottom on tty output
4205 * (rxvt).
4206 * Ps = 1 0 1 1 -> Don't scroll to bottom on key press (rxvt).
4207 * Ps = 1 0 3 4 -> Don't interpret "meta" key. (This disables
4208 * the eightBitInput resource).
4209 * Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num-
4210 * Lock keys. (This disables the numLock resource).
4211 * Ps = 1 0 3 6 -> Don't send ESC when Meta modifies a key.
4212 * (This disables the metaSendsEscape resource).
4213 * Ps = 1 0 3 7 -> Send VT220 Remove from the editing-keypad
4214 * Delete key.
4215 * Ps = 1 0 3 9 -> Don't send ESC when Alt modifies a key.
4216 * (This disables the altSendsEscape resource).
4217 * Ps = 1 0 4 0 -> Do not keep selection when not highlighted.
4218 * (This disables the keepSelection resource).
4219 * Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables
4220 * the selectToClipboard resource).
4221 * Ps = 1 0 4 2 -> Disable Urgency window manager hint when
4222 * Control-G is received. (This disables the bellIsUrgent
4223 * resource).
4224 * Ps = 1 0 4 3 -> Disable raising of the window when Control-
4225 * G is received. (This disables the popOnBell resource).
4226 * Ps = 1 0 4 7 -> Use Normal Screen Buffer, clearing screen
4227 * first if in the Alternate Screen. (This may be disabled by
4228 * the titeInhibit resource).
4229 * Ps = 1 0 4 8 -> Restore cursor as in DECRC. (This may be
4230 * disabled by the titeInhibit resource).
4231 * Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor
4232 * as in DECRC. (This may be disabled by the titeInhibit
4233 * resource). This combines the effects of the 1 0 4 7 and 1 0
4234 * 4 8 modes. Use this with terminfo-based applications rather
4235 * than the 4 7 mode.
4236 * Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode.
4237 * Ps = 1 0 5 1 -> Reset Sun function-key mode.
4238 * Ps = 1 0 5 2 -> Reset HP function-key mode.
4239 * Ps = 1 0 5 3 -> Reset SCO function-key mode.
4240 * Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6).
4241 * Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style.
4242 * Ps = 2 0 0 4 -> Reset bracketed paste mode.
4243 */
4244 Terminal.prototype.resetMode = function(params) {
4245 if (typeof params === 'object') {
4246 var l = params.length
4247 , i = 0;
4248
4249 for (; i < l; i++) {
4250 this.resetMode(params[i]);
4251 }
4252
4253 return;
4254 }
4255
4256 if (!this.prefix) {
4257 switch (params) {
4258 case 4:
4259 this.insertMode = false;
4260 break;
4261 case 20:
4262 //this.convertEol = false;
4263 break;
4264 }
4265 } else if (this.prefix === '?') {
4266 switch (params) {
4267 case 1:
4268 this.applicationCursor = false;
4269 break;
4270 case 3:
4271 if (this.cols === 132 && this.savedCols) {
4272 this.resize(this.savedCols, this.rows);
4273 }
4274 delete this.savedCols;
4275 break;
4276 case 6:
4277 this.originMode = false;
4278 break;
4279 case 7:
4280 this.wraparoundMode = false;
4281 break;
4282 case 12:
4283 // this.cursorBlink = false;
4284 break;
4285 case 66:
4286 this.log('Switching back to normal keypad.');
4287 this.applicationKeypad = false;
4288 this.viewport.syncScrollArea();
4289 break;
4290 case 9: // X10 Mouse
4291 case 1000: // vt200 mouse
4292 case 1002: // button event mouse
4293 case 1003: // any event mouse
4294 this.x10Mouse = false;
4295 this.vt200Mouse = false;
4296 this.normalMouse = false;
4297 this.mouseEvents = false;
4298 this.element.style.cursor = '';
4299 break;
4300 case 1004: // send focusin/focusout events
4301 this.sendFocus = false;
4302 break;
4303 case 1005: // utf8 ext mode mouse
4304 this.utfMouse = false;
4305 break;
4306 case 1006: // sgr ext mode mouse
4307 this.sgrMouse = false;
4308 break;
4309 case 1015: // urxvt ext mode mouse
4310 this.urxvtMouse = false;
4311 break;
4312 case 25: // hide cursor
4313 this.cursorHidden = true;
4314 break;
4315 case 1049: // alt screen buffer cursor
4316 ; // FALL-THROUGH
4317 case 47: // normal screen buffer
4318 case 1047: // normal screen buffer - clearing it first
4319 if (this.normal) {
4320 this.lines = this.normal.lines;
4321 this.ybase = this.normal.ybase;
4322 this.ydisp = this.normal.ydisp;
4323 this.x = this.normal.x;
4324 this.y = this.normal.y;
4325 this.scrollTop = this.normal.scrollTop;
4326 this.scrollBottom = this.normal.scrollBottom;
4327 this.tabs = this.normal.tabs;
4328 this.normal = null;
4329 // if (params === 1049) {
4330 // this.x = this.savedX;
4331 // this.y = this.savedY;
4332 // }
4333 this.refresh(0, this.rows - 1);
4334 this.viewport.syncScrollArea();
4335 this.showCursor();
4336 }
4337 break;
4338 }
4339 }
4340 };
4341
4342
4343 /**
4344 * CSI Ps ; Ps r
4345 * Set Scrolling Region [top;bottom] (default = full size of win-
4346 * dow) (DECSTBM).
4347 * CSI ? Pm r
4348 */
4349 Terminal.prototype.setScrollRegion = function(params) {
4350 if (this.prefix) return;
4351 this.scrollTop = (params[0] || 1) - 1;
4352 this.scrollBottom = (params[1] || this.rows) - 1;
4353 this.x = 0;
4354 this.y = 0;
4355 };
4356
4357
4358 /**
4359 * CSI s
4360 * Save cursor (ANSI.SYS).
4361 */
4362 Terminal.prototype.saveCursor = function(params) {
4363 this.savedX = this.x;
4364 this.savedY = this.y;
4365 };
4366
4367
4368 /**
4369 * CSI u
4370 * Restore cursor (ANSI.SYS).
4371 */
4372 Terminal.prototype.restoreCursor = function(params) {
4373 this.x = this.savedX || 0;
4374 this.y = this.savedY || 0;
4375 };
4376
4377
4378 /**
4379 * Lesser Used
4380 */
4381
4382 /**
4383 * CSI Ps I
4384 * Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
4385 */
4386 Terminal.prototype.cursorForwardTab = function(params) {
4387 var param = params[0] || 1;
4388 while (param--) {
4389 this.x = this.nextStop();
4390 }
4391 };
4392
4393
4394 /**
4395 * CSI Ps S Scroll up Ps lines (default = 1) (SU).
4396 */
4397 Terminal.prototype.scrollUp = function(params) {
4398 var param = params[0] || 1;
4399 while (param--) {
4400 this.lines.splice(this.ybase + this.scrollTop, 1);
4401 this.lines.splice(this.ybase + this.scrollBottom, 0, this.blankLine());
4402 }
4403 // this.maxRange();
4404 this.updateRange(this.scrollTop);
4405 this.updateRange(this.scrollBottom);
4406 };
4407
4408
4409 /**
4410 * CSI Ps T Scroll down Ps lines (default = 1) (SD).
4411 */
4412 Terminal.prototype.scrollDown = function(params) {
4413 var param = params[0] || 1;
4414 while (param--) {
4415 this.lines.splice(this.ybase + this.scrollBottom, 1);
4416 this.lines.splice(this.ybase + this.scrollTop, 0, this.blankLine());
4417 }
4418 // this.maxRange();
4419 this.updateRange(this.scrollTop);
4420 this.updateRange(this.scrollBottom);
4421 };
4422
4423
4424 /**
4425 * CSI Ps ; Ps ; Ps ; Ps ; Ps T
4426 * Initiate highlight mouse tracking. Parameters are
4427 * [func;startx;starty;firstrow;lastrow]. See the section Mouse
4428 * Tracking.
4429 */
4430 Terminal.prototype.initMouseTracking = function(params) {
4431 // Relevant: DECSET 1001
4432 };
4433
4434
4435 /**
4436 * CSI > Ps; Ps T
4437 * Reset one or more features of the title modes to the default
4438 * value. Normally, "reset" disables the feature. It is possi-
4439 * ble to disable the ability to reset features by compiling a
4440 * different default for the title modes into xterm.
4441 * Ps = 0 -> Do not set window/icon labels using hexadecimal.
4442 * Ps = 1 -> Do not query window/icon labels using hexadeci-
4443 * mal.
4444 * Ps = 2 -> Do not set window/icon labels using UTF-8.
4445 * Ps = 3 -> Do not query window/icon labels using UTF-8.
4446 * (See discussion of "Title Modes").
4447 */
4448 Terminal.prototype.resetTitleModes = function(params) {
4449 ;
4450 };
4451
4452
4453 /**
4454 * CSI Ps Z Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
4455 */
4456 Terminal.prototype.cursorBackwardTab = function(params) {
4457 var param = params[0] || 1;
4458 while (param--) {
4459 this.x = this.prevStop();
4460 }
4461 };
4462
4463
4464 /**
4465 * CSI Ps b Repeat the preceding graphic character Ps times (REP).
4466 */
4467 Terminal.prototype.repeatPrecedingCharacter = function(params) {
4468 var param = params[0] || 1
4469 , line = this.lines.get(this.ybase + this.y)
4470 , ch = line[this.x - 1] || [this.defAttr, ' ', 1];
4471
4472 while (param--) line[this.x++] = ch;
4473 };
4474
4475
4476 /**
4477 * CSI Ps g Tab Clear (TBC).
4478 * Ps = 0 -> Clear Current Column (default).
4479 * Ps = 3 -> Clear All.
4480 * Potentially:
4481 * Ps = 2 -> Clear Stops on Line.
4482 * http://vt100.net/annarbor/aaa-ug/section6.html
4483 */
4484 Terminal.prototype.tabClear = function(params) {
4485 var param = params[0];
4486 if (param <= 0) {
4487 delete this.tabs[this.x];
4488 } else if (param === 3) {
4489 this.tabs = {};
4490 }
4491 };
4492
4493
4494 /**
4495 * CSI Pm i Media Copy (MC).
4496 * Ps = 0 -> Print screen (default).
4497 * Ps = 4 -> Turn off printer controller mode.
4498 * Ps = 5 -> Turn on printer controller mode.
4499 * CSI ? Pm i
4500 * Media Copy (MC, DEC-specific).
4501 * Ps = 1 -> Print line containing cursor.
4502 * Ps = 4 -> Turn off autoprint mode.
4503 * Ps = 5 -> Turn on autoprint mode.
4504 * Ps = 1 0 -> Print composed display, ignores DECPEX.
4505 * Ps = 1 1 -> Print all pages.
4506 */
4507 Terminal.prototype.mediaCopy = function(params) {
4508 ;
4509 };
4510
4511
4512 /**
4513 * CSI > Ps; Ps m
4514 * Set or reset resource-values used by xterm to decide whether
4515 * to construct escape sequences holding information about the
4516 * modifiers pressed with a given key. The first parameter iden-
4517 * tifies the resource to set/reset. The second parameter is the
4518 * value to assign to the resource. If the second parameter is
4519 * omitted, the resource is reset to its initial value.
4520 * Ps = 1 -> modifyCursorKeys.
4521 * Ps = 2 -> modifyFunctionKeys.
4522 * Ps = 4 -> modifyOtherKeys.
4523 * If no parameters are given, all resources are reset to their
4524 * initial values.
4525 */
4526 Terminal.prototype.setResources = function(params) {
4527 ;
4528 };
4529
4530
4531 /**
4532 * CSI > Ps n
4533 * Disable modifiers which may be enabled via the CSI > Ps; Ps m
4534 * sequence. This corresponds to a resource value of "-1", which
4535 * cannot be set with the other sequence. The parameter identi-
4536 * fies the resource to be disabled:
4537 * Ps = 1 -> modifyCursorKeys.
4538 * Ps = 2 -> modifyFunctionKeys.
4539 * Ps = 4 -> modifyOtherKeys.
4540 * If the parameter is omitted, modifyFunctionKeys is disabled.
4541 * When modifyFunctionKeys is disabled, xterm uses the modifier
4542 * keys to make an extended sequence of functions rather than
4543 * adding a parameter to each function key to denote the modi-
4544 * fiers.
4545 */
4546 Terminal.prototype.disableModifiers = function(params) {
4547 ;
4548 };
4549
4550
4551 /**
4552 * CSI > Ps p
4553 * Set resource value pointerMode. This is used by xterm to
4554 * decide whether to hide the pointer cursor as the user types.
4555 * Valid values for the parameter:
4556 * Ps = 0 -> never hide the pointer.
4557 * Ps = 1 -> hide if the mouse tracking mode is not enabled.
4558 * Ps = 2 -> always hide the pointer. If no parameter is
4559 * given, xterm uses the default, which is 1 .
4560 */
4561 Terminal.prototype.setPointerMode = function(params) {
4562 ;
4563 };
4564
4565
4566 /**
4567 * CSI ! p Soft terminal reset (DECSTR).
4568 * http://vt100.net/docs/vt220-rm/table4-10.html
4569 */
4570 Terminal.prototype.softReset = function(params) {
4571 this.cursorHidden = false;
4572 this.insertMode = false;
4573 this.originMode = false;
4574 this.wraparoundMode = false; // autowrap
4575 this.applicationKeypad = false; // ?
4576 this.viewport.syncScrollArea();
4577 this.applicationCursor = false;
4578 this.scrollTop = 0;
4579 this.scrollBottom = this.rows - 1;
4580 this.curAttr = this.defAttr;
4581 this.x = this.y = 0; // ?
4582 this.charset = null;
4583 this.glevel = 0; // ??
4584 this.charsets = [null]; // ??
4585 };
4586
4587
4588 /**
4589 * CSI Ps$ p
4590 * Request ANSI mode (DECRQM). For VT300 and up, reply is
4591 * CSI Ps; Pm$ y
4592 * where Ps is the mode number as in RM, and Pm is the mode
4593 * value:
4594 * 0 - not recognized
4595 * 1 - set
4596 * 2 - reset
4597 * 3 - permanently set
4598 * 4 - permanently reset
4599 */
4600 Terminal.prototype.requestAnsiMode = function(params) {
4601 ;
4602 };
4603
4604
4605 /**
4606 * CSI ? Ps$ p
4607 * Request DEC private mode (DECRQM). For VT300 and up, reply is
4608 * CSI ? Ps; Pm$ p
4609 * where Ps is the mode number as in DECSET, Pm is the mode value
4610 * as in the ANSI DECRQM.
4611 */
4612 Terminal.prototype.requestPrivateMode = function(params) {
4613 ;
4614 };
4615
4616
4617 /**
4618 * CSI Ps ; Ps " p
4619 * Set conformance level (DECSCL). Valid values for the first
4620 * parameter:
4621 * Ps = 6 1 -> VT100.
4622 * Ps = 6 2 -> VT200.
4623 * Ps = 6 3 -> VT300.
4624 * Valid values for the second parameter:
4625 * Ps = 0 -> 8-bit controls.
4626 * Ps = 1 -> 7-bit controls (always set for VT100).
4627 * Ps = 2 -> 8-bit controls.
4628 */
4629 Terminal.prototype.setConformanceLevel = function(params) {
4630 ;
4631 };
4632
4633
4634 /**
4635 * CSI Ps q Load LEDs (DECLL).
4636 * Ps = 0 -> Clear all LEDS (default).
4637 * Ps = 1 -> Light Num Lock.
4638 * Ps = 2 -> Light Caps Lock.
4639 * Ps = 3 -> Light Scroll Lock.
4640 * Ps = 2 1 -> Extinguish Num Lock.
4641 * Ps = 2 2 -> Extinguish Caps Lock.
4642 * Ps = 2 3 -> Extinguish Scroll Lock.
4643 */
4644 Terminal.prototype.loadLEDs = function(params) {
4645 ;
4646 };
4647
4648
4649 /**
4650 * CSI Ps SP q
4651 * Set cursor style (DECSCUSR, VT520).
4652 * Ps = 0 -> blinking block.
4653 * Ps = 1 -> blinking block (default).
4654 * Ps = 2 -> steady block.
4655 * Ps = 3 -> blinking underline.
4656 * Ps = 4 -> steady underline.
4657 */
4658 Terminal.prototype.setCursorStyle = function(params) {
4659 ;
4660 };
4661
4662
4663 /**
4664 * CSI Ps " q
4665 * Select character protection attribute (DECSCA). Valid values
4666 * for the parameter:
4667 * Ps = 0 -> DECSED and DECSEL can erase (default).
4668 * Ps = 1 -> DECSED and DECSEL cannot erase.
4669 * Ps = 2 -> DECSED and DECSEL can erase.
4670 */
4671 Terminal.prototype.setCharProtectionAttr = function(params) {
4672 ;
4673 };
4674
4675
4676 /**
4677 * CSI ? Pm r
4678 * Restore DEC Private Mode Values. The value of Ps previously
4679 * saved is restored. Ps values are the same as for DECSET.
4680 */
4681 Terminal.prototype.restorePrivateValues = function(params) {
4682 ;
4683 };
4684
4685
4686 /**
4687 * CSI Pt; Pl; Pb; Pr; Ps$ r
4688 * Change Attributes in Rectangular Area (DECCARA), VT400 and up.
4689 * Pt; Pl; Pb; Pr denotes the rectangle.
4690 * Ps denotes the SGR attributes to change: 0, 1, 4, 5, 7.
4691 * NOTE: xterm doesn't enable this code by default.
4692 */
4693 Terminal.prototype.setAttrInRectangle = function(params) {
4694 var t = params[0]
4695 , l = params[1]
4696 , b = params[2]
4697 , r = params[3]
4698 , attr = params[4];
4699
4700 var line
4701 , i;
4702
4703 for (; t < b + 1; t++) {
4704 line = this.lines.get(this.ybase + t);
4705 for (i = l; i < r; i++) {
4706 line[i] = [attr, line[i][1]];
4707 }
4708 }
4709
4710 // this.maxRange();
4711 this.updateRange(params[0]);
4712 this.updateRange(params[2]);
4713 };
4714
4715
4716 /**
4717 * CSI Pc; Pt; Pl; Pb; Pr$ x
4718 * Fill Rectangular Area (DECFRA), VT420 and up.
4719 * Pc is the character to use.
4720 * Pt; Pl; Pb; Pr denotes the rectangle.
4721 * NOTE: xterm doesn't enable this code by default.
4722 */
4723 Terminal.prototype.fillRectangle = function(params) {
4724 var ch = params[0]
4725 , t = params[1]
4726 , l = params[2]
4727 , b = params[3]
4728 , r = params[4];
4729
4730 var line
4731 , i;
4732
4733 for (; t < b + 1; t++) {
4734 line = this.lines.get(this.ybase + t);
4735 for (i = l; i < r; i++) {
4736 line[i] = [line[i][0], String.fromCharCode(ch)];
4737 }
4738 }
4739
4740 // this.maxRange();
4741 this.updateRange(params[1]);
4742 this.updateRange(params[3]);
4743 };
4744
4745
4746 /**
4747 * CSI Ps ; Pu ' z
4748 * Enable Locator Reporting (DECELR).
4749 * Valid values for the first parameter:
4750 * Ps = 0 -> Locator disabled (default).
4751 * Ps = 1 -> Locator enabled.
4752 * Ps = 2 -> Locator enabled for one report, then disabled.
4753 * The second parameter specifies the coordinate unit for locator
4754 * reports.
4755 * Valid values for the second parameter:
4756 * Pu = 0 <- or omitted -> default to character cells.
4757 * Pu = 1 <- device physical pixels.
4758 * Pu = 2 <- character cells.
4759 */
4760 Terminal.prototype.enableLocatorReporting = function(params) {
4761 var val = params[0] > 0;
4762 //this.mouseEvents = val;
4763 //this.decLocator = val;
4764 };
4765
4766
4767 /**
4768 * CSI Pt; Pl; Pb; Pr$ z
4769 * Erase Rectangular Area (DECERA), VT400 and up.
4770 * Pt; Pl; Pb; Pr denotes the rectangle.
4771 * NOTE: xterm doesn't enable this code by default.
4772 */
4773 Terminal.prototype.eraseRectangle = function(params) {
4774 var t = params[0]
4775 , l = params[1]
4776 , b = params[2]
4777 , r = params[3];
4778
4779 var line
4780 , i
4781 , ch;
4782
4783 ch = [this.eraseAttr(), ' ', 1]; // xterm?
4784
4785 for (; t < b + 1; t++) {
4786 line = this.lines.get(this.ybase + t);
4787 for (i = l; i < r; i++) {
4788 line[i] = ch;
4789 }
4790 }
4791
4792 // this.maxRange();
4793 this.updateRange(params[0]);
4794 this.updateRange(params[2]);
4795 };
4796
4797
4798 /**
4799 * CSI P m SP }
4800 * Insert P s Column(s) (default = 1) (DECIC), VT420 and up.
4801 * NOTE: xterm doesn't enable this code by default.
4802 */
4803 Terminal.prototype.insertColumns = function() {
4804 var param = params[0]
4805 , l = this.ybase + this.rows
4806 , ch = [this.eraseAttr(), ' ', 1] // xterm?
4807 , i;
4808
4809 while (param--) {
4810 for (i = this.ybase; i < l; i++) {
4811 this.lines.get(i).splice(this.x + 1, 0, ch);
4812 this.lines.get(i).pop();
4813 }
4814 }
4815
4816 this.maxRange();
4817 };
4818
4819
4820 /**
4821 * CSI P m SP ~
4822 * Delete P s Column(s) (default = 1) (DECDC), VT420 and up
4823 * NOTE: xterm doesn't enable this code by default.
4824 */
4825 Terminal.prototype.deleteColumns = function() {
4826 var param = params[0]
4827 , l = this.ybase + this.rows
4828 , ch = [this.eraseAttr(), ' ', 1] // xterm?
4829 , i;
4830
4831 while (param--) {
4832 for (i = this.ybase; i < l; i++) {
4833 this.lines.get(i).splice(this.x, 1);
4834 this.lines.get(i).push(ch);
4835 }
4836 }
4837
4838 this.maxRange();
4839 };
4840
4841 /**
4842 * Character Sets
4843 */
4844
4845 Terminal.charsets = {};
4846
4847 // DEC Special Character and Line Drawing Set.
4848 // http://vt100.net/docs/vt102-ug/table5-13.html
4849 // A lot of curses apps use this if they see TERM=xterm.
4850 // testing: echo -e '\e(0a\e(B'
4851 // The xterm output sometimes seems to conflict with the
4852 // reference above. xterm seems in line with the reference
4853 // when running vttest however.
4854 // The table below now uses xterm's output from vttest.
4855 Terminal.charsets.SCLD = { // (0
4856 '`': '\u25c6', // '◆'
4857 'a': '\u2592', // '▒'
4858 'b': '\u0009', // '\t'
4859 'c': '\u000c', // '\f'
4860 'd': '\u000d', // '\r'
4861 'e': '\u000a', // '\n'
4862 'f': '\u00b0', // '°'
4863 'g': '\u00b1', // '±'
4864 'h': '\u2424', // '\u2424' (NL)
4865 'i': '\u000b', // '\v'
4866 'j': '\u2518', // '┘'
4867 'k': '\u2510', // '┐'
4868 'l': '\u250c', // '┌'
4869 'm': '\u2514', // '└'
4870 'n': '\u253c', // '┼'
4871 'o': '\u23ba', // '⎺'
4872 'p': '\u23bb', // '⎻'
4873 'q': '\u2500', // '─'
4874 'r': '\u23bc', // '⎼'
4875 's': '\u23bd', // '⎽'
4876 't': '\u251c', // '├'
4877 'u': '\u2524', // '┤'
4878 'v': '\u2534', // '┴'
4879 'w': '\u252c', // '┬'
4880 'x': '\u2502', // '│'
4881 'y': '\u2264', // '≤'
4882 'z': '\u2265', // '≥'
4883 '{': '\u03c0', // 'π'
4884 '|': '\u2260', // '≠'
4885 '}': '\u00a3', // '£'
4886 '~': '\u00b7' // '·'
4887 };
4888
4889 Terminal.charsets.UK = null; // (A
4890 Terminal.charsets.US = null; // (B (USASCII)
4891 Terminal.charsets.Dutch = null; // (4
4892 Terminal.charsets.Finnish = null; // (C or (5
4893 Terminal.charsets.French = null; // (R
4894 Terminal.charsets.FrenchCanadian = null; // (Q
4895 Terminal.charsets.German = null; // (K
4896 Terminal.charsets.Italian = null; // (Y
4897 Terminal.charsets.NorwegianDanish = null; // (E or (6
4898 Terminal.charsets.Spanish = null; // (Z
4899 Terminal.charsets.Swedish = null; // (H or (7
4900 Terminal.charsets.Swiss = null; // (=
4901 Terminal.charsets.ISOLatin = null; // /A
4902
4903 /**
4904 * Helpers
4905 */
4906
4907 function on(el, type, handler, capture) {
4908 if (!Array.isArray(el)) {
4909 el = [el];
4910 }
4911 el.forEach(function (element) {
4912 element.addEventListener(type, handler, capture || false);
4913 });
4914 }
4915
4916 function off(el, type, handler, capture) {
4917 el.removeEventListener(type, handler, capture || false);
4918 }
4919
4920 function cancel(ev, force) {
4921 if (!this.cancelEvents && !force) {
4922 return;
4923 }
4924 ev.preventDefault();
4925 ev.stopPropagation();
4926 return false;
4927 }
4928
4929 function inherits(child, parent) {
4930 function f() {
4931 this.constructor = child;
4932 }
4933 f.prototype = parent.prototype;
4934 child.prototype = new f;
4935 }
4936
4937 // if bold is broken, we can't
4938 // use it in the terminal.
4939 function isBoldBroken(document) {
4940 var body = document.getElementsByTagName('body')[0];
4941 var el = document.createElement('span');
4942 el.innerHTML = 'hello world';
4943 body.appendChild(el);
4944 var w1 = el.scrollWidth;
4945 el.style.fontWeight = 'bold';
4946 var w2 = el.scrollWidth;
4947 body.removeChild(el);
4948 return w1 !== w2;
4949 }
4950
4951 function indexOf(obj, el) {
4952 var i = obj.length;
4953 while (i--) {
4954 if (obj[i] === el) return i;
4955 }
4956 return -1;
4957 }
4958
4959 function isThirdLevelShift(term, ev) {
4960 var thirdLevelKey =
4961 (term.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
4962 (term.browser.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
4963
4964 if (ev.type == 'keypress') {
4965 return thirdLevelKey;
4966 }
4967
4968 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
4969 return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
4970 }
4971
4972 function matchColor(r1, g1, b1) {
4973 var hash = (r1 << 16) | (g1 << 8) | b1;
4974
4975 if (matchColor._cache[hash] != null) {
4976 return matchColor._cache[hash];
4977 }
4978
4979 var ldiff = Infinity
4980 , li = -1
4981 , i = 0
4982 , c
4983 , r2
4984 , g2
4985 , b2
4986 , diff;
4987
4988 for (; i < Terminal.vcolors.length; i++) {
4989 c = Terminal.vcolors[i];
4990 r2 = c[0];
4991 g2 = c[1];
4992 b2 = c[2];
4993
4994 diff = matchColor.distance(r1, g1, b1, r2, g2, b2);
4995
4996 if (diff === 0) {
4997 li = i;
4998 break;
4999 }
5000
5001 if (diff < ldiff) {
5002 ldiff = diff;
5003 li = i;
5004 }
5005 }
5006
5007 return matchColor._cache[hash] = li;
5008 }
5009
5010 matchColor._cache = {};
5011
5012 // http://stackoverflow.com/questions/1633828
5013 matchColor.distance = function(r1, g1, b1, r2, g2, b2) {
5014 return Math.pow(30 * (r1 - r2), 2)
5015 + Math.pow(59 * (g1 - g2), 2)
5016 + Math.pow(11 * (b1 - b2), 2);
5017 };
5018
5019 function each(obj, iter, con) {
5020 if (obj.forEach) return obj.forEach(iter, con);
5021 for (var i = 0; i < obj.length; i++) {
5022 iter.call(con, obj[i], i, obj);
5023 }
5024 }
5025
5026 function keys(obj) {
5027 if (Object.keys) return Object.keys(obj);
5028 var key, keys = [];
5029 for (key in obj) {
5030 if (Object.prototype.hasOwnProperty.call(obj, key)) {
5031 keys.push(key);
5032 }
5033 }
5034 return keys;
5035 }
5036
5037 var wcwidth = (function(opts) {
5038 // extracted from https://www.cl.cam.ac.uk/%7Emgk25/ucs/wcwidth.c
5039 // combining characters
5040 var COMBINING = [
5041 [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489],
5042 [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2],
5043 [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603],
5044 [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670],
5045 [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED],
5046 [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A],
5047 [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902],
5048 [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D],
5049 [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981],
5050 [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD],
5051 [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C],
5052 [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D],
5053 [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC],
5054 [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD],
5055 [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C],
5056 [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D],
5057 [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0],
5058 [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48],
5059 [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC],
5060 [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD],
5061 [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D],
5062 [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6],
5063 [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E],
5064 [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC],
5065 [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35],
5066 [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E],
5067 [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97],
5068 [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030],
5069 [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039],
5070 [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F],
5071 [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753],
5072 [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD],
5073 [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD],
5074 [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922],
5075 [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B],
5076 [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34],
5077 [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42],
5078 [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF],
5079 [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063],
5080 [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F],
5081 [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B],
5082 [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F],
5083 [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB],
5084 [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F],
5085 [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169],
5086 [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD],
5087 [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F],
5088 [0xE0100, 0xE01EF]
5089 ];
5090 // binary search
5091 function bisearch(ucs) {
5092 var min = 0;
5093 var max = COMBINING.length - 1;
5094 var mid;
5095 if (ucs < COMBINING[0][0] || ucs > COMBINING[max][1])
5096 return false;
5097 while (max >= min) {
5098 mid = Math.floor((min + max) / 2);
5099 if (ucs > COMBINING[mid][1])
5100 min = mid + 1;
5101 else if (ucs < COMBINING[mid][0])
5102 max = mid - 1;
5103 else
5104 return true;
5105 }
5106 return false;
5107 }
5108 function wcwidth(ucs) {
5109 // test for 8-bit control characters
5110 if (ucs === 0)
5111 return opts.nul;
5112 if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0))
5113 return opts.control;
5114 // binary search in table of non-spacing characters
5115 if (bisearch(ucs))
5116 return 0;
5117 // if we arrive here, ucs is not a combining or C0/C1 control character
5118 return 1 +
5119 (
5120 ucs >= 0x1100 &&
5121 (
5122 ucs <= 0x115f || // Hangul Jamo init. consonants
5123 ucs == 0x2329 ||
5124 ucs == 0x232a ||
5125 (ucs >= 0x2e80 && ucs <= 0xa4cf && ucs != 0x303f) || // CJK..Yi
5126 (ucs >= 0xac00 && ucs <= 0xd7a3) || // Hangul Syllables
5127 (ucs >= 0xf900 && ucs <= 0xfaff) || // CJK Compat Ideographs
5128 (ucs >= 0xfe10 && ucs <= 0xfe19) || // Vertical forms
5129 (ucs >= 0xfe30 && ucs <= 0xfe6f) || // CJK Compat Forms
5130 (ucs >= 0xff00 && ucs <= 0xff60) || // Fullwidth Forms
5131 (ucs >= 0xffe0 && ucs <= 0xffe6) ||
5132 (ucs >= 0x20000 && ucs <= 0x2fffd) ||
5133 (ucs >= 0x30000 && ucs <= 0x3fffd)
5134 )
5135 );
5136 }
5137 return wcwidth;
5138 })({nul: 0, control: 0}); // configurable options
5139
5140 /**
5141 * Expose
5142 */
5143
5144 Terminal.EventEmitter = EventEmitter;
5145 Terminal.inherits = inherits;
5146
5147 /**
5148 * Adds an event listener to the terminal.
5149 *
5150 * @param {string} event The name of the event. TODO: Document all event types
5151 * @param {function} callback The function to call when the event is triggered.
5152 */
5153 Terminal.on = on;
5154 Terminal.off = off;
5155 Terminal.cancel = cancel;
5156
5157 module.exports = Terminal;