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