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