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